Posts

Showing posts from May, 2011

c - How do i count the number of elements on a given line of a file? -

something along line of: int n = sscanf(%s %s ... it save how many string element on given line in int n, the file can contain many lines each line having many elements e.g. efefefef efefef dfefe fefef eef efef efef efefef efefef efefef efefe efeefef [wdfefefef] first line n = 2 ; second line n = 6 also how should remove brackets strings thr string inside bracket? regards presuming 'element' mean word, best bet use strtok , pass appropriate list of terminators (which include space, '[', ']', etc.

datetime - How to get the total hr from start time to end time using 12 Hour Format in php -

how can total hour 2 given time "hh:mm:ss" format? here code: $start = 01:00:00 pm; $end = 02:00:00 pm; expected output: $total = 1; you can try this: $start = new datetime('01:00:00 pm'); $end = new datetime('02:00:00 pm'); $diff = $start->diff($end); echo $diff->format('%h'); you can more info: http://in1.php.net/manual/en/datetime.diff.php

python - Multiprocessing incompatible with NumPy -

this question has answer here: why multiprocessing use single core after import numpy? 3 answers i trying run simple test using multiprocessing. test works until import numpy (even though not used in program). here code: from multiprocessing import pool import time import numpy np #this problematic line def costlyfunc(n): """""" tstart = time.time() x = 0 in xrange(n): j in xrange(n): if % 2: x += 2 else: x -= 2 print "costlyfunc : elapsed time %f s" % (time.time() - tstart) return x #serial application resultlist0 = [] starttime = time.time() in xrange(3): resultlist0.append(costlyfunc(5000)) print "elapsed time (serial) : ", time.time() - starttime #multiprocessing application starttime = time.time() pool = pool() asyncresult = pool.map_async(

Clear firefox cache quicker -

i make changes js clear out cache doing cmd + shift + space (on mac) , select want clear out cache , leave cookies etc alone. i wondering there faster way clear out cache. any firefox plugin in 1 click or 1 button? thanks ctrl f5: refresh page clearing cache. reloads images, css, js , swf

package - Update multiple dependencies with Bower -

i listed (and/or installed) several dependencies bower inside bower.json file and/or bower install https://github.com/username/project.git that worked fine. now can list them with bower list and can pick name of each dependency of project , run bower update dependency-name question: how can bulk update of them? or have write shell script loop through , update them? you can update running bower update . use -h flag on command see how can use it. eg bower update -h .

Printing different than on page with JavaScript -

i've been printing images using standard window.print() function. i'm dealing image when printed, doesn't print correctly on 1 page(takes 2 pages no matter how small make image). put image in .pdf can format print size , orientation need, have no clue how make .pdf print without new popup window. there solutions out there, perhaps image size accomplish printing image onto 1 8 1/2 x 11 inch page? i've googled no luck, i'm kind of new, maybe i'm searching incorrectly.

loops - How to calculate a sum of sequence of numbers in Prolog -

the task calculate sum of natural numbers 0 m. wrote following code using swi-prolog: my_sum(from, to, _) :- > to, !. my_sum(from, to, s) :- = 0, next 1, s 1, my_sum(next, to, s). my_sum(from, to, s) :- > 0, next + 1, s s + next, my_sum(next, to, s). but when try calculate: my_sum(0,10,s), writeln(s). i got false instead of correct number. going wrong example? this surely false next \= 0: s s + next . more fundamental problem you're doing computation in 'reverse' order. is, when from > to , program stop, don't 'get back' result. should add accumulator (another parameter, propagated recursive calls) , unify partial sum @ last step... anyway, should simpler: my_sum(from, to, s) :- < to, next + 1, my_sum(next, to, t), s t + from. my_sum(n, n, n). | ?- my_sum(2, 4, n). n = 9

Opening a xml file from eclipse and from a .jar file in java -

yesterday, had problem because couldn't manage open xml file (it owuld give me filenotfoundexception) located in ressources folder of .jar file, managed open on eclipse using following lines of code. can see old problem here . code problem : file xmlfile = new file("ressources/emitter.xml"); configurableemitter emitter = particleio.loademitter(xmlfile); someone told me 1 way use getclassloader().getressourceasstream method open xml file in .jar file exported inputstream i= this.getclass().getclassloader().getresourceasstream("ressources/emitter.xml"); configurableemitter emitter = particleio.loademitter(i); unfortunately, solution works when export project .jar file, if want go debugging program, have take old code works on eclipse. my question is: there better way without having change code if want export or if want debug it? thank you edit : thank all, works fine problem put ressources folder : +project +src +ressources +emitter.

Accessing attributes of Chef::Provider::Package subclass instance from recipe -

i need somehow "return" variable custom subclass of chef::provider::package recipe called from, can use variable later in same recipe. i tried add custom chef::resource::package subclass attribute , appropriate setter/getter wrapper set_or_return function. can write , read attribute chef::provider::package subclass, when try access attribute recipe see nil value. can illustrated following recipe: a = apt_package "bzip2" action :install end # won't work, a.version nil log "bzip package version #{a.version}" however, can see in lib/chef/provider/package/apt.rb @current_resource.version being set: @current_resource.version(installed_version) what right way of reading arbitrary attribute ( version in example) of chef::resource::aptpackage instance, created apt_package provider same recipe? maybe like:: a = apt_package "bzip2" action :install end ruby_block "init logger"

matlab - Using MNIST DATABASE for digits recognition. -

i trying use mnist database in order recognize hand written digits. have far binary matrix represents digit , algorithm written in matlab . love on getting started using mnist database recognize digit binary image. thanks. if using matlab , have binary images need to: 1) extract features images (you have many choices). example, can start using raw pixels ==> convert each image matrix row vector. (use part of data training , rest testing) create feature matrix these row vectors. each row "instance" in feature matrix. 2) can select , try different classifiers. try example, svm (support vector machine). basic way using svmtrain , svmclassify functions. usage simple , explained in matlab's help. 3)test different partitions of data. 4)experiment other features , classifiers.

c++ - Restriction of access to function -

this question has answer here: std::enable_if conditionally compile member function 6 answers i have generic class function want restrict instances of floating point types only, @ compile time. shown in example below: template <typename t> class classname { // instance variables, etc.. void some_method() { // stuff, floating point types } } how make compiler reject usage of some_method classname of non-floating point types? i have been looking @ sfinae can't work, after several hours of failing i'm asking help. thanks :) you can use combination of std::is_floating_point , std::enable_if enable function floating point types: #include <type_traits> template <typename t> class classname { // instance variables, etc.. public: template<typename t2 = t, typename = typename std::en

html - Hovering images main menu -

Image
this when hover title , can see there little white arrow, when go on subtitle image disappears. #menu { float: left; height: 58px; width: 100%; margin-top: 30px; } #menu .menu_layer { float: left; height: 58px; width: 100%; filter: alpha(opacity = 50); -moz-opacity: 0.5; opacity: 0.5; border-top: #d8d6d2 1px solid; border-bottom: #f5f3f0 1px solid; background: #ffffff; z-index: 99; } #menu .menu_list { position: absolute; width: 100%; height: auto; z-index: 9999; } #menu .menu_list .egnav_menu_box { width: 940px; height: 60px; margin: 0 auto; } #menu .egnav_menu_box .egmenulevel_0 { float: left; position: relative; display: block; z-index: 99999; } #menu .egnav_menu_box .egmenulevel_0 { display: block; line-height: 60px; font-size: 14px; float: left; margin-left: 48px; font-family: "open_sanslight"; font-size: 16px; color: #666666; } #

delphi - Deploying Custom Units and Components -

when has come redoing or reinstalling delphi, i've run hassle. when comes components , units i've produced use in projects, run having go through entire backup of projects find things i've used in other projects , copy units over, install components through delphi interface, , make sure present. then, forget , when pull out project uses 1 of these units or components, have stop whatever i'm doing, find backup disk, find data install, before continue... main question: has come solve scenario automating of this? otherwise, people here when comes administration of delphi in way? some tips: when possible, avoid installation of components , create instances @ run time. reduce time install them in ide. example, non-visual components not have installed design mode. use build tool apache ant compile projects build script. build script serves documentation of environment , source path requirements. when run build on new computer, need check ant build scrip

java - When inserting objects into a type-safe heterogeneous container, why do we need the class reference? -

i'm checking out heterogeneous container pattern bloch's effective java , i'm trying determine why class reference needed when inserting objects heterogeneous container. can't use instance.getclass() reference? isn't jpa's entity manager example of this? interface blochsheterogeneouscontainer { <t> void put(class<t> clazz, t instance); <t> t get(class<t> clazz); } interface alternativeheterogeneouscontainer { // class<t> not needed because can use instance.getclass() <t> void put(t instance); <t> t get(class<t> clazz); } no can't that, won't give class of reference type in case of inheritance, rather class of actual object type. consider example: number num = new integer(4); system.out.println(num.getclass()); this print: class java.lang.integer and not java.lang.number .

sql - Select multiple columns into multiple variables -

how can in one select multiple columns , put each column in variable? something this: --code here v_date1 t1.date1%type; v_date2 t1.date2%type; v_date3 t1.date3%type; select t1.date1 v_date1, t1.date2 v_date2, t1.date3 v_date3 t1 id='x'; --code here any help? ty your query should be select t1.date1, t1.date2, t1.date3 v_date1, v_date2, v_date3 t1 id='x'; share , enjoy.

Session management across J2EE app and CQ in tomcat server -

my j2ee app running in tomcat server , trying deploy cq war file in same tomcat container. know cq not support ootb session management.would able maintain session between cq , j2ee app in same tomcat container? mean want store data in session can reuse when navigate , forth between j2ee pages , cq pages? afaik cq doesn't use sessions. can jet cookies , access j2ee , cq pages. trying do?

Are "(function ( ) { } ) ( )" and "(function ( ) { } ( ) )" functionally equal in JavaScript? -

this question has answer here: location of parenthesis auto-executing anonymous javascript functions? 4 answers both of these code blocks below alert foo bar . difference })() , }()) . code 1: (function() { bar = 'bar'; alert('foo'); })(); alert(bar); code 2: (function() { bar = 'bar'; alert('foo'); }()); alert(bar); so there difference, apart syntax? no; identical however, if add new beforehand , .something afterwards, different. code 1 new (function() { this.prop = 4; }) ().prop; this code creates new instance of function's class, gets prop property of new instance. returns 4 . it's equivalent function myclass() { this.prop = 4; } new myclass().prop; code 2 new ( function() { return { class: function() { } }; }() ).class; this code calls new on cla

Eclipse JFace Wizard jump to next page programatically -

i created jface wizard showing single list user supposed make selection. since page contains list, enable double click selection. if user performs double click on single event, wizard should jump next page. i got following code far: viewer.adddoubleclicklistener(new idoubleclicklistener() { @override public void doubleclick(doubleclickevent event) { istructuredselection selection = (istructuredselection) event.getselection(); if (selection.getfirstelement() instanceof file) { if(canfliptonextpage()) { //perform jump next page here. } } } }); apparently there no method programmatic execution of next button. thank you. you first need reference wizard page want go. if don't have through other means, can find wizard pages via api: getwizard().getpages() next, make following call: getcontainer().showpage( desiredpage )

reporting services - Create different title level with SSRS -

Image
i'm desperately try create report should this: page header title 1 title 2 title 3 title 4 data title 2 title 3 title 4 data page footer the title 1 4 have repeat themself each page. first though using subreport since page header , footer not possible in subreport, i'm stuck. tried table table header wasn't able either. if have idea welcomed. thanks in advance here more details of i'm trying do: the fisrt static row title1, i've put properties, repeatonnewpage= true, keepwithgroup = after, fixeddate=true. made group on 1 have block. each of 2 static row inside detail group filled tablix have different title inside. header of inside tablix render correctly on each page, first row render on first page , cannot understand why. any idea? add each title 'row group' , nest under other. in 'design' mode under 'row groups' should start out 'details', right click , choose 'a

java - NoClassDefFoundError when code moved from R2007a to R2013a -

i working on moving code r2007a r2013a. getting java.lang.noclassdeffounderror during run in r2013a not appear in r2007a. occurs when call. feval('get',fname,jevent); where fname product.proxyfield object object filter , jevent product.format.java.internal.javaevent . class in jar file on path , being accessed class in same jar file. stack trace not leave realm of product if helps. i not have access original code jar file. have access code derived original code , both classes in same package. i'm guessing has differences in java version i'm not sure since don't have original code recompile. unfortunately can't provide actual source or full detail google search yielded results matlab startup issues. thoughts? seems difference between r2007a , r2013a first uses 1.5 jre , second uses 1.6 jre. easier if provided stack trace showing exception. classes moved around in between jvm versions, having actual missing classes in determining if m

css - Is there a way to get a second line of text to fill vertically? -

i'm having bit of trouble getting various products line on site. of items have name long enough create second line of text, , when so, items still align top of text rather aligning top of each image. want use of empty space above each div fit second line of text, rather pushing picture down , aligning @ top. code i'm using create divs in loop within php: <div class="new_prod_box"> <a href="details.html"> '.$title.' </a> <div class="new_prod_bg"> <a href="details.html"> <img src="images/'.$image.'" alt="'.$title.'" title="" class="thumb" border="0" /> </a> </div> <a href="cart.php?action=add&id='.$id.'"> <u>add cart</u> </a> </div> here's picture explaining mean: my website here's rules in css: .new_prod_box{ float

c# - Get the URI of a specific webform -

i'm in process of learning .net, , need uri of specific webform. the framework asp.net 3.5 example: i'm in aboutme.aspx.cs , need find out uri of contactme.aspx be. edit clarify : give method path contactme.aspx --> "~/contactme.aspx" , "www.porcupine.com/contactme.aspx" the reason i'm trying figure out want render email template page, has specific variables per person, , able copy entire page string via webclient().downloadstring() method. method requires uri of page convert string. does know of way this? or of elegant alternative way (i.e., without writing out entire page body of message, etc.)? this should work need: string url = request.url.scheme + system.uri.schemedelimiter + request.url.host + (request.url.isdefaultport ? "" : ":" + request.url.port) + resolveurl("~/contactme.aspx"); in case returns: http://localhost:3165/website88/contactme.aspx

ios - How do I make sure when I change to different views each is set as the First Responder? -

i have app uses tab bar controller 5 different tabs using 1 viewcontroller (uiviewcontroller). on primary viewcontroller there audio function play audio , when switch other views, no longer able use headset buttons make adjustments audio playback (play/stop). told need make each view act first responder can receive notification adjust audio playback. how do this? i using 1 uiviewcontroller entire app, should setup different view controllers each tab of application instead? i'm using xcode 4.6.4 ios sdk 6.1 thanks.

sql - How to I add unique id's to mysql table? -

i have big mysql database. there 800000 records. there no uids have. how can add uids automaticly? alter table `your_table_name` add `uid` int not null auto_increment primary key first; be patient after executing statement. edit: alter table `your_table_name` auto_increment = 300000;

mysql - One-to-One Relationship -

i'm having trouble relationships mysql. tell me if 1 one relationship (between account , guest). create table if not exists account ( accountid int unsigned not null comment 'primary key', guestfk int unsigned not null comment 'account linked particular guest', password varchar(20) not null comment 'password of guest account', constraint account_pk primary key (accountid), constraint account_fk foreign key (accountid) references hotel.guest(guestid) ); create table if not exists guest ( guestid int unsigned not null auto_increment comment 'primary key', addressfk int unsigned not null comment 'foreign key of guest address', vehiclefk int unsigned comment 'foreign key of guest vehicle', firstname varchar(50) not null comment 'first name of guest', lastname varchar(50) not null comment 'last name of guest', phonenum int unsigned no

python - Modifying a file text -

i have text file this: 0 1 0 10.2 5.82 4.82 1 -1 0 8.21 5.74 3.62 0 1 1 5.33 8.66 5.47 this text file has few hundred rows pattern. in first row, if first column 0, fourth column same. second column 1, fifth column has +10, value 15.82. in second row, if first column 1, forth column has +10, value 18.21. second column -1, fifth column has -10, value -4.26. etc. the final output this: 10.20 15.82 4.82 18.21 -4.26 3.62 5.33 18.66 15.47 i have tried using code wrote: with open('abc') f, open('out.txt', 'w') f1: line in f: reff = line.split() if reff[0] == '0': value = float(reff[3]) = str(value) line = "".join(a) + " " + "".join(reff[4]) + " " + "".join(reff[5]) + '\n' elif reff[0] == '1': value = float(reff[3]) + 10 = str(value) line = "".jo

php - Form not POSTing values -

form: <form id="register" method="post" action="pro/register.php"> <input type="text" maxlength="30" placeholder="username" id="user" /><br /> <input type="email" maxlength="64" placeholder="email" id="email" /><br /> <input type="password" placeholder="password" id="pass1" /><br /> <input type="password" placeholder="confirm password" id="pass2" /><br /> <input type="submit" value="register" id="submit_register" /> </form> pro/register.php page : $user = $_post['user']; $email = $_post['email']; $pass1 = $_post['pass1']; $pass2 = $_post['pass2']; //debug echo "<strong>details:</strong><br>"; echo $user.", ".$email.", &

Convert integer to binary in python and compare the bits -

how convert int n binary , test each bit of resulting binary number? i have got following after lot of googling: def check_bit_positions(n, p1, p2): print int(str(n),2) however error invalid literal int() base 2 . let me know how can binary form of input number , test each bit @ position p1 , p2 edit: binary = '{0:b}'.format(n) if list(binary)[p1] == list(binary)[p2]: print "true" else: print "false" the above code works now, how can check postions p1 , p2 end of list? use bin() function: >>> bin(5) '0b101' or str.format : >>> '{0:04b}'.format(5) '0101'

java - Linux javac command erroring on wildcard in classpath -

i running windows 7 java version 1.6.0_31-b05 on pc, , computerlab's network linux (fedora, possibly version 13) running java version 1.6.0_35-b10 . i have c:\myproject (et al) directory, src , lib , , bin subdirectories. the src folder contains of source code in tree structure, corresponds java packages. the lib directory contains jar files. i have re-created tree in linux, under ../myproject (et al). when attempt compile in dos, ..\myproject\src directory, command below, works fine: javac -cp ".;../bin;../lib/*" -d ../bin org/unlv/schillerlab/motif_diversity/step02/*.java when attempt compile in linux, ../myproject/src directory, message incorrect classpath : ../lib/* : javac -cp ".:../bin:../lib/*" -d ../bin org/unlv/schillerlab/motif_diversity/step02/*.java the computerlab network location accessible both dos , linux. in linux, first created ../myproject/src , ../myproject/lib , , ../myproject/bin directories. then, i

java - How can I make sure my JUnit test method's specific cleanup always runs? -

i have junit test class has 2 test methods: @test public void test1() { // setup: create foo1.m // exercise // tear down: delete foo1.m } @test public void test2() { // setup: create foo2.m // exercise // tear down: delete foo2.m } for each method, make sure that, if exercise section fails reason, tear down still run. note setup , tear down code both test methods different, don't think can use junit's @before , @after annotations want. i put try-catch blocks each test method: @test public void test2() { // setup: create foo2.m try { // exercise } { // tear down: delete foo2.m } } but seems ugly. there way make sure test-method-specific tear down code in each test method executed, without using try-catch block? update: i found better solution, include here, original answer can found below. think junit 4 rules can used here: class preparefile implements org.junit.rules.testrule { @retention(r

Is there a way to override and not execute the headerCallBack in Spring Batch -

i've created abstract parentflatfilewriter included headercallback default header. works great because i'm writing 6 files. but, on 1 file i'm writing, want skip header 1 file. still want use abstract bean rest of outfiles. can override inherited headercallback property , not write header? thanks header written flatfileitemwriter.headercallback property setted else header writing skipped. in 7th writer set flatfileitemwriter.setheadercallback(null) . in spring xml write: <bean id="my7thwriter" class="my7thwriterimpl" parent="parentflatfilewriter"> <property name="headercallback"><null/></property> </bean>

mysql - JOIN skipping duplicates -

select `bilder_w2l`.filnamn, `bilder_w2l`.md5_hash, `bilddata_w2l`.bildkategori `bilder_w2l` inner join `bilddata_w2l` on `bilder_w2l`.bildid = `bilddata_w2l`.bildid `bilder_w2l`.status = 0 bilddata_w2l has 28 rows. bilder_w2l has 21 rows. i want row data bilddata_w2l on 21 rows... rows in bilddata_w2l can have duplicate bildid. it's issue inner join, say. i'm not sure 1 use or how change sql. select `bilder_w2l`.filnamn, `bilder_w2l`.md5_hash, `bilddata_w2l`.bildkategori `bilder_w2l` left outer join `bilddata_w2l` on `bilder_w2l`.bildid = `bilddata_w2l`.bildid `bilder_w2l`.status = 0 is looking for?

javascript - append meta tag to the head of the main document from iframe -

so i've got issue i've made document responsive it's displayed in iframe parent document has wrong meta tag. i set test see if in iframe. it's appending meta tag head of iframe not main document. have suggestions? index.html <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>iframe test</title> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> </head> <body> <iframe id="testframe" name="testframe" src="iframe.html"></iframe> </body> </html> iframe.html <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>iframe</title> <script> var viewporttag=document.createelement('meta'); viewporttag.id="viewport"; viewporttag.name = "viewport"; viewportt

html - can't get buttons to be responsive and scale like the rest of my page -

i've got of page responsive thing can't seem figure out 2 buttons. using javascript mouseover effect not sure if messing things or not. want images scale along rest of page when view in different resolutions. http://74.117.156.152/~pr0digy/ here html: <!doctype html> <html lang="en"> <head> <title>us legal support - capex</title> <meta charset="utf-8" /> <link rel="stylesheet" href="style.css" type="text/css" /> <meta name="viewport" content="width-device-width, initial-scale-1.0"> <script type="text/javascript"> if (document.images) { new1 = new image; new2 = new image; existing1 = new image; existing2 = new image; new1.src = "images/new1.png"; new2.src = "images/new2.png"; existing1.src = "images/existing1.png"; existing2.src = &qu

java - Using SVN 1.4.6 with Intellij IDEA 12 -

the project i'm working on configured svn 1.4.6. idea has integration problem when try update/commit, says: problems while loading file history: svn: e155021: client old work working copy @ c:\users....... on machine, i'm using svn tortoise: tortoisesvn 1.8.0, build 24401 - 64 bit | subversion 1.8.0 how can use old svn working copy idea? idea doesn't support subversion 1.8 working copies , can checkout project using idea built-in subversion client compatible working copy.

Embed Spring Security login form to an existing page -

how add spring security login form existing page? for example, let's have following test.jsp page (which not spring login form page): <html> <head>existing page</head> <body> <div id="login-form"></div> </body> </html> i add login form configured in spring-security.xml inside login-form div. typically believe people put form right in page (i.e. within div have there.) like: <form id="blah" action="/j_spring_security_check"> <input type="text" name="j_username" /> <input type="text" name="j_password" /> <input type="submit" name="submit" value="login" /> <input type="reset" name="reset" /> </form> then use css make fit , feel of rest of application.

objective c - How to zoom UIScrollview together with added UIImage -

i have background image added uiscrollview zoom enabled. trying add additional uiimage's on top of background image zoom background image? the idea have background multiple playing cards user can either see whole playing field small playing cards or zoom in whole background including playing cards better views on playing cards. your uiscrollview should contain single zoomable uiview subview. subview should contain background uiimageview , of card uiimageview s it's own subviews (if add background image first, layered @ of resulting composite view) the containing uiview immediate subview of scrollview should return value uiscrollviewdelegate method - (uiview *)viewforzoominginscrollview:(uiscrollview *)scrollview you can manage view hierarchy through uiview 's subviews property, nsarray of views. layered in order of array, first view on array @ when views composited display.

actionscript 3 - AS3 - Loading multiple videos into the same container - addChild removeChild -

this function loads specific video movieclip container @ 0.0 using video class. public var mainvideo:simplevideo; public function loadvideo(videostring:string) :void{ mainvideo = new simplevideo("videos/"+videostring+".flv","",true,video_container.positionmc); video_container.addeventlistener(mouseevent.mouse_down,controlvideoplayer); addchild(mainvideo); trace('adding new video container'); } i'd preferably check, each time video loaded, see if there video loaded. , if there is, remove it, , add new video. i've tried using removechild() in variety of ways, doesn't seem work correctly. would use removechild(mainvideo) ? video_container.removechild(mainvideo) ? , how able check if there existing mainvideo ? any appreciated! -update- if try , use removechild(mainvideo) error: typeerror: error #2007: parameter child must non-null. @ flash.display::displayobjectcontainer/removechild() @ ma

Parsing text from one array into another array in Objective C -

i created array called nsarray citieslist text file separating each object "," @ end of line. here raw data looks text file. city:san jose|county:santa clara|pop:945942, city:san francisco|county:san francisco|pop:805235, city:oakland|county:alameda|pop:390724, city:fremont|county:alameda|pop:214089, city:santa rosa|county:sonoma|pop:167815, the citieslist array fine (i can see count objects, see data, etc.) want parse out city , pop: in each of array objects. assume create loop run through objects, if wanted create mutable array called citynames populate city names array use kind of loop: smutablearray *citynames = [nsmutablearray array]; (nsstring *i in citieslist) { [citynames addobject:[???]]; } my question what query should use find city: san francisco objects in array? you can continue use componentsseparatedbystring divide sections , key/value pairs. or can use nsscanner read through string parsing out key/value pairs. use rang

php - Converting a nummeric array to comma separated string -

i have array this: [participants] => array ( [0] => 9 [1] => 8 [2] => 12 ) i want put in variable this: "9,8,12" i tried code below not output anything: $mem = ""; for($i = 0; $i < count($participants); $i++) { $mem.$participants[$i]; } echo $mem; what can problem? the easiest way use implode : implode(',', $participants); in code should have used concatenation this: $mem .= $participants[$i].','; however, have preferred foreach this: $mem = ""; foreach ($participants $key => $value){ $mem .= $value.','; } if you're looping in way, have rid of last comma when you're done: $mem = rtrim($mem, ',');

javascript - Function doesn't correctly perform unless it is called twice -

some background: using javascript vertically center child divs vary in height depending on conditions in parent div. centering function follows: function autocenter() {var firstline = document.getelementbyid("ntext"); var secondline = document.getelementbyid("dtext"); var l1h = parseint(getcomputedstyle(firstline)["height"]); var l2h = parseint(getcomputedstyle(secondline)["height"]); var d1h = parseint(getcomputedstyle(document.getelementbyid("design"))["height"]); var d2h = parseint(getcomputedstyle(document.getelementbyid("design2"))["height"]); var totalh = l1h + l2h + d1h+ d2h; document.getelementbyid("desdiv").style.top = (212-totalh)/2 + "px"; firstline.style.top = (212-totalh)/2 + d1h +"px"; secondline.style.top = (212-totalh)/2 + l1h + d1h + "px"; document.getelementbyid("desdiv2").style.top = (212-totalh)/2 + l1h + l2h + d1h+ "px";

How to enforce a 2.0-capable processor in an XSLT? -

using xslt 2.0 , how can check in stylesheet actual xslt 2.0 capable processor being used? system-property() , 2.0 function, still returns 2.0 on ones cannot support properly. when run http://home.arcor.de/martin.honnen/xslt/processortest2.xml saxon 6.5.5 or firefox or chrome or opera or ie 10 report xsl:version 1 or 1.0 , none of them reports 2.0 . have not tried xalan however.

python - Pickling multiple dictionaries -

so i'm new python , i'll asking many noob questions throughout learning process (if haven't been asked/answered of course). one question have if there way save multiple dictionaries 1 text file using pickle, or if each individual dictionary has saved it's own separate file. example, if want create program manage web accounts, each account having variety of arbitrary keys/values, can save these individual accounts 1 archive separate dictionaries? thanks in advance, , noob appreciate example code and/or suggestions. one quick solution place both dictionaries in list, pickle list. here example writes out binary file. import cpickle pkl myfirstdict = { "hat": 7, "carpet": 5 } myseconddict = { "syrup":15, "yogurt": 18 } mydicts = [myfirstdict, myseconddict] pkl.dump( mydicts, open( "mydicts.p", "wb" ) ) here 1 loads it. import cpickle pkl mydicts = pkl.load( o

Android out of memory error on choosing second image -

my app works stepping out of main activity, starts second activity, displays image chosen user , analyzes image. after analysis of first image, used button go main activity , proceed second activity again choose second image. user chooses second image, android give me out of memory error. tried keeping track of available memory. strange thing right before second image chosen, there more memory available before first image chosen. how should go solving this? thanks! ps code runs out of memory @ bitmapfactory.decodefile(picturepath); if running on pre 3.0 hardware, memory value see not include memory used bitmaps, that's possible reason behavior described. as rule of thumb, should check dimension of image app retrieve dynamically (either user selection or net), , scale size makes sense app. example, gallery app should rescale picture phone takes dimension of screen. below code sample decoding scaled bitmap: private bitmap decodefile(file f, int width_tmp,

webforms - ValidationGroup issue - without group: `DoPostBackWithOptions`, with group: `__dopostback` -

Image
validation works fine until make use of validationgroup. afterward form submits no validation occurs. href on linkbutton before , after use validationgroup. before: javascript:dopostbackwithoptions(...) after: javascript:__dopostback(...) the causesvalidation property set true. why adding validationgroup change postback code that? once set validationgroup on button, button should trigger matched group validator. asp.net generates webform_dopostbackwithoptions because there group validator on page matching button's attribute ‘validationgroup’. your link button markup code should similar that: <input type="submit" name="btngroup1" value="group1" onclick="javascript:webform_dopostbackwithoptions( new webform_postbackoptions('btngroup1', '', true,'group1','', false, false))" id="btngroup1" /> through debugging js code, should able find there js function used find grou

linux - C - ioctl wlan operstate, link quality, and tx/rx status -

i borrowed this gentleman in order request signal strength of wireless connection on device. use ioctl operstate , whether or not there's up/down stream information flowing on connection. basically, i'm attempting modernize of device, adding real-time status icons of link operability, quality, , activity. originally, using popen() cat , parse /proc/net/wireless , /sys/class/net/wlan0/operstate. issue fail (i assume because os had locked file) causing crashes. so, questions two: one, can use ioctl in way similar 1 described in link above monitor operstate , connection activity? information find pertaining ifreq, not iwreq. two, occurred me while writing should have kernel telling application when status of wireless device changes, shouldn't i? can't imagine various desktops' system trays have polling loops in them. actual two: there way have kernel feed information application operstate, link quality, , link activity in real-time? thank in advance. =

Programmatically make a continuous (forever) video feed (for free?) -

what services , software might required simply: write code programmatically generates time-based media (presentations of picture, sound, , text , transitions between them) (probably using html/css/js) , have streamed continuously video (a la ustream) can watched thousands of viewers @ once? the key here should able run continuously without intervention for, like, year, while can, whenever please, deploy new time-based-media-generating scripts used main video-generating program, either randomly, or in queue. nothing free, no-one giving free bandwidth stream videos years... eigther show ads in between or have pay. thousands of viewers @ once free, if set own streaming server , infrastructure, have have leased line or multiple t1 lines stream. if above issues not concern, there plenty of softwares out there in market (search tv software), these softwares can output video stream continously u can pick , stream. windows media encoder lightwiight option.

jquery - Backbone:.js: How to find out who is deleting my model from my collection? -

my view subscribed model's delete event. i'm seeing model delete event being mysteriously triggered , can't find where/how that's being sent code. @ runtime, see models being added collection, before being deleted. how can troubleshoot issue? as noted above: if view listening destroy event. give callback method it. put debug point inside event , check call stack. can find on right side in source tab of developer tools when in debug mode.

wxpython, How to display buttons label into textctrl area -

i new wxpython struggling this. want create button label , label when press button displayed textctrl area,for example cellphone, when press 1 number 1 displayed on screen! import wx class example(wx.frame): def __init__(self,parent,id): wx.frame.__init__(self,parent,id,' title', size = (205,330)) panel = wx.panel(self, wx.id_any) textctrl = wx.textctrl(panel, -1,("0"), pos=(10, 10),size=(170, 60)) button=wx.button(panel,label="1",pos=(100,210),size=(30,30)) self.bind(wx.evt_button, self.onbutton, button) def onbutton (self,evt): label = evt.geteventobject().getlabel() if __name__=='__main__': app=wx.pysimpleapp() frame=example(parent=none,id=-1) frame.show() app.mainloop() thanks you need keep references controls - can set them: import wx class example(wx.frame): def __init__(self,parent,id): wx.frame.__init__(self,parent,id,' title

html - how to create a canvas dynamically in javascript -

i have canvas can draw things mouse.. when click button has capture drawing , add right under canvas, , clear previous 1 draw new..so first canvas has static , other ones has created dynamically drawing draw .. should can help here jsfiddle http://jsfiddle.net/dqppk/378/ var canvas = document.getelementbyid("canvas"), ctx = canvas.getcontext("2d"), painting = false, lastx = 0, lasty = 0; here's function use this, part of library made , use ease few things canvas. put on github in case other function might be of use, i'll have make readme later... https://github.com/gamealchemist/canvaslib with namespaceing removed, code follow insert canvas : // insert canvas on top of current document. // if width, height not provided, use document width / height // width / height unit css pixel. // returns canvas. insertmaincanvas = function insertmaincanvas (_w,_h) { if (_w==undefined) { _w = document.documentelement.clientwidth & (~3) ; }

php - Shorten sentence and find nearest dot -

i'm writing blog , need function shows excerpt of post. i'm using substring checking if text longer 503 chars. but cuts text in middle of word , in middle of html tag rest of page tag half written. i.e: " text text text <strong>another piece of te [...] , rest of page strong till hits new strong-end tag. i tried removing elements post un-formats text. how go in order "ok, text 980 chars, cut @ 503+whatever else needed last dot (.) or complete tag. follows current code: <?php $testo_preview = preg_replace("/<img[^>]+\>/i", ' ', $valore->testo); $testo_preview = preg_replace("/<a[^>]+>/i", '<a>', $testo_preview); $testo_preview = preg_replace("/<span[^>]+>/i", '<span>', $testo_preview); $testo_preview = preg_replace("/<div[^>]+>/i", '', $testo_preview); $testo_preview = str_replace("</div>", '&

jQuery won't act on a partial rendered through AJAX in Rails -

my app has called "memos". , can reply other memos using @ tags inside memo. example: hi reply @123 then, if click, @123, memo #123 rendered underneath memo you're viewing. _memo.html.erb: <div class="memo"> <div class="memo-content"> <%= raw simple_format(memo.content).gsub(/@([a-z0-9a-z]+)/, '<a data-remote="true" class="marker" href="/memos/\1">@\1</a>')%> </div> </div> app/assets/javascripts/memo.js: $(function() { $(".marker").on("ajax:success", function(e, content){ console.log("hi") $(".memos-container").append(content); }); }) memos_controller.rb: def show @memo = memo.find(params[:id]) if request.xhr? render partial: "shared/memo", locals: { memo: @memo } end end the first click works fine. if click on @123 , memo #123 rendered

ruby - Get all items inside quotes in Cucumber Step Definition -

i have string: i attach "dog.png", "cat.png", , "alphabet.doc" this want matched: 1. dog.png 2. cat.png 3. alphabet.doc i can doing "([^"]*)" , however, string has start 'i attach' this current rule have in step definition: /^i attach "([^"]*)"$/ doesn't work. this cucumber/gherkin, can figure out using scan don't think can use in cuke/gherkin? any suggestions on how this? thanks if want capture variable number of inputs in single step, think best option use scan . while cannot use scan directly in step name, can capture full list of files , parse captured result. try following step definition: given /^i attach (.*)$/ |file_list| files = file_list.scan(/"(.+?)"/).flatten #=> ["dog.png", "cat.png", "alphabet.doc"] end this create array of files attach. can handle 1 infinite files.

How can i include some predefined stuff in JIRA Greenhopper project -

i using jira + green hopper agile project managment . projects web application based. so every project , have 4-5 predefined epics , stories want inlcude in projects like serversetup analytics setup backups is there way can set them template dont need enter them again , again this link may helpful https://answers.atlassian.com/questions/32564/is-it-possible-to-generally-setup-project-templates . in 2 words jira doesn't provide such functionality , there plugins may handle this. if running projects on ondemand version may consider option of writing simple program or script creating predefined list of tickets project specify. can take @ examples of using rest api. link below contains few examples of how create issue via rest api. https://developer.atlassian.com/display/jiradev/jira+rest+api+example+-+create+issue#jirarestapiexample-createissue-exampleofcreatinganissueusingprojectidsandissuetypeids .

ios - Adding seconds to a self.timepicker date (for localnotification purposes) -

i want know if possible add seconds local notification? trying create loop schedule local notifications 30 seconds after each others. so, in loop below, can keep on "delaying" firedate 30 seconds after each other. don't know if question makes sense, that's best can describe problem as. think of 30 second interval, manually scheduling each notification. for (notifs = 1, notifs <= 64, notifs ++) { uilocalnotification* localnotification = [[uilocalnotification alloc] init]; localnotification.firedate = [self.timepicker date]; //can write [self.timepicker date] + 30000? localnotification.soundname = @"notifsound.caf"; localnotification.alertbody = @"wake up!!!"; localnotification.timezone = [nstimezone defaulttimezone]; } thanks. you use nsdate's datebyaddingtimeinterval: , pass current iteration number multiplied 30. for (notifs = 1; notifs <= 64; notifs ++) { uilocalnotification* localnotification =

ruby on rails - How to place an image inside of a link? -

i'm trying simple, inside link want there text , image. = link_to 'nvidia graphics', inventory_url, class: 'lato' = image_tag 'list-highlighter.png' i'd output like: <a href="/inventory"> nvidia graphics <img src="list-highlighter.png" /> </a> how can achieve using slim? current code causes website crash. undefined method `stringify_keys' " http://foobar.com/inventory ":string = link_to inventory_url, class: 'lato' | nvidia graphics = image_tag 'list-highlighter.png' i think should work.. not 100% slim syntax. link_to shouldn't have content when wrapping block -- is, should followed url. content inside wrapped <a> tag output. non-slim, like <%= link_to inventory_url, class: 'lato %> nvidia graphics <%= image_tag 'list-highlighter.png' %> <% end %>

c - finding the minimum element in a cyclic sorted array -

this question has answer here: need algorithm special array (linear field) 3 answers i have tried following code find out minimum element in cyclic sorted array. fails when low = 1 , high =2 because mid 1 , a[mid]=a[1] greater a[high]. i trying use binary search here find solution. //finding minim element in cyclic sorted array int arrc[]={10,13,1,3,4,5,8}; int low=0,high =6; int mid=0,reset =1; while (low < high) { mid = (low+ high)/2; if (arrc[mid]>arrc[high]) { low = mid; } else if (arrc[mid] < arrc[high]) { high = mid; } } printf("minimum element %d",arrc[mid+1]); use normal binary search, if arrc[high] < arrc[low] , treat arrc[high] infinity account wrap around. change line: if (arrc[mid]>arrc[high]) to: if (arrc[high] < arrc[low] || arrc[mid] > arrc[high])

mysql - Sql to find timediff between two rows based on ID -

the subject of question not explanatory, sorry that. ya question follows: have database structure below pk primary key, id multiple many rows. +------+------+---------------------+ | pk | id | value | +------+------+---------------------+ | 99 | 1 | 2013-08-06 11:10:00 | | 100 | 1 | 2013-08-06 11:15:00 | | 101 | 1 | 2013-08-06 11:20:00 | | 102 | 1 | 2013-08-06 11:25:00 | | 103 | 2 | 2013-08-06 15:10:00 | | 104 | 2 | 2013-08-06 15:15:00 | | 105 | 2 | 2013-08-06 15:20:00 | +------+------+---------------------+ what need is, value difference between first 2 rows (which ordered value) each group (where group id). according above structure need timediff(value100, value99) [ id 1 group] , timediff(value104, value103) [ id 2 group] i.e. value difference of time ordered value 1st 2 rows in each group. one way can think 3 self joins (or 3 sub queries) find first 2 in 2 of them , , third query subtracting it. suggestions? loo

winapi - C++ Win32 Draw to a DC and Keeping It -

i trying draw simple few rectangles , store result, need draw once. so, keeping hdc (hdcbackround) @ top "globaly." void drawbackground(hwnd hwnd) { // hwnd main windows handle // dimensions rect rect; getwindowrect(hwnd, &rect); hdc hwindc = getdc(hwnd); hdcbackground = ::createcompatibledc(hwindc); // "global" hbitmap hbm = ::createcompatiblebitmap(hwindc, rect.right, rect.bottom); ::selectobject(hdcbackground, hbm); setbkmode(hdcbackground, transparent); selectobject(hdcbackground, hfont[hf_default]); selectobject(hdcbackground, hbrush[hb_topbg]); selectobject(hdcbackground, hpen[hp_thinborder]); // draw rectangle(hdcbackground, 0, 0, rect.right, 20); selectobject(hdcbackground, hbrush[hb_lowbg]); rectangle(hdcbackground, 50, 20, rect.right, 40); // ??? clean after works releasedc(hwnd, hwindc); } i call function once, , in timer bitblt() hdcbackground screens hdc. when test out, draws both rectangles, 1px border (as pen set

Python heapq not being pushed in right order? -

util.py import heapq class priorityqueue: def __init__(self): self.heap=[] def push(self,item,priority): pair = (priority,item) heapq.heappush(self.heap,pair) def pop(self): (priority,item) = heapq.heappop(self.heap) return item def getheap(self): return self.heap class priorityqueuewithfunction(priorityqueue): def __init__ (self,priorityfunction): self.priorityfunction = priorityfunction priorityqueue.__init__(self) def push(self,item): priorityqueue.push(self, item, self.priorityfunction(item)) pqtest.py import os,sys lib_path = os.path.abspath('../../lib/here') sys.path.append(lib_path) import util import string import random def str_gen(): return ''.join(random.choice(string.ascii_uppercase + string.digits) x in range(random.randint(2,8))) def pqfunc(item): return len(str(item)) rdy = util.priorityqueuefunction(pqfunc) in range(1,10): rdy.pu

SQL Server CE can't parse my query (Insert and then select) -

i error when run query: there error parsing query. [ token line number = 1,token line offset = 157,token in error = select ] this use when writing while using 2008 r2... here query: insert tblexample([example], [groupid], [key], [value], [expectedcolumn]) values (@example, @groupid, @k, @v, @expectedcolumn); select @@identity; the execution: if (db == null) { throw new exception("you must give me actiavted dbcon!"); } object ret = null; db.command.commandtext = query; addparameters(db.command, parameters); if (db.connection.state != connectionstate.open) db.connection.open(); var temp = db.command.executescalar(); if (temp != null && temp != dbnull.value) { ret = temp; } return ret;

Running applescript in new terminal tab and do file logging -

i need following thing i'm unable find in forum. if link exists kindly redirect me it. i need invoke applescript running terminal window . how make sure applescript running in new tab , not in new window. also, i'm supposed watch exceptions in new tab possible simultaneously view in terminal , log exception details in separate file time stamp? thanks in advance ! you cannot run applescript in terminal, can run applescript from terminal. using osascript command, can run applescript file or run statement using applescript. osascript "file path here" [arguments] # runs applescript file optional arguments osascript -e 'applescript statement' # runs 1 line of applescript code terminal note: -e flag can used many times make functional applescript (line line) terminal. add flag after line of code , continue coding. if want log or print applescript in terminal window, can use log "hello world" in applescript code.

javascript - Warnings in passing three.js scenes into backbone.js models -

i running errors when trying pass instance of three.scene backbone.model so: var scene = new three.scene(); new (backbone.model)(scene); and end warnings: deprecated: object3d's .eulerorder has been moved object3d's .rotation.order. three.min.js:148 deprecated: object3d's .usequaternion has been removed. library uses quaternions default. three.min.js:148 i using three.js r59 , backbone.js 1.0.0 the problem lies in how backbone creates models. to create model reads in properties of object( causes warning) , sets them named property on model.

How can I make a <select> dropdown in AngularJS default to a value in localstorage? -

i have <select> populating list of values. works , see expected list. have value set locally stored value if available. i have code below. when run code number after type in label changes match in localstorage select box not change. getcontenttypeselect: function ($scope) { entityservice.getentities('contenttype') .then(function (result) { $scope.option.contenttypes = result; $scope.option.contenttypesplus = [{ id: 0, name: '*' }].concat(result); $scope.option.selectedcontenttype = localstorageservice.get('selectedcontenttype'); }, function (result) { alert("error: no data returned"); }); }, <span class="label">type {{ option.selectedcontenttype }}</span> <select data-ng-disabled="!option.selectedsubject" data-ng-model="option.selectedcontenttype" data-ng-options="item.id

ios - use uidatepicker to set textfield value -

i have uidatepicker stores date selected textfield. want text field calculates how old person (as whole int) depending on date entered, e.g. "15". unsure how that. point me in right direction please . here's have far. -(void)viewdidappear:(bool)animated{ [birthdaydatepicker addtarget:self action:@selector(datechanged:) forcontrolevents:uicontroleventvaluechanged]; } - (void) datechanged:(id)sender{ nsdateformatter *dateformatter = [[nsdateformatter alloc] init]; dateformatter.datestyle = nsdateformatterlongstyle; birthdaytextfield.text = [nsstring stringwithformat:@"%@", [dateformatter stringfromdate:birthdaydatepicker.date]]; //look @ todays date, subtract date in birthdaytextfield calculate age maybe? } you can try this - (void) datechanged:(id)sender{ nsdateformatter *dateformatter = [[nsdateformatter alloc] init]; [dateformatter setdateformat:@"yyyy-mm-dd hh:m

Oracle DB daily partitioning -

i have following table create table "metric_value_raw" ( "subelement_id" integer not null , "metric_metadata_id" integer not null , "metric_value_int" integer, "metric_value_float" float(126), "time_stamp" timestamp not null ) ; every hour data loaded table using sql loader. i want create partitions data every day go partition. in table want store data 30 days. when crosses 30 days, oldest partition should deleted. can share ideas on how can design partitions. as said , there big differences in partition automation between 10g , 11g. in 10g have manually manage partitions during etl process (i'm sure every 10g dba has utility package wrote manage partitions ... ). for steps 1 & 2 , have several options load data directly daily partition. load data new partition , merge daily one. load data new partition every hour, , during maintenance window merge h

python - Acess Foreign key on django template from queryset values -

i can't seem find i'm doing wrong. here's setup from django.db import models django.conf import settings """ simple model handle blog posts """ class category(models.model): def __unicode__(self): return self.name name = models.charfield(max_length=50) class blogentry(models.model): def __unicode__(self): return self.blog_post_name blog_post_name = models.charfield(max_length=200) blog_post_content = models.charfield(max_length=1024) blog_pub_date = models.datetimefield(auto_now=true) blog_post_image = models.imagefield(upload_to = settings.media_root, default = '/media_files/douche.jpg') blog_post_category = models.foreignkey(category) views.py django.shortcuts import render blog_post.models import blogentry, category blog_post.forms import blogpostform django.shortcuts import httpresponseredirect time import gmtime, strftime """