Posts

Showing posts from July, 2015

java - Can I remove unnecessary newlines/whitespace in my Spring Framework webapp response data? -

in response server gives client, noticing quite bit of whitespace , newlines. response body seems sending newline every line of parsed jsp. curious if problem has written bean for? need worry about? example jsp: <!doctype html public "-//w3c//dtd html 4.01//en" "http://www.w3.org/tr/html4/strict.dtd"> <%@page import="java.util.date"%> <%@page import="java.util.gregoriancalendar"%> <%@page import="java.util.properties"%> <%@page import="java.util.map"%> <%@page import="java.util.hashmap"%> <%@page import="java.io.ioexception"%> <head> <title>my page!</title> <% string message = "hello world!"; %> </head> <body> <div><%=message%></div> </body> </html> example html response: <!doctype html public "-//w3c//dtd html 4.01//en" "http://www.w3.org/tr/html4/strict.

cpython - Is it possible to use stackless python 2.7.2 with pythondotnet? -

platform: windows 7 assume 32bit versions of both. my current understanding is not possible since both installation processes involve replacing python.exe itself. i guess source each have merged in order functionality both? stackless python: http://zope.stackless.com/ python .net: http://pythonnet.github.io/ we using python .net on ironpython since want access full range of cpython libraries (e.g. matplotlib among others). as state - no, not possible: "merging source" of both projects non-trivial task, well. however, sicne have problem handled stackless, i'd suggest write part of project need stackless python written in it, , part of project, needs .net use regular ironpython - can comunicate data between 2 parts of program using xmlrpc (or jsonrpc) calls -- not complicated thing in python, , work in both python flavors (example here: http://code.activestate.com/recipes/81549-a-simple-xml-rpc-server/ )

ruby on rails - delayed_job and paperclip - Images aren't processed, but no error? -

i'm having big issues trying delayed_job working amazon s3 , paperclip. there few posts around how it, whatever reason it's not working me. i've removed couple of things how others doing - had save(validations => false) in regenerate_styles, seemed cause infinite loop (due after save catch), , didn't seem necessary (since urls have been saved, images not uploaded). here's relevant code model file, submission.rb : class submission < activerecord::base has_attached_file :photo ... ... before_photo_post_process |submission| if photo_changed? false end end after_save |submission| if submission.photo_changed? delayed::job.enqueue imagejob.new(submission.id) end end def regenerate_styles! puts "processing photo" self.photo.reprocess! end def photo_changed? self.photo_file_size_changed? || self.photo_file_name_changed? || self.photo_content_type_changed? || self.photo_updated_a

c# - NoBufferSpaceAvailable when sending data to socket -

i use on connected socket on server send data client: iasyncresult asyncres = connectionsocket.beginsend(data, 0, length, socketflags.none, out error, new asynccallback(senddatadone), signalwhendatasent); as seems, when there slow internet connection between server , client receive exception description this: nobufferspaceavailable what error mean ? internal os buffer socket connectionsocket full ? means make work. context appears in http proxy server. might indicate, i suppose , rate @ data coming origin server higher rate server can handle proxy client. how deal ? i using tcp. the way fix problem correlate way 1 reads 1 socket speed 1 writes other socket because if no buffering cannot write socket @ higher speed client connected @ end can read. you 1 uses synchronous sockets problem not appear because block long operation still pending not case async calls.

android - How to create relativelayouts with java code? -

i need learn creating relativelayouts java code instead of xml code. for example, nice understand how build xml java code: <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <button android:id="@+id/btnbutton1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="button 1"/> <button android:id="@+id/btnbutton2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="button 2" android:layout_torightof="@+id/btnbutton1"/> <button android:id="@+id/btnbutton3" android:layout_width="wrap_content" android:layout_height="wrap_content" androi

Updating SQL Server 2008 LOGIN SID -

if active directory sid doesn't match sql server 2008 login sid ( sys.server_principal ) there doesn’t appear way alter/update value. alter user allow remap user login, alter login not allow remap login active directory question… is there way, documented or otherwise, update login sid ad sid besides dropping , recreating login? using openrowset ad sid value, can't find way update login sid (mostly because don't think can done) by way, aware ad-hoc queries system tables not allowed (because tried already). answer 1 correct, shady. one upside of remapping login sid different ad sid enable administrator implement role based authentication. database user defined user = "financial_officer" (fo) in multiple database and/or multiple servers, placed in multiple groups, , views join lookup tables created provide appropriate row level security. when fo retires or quits, sid of "financial_officer" login swapped out provide privileges o

iphone - change UILabel frame dynamically in custom TableViewCell -

i have written subclass of uitableviewcell consists of various uilabels have defined style of uilabel in (id)initwithstyle:(uitableviewcellstyle)style reuseidentifier:(nsstring*)reuseidentifier and frame rect of labels in (void)layoutsubviews now after defining static rect uilabels want modify rect of uilabels, , write function in modifying frame labels, calling function doesn't modify frame of uilabels. if has idea how achieve dynamic frame of labels please share it. the way typically achieve implementing custom tableviewcell , implement own drawrect method in subview specify size of label, this: @implementation compositesubviewbasedrestaurantcellcontentview - (id)initwithframe:(cgrect)frame cell:(restaurantcell *)cell { if (self = [super initwithframe:frame]) { _cell = cell; self.opaque = yes; self.backgroundcolor = _cell.backgroundcolor; } return self; } - (void)drawrect:(cgrect)rect { _highli

java - Nested Tables in JBehave -

hi have scenario need test whether search service bringing correct results. story looks this: narrative: in order discover if player registered in loyalty program customer service representative want able search registered players player first , last name scenario: retrieve player information first , last name given players registered in data warehouse , combination of loyalty1 and/or loyalty2 programs: |first name|last name|city |province|loyalty1 |loyalty2| |pete |walter |winnipeg |<null> |false |true | |jon |dewit |winnipeg |mb |true |true | |john |dewit |<null> |<null> |true |true | |peter |dewalt |<null> |<null> |true |false | when <firstnamecriteria> , <lastnamecriteria> criteria specified system displays correct results, using case-insensitive "begins with" search follows: |firstnamecriteria|lastnamecriteria|results | |jo

CakePHP use MS Access database (.mdb, not accdb): Do I need to write a driver? How to build it? -

i'm in unlucky situation client requires use read-only ms access database render webpage contents on website (built me). because ms access file updated once per month , don't want manually converting sql query , import in mysql, make webpages read directly it. what discovered there isn't driver (at least in cakephp installation) ms access database (but in older versions of cake exist) or @ least didn't find of them. i need know can find such drivers or how correctly implement 1 of them read operations (i think should implement dbosource class, don't know should override because there isn't such virtual or abstract or interface guide me through this). i didn't understand if should create adodb driver or oledb driver. think sqlserver driver lot similar should build (except connectionand details); if can use in way shorten job, helpful. edit 1: because no 1 answering, can i'm ok use ms access "normal" queries (without requiring

c# - webservice calculate sum in console app? -

not sure if able understand here code: case 1: double[] myarrai1 = new double[3]; console.foregroundcolor = consolecolor.yellow; console.backgroundcolor = consolecolor.darkgray; console.writeline("*-------------------------------------------------------* "); console.writeline("* enter array of numbers sum total * "); console.writeline("*-------------------------------------------------------* "); console.writeline("insert number"); myarrai1[0] = double.parse(console.readline()); console.writeline("insert number"); myarrai1[1] = double.parse(console.readline()); console.writeline("insert number"); myarrai1[2] = double.parse(console.readline()); drawstarline(); foreach (double d in myarrai1) console.writeline( d ); webservices09004961.servicereference1.calculatesumrequest array = ne

iphone - What Kind of Label to use -

i creating tutorial scene game have use lots of text. best label option use. i have tried cclabelttf, good, use multi line , people recommended not use it. i tried use glyph designer not use long text (goes out of screen) , multi line. my screen looks this how play game something , again that something this something something , again that use uitextview. turn off scrolling , editable.

javascript - Google Chrome - Failed GET ajax request -

i developing website loads html template page loads content xml. instance these called in document.ready function $.ajax({ type : "get", url : "template.html", datatype : "html", success : function(html) { var ndoc = document.createelement('html'); ndoc.innerhtml = html; page = $('body', ndoc); $('body').html(page.html()); $.ajax({ type : "get", url : "xml/content.xml", datatype : "xml", success : function(xml) { page = $(xml).find('chisiamo').find('dialogue')[0]; setuppage(page); } }); } }); thi

testing - How can I decrease my Rails test overhead? -

i'm using test::unit on large app large number of gem dependencies (>75). i'm trying develop using bdd, takes minutes app load it's dependencies before can run tests. there way preload dependencies , auto-run test on changes, or similar solution? i using rspec , there's great tool it, called spork . loads app once , reloads modified parts. if combine guard , "continuous testing". is, hit 'save' in editor , tests start executing, giving instant feedback. still amazes me after months :) edit as @them points out, there's plugin spork support testunit. should it.

sql - Inserting multiple rows into a Company - Parameter - Value table -

alright, let's have database table named "company_parameters" looks (the first 2 columns keys): comp_id | param_name | param_value | parameter 1| 10 | sample_ind | y b | parameter 1| 20 b | sample_ind | n i insert new parameter, let's parameter 2 table, every company id in table. not know company id expect, since client can have company id want, 1 client might have company ids 1,2,3,4 , might have a,b,c,d, etc. use series of update scripts store on repository time update database. i've asked around , 1 of rare (only) tables unique every client, try anyway. i've been working databases less year , don't know start problem this. guess use select statement find unique comp_ids , insert row every 1 of them. your appreciated. -asaf insert company_parameters (comp_id, param_name) select distinct cp.comp_id, 'parameter 2' company_parameters cp; if wanted careful, extend query make sure ne

ios - How to use a UISplitTableViewController correctly to display two UITableViewControllers? -

i (still) in process of converting iphone app universal app. i want push uisplitviewcontroller onto uiview. discussed here trying create flow: uiview -> uisplitviewcontroller (containing 2 uitableviews use in iphone version) -> uiview i want button attached ibaction make tableview appear on iphone (which set , working) , splitviewcontroller appear on ipad: -(ibaction)makestory:(id)sender{ nslog(@"makestory:"); if (ui_user_interface_idiom() == uiuserinterfaceidiompad) { //code here push split view. } else { //i iphone! makestorytableviewcontroller = [[makestorytableviewcontroller alloc] initwithnibname:@"makestorytableviewcontroller" bundle:nil]; [self.navigationcontroller pushviewcontroller:makestorytableviewcontroller animated:yes]; [self.navigationcontroller setnavigationbarhidden:no animated:yes]; } } i've read tutorials here , here - can't head around how add existing app correctly. appreciat

Better way to handle value conversion for mixed variable types in an array, PHP -

i'm working [generally not used] php framework in class i'm working has array of fields correlate columns in sql. well, setting values class objects there's class method setfieldvalue , conventionally done: protected $fields = array('id', 'name', 'body'); function setfieldvalue($field, $value) { switch($field) { case 'id': return parent::setfieldvalue($field, intval($value)); case 'name': return parent::setfieldvalue($field, strval($value)); case 'body': return parent::setfieldvalue($field, strval($value)); } } i'm looking bit more dynamic (and cleaner, i'll have many fields), maybe like: protected $fields = array('id' => 'intval', 'name' => 'strval', 'body' => 'strval'); function setfieldvalue($field, $value) { if(array_key_exists($field, $this->fields)) { return par

jqueryui autocomplete doesn't show dropdown for same input -

i found when enter same term jquery autocomplete second time dropdown doesn't appear. know how fix problem? if write again show dropdown if select form auto suggest not because see no diference between previous , current.

php - Check domain validity with wildcard resolver -

i have site record links user-provided web pages. want record them if valid. i using checkdnsrr($domain, 'a') check domain validity, , noticed returning true . i'm on shared hosting (so can't change anything). reported bug server admin, , replied: we use opendns our resolvers on servers. resolvers return ip/dns record invalid domains have wildcard set point invalid domains default ip. because of domains enter show having record. okay then. i want avoid using curl on invalid domain waste, there bigger problem. believe resolver returns kind of error page "this domain not exist," , emits 200 or other supposedly valid return status. use status confirm page indeed valid, invalid domain recorded valid site. (humorously, valid domain invalid url leads page emitting 404 or other error status not recorded). anyway, there other way check domain validity? don't mind using third party site. opendns (and others this) return same ip

cherokee - Strange django media deployment issue -

i managed deploy cherokee reverse proxy django app running cherrypy information source. all of static files , media files seem served correctly except particular image. on http://mydomain.com/media/files/none.png , the image "http://mydomain.com/media/files/none.png" cannot displayed because contains errors. but if append ? behind file's url, shows correctly 1x1 pixel image. http://mydomain.com/media/files/none.png? will give none.png (png image, 1 x 1 pixels) which expected , correct. why so? browser cache problem. issue solved while back. closing this.

java - Modify persistence.xml on runtime -

i'm developping program uses jpa, , deployed in single jar. wish modify (or ask user, in menú item) configuration of connection data database server. it's possible modify data (user, password, ip) of server "on fly"? (i apologize bad english) the jpa spec doesn't allow dynamic modification of persistence-units. implementations may provide implementation-specific way of defining persistence-unit dynamically. datanucleus jpa per foot of this page

android - Deserialize error with Jackson (png encoding) -

i have following string parse (string object) : { "langues" : [ {"iso":"en", "id":1, "flag":[0,144,255,62,1,152,84,62,1,104,50,63,1,32,90,61,1,172,110,66,1,216,...]} , {"iso":"fr", "id":2, "flag":[0,208,0,63,1,208,106,62,1,120,49,63,1,32,90,61,1,60,110,...]} , { etc... } ], "when" : 133111... // timestamp } the flag array of byte png image and following objects : public class langues { private long when; private arraylist<langue> langues; public long getwhen(){ return when; } public void setwhen(long when) { this.when=when; } ... } public class langue { private int id; private string iso; private byte[] flag; // getters / setters } this throw me error : objectmapper mapper = new objectmapper(); langues node = mapper.readvalue(mystring, langues.class); jsonparseexception

javascript - Is there a way to only show parent nodes in a extjs tree -

i want show parent nodes of tree in extjs. in datastore there leaf nodes well. the output should - folder 1 folder 1.1 folder 2 folder 3 create filter object gets parent nodes , add store config: e.g. filter parent nodes only: var nodefilter = new ext.util.filter({ property: 'leaf', value : false }); putting on treestore config: var yourtreestore = ext.create('ext.data.treestore', { // other configs ... filters: [nodefilter] }); edit: incutonez right, submitted according api properties did not notice missing functions. easy enough override though apply filtering treestore though. working me in 4.1b2: ext.override(ext.data.treestore, { hasfilter: false, filter: function(filters, value) { if (ext.isstring(filters)) { filters = { property: filters, value: value }; } var me = this, decoded = me.decodefilters(filters),

sphinx performance after idle -

i'm writing web application i'm using sphinx search around million documents. the performance excellent, typical query taking 0.05 seconds, if no queries made few hours, takes longer - 1000x longer couple of queries, returns normal. query log looks this: [wed mar 7 17:23:55.937 2012] 0.221 sec [wed mar 7 17:32:00.726 2012] 0.012 sec [wed mar 7 17:32:00.984 2012] 0.052 sec [wed mar 7 17:32:01.416 2012] 0.222 sec [thu mar 8 09:15:10.418 2012] 10.147 sec [thu mar 8 09:16:00.560 2012] 48.262 sec [thu mar 8 09:16:55.429 2012] 54.153 sec [thu mar 8 09:17:54.454 2012] 0.012 sec [thu mar 8 09:17:54.713 2012] 0.052 sec [thu mar 8 09:17:55.141 2012] 0.218 sec i'm guessing maybe busy server swapping sphinx's memory when unused or something. how can resolve this? i considered scripting fake queries every minute seems quite ugly hack. how fast disks on server? i imagine due having go disk indexes. once accessed few times, os have cached fi

sql server - return a default record from a sql query -

i have sql query run against sql server database eg. select * mytable id = 2 this may return number of records or may return none. if returns none, alter sql query return default record, possible , if so, how? if records returned, default record should not returned. cannot update data need alter sql query this. another way (you empty initial rowset returned); select * mytable id = 2 if (@@rowcount = 0) select ...

ruby on rails - How to simplify my model code? -

i new rails , wonder if there's way simplify code model: class item < activerecord::base def subtotal if price , quantity price * quantity end end def vat_rate if price , quantity 0.19 end end def total_vat if price , quantity subtotal * vat_rate end end end as far know *before_filter* not work within models? i'd do: class item < activerecord::base vat_rate = 0.19 def subtotal (price || 0) * (quantity || 0) end def total_vat subtotal * vat_rate end end

javascript - custom widget iframe or js+json or else? -

we develop widget contain news users profile. , couple of images flickr. i wondering keys points while developing widget, placed in users blogs , profile pages? i saw couple of iframe solutions , couple of json , js solutions ? 1 doing more effective , reliable. or know other options ? edit: found previous discussion , post can call inline js widgets evil ? , no 1 use ? widget - iframe versus javascript http://prettyprint.me/2009/05/30/widgets-iframe-vs-inline/

How to pause flash application in browser? -

how pause flash application in browser if there isn't buttons allow ? well, there website, there swf file, want pause it. do have access these files , source? on same domain? anyway, previous 2 answers suggested wrapping swf flash application , setting framerate 0. that's not accurate, because minimum framerate can set 0.01. flash code built around framerate, makes sense. http://help.adobe.com/en_us/flashplatform/reference/actionscript/3/flash/display/stage.html#framerate if have access original files want pause, proper way accomplish through externalinterface http://help.adobe.com/en_us/flashplatform/reference/actionscript/3/flash/external/externalinterface.html http://www.viget.com/inspire/bi-directional-actionscript-javascript-communication/

asp.net mvc 3 - JQuery + MVC 3: Client-Side Dynamic Data Binding to Html.DropDownList -

i have "create user" form user can have number of roles. hence decided add dropdownlist populated roles , add "add" link/button next: <label for="role">roles</label> @html.dropdownlist("roles", new selectlist((ienumerable<rolesummaryview>)viewdata["roles"], "id", "name")) <div> <a href="#" class="ym-gbox tbalign" style="padding-top:3px;">add</a> <a href="#" class="ym-gbox tbalign" style="padding-top:3px;">delete</a> </div> in scenario supposed when "add" clicked dropdownlist populated same roles data , "add" , "delete" links/buttons next list should added in new line. if user clicks "add" same process repeated. if user clicks "delete" dropdownlist next link/button should gone. i've tried write javascript code , controller no success

c# - Overloading generic type parameters disallowed? -

it's part curiosity , part because trying use this. if have following definitions, not allowed compiler because says member defined. what's reasoning behind not allowing exclusive overloads of generic type parameters? void get<t>() t: struct {} void get<t>() t: class {} it seems me there's no inherent problem this. 1 might argue not clear compiler should choose in cases definitions overlap (but common resolution seems specific match first). can me understand or point resource reasoning behind disallowing this? eric lippert answered one, in blog post on generic constraints , method signatures: http://blogs.msdn.com/b/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx constraints on generic types not part of method signatures in clr, therefore can't have 2 methods differ in generic type constraints. without clr support quite fiddly c# support these in sensible fashion compatible other .net languages.

Implement multiple sign in with Rails and Devise -

how mimic google's multiple sign-in in rails app? essentially, need allow user sign in 2 or more different unlinked accounts , able switch between them without signing out , in each time. user have authenticate username , password once each account wishes use, subsequently not have login accounts again until session expiration. i saw post guesses @ google's implementation, hints best way approach in rails 3.1. i'm using devise cas plugin . assume need override current_user method pick correct account, i'm not sure else do. or maybe can use scopes this? issue though need arbitrary number of accounts logged in simultaneously. devise not default , have implement yourself. believe best approach solve problem maintain signed cookie ( cookies.signed ) ids of users signed in. basically, every time user signs in, add id cookie if isn't there yet (there warden callback every time user signs in). now have ids, can show signed in names in corner google. w

asp.net mvc - MVC3 Razor URL.Action Parameter Value with forward slash. giving error -

its small question on mvc3 razor, have string id "a/b" when trying call details or delete method of controller. getting error system assuming "a/b" 2 parameters have pass in 1 string value parameters. --edit < href="@url.action("details", "search", new {id = "a/b"})">details </a> my controller/method search/details (string id) and want send id = 'a/b' . .net assuming 2 parameters in url. please suggest. it appears forward slashes not automatically encoded, , reason because if encoded (%2f), time reach routing engine have been decoded forward slash. (search robj in this post phil haack (former manager on mvc team)). however, .net mvc routing w/ url encoding problems poses same problem, , appears way solve insert encoded slash query string. this: < href="@url.action("details", "search")?id=@url.encode("a/b")">details </a> and t

asp.net - How to avoid System.ArgumentException: Invalid JSON primitive: new. when parsing json in c# -

i'm parsing json using microsoft json parser: var json = new javascriptserializer() { maxjsonlength = int.maxvalue }; return json.deserializeobject(jsonstr); when following json server: [{"date_of_birth": new date("thu, 17 nov 1983 00:01:00 gmt")},{"date_of_birth": new date("wed, 23 nov 1904 00:01:01 gmt")}] it throws following exception: system.argumentexception: invalid json primitive: new. @ system.web.script.serialization.javascriptobjectdeserializer.deserializeprimitiveobject() @ system.web.script.serialization.javascriptobjectdeserializer.deserializeinternal(int32 depth) @ system.web.script.serialization.javascriptobjectdeserializer.deserializedictionary(int32 depth) @ system.web.script.serialization.javascriptobjectdeserializer.deserializeinternal(int32 depth) @ system.web.script.serialization.javascriptobjectdeserializer.deserializelist(int32 depth) @ system.web.script.serialization.jav

php - How to retrieve more than 200 tweets -

i know how retrieve more 200 tweets twitter page. know limited 200 read can retrieve more,im using php , using following line of code 200 tweets $xmldata = 'http://twitter.com/statuses/user_timeline/bbcnews.xml?count=200'; could show me example code in how this? thanks with twitter api can 200 posts per page. have add &page=x page of tweets (there hard limit of 3200 posts) view api documentation here https://dev.twitter.com/docs/api/1/get/statuses/user_timeline an example of api call json https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=twitterapi&count=200&page=2 and example xml call https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=twitterapi&count=200&page=2 so suggest if want 3200 posts set script in function change page number each time

jquery - Ajax call not working as expected -

i'm trying clear session variables after successful call realex ( company processes credit card transaction ). session variables contain shopping cart contents, once transaction successful, want clear out. code follows: jquery.ajax({ async: false, url: templateuri+'/realex_go_pay.php', type: 'post', data: { amount: ordertotal, orderid: orderid, orderkey: orderkey, cardtype: type, cardnumber: number, cardname: name, expdate: expiry, cvv: cvv, issueno: issueno }, success: function(data){

php - How can I recursively search through a database? -

i have mysql table 3 columns *id, item_id, dependency* i want know best way recursively check through dependencies example checking item_id 3's dependencies , requires item_id 2 need check dependencies item_id 2 what best way achieve php? id | item_id | dependency | ---+---------+------------+ 1 | 3 | 2 | ---+---------+------------+ 2 | 2 | 4 | ---+---------+------------+ 3 | 2 | 5 | ---+---------+------------+ pseudo code: func myquery(item_id) { query (item_id) if (!item_id.dependency()) else (myquery(item_id.dependency()) } this continue down column until reach item not have dependency. summary of process: pass first item function. check if has dependency, if does, call function again dependency. otherwise nothing , function return. of course you'll want save items returned query i'll leave you. want statement @ end of function when said , done have data ordered no dependencies dependen

javascript - alert when a var equal div value -

i trying to show alert message when javascript var equal div value , here trying here : function checkmydiv() { var elementcssclass = document.getelementbyid("target"); if (elementcssclass == "hello") { alert("the div has value"); } ​}​ here html code <div id="target" >hello</div> <input type="button" value="bader" onclick = "checkmydiv();" />​ i not know did go wrong , nothing popup when click button bader appreciated :) you need text content element. right now, you're comparing object reference against hello which won't work. if (elementcssclass.textcontent == "hello") { } is you're looking for. one word auf caution: .textcontent supported modern browsers (=latest versions). however, old'ish version of ie might not recognize property. might want either like var mytext = elementcssclass.textcontent || elementcsscla

ios - how do you assign touches to two CCColorLayer? -

i have created 2 color layers , displayed them on screen: if( (self=[super init] )) { self.istouchenabled = yes; cgsize s = [[ccdirector shareddirector] winsize]; cclayercolor* layer1 = [cclayercolor layerwithcolor: ccc4(255, 255, 0, 80) width: 100 height: 300]; layer1.position = ccp(s.width/3, s.height/2); layer1.isrelativeanchorpoint = yes; [self addchild: layer1 z:1]; cclayercolor* layer2 = [cclayercolor layerwithcolor: ccc4(0, 0, 255, 255) width: 100 height: 300]; layer2.position = ccp((s.width/3)*2, s.height/2); layer2.isrelativeanchorpoint = yes; [self addchild: layer2 z:1]; } return self; } i want to enable touches each layer, layer 1 , layer 2, example if user touches layer

button - Android kernel LED control -

im new forum nice ;) have followed rules :) i helping dev kernel use. since mod want me figured duty working myself. the problem: have edited *.kl files disable 5 front facing hardware buttons waking device , allow volume / down buttons wake device front facing buttons pressed when in pocket. however, though front facing buttons no longer turn on device , when pressed light adding 6ma drain . what i've tried: wrote apk change permissions of /sys/class/leds/button-backlight/brightness file keep them off. despite program working , permissions allow file edited, causing them light up. what need on: downloaded dev's kernel using git , want edit kernel myself keep button lights off during sleep . kernel code not comfort zone .. need . thanks helping , reading ! 1) messing code bad idea (especially if lack skill , don't know c , unix). 2) looking script run on startup ( initrc ) , there need set , change permissions using chmod command. thus need set

Passing code to python from PHP -

i have custom codechecker in python, there bigger project running in php, stores users code in mysql database. i new python, i'm not sure how can pass code php python. do have store file filesystem pass python? (in case many files might created, , cleanup after execution has taken care) to expand on brad's answer, there's several options, each pros & cons... pipes (ie: stdin/stdout): proc_open() shared memory: shmop_open() af_unix family sockets: socket_bind() you'll want use first option read on others before making commitment.

c++ - SOIL not linking correctly -

this question has answer here: what undefined reference/unresolved external symbol error , how fix it? 27 answers i linking soil in library when compile these linker errors: 1>link : warning lnk4098: defaultlib 'msvcrt' conflicts use of other libs; use /nodefaultlib:library 1>libsoil.lib(stb_image_aug.o) : error lnk2019: unresolved external symbol __alloca referenced in function _stbi_zlib_decode_noheader_buffer 1>libsoil.lib(image_helper.o) : error lnk2019: unresolved external symbol _sqrtf referenced in function _rgbe_to_rgbdiva2 i did link libsoil.lib in addition dependencies. the unresolved symbol errors, error lnk2019, symbols in libgcc.lib or standard library implementation (see here microsoft options) not being linked to. alloca , sqrtf both standard library functions. if aren't linking standard library, link 1 adding link

php url data fetch stop on perticular time -

i using php 5.2 , fetching data url using file_get_contents function. loop 5000 , have divided 500 slots , set script this. 500 taking 3 hours complete because url taking time , in 1 sec fine. what want if url taking more 30 sec skip , go next. want stop fetch after 30 sec. <?php // create stream context $context = stream_context_create(array( 'http' => array( 'timeout' => 1 // timeout in seconds ) )); // fetch url's contents echo date("y-m-d h:i:s")."\n"; $contents = file_get_contents('http://example.com', 0, $context); echo date("y-m-d h:i:s")."\n"; // check empties if (!empty($contents)) { // woohoo // echo $contents; echo "file fetched"; } else { echo $contents; echo "more 30 sec"; } ?> i have done not working me because file_get_contents function not stoping continue , thing getting no result after 30 sec time taking sameas u can see in o

How to implement the flood-fill algorithm in android? -

how implement flood-fill algorithm in android.but code written in c language.could implement algorithm in android.is there open source code available or website tutorial link algorithm flood fill simple recursive one. //initialize , j place start floodfill(int arr[][], target_color, replace_color) { if(arr[i][j] == replace_color) return; replace(target_color, replace_color); floodfill(int[i+1][j], target_color, replace_color); floodfill(int[i][j+1], target_color, replace_color); floodfill(int[i-1][j], target_color, replace_color); floodfill(int[i][j-1], target_color, replace_color); } flood fill using queue. use asynctask flood fill. parameters bitamp filled point user touches (x,y cordinates) color of pixel use touches color replaced. public class floodfill { public void floodfill(bitmap image, point node, int targetcolor, int replacementcolor) { int width = image.getwidth(); int height = image.getheight(); int target =

Crystal Reports - Suppressing a header in main report when sub-report is present -

good day everyone. i'm running crystal reports 9. i have report listing bunch of records, , sub report containing graph. suppress page header of main report, page sub-report (graph) shown. i can't seem able think formula test presence of graph / sub-report suppress page header in main report with. any advice appreciated. hopefully subreport/graph in it's own section? insert new formula in first section of report (report header a): global booleanvar no_header := false; insert new section right above subreport section 0 height. insert new formula in section: global booleanvar no_header := true; insert new formula in subreport section: global booleanvar no_header := false; in page header conditional suppression formula enter formula: global booleanvar no_header; you may have prefix of formulas whileprintingrecords; and may have tweak suggestion little idea?

sql - PostgreSQL equivalent for TOP n WITH TIES: LIMIT "with ties"? -

i'm looking similar in sql server: select top n ties tablename i know limit in postgresql, equivalent of above exist? i'm curious save query each time me. if have table numbers attribute nums : {10, 9, 8, 8, 2} . want like: select nums numbers order nums desc limit *with ties* 3 it should return {10, 9, 8, 8} because takes top 3 plus 8 since ties other one. there no with ties clause in postgresql there in sql server . in postgresql substitute top n ties .. order <something> : with cte ( select *, rank() on (order <something>) rnk tbl ) select * cte rnk <= n; to clear, rank() right, dense_rank() wrong (return many rows). consider quote sql server docs (from link above): for example, if expression set 5 2 additional rows match values of order columns in row 5, result set contain 7 rows. the job of with ties include peers of last row in top n defined order by clause. rank() gives exact same result.

Mixing php and javascript -- under what conditions? -

under conditions can put php javascript code? ok? bad idea? surprised have not seen more. for example, came across this.. $('#thumbnail').imgareaselect({aspectratio: '<?php echo $thumb_height/$thumb_width;?>', onselectchange:preview}); ..which in onpage script element. i'm not experienced, surprised had never seen mixed js/php before. can put php in .js files well? if set file extension .php, file parsed? you can put php code *.js files need tell webserver execute php interpreter on *.js files. should in httpd.conf <ifmodule php5_module> addtype application/x-httpd-php .php .php5 .js ... </ifmodule> a better solution rename *.js files *.js.php or *.php . browsers won't mind , php interpreter executed on those.

vba - Read Chinese characters from Excel worksheet? (Always returns "????") -

how read chinese characters excel cells , write them file? when take values worksheets(activecell.worksheet.name).cells(3, columnnumbers(0)).value it returns "????????" dim filestream, filepath string 'full properties file path propfilepath = "c:\file.properties" 'create stream object set filestream = createobject("adodb.stream") 'specify stream type – want save text/string data. filestream.type = 2 'specify charset source text data. filestream.charset = "utf-8" 'open stream , write binary data object filestream.open filestream.writetext "write here" 'save binary data disk filestream.savetofile filepath, 2 filestream.close

ruby on rails - MongoDB : Search on multiple keys on embeds documents -

i've translation document embeds many translation locales documents : class translation include mongoid::document field :key, :type => string embeds_many :locales, :class_name => 'translationlocale' end class translationlocale include mongoid::document embedded_in :translation field :code, :type => string field :state, :type => boolean, :default => false field :text, :type => string end i want able find translation documents including particular locale in given state. translation.where('locales.code' => 'en', 'locales.state' => false).all the problem query translation documents embedding locale code=en , locale state=false not on same sub document. any appreciated, thank you! try this: translation.where(:locales.matches => {:code=> 'en', :state=> false}).all example here

android - how to use listview to fetch the record from sqlite -

i create database , 1 table table_name . need fetch record from table list view. after list view should enable for delete record. novice @ android , don't know how use list view. please provide me code or reference. in advance.. try class create , copy database , , delete records.. http://code.google.com/p/nithin-warriers-code-base/source/browse/trunk/sampledatabase/src/com/smartandroidians/database/dbhelper.java?spec=svn10&r=10 after implement class u need add , delete finction class.. if query ask freely...

Javascript + XML: Parsing text-only and mixed nodes (into JSON) -

i'm working on converting xml document special json format using javascript. using standard dom processing methods in javascript, need constructing efficient, elegant algorithm determining whether node contains non-text nodes or attributes, , organizing json object differently depending on node contents. example: <demo> <title>text test</title> <textonly id="demotext"> text-only node! doesn't need 'text' property. </textonly> <mixed id="amixednode"> text <!-- comment node --> <another /> <!-- note element has not 4, 7 nodes -- counting text between non-text nodes! --> more text! </mixed> <textonly id="specialtext" special="something"> text-only node, it's not because attribute requires create 'text' property </textonly> <textonly id="validtext&

iphone - Mac-address changed -

i'm facing problem here, using library uidevice uniqueidentifier ios 5 generate unique identifier ios device, simple md5 hash of mac address. , ok, i've published app in appstore, , after time i've decided write small update. app uses dedicated server api, identifying user important. when started app after update (i integrating tapjoy) - had mac address, , other unique identifier. thought mac address cannot change, wrong? same keeps happening in simulator , on device. yeah, figured out. tapjoy. library implements [[uidevice currentdevice] macadress] method. also, uidevice uniqueidentifer ios 5 implements same method. difference between them - colons in mac address. tapjoy implementation doesn't have them, when uniqueidentifier does. , when use both of libraries @ same time, can cause issues. warned! did, renaming method [[uidevice currentdevice] macadress] in uniqueidentifier lib, [[uidevice currentdevice] macadress_colons] , did trick.

javascript - Concatenating my object with a string -

this question objects in javascript. i notice can add string , error object fine, , error object text concatenated no problems. try { throw new error('sample text'); } catch (error) { document.writeln('there error. ' + error); // go plus sign! } this outputs there error. error: sample text pretty cool. error object knew string wanted concatenate. own objects not act nice this. var myobject = (function () { var text = 'text want concat.', get_text = function () { return text; }, = {}; that.get_text = get_text; return that; }()); document.writeln('what object say: ' + myobject); // uncool my own object outputs what object say: [object object] , not act nice error object does. i not want [object object] output. how can change string myobject spits out when being added string? you should give objects tostring method returns appropriate string. need rename get_text tostring . write this: var

Why doesn't get_post_custom() work within the loop in WordPress? -

i've created custom post type in wordpress, , in single post template, i'm pulling in custom data using get_post_custom() function. but inside loop on list of posts, function doesn't work , comes empty array. here's have: <?php $loop = new wp_query( array( 'post_type' => 'web-design', 'posts_per_page' => 10 ) ); ?> <?php $i = 0; ?> <?php while ( $loop->have_posts() && $i < 3 ) { $loop->the_post(); ?> <article class="project-link <?php echo 'num' . $i ?>"> <div class="pad"> <?php $project_info = get_post_custom(); ?> <?php foreach ($project_info $i => $values) { print "$i {\n"; foreach ($values $key => $value) { print "$key => $value\n"; } print "}\n"; } ?> <?php echo $

OpenCL creates new threads upon first function call, why? -

when call opencl function wouldn't imagine create new threads, in case platform ids, program creates 8 new threads. cl_platform_id platforms[10] = {0}; cl_uint numberofplatforms = 0; clgetplatformids(10, platforms, &numberofplatforms);//this creates 8 threads due me not creating context, asking platform ids see available, why function create these threads? i'm using windows 7 64 bit, i7 920 ht (i suspicious creating 8 threads because have 8 cores), both intel , nvidia sdk( have gts 250 , gtx 560), while i'm linking nvidia opencl libraries , using headers. this isn't big concern, if decide not use opencl after analyzing devices, have 8 useless threads "lying around". know why happens? a lot of opencl functions non-blocking, meaning issue commands device in form of queue , i'm pretty sure threads used control device while host program continues run rest of code. to illustrate: when call clenqueuendrangekernel, kernel n

MongoDB Nested Design Philosophy -

i'm creating system company has multiple users, customers etc. can't decide whether make "objects", such users, separate collection or embedded documents of company document. company (object) -> users (object) -> profile (object) -> ...attrs.. history (object) -> ...attrs... customers -> ...attrs... i'm stuck in relational database mind set right now, , not sure "proper" way nosql. thoughts? what happens when double embedded document (like company>users->history) gets ridiculously large? what other cons embedded document approach (if any)? again, i'm biased towards relational mind-set. thanks in advance. http://www.mongodb.org/display/docs/schema+design has advice on schema design, there various presentations members of 10gen one: http://dl.dropbox.com/u/205597/sts/sts-04-2012-mongo-and-nosql-schema.pdf given number of users in company , number o

gridview - Programmatically create a 2*2 and 2*1 grid view in iphone -

currently referring this post , able create 2*2 grid view int rows = 2; int cols = 2; float gridwidth = 1024.0; float gridheight = 1024.0; float buttonwidth = 100.0; float buttonheight = 100.0; // float gaphorizontal = (gridwidth - (buttonwidth * rows)) / (rows + 1); // float gapvertical = (gridheight - (buttonheight * cols)) / (cols + 1); float gaphorizontal = 40; float gapvertical = 40; float offsetx; float offsety; int count = 0; { offsetx = gaphorizontal + ((count % rows) * (buttonwidth + gaphorizontal)); offsety = gapvertical + ((count / rows) * (buttonheight + gapvertical)); uiview *view = [[uiview alloc] initwithframe:cgrectmake(offsetx, offsety, buttonwidth, buttonheight)]; view.backgroundcolor = [uicolor yellowcolor]; [self.view addsubview:view]; offsetx+= buttonwidth + gaphorizontal; count++; } while(count < rows * cols); but when try create 2*1 grid view by changing int rows = 2; int cols = 1; i'm not able so. c

java - Can't get resource files in my template files (using Restlet and Freemarker) -

i'm trying develop webapp restlet , have little problem access /public/css/* , /public/js/*. i have messages in console : info: 2012-03-10 23:52:59 127.0.0.1 - - 8182 /public/css/bootstrap-responsive.min.css - 404 439 0 0 http://localhost:8182 mozilla/5.0 (x11; linux x86_64) applewebkit/535.11 (khtml, gecko) ubuntu/11.10 chromium/17.0.963.65 chrome/17.0.963.65 safari/535.11 http://localhost:8182/hello i have helloworld using html template : public class restletservertest extends serverresource { public static void main(string[] args) throws exception { component component = new component(); component.getservers().add(protocol.http, 8182); component.getdefaulthost().attach("/hello", new helloworldapplication()); component.start(); } } public class helloworldapplication extends application { private configuration configuration; @override public synchronized restlet createinbound

mysql - SQLSTATE[28000] [1045] (Magento) Access denied for user .. (but new PDO, works in test program) -

i copied magento store provider , installed database. nothing special. with testing error mysql database: sqlstate[28000] [1045] access denied user ‘xx’@’localhost’ (using password: yes) i found program /httpdocs/lib/zend/db/adapter/pdo/abstract.php , has statement: try { $this->_connection = new pdo( $dsn, $this->_config[’username’], $this->_config[’password’], $this->_config[’driver_options’] ); if use same statement same settings in short test program on same server, connection works. how possible? there in pdo different working while called in magento? i forgot write, domain has shared ip address , domain name (but no dns yet), coupled ip address domain name in windows hosts file. domain www.xxxx.com exists on internet already, use xxxx.com in windows host file coupled shared ip address. in way tested new websites without transferred domain yet. when copy own server (localhost.com magento), have find it, works well. has si

iphone - Bug Loading Photo in Dispatch Queue -

i have block of code here use load image on dispatch queue: dispatch_async(dispatch_get_global_queue(0, 0), ^ { cgimageref x = self.asset.defaultrepresentation.fullscreenimage; dispatch_async(dispatch_get_main_queue(), ^ { [[self imageview] setimage: [uiimage imagewithcgimage: x]]; }); }); the code seems work couple of times until bad access @ line [[self imageview] setimage: [uiimage imagewithcgimage: x]]; . know causing this? use cgimageref x = cgimagecreatecopy(self.asset.defaultrepresentation.fullscreenimage); and cgimagerelease(x) after set that

objective c - program crashes when trying to present modal view controller -

i want load xib, , use simple code: addelementviewcontroller *viewtoload = [[addelementviewcontroller alloc] initwithnibname:@"addelementviewcontroller" bundle:nil]; viewtoload.modaltransitionstyle = uimodaltransitionstylecoververtical; [self presentmodalviewcontroller:viewtoload animated:yes]; for reason throws me out output: 2012-03-11 11:56:57.990 weesh[14650:11603] -[mainviewcontroller addpressed:]: unrecognized selector sent instance 0x7b55b40 2012-03-11 11:56:57.991 weesh[14650:11603] *** terminating app due uncaught exception 'nsinvalidargumentexception', reason: '-[mainviewcontroller addpressed:]: unrecognized selector sent instance 0x7b55b40' *** first throw call stack: (0x13da052 0x198ed0a 0x13dbced 0x1340f00 0x1340ce2 0x13dbec9 0x32a5c2 0x32a55a 0x3cfb76 0x3d003f 0x3cf2fe 0x34fa30 0x34fc56 0x336384 0x329aa9 0x22c7fa9 0x13ae1c5 0x1313022 0x131190a 0x1310db4 0x1310ccb 0x22c6879 0x22c693e 0x327a9b 0x1cad 0x1c15) terminate

How do I return data that is ordered today in C# or SQL Server? -

i have table in sql server database called orderdetail stores order data. have column in table called orderdate stores date , time information orders. i want retrieve orders orderdetail table created today. my scenario want make button click admin @ night see how many orders done today? any regard appreciated. try this: select a.orderid, ... orderdetail 'a' inner join orderdate 'b' on a.orderid = b.orderid b.dateoforder between '5/20/2011 00:00:00' , '5/20/2011 23:59:59' i assumed have id in orderdetail , id same in orderdate table.

c# - Generic EventArgs for built-in types -

posters @ are eventarg classes needed have generics , does .net have built-in eventargs<t>? advising against generic eventargs, @ least that's feeling get. is justified use when need 1 of build-in types? in specific case i'm reading stream on tcp, , when data received, subscribers notified. public event eventhandler<eventargs<string>> data_received = delegate { }; ... while (!reader.endofstream) { if ((data = reader.readline()) != "") { this.data_received(this, new eventargs<string>(data)); } } or perhaps event isn't best way pass data subscribers? short answer: depends. you can consider eventargs<t> class tuple<t> passing , returing data to/from method. in simple cases , internal usage tuple<t> appropriate more complex cases or public surface more appropriate use separate type. with eventargs<t> have more or less same dilema. internal usage ok use type, public api l

Express C# generic type arguments more succinctly? -

inspired comparing 2 collections equality irrespective of order of items in them i created extension method test whether 2 collections equivalent. use extension method, have specify 2 type parameters this: isequivalenttotesthelper<observablecollection<string>, string>(first, second, true); is there way implement extension method 1 generic constraint (e.g. observablecollection<string> ) need specified? update : posted modified code based on answers additional response question inspired one. here's original code: static public class enumerableextensions { static public bool isequivalentto<e,t>(this e first, e second) e : ienumerable<t> { if ((first == null) != (second == null)) return false; if (!object.referenceequals(first, second) && (first != null)) { if (first.count() != second.count()) return false; if ((first.count() != 0) &&