Posts

Showing posts from July, 2011

ios - How To implement double exposure for picking images? -

in app i'm having 2 imageviews, first imageview constant , second imageview ,after picking image zoom , can place in view , second image merged first image , after merging second imageview nil , first imageview having 2 images , can pic many images in second imageview , can move anywhere need pic single image @ single time.how implement this.?.thanks in advance. a simple image has 32bit of color information per pixel (rgb: ff ff ff), grayscale image has 8bit. should obvious conversion 32bit 8bit not reversible.

jquery - Group Events by Date using KnockoutJS -

update : provided best answer problem. feel free improve readability and/or efficiency. problem : using fullcalendar.io in requirejs set up, event objects (received ajax call .ashx handler) populated on calendar on every next/prev/view change. use json object on callback create list of events grouped startdate property. what i've done on calendar update, such new month, able set basic viewmodel populate new list of events observable array. part missing group by, such this example. since i'm looking group event object's start date , sort each group ascending start date, i'm not sure of best practices should take, such if necessary transform json data objects. continue update post learn more. reason not using linked example because not understand complete terminology behind handler, understand keywords $root @ point. ajax call , requirejs module load : fullcalendar var fullcalendar = ".calendar-module", viewmodel; function initfullcalendar() ...

python - Matplotlib multiple lines on graph -

i've been having issue saving matplotlib graphs images. images saving differently shows when call .show() method on graph. example here: http://s1.postimg.org/lbyei5cfz/blue5.png i'm not sure else do. i've spent past hours trying figure out what's causing it, can't figure out. here code in it's entirety. import matplotlib.pyplot plt import random turn = 1 #for x values class graph(): def __init__(self, name, color): self.currentvalue = 5 #for y values self.x = [turn] self.y = [self.currentvalue] self.name = name self.color = color def update(self): if random.randint(0,1): #just show if graph's value goes or down self.currentvalue += random.randint(0,10) self.y.append(self.currentvalue) else: self.currentvalue -= random.randint(0,10) self.y.append(self.currentvalue) self.x.append(turn) def plot(self): lines = plt....

How to get unique values from specific column in SQL Server? -

i have table tblfruit_id tblfruit_fruittype tblfruit_fruitname -------------------------------------------------- 1 citrus orange 2 citrus lime 3 citrus lemon 4 seed cherry 5 seed banana i can't set distinct tblfruit_fruittype column only, , if use group by (i want count function), getting error. my expected output: tblfruit_id tblfruit_fruittype tblfruit_fruitname ------------------------------------------------------ 1 citrus orange 4 seed cherry use window function ;with cte (select row_number()over (partition tblfruit_fruittype order tblfruit_id) rn, * tablename) select tblfruit_id, tblfruit_fruittype, tblfruit_fruitname cte rn = 1

ruby - Rails schema dump is putting string in for postgres point.. How do I fix this? -

i have point defined in migrations... when run migrations point in database.. perfect!! asked for. but.. see in schema.rb t.string? messes ci system, because builds database based on schema.rb. co-worker wants change type in database array, because easy. find leaves stink in code. q: how make schema.rb file show column point? completeness /20141120 ... .rb class addheadertouser < activerecord::migration def change add_column :users, :header_image_centre, :point end end /schema.rb t.string "header_image_centre", limit: nil this seems fixed in rails 4.2

Redbean php R::freeze(true) not working -

i have used r::freeze(true); in php application. don't know why redbean alters database table structure. noticed interger type column becomes text automatically. also have updated variable protected $isfrozen = true; in rb.php. no effect. without knowing php structure or framework (if any), it's impossible provide answer in relation that. in event, r::freeze( true ) correct syntax. make sure add statement in beginning of application. i have lot of slimphp applications using readbean , put @ top of index.php right after running r::setup(); <?php require 'vendor/autoload.php'; r::setup(); r::freeze( true );

ios - UIWebview Landscape support in Hybrid Application -

i developing hybrid application using uiwebview. html pages loaded local. have requirement 1 page should support both landscape , portrait mode. rest html page should support portrait mode only. have done following implementation that: - (nsuinteger) application:(uiapplication *)application supportedinterfaceorientationsforwindow:(uiwindow *)window{ if (isfullscreenplaying) { nslog(@"**********************************orienattion landscape%@",[window description]); return uiinterfaceorientationmaskallbutupsidedown; } nslog(@"**********************************orienattion portrait%@",[window description]); return uiinterfaceorientationmaskportrait; } i enabling isfullscreenplaying variable when have have url request equal full screen playing: **if([urlstring hasprefix:@"fullscreenvieweron://"]){ nslog(@"**********************************isfullscreenplayingyes"); isfullscreenplaying = yes; return no; }** but problem c...

Android Send User Latitude And Longitude On Xmpp Server Using ASmack -

i new in android , xmpp. setup xmpp server asmack library in android. aim want send user latlng server , track user on server side map (with php). sending latlng throw message ( using asmack ) server.but think not way. friends please tell me right way how that. sorry bad english. thankx in advance. possible, depends on want. if tracing coordinates without creating path points, can use simple, may udp or http... if want accumulate data, that's needed queues support...

html - Custom CSS for a Blog List -

Image
i creating php based website needs list programmes... tried creating custom css code myself, tried breaking templates css. failed. me css code div 1 given below i add classes buttons , other icons myselves. want div reponsive. not expert in css. want alignment. not fancy elements inside it. i have made fiddle here please check out, hope can edit fiddle based on needs html <div class='customheight'> <div class='row'> <div class='col-sm-6 custom'> <div class='dateholder'>27 nov</div> </div> <div class='col-sm-6'> <div class='row '> <h3>some title goes here</h3> </div> <div class="row bottomgap">location / date goes here</div> <div class="row bottomgap">content goes here content goes here content g...

java - How to create jar for Junit test class -

i following maven package structure.in project have class payloadprocessortest.java , has dependencies i want create jar file payloadprocessortest dependencies can 1 please me create jar dependencies <plugin> <artifactid>maven-assembly-plugin</artifactid> <version>2.2-beta-2</version> <executions> <execution> <id>create-test-dependency</id> <phase>process-test-classes</phase> <goals> <goal>single</goal> </goals> <configuration> <finalname>classloader-test-deps</finalname> <attach>false</attach> <descriptors> <descriptor>src/main/assembly/test-assembly.xml</descriptor> </descriptors> </configuration> </execution> </executions> </plugin> this content of test-assembly.xml <assembly> <id>test-cla...

Eclipse, libgdx and Gradle. Cannot get Google play services admob to work -

i want use admob in libgdx (1.4.1) project using eclipse (indigo). have donwload google play services , google repositry using sdk. have added following gradle.build file in android project: project(":android") { apply plugin: "android" configurations { natives } dependencies { compile project(":core") compile "com.badlogicgames.gdx:gdx-backend-android:$gdxversion" compile 'com.google.android.gms:play-services:6.+' {more not listed} this output of gradle task :android:androiddependencies : :android:androiddependencies debug \--- com.google.android.gms:play-services:6.1.71 \--- com.android.support:support-v4:20.0.0 debugtest no dependencies release \--- com.google.android.gms:play-services:6.1.71 \--- com.android.support:support-v4:20.0.0 in android project, directory gradle dependencies (persisted) can see support-v4-20.0.0.aar play-services-6.1.71.aar however, when try create protected adv...

ruby - What is the most efficient way to search for a sub-string -

in below string revision number 153. part inside string beside text "revision: 153\n". string = "path: blah\blah\nworking copy root path: blah\blah\nurl: blah\blah\nrelative url: ^/readme.txt\nrepository root: blah\blah\nrepository uuid: 2d7234b632a-38239d-4384f-9ac3-c05286096652\nrevisio n: 153\nnode kind: file\nschedule: normal\nlast changed author: user_name\nlast changed rev: 153\nlast changed date: 2014-11-27 11:38:21 +0530 (thu, 27 nov 2014)\ntext last updated: 2014-11-27 12: 05:24 +0530 (thu, 27 nov 2014)\nchecksum: 7ecb9f79f244r4f996e637d6f23\n\n" currently doing way : string.split('revision').last.split('node').first.chomp.gsub(': ','').to_i which outputs 153 . is there better way it? you can use string's [] , regular expression here: string[/revision:\s(\d+)/, 1]

objective c - iOS Instagram profile View and scrolling -

Image
how did instagram developers make profile view switch between uicollectionview , uitableview? i got 2 solutions: uiscrollview contains uiview @ top, , uiview holds uicollectionview , uitableview , delegates scrolling these views? or uitableview , uicollectionview top insests @ each view? which 1 better, think? may provide other solutions?

c# - Error 4 A namespace cannot directly contain members such as fields or methods -

i supposed project in class have setup website scratch using c# , asp.net. my objective create contact form in case function send email designated address upon clicking of button i've tried create googling codes. however, i've encountered error , "a namespace cannot directly contain members such fields or methods. " could help? in advance! the codes i've used on page follows: using system; using system.collections.generic; using system.linq; using system.web; using system.web.ui; using system.web.ui.webcontrols; <%@import namespace="system.web.mail" %>; <script language="c#" runat="server">; public partial class contactus : system.web.ui.page { protected void page_load(object sender, eventargs e) { } protected void button1_click(object sender, eventargs e) { mailmessage msg = new mailmessage(); msg.to = "sarahhhhh@gmail.com"; msg.from = nametb.tex...

java - Exception caused by other exception -

in application, seeing logs show exception1 caused by: exception2 caused by: exception3 so, if want handle scenario using try-catch, exception should give in catch block? i'am using jdk 1.6, single catch multiple exceptions not solution. using multi-catch blocks last choice. you should catch exception1 , since that's last exception thrown. first exception3 thrown , caught. catch block caught threw exception2 . then exception2 caught. catch block caught threw exception1 .

mysql - Must appear in the GROUP BY clause or be used in an aggregate function (PostgreSQL) -

Image
i have query : select u.fullname ,s.schedate, sum(case when s.isvisiting =1 s.isvisiting else 0 end) visit , count(s.custid) cust, sum(case when s.isclosing = 1 s.isclosing else 0 end)as orders vmstrschedule s join vmsmsuser u on u.usercode = s.salesmanid u.branchid = 'bll' group u.fullname but shows error : must appear in group clause or used in aggregate function it works in mysql , when tried in postgresql didn't work . want display data , per month : but if used query : select u.fullname,s.schedate, sum(case when s.isvisiting =1 s.isvisiting else 0 end) visit , count(s.custid) cust, sum(case when s.isclosing = 1 s.isclosing else 0 end)as orders vmstrschedule s join vmsmsuser u on u.usercode = s.salesmanid u.branchid = 'bll' group u.fullname,s.schedate order u.fullname it shows data : if "works" mean arbitrarily selects 1 of possible schedate values each group, you're correct. however, postgresql , other sql...

How do I play a HTTPS audio stream in MediaPlayer on Android[Nexus 5,7] -

our app has stream music network source. question why mediaplayer play when play music using http stream, got error(1,-1004) when use https stream source play in devices. **important:**it got error(1,-1004) in devices, such nexus5, nexus7 , asus fonepad 7. here snippet : string url ="http://10.0.0.45/o0$1$8i87308.mp3"; mediaplayer mymediaplayer = new mediaplayer(); mymediaplayer.setaudiostreamtype(audiomanager.stream_music); try { mymediaplayer.setdatasource(url); mymediaplayer.prepareasync(); // might take long! (for buffering, etc) } catch (ioexception e) { toast.maketext(this, "mp3 not found", toast.length_short).show(); e.printstacktrace(); } //mp3 started after completion of preparing... mymediaplayer.setonpreparedlistener(new mediaplayer.onpreparedlistener() { @override public void onprepared(mediaplayer player) { player.start(); system.out.print...

.net - Dynamic call to native library -

i trying invoke function native c++ dll, given name, arguments , return type. having problem make delegate marshalling. i doing this: object^ invike(type^ return_type, array<type^>^ types, array<object^>^ parameters) { //demo data return_type=long::typeid; types = gcnew array < type^ > {string::typeid, int::typeid}; parameters = gcnew array < type^ > {"test",1}; //parameters initializated in class constructor //intptr dll_file = native_dll::loadlibrary(dll_name); //intptr init_function = native_dll::getprocaddress(dll_file, "_mcamgetnumberofcameras@0"); dynamicmethod^ function_prototype = gcnew dynamicmethod("test", return_type, types); //argumentexception exception in line delegate^ function_delegate = marshal::getdelegateforfunctionpointer(init_function, function_prototype->gettype()); object^ result = function_delegate->dynamicinvoke(parameters); return result; } at line creating function_delegate...

Android issue with boolean on shared preferences -

android issue boolean on shared preferences sharedpreferences spref = preferencemanager.getdefaultsharedpreferences(this); boolean isslide=spref.getboolean("slide_show",false); //in isslide getting right value if statement not working if(isslide==true){ //if true page slide works in false } i tried in link issue boolean on shared preferences answer not clear settings code: <preferencecategory android:title="slide show" > <checkboxpreference android:title="slide show" android:key="slide_show" /> </preferencecategory> you may want check if sharedpreference variables active. example on how set sharedpreference. to write sharedpreference: sharedpreferences prefs = getsharedpreferences("mypref", 0); sharedpreferences.editor editor = prefs.edit(); editor.putboolean("mybool", true); editor.commit(); to read sharedpreference: sharedpreferences prefs = getsharedprefere...

sql - Why is like-operator so fast -

you know operator in sql. example: select * customer email '%goog%' so question how can database return fast result? when should program function this, loop on customers , on each email. slow. heard indexes. how can database use index when database doesn't know first or last letter is? or other way it? i don't want program this. want know how works. i have no idea engine using , what's beneath actual hood here helpful information regarding problem: often, sql engines uses free text search inside column able extract queries fast. done creating inverted index , maps each word "documents" (row,column) contains them. 1 used library apache lucene . unfortunately, ir (information retrieval) libraries not support wild card @ beginning of query (but anywhere else), specific example cannot searched in such index. you can create index support wild card @ beginning of index, using suffix tree . suffix trees excellent searching substring, exam...

Cordova/Phonegap upload image to amazon S3 through javascript -

please me on one. can't seem find problem is. looks goes way (fetching image, policy, signature etc.) until uploads file. rejected amazon... idea why? here's upload code: policy_json = { "expiration": "2020-08-06t12:00:00.000z", "conditions": [ {"bucket": "gloportalmobile"}, {"acl": "public-read"} ] }; var policyencbase64 = btoa(json.stringify(policy_json)); var secret = "--my--secret--key--here--"; var encodedsignature = b64_hmac_sha1(secret, policyencbase64); b64_hmac_sha1(secret, policyencbase64); var s3uri = encodeuri("https://gloportalmobile.s3.amazonaws.com/"), policybase64 = policyencbase64, signature = encodedsignature, awskey = 'my--aws--key--here--', acl = "public-read"; function upload(imageuri, filename) { ...

python - Google App Engine - why is User Class user_id different from Googleapis id -

user_id in gae different id in google apis example - same email@gmail.com gae (user_id) = 115540519337309141732 whereas google api https://www.googleapis.com/oauth2/v1/userinfo (id) = 135544519337309141732 happens same id if go plus.google.com/id so wondering if it's possible google api id in gae without having go through oauth2 because can't work, can users class work. thanks! you correct, id space used app engine different used other google sign in apis , there's no easy way conversion. please file bug @ https://code.google.com/p/googleappengine/issues if issue important you.

Aggregate Command in R, Remove Columns? -

my aggregate command takes mean of of columns based on specific variable. apply function columns. have code in following format aggregate: aggregate(dataframe,list(name=variable),mean) this gives me mean different columns based on specific variable.i selectively choose columns. if want apply function select columns 2 , 3 (numeric index) aggregate(dat1[,2:3], list(name=dat1[,'variable']), fun=mean) # name v1 v2 #1 10.2 11.2 #2 b 12.8 7.6 or replace numeric index column names aggregate(dat1[,c("v1", "v2")], list(name=dat1[,'variable']), fun=mean) # name v1 v2 #1 10.2 11.2 #2 b 12.8 7.6 or using dplyr library(dplyr) dat1 %>% group_by(variable) %>% summarise_each(funs(mean=mean(., na.rm=true)), v1,v2) # variable v1 v2 #1 10.2 11.2 #2 b 12.8 7.6 or using data.table library(data.table) setdt(dat1)[, lapply(.sd, mean), by=variable, .sdcols=colnames(...

jsf - rich:calendar custom footer not being recognized -

Image
i've having problems trying customize footer on calendar using f:facet tag . content in tag being ignored, being default footer shown instead. can customise footer using rich:calendar attributes showapplybutton , think not possible remove selected date appears on left of clean button ('netejar' in image) without adding apply button, customer doesn't want. we using richfaces 4.3.5.final. code: <rich:calendar value="#{yourbeanhere.yourdatehere}" locale="es_es"> <f:facet name="footer"> <h:panelgrid columns="3" width="100%" columnclasses="fake, width100 talign"> <h:outputtext value="{selecteddatecontrol}" style="font-weight:bold;" /> <h:outputtext value="{timecontrol}" style="font-weight:bold;" /> <h:outputtext value="{todaycontrol}" style="font-weight:bold;...

ios - Why should the classes in the FrameWork must be public? -

i create framework using swift, , create test project check if framework goes well. the framework has 2 classfile named "pubutils" , "utils". in test project, can use public class pubutils. cannot use utils class, because cannot find it. , method in pubutils must public if want use them. donnot know apple design or make mistakes. yes . classes/method public access level visible external world. restrict others using internal classes/methods. default access level internal means accessible within same target/module. private access level has little visibility. how access control mechanism in swift works. in case, if want other source files use framework classes, make them public. each framework considered separate module. read more about: access control

c# - Check if 'Restrict background data' is active on Windows Phone -

there settings in data sense 'restrict background data' , 'restrict background data when roamind'. blocking background tasks without notification application. how check state app, can alert user? i think exception message way detect it. in background task sample code . // place call add in try block in case user has disabled agents. try { scheduledactionservice.add( task ); } catch ( invalidoperationexception exception ) { if ( exception.message.contains( "bns error: action disabled" ) ) { // background agents application have been disabled user. } if ( exception.message.contains( "bns error: maximum number of scheduledactions of type have been added." ) ) { } //... }

android - Translate animation created programmatically has incorrect duration and offset -

here's needs done: i have top bar 3 buttons. 2 on right can pressed , nothing interesting them. left 1 replaces 3 buttons other three. animation: middle , right (new ones) buttons slide out left button's position corresponding places, while old buttons fade out. left button gets replaced without movement: old 1 fades out, new 1 fades in. how done: final animation fadeout, fadein; animation fadeoutwithlistener; fadein = animationutils.loadanimation(this, r.anim.camera_top_bar_fade_in); fadeout = animationutils.loadanimation(this, r.anim.camera_top_bar_fade_out); final translateanimation slideanim; slideanim = new translateanimation( animation.relative_to_parent, -flashautobtn.getleft(), animation.relative_to_self, 0, animation.relative_to_self, 0, animation.relative_to_self, 0); slideanim.setduration(1000l); slideanim.setstartoffset(0); fadeoutwithlistener = animationutils.loadanimation(this, r.anim.camera_top_bar_fade_out); fadeoutwithlistener.setanim...

android - Cordova: How to set different package names per platform using the cordova-cli? -

i have app ios , android upgrading phonegap 2.x cordova 4.0. as ios , android apps created using phonegap 2.x have 2 separate projects (i.e. project ios , project android). these projects have shared www directory (using symbolic links) html/css/javascript assets. when upgrade cordova 4.0 can have single cordova project , use cordova cli create projects each platform in platforms directory. the package name used each platform in cordova set in shared config.xml file though. cordova cli uses package name set in config.xml perpare, build , add platform commands. unfortunately package names used phonegap 2.x apps not same (i.e. package name android app different package name of ios app). for example: android app has package name com.example.applongname ios app has package name com.example.appshortname. beginning of package name (i.e. reverse company domain name) same each app application names differ. ios application name contains capital letters. i need keep package names ...

c# - wpf mvvm - master detail in one view best implementation? -

i have view contains datagrid. below datagrid have controls edit properties of selected item (lets manager) datagrid. so have property bound datagrid selecteditem: a manager has example property called name. when manager selected. textbox below datagrid has bound name property can in xaml this: <textbox text="{binding path=selectedmanager.name, updatesourcetrigger=propertychanged}" /> the problem implement code when value of selectedmanager.name changes need property in viewmodel this: private manager _selectedmanager; public manager selectedmanager { { return _selectedmanager; } set { _selectedmanager = value; raisepropertychanged("selectedmanager"); } } so when selectedmanager changes not update managername property ofcourse. have 3 solutions , know think these or have better way. solutuions are: 1: when selectedmanager set can call raisepropertychanged(string.empty); update bindings. 2: when selectedmanage...

telephonymanager - How can i get SIM ID of both sim in dual android device...? -

by code i'm getting 1 sim id telephonymanager m = (telephonymanager)getsystemservice(context.telephony_service); string phonenumber = m.getline1number(); string simid = m.getsimserialnumber(); string phoneimei = m.getdeviceid(); tvsim.settext("phone number : " + phonenumber); tvsimid.settext("sim id : " + simid); tvimei.settext("imei" + phoneimei); there no general method info second\third\fourth sim in device, detect presence ;-( all dual-sim mechanisms vendor-specific. had been discussed lot; please use search on stackoverflow.com see details, , code sketches.

javascript - ASP.Net Mvc Ajax Request in Progress -

i using @ajax.actionlink call controller action in ajax fashion .is there way detect if there ajax request running/pending on page?the functionality want pretty basic i.e. once user clicks link should wait either request succeed or fail.he should allowed click again( generate new request server). i have disabled link not that(i guess href cant disabled) try this, this code check executing ajax request before making new ajax request. can subscribe onsuccess, onfailure callbacks : @ajax.actionlink("home", "index", "home", new ajaxoptions { onbegin = "return onbegin();", oncomplete = "oncomplete", updatetargetid = "article_site" }) and then: var request_executing = false; function onbegin() { if (request_executing == true) {return false ;} request_executing = true; return true; } function oncomplete() { request_executing = false; } or jquery alternative (so don't need ...

c - What is the GID/UID of the system on Android? -

how identify number (integer value) of particular group associated file? ls -l drwxr-x--x root system 2014-11-26 10:59 xyz i have managed check group id of root 0 . corresponding number of group id system ? i need change group of file system. how do using chown ? gid_t internally of int type. value should pass make system? how know? at adb shell su 1000 since 1000 system uid id this returns uid=1000(system) gid=1000(system) so gid system 1000 too

javascript - Manipulate http response body in CapserJS -

i using casperjs 1.1.0-beta3 combined phantomjs 1.9.8. how can edit response body content before phantomjs parses , renders it? something like: casper.on("resource.received", function(response) { response.body.add("<h1>bla</h1>"); } you can't this. phantomjs not expose body, cannot change it. there some tricks when receive javascript, cannot applied type of resource. it seems receive html resource. it page resource if html resource page resource, can abort request using resource.requested event handler, use __utils__.sendajax retrieve page source, change content based on rules , load current content. var done = false; casper.on("page.resource.requested", function(req, network){ if (req.url === "someurl") { network.abort(); var content = this.evaluate(function(url){ return __utils__.sendajax(url, "get"); }, req.url); content = content.replace...

php - Chart not rendered properly -

Image
i have small table and want create type_donutchart phpexcel library. took example code examples/33chartcreate-pie.php file , adapted accordingly: $dataserieslabels2 = array( //new phpexcel_chart_dataseriesvalues('string', 'summen!$a$1', null, 1), ); $xaxistickvalues2 = array( new phpexcel_chart_dataseriesvalues('string', 'summen!$b$1:$c$1', null, 2), ); $dataseriesvalues2 = array( new phpexcel_chart_dataseriesvalues('number', 'summen!$b$2:$c$2', null, 2), ); the file served script, when try open it, error message occurs: we found problem content in "myfile.xlsx". want try recover as can? if trust source of workbook, click yes. when click yes , activate editing on document, following message this: excel has finished check , repair of file. parts of file have been repaired or discarded. removed part: part /xl/drawings/drawing4.xml. (drawing form) what's wrong in code? have modify...

Converting XML to c# class -

i receiving xml file on socket , want retrieve values inside xml converting c# class object please guide me how this i need values of sno,file,it , maxit p.s. using visual studio 2010 here xml file: <?xml version="1.0" standalone="yes"?> <newdataset> <default.xml> <sno>31</sno> <file>300k</file> <it>5</it> <maxit>10</maxit> </default.xml> <default.xml> <sno>32</sno> <file>200k</file> <it>5</it> <maxit>10</maxit> </default.xml> </newdataset> [edited] please note need use these values dynamically working on utility sends xml file system via sockets. dont think can ude xsd here to nodes use xpath expression /default/default. first slash means node must root node. selectnodes method returns collection xmlnodelist contain nodes. value of sub node can index ...

r - How to calculate rowMeans for dataframe? -

i trying calculate rowmeans dataframe using these command stamrow <- data.frame(probeid=stam[,1], means=rowmeans(stam[,c(-1,-2,-3)])) stam$means <- rowmeans(stam[,-(1:3)]) but getting error in both case rowmeans(stam[, -(1:3)]) : 'x' must numeric my dataset this: stam = probeid chr position sample1 sample2 sample3 sample4 sample5 chr10fs00300029 10 3000293 0.132 0.135 0.312 0.724 0.889 chr10fs003018825 10 3018825 0.524 0.446 0.203 -0.022 0.581 thanking in advance it works data posted. check str(stam) see if columns numeric . data.frame(probeid=stam[,1], means=rowmeans(stam[,-c(1:3)])) # probeid means #1 chr10fs00300029 0.4384 #2 chr10fs003018825 0.3464 update if numeric columns start 4 15 , can convert columns factor class numeric first stam[,4:15] <- lapply(stam[,4:15], function(x) as.numeric(as.character(x))) ...

javascript - Change class on scroll -

i've been looking around online can't find problem im having (at least not limited js level) i'm trying achieve effect change .class css when scrolls or swipes down page. eg. <a> tages blue, if user scrolls 20px down or 50px down... <a > tags turn green , id scrolling stops. tags turn blue you'll need bind scroll event, using window.onscroll: https://developer.mozilla.org/en-us/docs/web/api/window.onscroll function changes class on element you're interested in. // event "onscroll" on window object, we're binding , passing // anonymous function function executed when event triggered window.onscroll = function (event) { // here (inside anonymous function that's being passed in), add class // "my-class" document body. document.body.classlist.add("my-class"); } note: should give enough information solve problem yourself, don't want solve - in example, function called ...

javascript - Specific handlebars template based on json key value -

i have recipe api has different types of recipe: starter, main, dessert etc. what i'd fetch of data api in 1 call , let handlebars populate particular template (these same added different placeholders) based on 'category' field. however, code below, html injected placeholder divs no data. strangely, 4 instances of template data well. here's code: jquery ajax call api: $( document ).ready(function() { $.ajax({ type: "get", url: "http://example.org/api/recipes", contenttype: "application/json; charset=utf-8", datatype: "json", success: function (msg) { var source; var template; $.each(msg, function (i, o) { if (o['category'] === "starter") { source = $("#startertemplate").html(); template = handlebars.compile(source); $("#starters").html(template(o)); ...

Python Hive Client pyhs2: How to return results from a select statement? -

below code: import pyhs2 pyhs2.connect(host='localhost', port=10000, authmechanism="plain", user='biuser', password='biuser', database='default') conn: conn.cursor() cur: #execute query cur.execute("select * some_table") print "executed" #fetch table results in cur.fetch(): print this above code continues run after printing "executed" no end in sight! supposed take time? other executions getting various database names , getting table names don't take time. how capture results of select statement here? this should work you; replace loop with: while cur.hasmorerows: print cur.fetchone()

javascript - Internet explorer browser effective area -

given complex js application produced gwt need use complete browser area without let scrollbar compare not disabling them because there's couple of exception rule, need calculate client area , since tool selected better directly in gwt supported pure js solution acceptable. as usual browsers (chrome, safari, ff) except ie11 works fine standard solution of rootpanel.setpixelsize(window.getclientwidth()-1, window.getclientheight()-1); but when it's used in ie11 on screen 1440x900 value of getclientheight 1440x845 (seems ok) after rendering using space scrollbars compare wasting space, 10pixels.. rootpanel.setpixelsize(window.getclientwidth()-1, window.getclientheight()-10); seems solve..where gone 10 pixel comparing result other browsers? think contents not relevant since size set on body , first div <html> <head>... <body style="width:1439;height:xxx;"> <iframe out of visibility (position absolute , visible fal...

mysql - SQL Text Search - EXACT before space, LIKE after in search term -

i'm trying create sql query supply values auto completion text field. working can't seem create sql query exact enough purposes want. using mysql. if there space (or multiple spaces) in search term, want query comparison on part of string after last space. for example, have 2 possible values in database: bolt bolts large currently if user types 'bolt' space, both values above returned using query - select name items name 'search_term%' what want if user types 'bolt' space, bolt returned database. effectively meaning last part of search term after space compared using like, results should match until last space. i've tried: select name items name 'search_term[a-z]%' but returns no results using above scenario. is i'm after possible? i've tried explore using full text search have had no that. believe full text search enabled on name field, have limited experience this. query below didn't work. selec...

html - How to place text after the relative positioned element? -

i have absolute positioned div tag (child) placed inside relative positioned div tag (parent). want show text after parent div, placed in incorrect position. html <div class="parent"> <div class="child" style="width: 200px; height: 100px; background-color: red;"></div> </div> <p>the text should shown after parent div</p> css .parent { position: relative; } .child { position: absolute; top: 20px; left: 30px; } what do? updated type mistakes has been corrected. solution, proposed vitorino fernandes, indicate height of parent div good. if don't know exact height of parent div? can omit height of parent div , put text excatly after it? typo mistake should position not postion should height:100px not height 100px , add height relative element .parent { position: relative; width: 250px; height:300px; border:1px solid red; } .child { position: absolute; t...

unity3d - how to destroy instantiate object unity c# -

using unityengine; using system.collections; public class myscript : monobehaviour { public transform platform; public float z = 0.0f; void update () { float c_z=0.0f; instantiate(platform,new vector3(z++,0,0),quaternion.identity); camera.main.transform.translate (0,0,c_z=c_z+0.1f); } } in above code platform instantiated , have destroy tail of platform when camera move ahead. how? try: using unityengine; using system.collections; public class myscript : monobehaviour { public transform platform; public float z = 0.0f; private gameobject _obj; void update () { float c_z=0.0f; _obj = instantiate(platform,new vector3(z++,0,0),quaternion.identity) gameobject; camera.main.transform.translate (0,0,c_z=c_z+0.1f); } } then call destroy(obj) whenever ready destroy platform.

c# - ScrollViewer scroll changed occurs continuously -

i have data grid wherein each row has multiple row details. because of need of virtualization , because data in nested grid huge (row details), had enable internal scroll bar each of row details grid. everything seems working fine except see scroll viewer scroll changed occurring continuously , never stops. have subscribed event dynamically set max height row details grid's enable/disable internal scroll bar. i unable find issue this. problem??

Ruby chaining methods with if-statement -

this question has answer here: one line if statement in ruby 1 answer i have following: def method(integer) = 3+integer += 10 if "one"<"another" end can write in 1 line somehow chaining methods? something a = 3+f += 10 if "one"<"another" ? since and or && both use short-circuit evaluation , use: (a = 3+integer) , ("one"<"another") , (a += 10) it says in ' using “and” , “or” in ruby ': and useful chaining related operations until 1 of them returns nil or false another way of thinking and reversed if statement modifier

html - Use of Delete method in REST application -

i have created book library project using rest+json has html page having many options. 1 of them delete, unable use in html doesn't define it. can tell me how use http method? example: <form action="rest/bklib/remove" method="delete"> enter bookname:<input type="text" name="bookname"> <p> <input type="submit" value="delete"> <p> </p> </form> this post scott hanselman helpful in case. from post: one thing can "tunnel" http methods inside http header. have header says "no, seriously, know got here via post, use 1 instead." still post, you'd have "x-http-method-override:put" header. i haven't use myself, but, hey, if scott says it, i'd give go.

c# - removing switch calling function based on object type using polymorphism -

i have piece of code (shown below) want able call function depending on object type passed in, have switch statement manages feels kinda dirty me. best method of refactoring code make use of polymorphism enable me remove switch statement? if (entity != null) { //switch based on entity type switch (entity.gettype().name) { case "person": //person implementation break; case "organisation": //organisation implementation break; default: break; } } edit: clarification of else finding this, dont have access entity models source, led me mark answer such, if wasnt have marked jon's answer correct! there 3 approaches eliminate switch -based dispatch here: give person , organization common interface or superclass, , provide implementations based on class, implement visitor pattern in superclass / superinterface of person , organization , ...

Average number of days since a date in postgresql/rails -

i want calculate average number of days since 'date_from' (it varies) user.all.average('? - date_from', time.now.to_date) gives error undefined method `except' thu, 27 nov 2014:date see ruby_on_rails/activerecord/calculations the second parameter of average options (an hash) the options can used customize query :conditions, :order, :group, :having , :joins. so should generate average expression this: user.average("'#{time.now.to_date}' - date_from" ) then rails generate sql this: select avg('2014-11-27' - date_from) avg_id ...

jquery - HTML5 set input error manually from javascript -

i'm trying make form user has select box choose value from. but has input field can input text himself, , value requiered, putting 'required' on form submit give error, in case need check if input has value not give error. i'm making $each() function on every selects , it's working, have console.log sayng witch of them required , select or input empty. what need use normal input value missing standard html5, 1 shows when put 'required' tag on inputs, sayng default message. this code have rigth if helps, it's triggered when users click submyt button way $("input[name='guardar']").click(function() { $("select").each(function(key, valeu) { var requerido = $(this).attr('requerido'); var nome = $(this).attr('name'); var input = $("input[name='"+nome+"_default']").val(); if(requerido == "true"){ ...

c# - HTTPS connection timeout after disabling SSL v3.0 and switching to SHA 256 -

our server windows server 2012 iis 8.5 , run several web applications on it. last week, disabled ssl v3.0 , implemented forward secrecy on our server poodle attack. , released new version of our web applications. cpu went 30%-40%(normally 10-20%). other that, things running smoothly. this monday, renewed our certificates sha1 sha256 , had new certificates installed on our server. installation went fine , apps ran fine after that. then things got ugly tuesday some of our clients not access our application via https. requests small js file cannot completed , timed out. errors net::err_timed_out returned in chrome. meanwhile, requests via http okay , completed fast. the cpu went , down 10% 70%-80% , 10%. , server has plenty memory resource. we not figure out why , restarted apps several times , didn't work. so after while, we re-enabled ssl v3.0 , disabled forward secrecy , rebooted server. finally went normal again, still don't know root cause. all did disab...

Sphinx documentation: how to reference a Python property? -

how can reference method, decorated @property ? for simple methods, :py:meth: working fine, not properties: not create link them. you should use :py:attr: instead. example works fine me: class someclass(object): """this docstring of someclass.""" @property def some_property(self): """this docstring of some_property""" return none def some_method(self): """this docstring of some_method. , reference :py:attr:`~some_property` """

Handling different success and fail states for multiple ajax call using deferred objects in jQuery -

$.when returns deferred object multiple ajax calls queried simultaneously. if succeeds .done() executes , if 1 of url fails .fail() executes. how handle partial success states? (i.e) if 5 urls passed $.when , if 3 succeeds need handle success state , 2 fails need handle failure state. $.when($.getjson(headerurl), $.getjson(tasksurl), $.getjson(testingtrackerurl), $.getjson(highlightsurl))) .then(function(headerdata, tasksdata,testingtrackerdata,highlightsdata) { printdata(headerdata, tasksdata,testingtrackerdata,highlightsdata); }) .fail(function(data, textstatus, jqxhr) { console.error('got error in '+jqxhr); }); try var request = function (url) { return $.getjson(url) } , requests = [ headerurl , tasksurl , testingtrackerdataurl , highlightsdataurl ]; // return array of `resolved` , `rejected` jqxhr objects $.when( $.map(requests, function (_request, i) { return request(_request) }) )...

Scala error handling: Try or Either? -

given method in userservice: update , what's best way handle errors/exceptions here? option a: def update(...): try[user] in way, need define custom exceptions , throw them in function body while needed. of these exceptions business errors (e.g. user_id cannot changed, etc). point here no matter exception(s) thrown (business error, network exception, db io exception, etc), threat them same , return failure(err) - let upper layer handle them. option b: def update(...): either[error, user] this exception-free way. in function body catches possible exceptions , turns them error, , business errors return left[error] . using try seems more natural way me want handle errors. either more generic thing - either[error, t] 1 special case , think try invented special case. read should avoid using exceptions error handling... so, solution better, , why? there's no silver bullet. as noted already, try more specialized version of either , left type fixed...

c# - How to display gridview inside Multi view? -

i want display gridview inside multi view. have tried given below code. not displaying on design. me find solution. thank you. source: <asp:multiview id="multiview1" runat="server" > <asp:view id="view1" runat="server"> <asp:table id="table2" runat="server" borderwidth="1" width="973px" height="595px"> <asp:tablerow> <asp:tablecell> <br /> <asp:gridview id="gridview1" runat="server" autogeneratecolumns="false"> <columns> <asp:boundfield datafield="id" headertext="sl no" readonly="true" sortexpression="id" /> <asp:boundfield datafield="name" headertext="name" readonly="true" sortexpression="name" /> </columns> </asp:gridview> <br /> </asp:tablecell> </asp:tablerow...

ios - Disable Page scrolling in UIPageViewController -

this question has answer here: how disable swipe gesture of uipageviewcontroller? 7 answers i working on app in i'm using uipageviewcontroller. want disable page scrolling not gestures. want draw signature in view contain in uipageviewcontroller.for need disable page scrolling. i've done gesture disable not want. for (uigesturerecognizer *recognizer in pageviewcontroller.gesturerecognizers) { recognizer.enabled = yes; } and want of edit button when press page scrolling disable , enable pressing again. body can tell me how possible. if need disable scrolling in uipageviewcontroller - can return nil in data source methods: - (uiviewcontroller *)pageviewcontroller:(uipageviewcontroller *)pageviewcontroller viewcontrollerbeforeviewcontroller:(uiviewcontroller *)viewcontroller - (uiviewcontroller *)pageviewcontroller:(uipageviewcontroller *)page...

java - Error in AsyncTask with ImageView -

i'm making project university. try learn asynctask in half hour. hard! make game of "simon" , need colors flash 1 second, 1 after other. i'm not understanding error , how solve... sorry english, i'm brazilian. that asynctask class... package com.example.genius; import android.os.asynctask; import android.widget.imageview; public class queue extends asynctask<void, void, imageview> { protected imageview doinbackground(void... params) { imageview imagem; int = gameactivity.numcor; imagem = gameactivity.cor; if(i == 0) imagem.setimageresource(r.drawable.greenlight); if(i == 1) imagem.setimageresource(r.drawable.redlight); if(i == 2) imagem.setimageresource(r.drawable.yellowlight); if(i == 3) imagem.setimageresource(r.drawable.bluelight); return imagem; } protected imageview onpostexecute() { imageview imagem; i...

c# - How can I get URLs of open pages from Chrome and Firefox? -

i'm writing system tray app needs check if internal web based app open. i can check ie using following: shdocvw.shellwindows shellwindows = new shdocvw.shellwindows(); string filename; bool sdopen = false; foreach (shdocvw.internetexplorer ie in shellwindows) { filename = path.getfilenamewithoutextension(ie.fullname).tolower(); if (filename.equals("iexplore")) { string[] urlparts = (ie.locationurl.tostring()).split('/'); string website = urlparts[2]; if (website == "myapp:8080") { sdopen = true; }; } } if (sdopen) { console.writeline("app open"); } else { console.writeline("app not open"); }; console.readkey(true); however, of users using system prefer chrome or firefox. how can same above (i.e. urls of open tabs in browser) chrome , firefox? (i'm not going bother oth...

javascript - Panel with start button that moves up on button click -

i want panel start button in middle of page. when button clicked panel should move , disappear. content of page should start loading after button pressed. start button game. currently use 2 html pages. first panel(index.html) , second content. when press button moves panel up, removes , loads second page. feel bit clunky wonder there better way this? i'm not sure if works canvas. said in comments suggest doing text-align:center; . works text , buttons. center other elements such divs try margin: auto; . luck canvas :-) i suggest expanding css knowledge because text-align common use margin:auto; .

javascript - How do you colour rectangles different colours using ctx.fill? -

Image
this might obvious alot of people im trying design game want rectangle player different colour walls. how colour them differently? right set ctx.fillstyle colour rectangles. question want rect1 lightgray , rect2 red have tried.also still need rectangles objects. ctx.fillstyle = "lightgray"; ctx.strokestyle = "skyblue"; ctx.beginpath() // moving rect 1 var rect1 = { x: 125, y: 10, w: 20, h: 20 }; ctx.closepath() ctx.fill() var direction1 = 0 ctx.fillstyle = "red"; ctx.strokestyle = "skyblue"; ctx.beginpath() var rect2 = { x:120, y:110, w:10, h:10 }; ctx.closepath() ctx.fill() your there! just add fill , stroke definitions rect objects: var rect1 = { x: 125, y: 10, w: 20, h: 20, fill:'lightgray', stroke:'skyblue', }; then can draw every rect using single function: drawrect(rect1); function drawrect(rect){ ctx.fillstyle=rect.fill; ctx.strok...