Posts

Showing posts from July, 2015

How do you make long list comprehensions in python? -

for example: >>> [x x in range(y) y in range(z) z in range(3)] traceback (most recent call last): file "<stdin>", line 1, in <module> nameerror: name 'y' not defined i expect behave same as: >>> a=[] >>> z in range(3): ... y in range(z): ... x in range(3): ... a.append(x) ... >>> [0, 1, 2, 0, 1, 2, 0, 1, 2] but doesn't. why? your current comprehension work if reverse order of loops: [x z in range(3) y in range(z) x in range(3)]

random - pulling an excel sheet with =rand(between) in a Python while loop, and exporting results as .dbf -

to preface question: new stack overflow, , relatively new python. i working on setting sensitivity analysis. working 40 parameters range 0.1 - 1. analysis requires simultaneously varying these parameters +-0.1 ~500 times. these values fed arcgis tool. so, need 500 sets of random values, 40 parameters. these parameter values compared output of tool, see parameters model sensitive to. i've set excel sheet randomly calculate these values each time it's opened, issue need in .dbf format read arcgis tool. i have set while loop (for 10 iterations start, need ~500) , tried 2 different methods, in hopes automate process of calling .xls generate random numbers, , exporting .dbf. the first, arcpy.copyrows_management correctly exported .dbf. issue output exact same each iteration, , instead of having values of 0.1, 0.2, 0.3 etc, contained values of 0.22, 0.37, 0.68 etc. wasn't tenths, though specified in formulas in .xls. i tried arcpy.tabletotable_conversion throwing erro

mysql - How to order by first record of another order by result? -

i trying create own messaging sms in phones. i have mysql table this id (the message id) from_member_id (the id of member sent message) to_member_id (the id of member message sent to) date sent (the date sent) active (if message deleted or active) text (the text) and want information in special ordered way. first has sorted id that's not (call 'other' id). each section of ordering, needs top record (which should recent date), , sort sections date value of record. i can first ordering this: select from_member_id, to_member_id, (case when from_member_id = ? to_member_id else from_member_id end case) conversation_member_id, date_sent table from_member_id = ? or to_member_id = ? order conversation_member_id desc, date_sent desc where ? id. but problem how second ordering, need order sections date of top record (which should recent date). note when section, mean group of records same

Issue with C++ console output -

#include <iostream> using namespace std; int main() { cout << 1; while (true); return 0; } i thought program should print 1 , hung. doesn't print anything, hungs. cout << endl or cout.flush() can solve problem, still want know why it's not working expected :) problem appeared during codeforces contest , spent lot of time on looking @ strange behavior of program. incorrect, hunged, hidden output debug information. i tried using printf (compiling gcc) , behaves cout , question can referred c also. you writing buffer. need flush buffer. @guvante mentioned, use cout.flush() or fflush(stdout) printf. update: looks fflush works cout. don't - may not fact in cases.

asp.net - C# SqlDataReader No data exists for the row/column -

i've been away programming while i've got need it. i have problem sql datareader using sql server compact edition 4.0 (vs2012 built-in). string connstring = "data source=c:\\..(path here)..\\vacationsdb.sdf"; sqlceconnection conn = new sqlceconnection(connstring); string strsql = "select * vacation vacationno = @val"; using (sqlcecommand cmd = new sqlcecommand(strsql, conn)) { //read search value from text field cmd.parameters.addwithvalue("@val", vacationno_txt.text); conn.open(); sqlcedatareader reader = cmd.executereader(); fname_txt.text = reader.getstring(0); mname_txt.text = reader.getstring(1); /* * .. snip */ vacationno_txt.text = reader.getstring(11); conn.close(); } i keep getting error: "invalidoperationexception unhandled. no data exists row/column." , error points @ fname_txt.text = reader.getstring(0); but there data there because "submit" button it

java - Sending command line arguments from Eclipse -

this question has answer here: how add command line parameters when running java code in eclipse? 3 answers public static void main(string[] args) throws filenotfoundexception, svgformatexception { svg svg = new svg("test.svg"); //so file called test.svg can called upon portablepixmap ppm = new portablepixmap(500, 500); //select size of pixmap(canvas) svg.drawpixmap(ppm); //draw on ppm ppm.writetofile("out.ppm"); //save file out.ppm file this code wrote, need these values command line input because if hard code this, user cannot select values want use. can please me how these values command line input? click little arrow next run button , select run configurations -> (x) = arguments tab , below program arguments: text box click variables button , have @ it. the next time run program, dialog box prompt argumen

php - Notice: Array to string conversion -

$land = $_post['land']; $resultxax = mysql_query("select * users land = '$land'") or die(mysql_error()); $number=mysql_num_rows($resultxax); echo $number; why error? $land value of multiselect dropdownbox. <select data-placeholder="choose country..." class="chosen-select" id="e9"multiple style="width:350px;" tabindex="4"> <?php include("../country_dropdown.php"); ?> </select> try $arrayval = join(',',$land); $resultxax = mysql_query("select * users land in ('$arrayval')") or die(mysql_error());

vb.net - Loop through DataGridView records and stop at the nearest match to my search criteria -

i have datagridview text values. user type text in textbox (txtsearch) , click button (btnsearch). want loop through values of column , stop @ first-match / closest match text in txtsearch. example: partnum desc pn10 pn10-1 pn10-13 pn12 pn12-1 pn12-2 pn12-3 pn13-1 pn15-2 pn19-1 i want when user types pn12 in search textbox loop through ordered column , stop @ first match , if user searches not on list pn14-1 stop @ closest match "pn15-2" i know how loop through rows , find exact match for each row datagridviewrow in me.dgentries.rows if row.cells.item("partnum").value = txtsearch.text exit but how find closest match. have loop through search text letter letter?? trying define 'nearest' more rigorously might nearer answer. instance, if numeric, might 9996 'nearer' 9998 9990. once have clear idea of mean nearer can calculate distance each item in col

bash - How do I use sed on a string? -

i want use sed strings in bash script without having read or write files. googled around , couldn't find anything specifically trying number of files in given directory doing somethign like: raw=$(ls $dirname | wc) # raw --> ? sed ? --> answer it's not sed , better problem. ls | wc -l in general, sed takes string input. example, ls | sed 's/\./period replaced sed/g'

Returning a PHP value to a Coldfusion page? -

i'm doing cfhttp post php page: <cfhttp method="post" url="https://www.example.com/ssl/roundpoint.php" result="mlresponse"> <cfhttpparam type="header" name="accept-encoding" value="deflate;q=0"> <cfhttpparam type="header" name="te" value="deflate;q=0"> <cfoutput> <cfif isdefined( "ppcid" )><cfhttpparam name="ppcid" type="formfield" value="#ppcid#"></cfif> <cfif isdefined( "product")><cfhttpparam name="product" type="formfield" value="#product#"></cfif> <cfif isdefined( "va_status" )><cfhttpparam name="va_status" type="formfield" value="#va_status#"></cfif> <cfif isdefined( "qs_product")><cfhttpparam name="qs_product" type="formfield" v

python - setting up numpy/scipy in idle -

i use numpy in python program creating, can not figure out how use inside of idle. download page numpy redirects 1 scipy, fine, infact download rest of scipy (especially matplotlib), isn't important me numpy, scipy download page tells larger packages, none of can figure out how use in idle. note use python 2.x series, , use other installed packages in same program such pygame, , wxpython. thank much. as the documentation linked says: you can assemble scipy stack individual packages. details of need, see the specification . ... christoph gohlke provides pre-built windows installers many python packages, including of core scipy stack. so, make list of main packages want, check specification see other dependencies you'll need install use packages, go pre-built installer page, download them, , run installers. obviously need download installers corresponding python. didn't whether you're using 64-bit or 32-bit python, , need know that. ot

jsp tags - Invalid tagdir attribute while web-fragment is used -

i using web-fragment feature maintain jsps , tags in jar, , using approach, jsp pages unable find tagdir, , cause "the value of tagdir attribute tag library invalid." here structure in jar. meta-inf -- resources     -- web-inf         -- tags             -- mytag.tag     -- mypage.jsp -- web-fragment.xml in mypage.jsp, specify taglib following: and got these errors: mypage.jsp:7:4: taglib directive must specify either "uri" or "tagdir" attribute. mypage.jsp:7:33: value of tagdir attribute tag library invalid. it seems under approach, cannot find tagdir. tried same structure in war web.xml, , able find tags. wonder if there way can use similar solution web-fragment approach. you don't need web-inf in web-fragment project. use structure instead: web-fragment project: meta-inf/ -- resources/ -- tags/ -- mytag.tag -- mypage.jsp -- web-fragment.xml everything inside resources directory avail

django - Connection Reset when port forwarding with Vagrant -

i have vagrant/virtualbox running ubuntu 12.04 lts os. have configured vagrant forward guest port 8000 host port 8888. [default] preparing network interfaces based on configuration... [default] forwarding ports... [default] -- 22 => 2222 (adapter 1) [default] -- 8000 => 8888 (adapter 1) [default] booting vm... [default] waiting vm boot. can take few minutes. [default] vm booted , ready use! when virtual machine starts up, start django dev server on port 8000. development server running @ http://127.0.0.1:8000/ quit server control-c. okay great, can put in background , can curl localhost:8000 , output server <div id="explanation"> <p> you're seeing message because have <code>debug = true</code> in django settings file , haven't configured urls. work! </p> </div> but when try hit server host machine firefox/chrome/telnet i'm getting connection reset/connection lost/err_connection_reset etc. f

ruby on rails - How to test via rspec that session variables updated in controller -

i trying write test using rspec tests if the session variable correctly changed: this part of gamescontroller want test: def change_player if session[:player] == 0 session[:player] = 1 else session[:player] = 0 end end this game_spec.rb file: require "spec_helper" describe gamescontroller describe "#change_player" "should change player 1" session[:player] = 0 :change_player assigns(session[:player]).should == 1 end end end this error message when run test: failures: 1) gamescontroller#change_player should set player 0 failure/error: session[:player] = 0 nameerror: undefined local variable or method `session' #<rspec::core::examplegroup::nested_1::nested_1:0x00000103b3b0d8> # ./spec/features/game_spec.rb:6:in `block (3 levels) in <top (required)>' finished in 0.01709 seconds 1 example, 1 failure failed examples: rspec ./spec/features/game_spec.rb:5 #

sql - How do I write a Rails ActiveRecord scope that combines rows and returns only latest date amongst three dates? -

i have rails application table this: id | parent_id | datetime_a | datetime_b | datetime_c 1 | 55 | 2013-08-03 11:00:00 | null | null 2 | 55 | null | 2013-08-04 13:01:11 | null 3 | 56 | 2013-08-02 17:33:23 | null | null 4 | 56 | null | 2013-08-01 18:00:00 | null 5 | 56 | null | null | 2013-07-12 07:45:00 i want write 3 activerecord scopes return single record per parent_id , chooses record latest datetime particular datetime_x column , narrows down rows datetime_x column filled. if particular parent_id has records more 1 datetime_x column, should return row if datetime_x narrowed latest of existing. scope datetime_a return: id | parent_id | datetime_a | datetime_b | datetime_c 3 | 56 | 2013-08-02 17:33:23 | null | null we row parent_id 56 because datetime_a latest of 3 date times. no ro

symfony - Stop SonataAdmin / Symfony2 from creating empty objects with sonata_type_admin embedded admins -

first of all, i'm not sure if sonata issue or symfony2 one, first time i'm working sf2 forms edit relationship. here's problem: i have 2 classes, let's call them old favourites: car , wheel . car has optional one-to-one relationship wheel (it's example, go it...). have set sonataadmin caradmin class embeds wheeladmin using sonata_type_admin , try create car without entering data wheel. however, on submit (somewhere in $form->bind()/$form->submit() far can trace) symfony and/or sonata instantiating wheel , trying persist (with values null ). since wheel has non-null constraints throws dbalexception complaining cannot insert wheel null vlaues. this naughty , i'd stop happening. if don't enter details wheel don't want phantom wheel menacing code , database. expect if enter no data there nothing insert/persist it's left alone. not what's happening... any ideas how tame sensible? here's long version, code blocks , everyt

Facebook Javascript API Requires IE to be in Protected Mode -

i have small webpage using facebook javascript api. why api not work in internet explorer if enable protected mode turned off zone in? getloginstatus returns unknown , fb.login displays blank window if protected mode off. have channelurl set although not seem using there no references in server logs. my web page works fine in ff, chrome, , in facebook tab works standalone page in ie if enable protected mode on. i have been using ie9 had test ie10 same results. update: reason had protected mode off because had site in intranet zone , default. have protected mode on , things work except getting permission denied errors. after page running few seconds, comes permission denied in xd_arbiter.php?version=26, line 33 character 50 if running ie9 in compatibility mode or running ie9 in browser mode ie7 (from f12 developer tools). happen "lucky" testing site in intranet zone without protected mode on plus running ie9 compatibility mode site (from previous test). though

How to put Processing in HTML page? -

is there way put processing in html page? have .pde file, , want on html web page, how that? (processing kind of graphics language.) you should able export pde file html page processing 's javascript mode . web-export folder created , containing need deployment ( index.html , processing.js , , other resource files...). you may consider take coursera course gives overview of processing can do. i've finished , it's fun , useful!

ios - Issues when testing on iPhone 5 on 4inch retina display simulator -

so released app , seemed fine. of sudden got reviews in , emails app did not function , doing weird things. turns out users using iphone 4s , 5. have iphone 4 running 6.1.3 , worked great. did testing in xcode found using iphone sim 3.5 inch screen worked perfect. if switched 4 inch retina display went crazy... button functions other screens mixed in current view. long story short... went in , fixed , ran tests using simulator. tools updated , looks good. released update itunes had issues use app. but... couple people have been speaking issues still there. not understand how since test in simulator. know how test app on version ios , if works on sim work on actual device. baffled issue. i using xcode 4.6.2 ios sdk 6.1 , app deployment target 4.3

c - Output of following code with integer, float, char variable -

this question has answer here: why isn't sizeof struct equal sum of sizeof of each member? 11 answers when run following, gives me output 20. int of 4 byte,float of 4 byte , character array of 10 byte, total 18 byte. why getting output 20 byte? #include<stdio.h> struct emp { int id; char name[10]; float f; }e1; main() { printf("\n\tsize of structure is==>%d\n",sizeof(e1)); } it address alignment . see : int 4 char 10 ==> 12 alignment float 4 like : iiii cccc cccc cc^^ <-- data pading make address alignment. ffff total 20

algorithm - How is one way hashing possible? -

i wondering, how 1 way hashing possible? how can encode string in 1 direction , not other? if reverse algorithm, can't decode md5? before, me, way possible have generate random answer instead of using algorithm. hashes same way every time. please explain me. if "reverse" algorithm, cannot original string back, because there more possible strings possible hash codes. think of algorithm has result 64-bit integers. there 2^64 = (2^8)^8 = 256^8 possible such numbers. but means, if there more 256^8 possible strings, there must 2 strings hash same value (this called the pigeonhole principle ). since there more strings @ length 9 (256^9 such strings), fact can hash value, not guarantee can "go back".

php - How to store expiration time? -

i want store expiration time in database. using below code store expiration time +1 year. $cdate = time(); $date = $cdate + 365*24*60*60; $date = date("y-m-d h:i:s",$date); but not storing correct time stores 2014-08-10 07:55:14 time on storing 2014-08-10 01:25:14 . aslo not sure or pm . thanks. time/date functions in php using timezones determine local time. if server in timezone gmt+6 means date() function return date/time 6 hours before gmt. you can check date_default_timezone_set() function manual find out how php selecting timezone. to set timezone, can use date_default_timezone_set() before calling date function or can set php.ini setting date.timezone timezone. for second part of question - when formatting time using date() function h format character return 24-hour format of hour leading zeros.

database - How to retrieve an Option[List[X]] instead of List[X] from a select statement in Play2!Scala Anorm? -

in play2 app, trying retrieve list of users 1 of database table. query responsible may potentially empty if there no row in database matching criteria (which firstname in our case). why have managed implement : db.withconnection { implicit connection => sql("""select u.* users u u.firstname '%{firstname}%' """).on("firstname" -> firstname).as(userparser *) } this query returns list[user] how can return option[list[user]] since query may not retrieve data corresponding provided param (firstname) ? any appreciated thanks... you don't need to. if no user found. list empty.

bash - Reverse order of a string -

i want "reverse" order of 4 octets (bytes) make ip address. suppose have ip: 202.168.56.32 i need convert into: 32.56.168.202 and remove first octet in reversed ip. final result: 56.168.202 my attempts: echo 202.168.56.32 | rev but it's returning : 23.65.861.202 this should trick: echo 202.168.56.32|awk -f. '{print $3"."$2"."$1}' you bash arrays: ip=202.168.56.32 parts=(${ip//./ }) echo ${parts[2]}.${parts[1]}.${parts[0]}

regex - Replacing numbers R regular-expression -

i trying code html tagging tool code in r , having difficulty finding , replace numbers colored numbers. i think following in right direction not sure do: txt <- gsub("\\<[:digit:]\\>", paste0(num.start,"\\1",num.end) , txt) this not seem job. overall, numbers not part of words identified , replaced tags before , after numbers change color , defined num.start, num.end variables. for example: num.start <- '<span style="color: #990000"><b>' num.end <- '</b></span>' so able feed in r code , have write html tags when appropriate. rcode: txt <- "a <- 3945 ; b <- 3453*3942*a" gsub("\\<[:digit:]\\>", paste0(num.start,"\\1",num.end) , txt) [1] "a <- <span style="color: #990000"><b>3945</b></span> ; b <- <span style="color: #990000"><b>3453</b></span>*<span sty

opencv - How to copy audio stream using FFMpeg API ( not a command line tool ) -

i'm developing video editing apps on android. the objective of app "editing videos on android". and... i'm completed making video file using images. but.. can't attach audio video. my method same follows. 1.videostream, audio stream creation using avformatcontext 2.movie encoding in video stream successful 3.encode codec open in audio stream successful 4.set sample format av_sample_fmt_fltp 5.sample rate , channel set same source audio 6.choose appropriate decoder , read packet 7.convert packets using swr_converter, setting same sample format 8.encode converted data 9.memory deallocation 10.end! problem here: video of created video file played. audio wasn't. it heared weird. have many noises , plays slowly. i've googled many keywords "ffmpeg command line usage". i wanna make ffmpeg api. not command line tool. please help. your question vague without kind of code go along it, trust me there lo

Linq and group by clause -

i curious x in a linq group clause: group x by ... the x can replaced 1: var query = box in c.boxes join item in c.items on box equals item.box group 1 new { boxid = box.boxid, item.itemtype.itemtypeid } g select new { g.key.boxid, g.key.itemtypeid, count = g.count() }; does have sample x (or wathever local variable chose in group ) of value? i mean var query2 = box in c.boxes group box box.boxid q select q.key; can replaced by var query2 = box in c.boxes group 1 box.boxid q select q.key; in group x by... x gets aggregated. so write var childrenbyage = child in class group getname(child) child.age; this gives grouping containing names of children each age. here simple example can test difference easily: static void main(string[] args)

html - Getting undesired space between 2 divs -

i don't understand why i'm getting undesired space, want clubs , events divs in same height under header div. practically, big space between header , clubs & events divs. the html: <!doctype html> <html> <head> <title>metzo</title> <link rel="stylesheet" type="text/css" href="index.css"> </head> <body> <div class="metzo"> <div class="header"> </div> <!-- getting huge space here in y-axis --> <div class="clubs"> hello </div> <div id="space1"> </div> <div class="events"> hello <?php //include("event.php"); //include("event.php"); //include("event.php"); ?> </div> </div> </body&g

ios - Compare two arrays and set an if else -

i need compare 2 arrays (a & b), elements of belong b need set if statement. explain me better: if (elementofarraya belong alsotoarrayb) { //do }else{ //do else } someone me? thanks nsarray has instance method called containsobject: this. for further clarification, check this out.

android - How can I simulate a listview inside a scrollview? -

i need display user comments , replies comments in hierarchical type of way child comment has slight padding left. i able listview view. listview inside scroll view , don't work obvious reasons. i need simulate listview scrollview scrollview. how can this? quoting docs you should never use scrollview listview, because listview takes care of own vertical scrolling. importantly, doing defeats of important optimizations in listview dealing large lists, since forces listview display entire list of items fill infinite container supplied scrollview. you inflate views add listview header , footer. have custom view , add footer public void addfooterview (view v) added in api level 1 add fixed view appear @ bottom of list. if addfooterview called more once, views appear in order added. views added using call can take focus if want. note: call before calling setadapter. listview can wrap supplied cursor 1 account header , footer views.

unit testing - Scoping variables in a Perl Test::More .t file -

is there way scope variables test::more tests in .t file? example: # 1st test $gotresult = $myobject->runmethod1(); $expectedresult = "value1"; is($gotresult, $expectedresult, "validate runmethod1()"); #2nd test $gotresult = $myobject->runmethod2(); $expectedresult = "value2"; is($gotresult, $expectedresult, "validate runmethod2()"); #3rd test ... i'm looking way discretely manage individual tests in .t file conflicts/errors not introduced if variable names reused between tests. sal. to expand on mirod's correct answer: may scope variables braces perl program, may take step further. test::more has concept of subtest, in define subref contains 1 or more tests run (and of course creating scope in process). subtest 'subtest description here' => sub { # setup, tests ok 1, 'the simplest test'; };

mysql - php mysqlquery with subquery and group by -

i trying fill table informations out of query getting error 500. doing wrong? for($count = 0; $count < $200; $count++) { $result = mysql_query("select jp.artnum, jp.bezeichnung, sum(jp.menge), rdatum journalpos jp, journal j j.rec_id=jp.journal_id , artnum not null , jp.journal_id in (select rec_id journal rdatum between now() - interval 1 day , now() ) group artnum limit $count , 30") or die(mysql_error()); $row = mysql_fetch_array( $result ); echo "<tr>"; echo "<td>"; echo $row['jp.artnum']; echo "</td>"; echo "<td>"; echo $row['jp.bezeichnung']; echo "</td>"; echo "<td>"; echo $row['sum(jp.menge)']; echo "</td>"; echo "<td>"; echo

iis - what are the things to change when switching from node.js to iisnode? -

i've been trying run node application on iisnode. app runs on node.js smoothly , has no problem. however, need integrate app asp.net application hence i've been trying run app on iis using iisnode! i've been facing difficulties! wondering there need changed in config or server.js file make work ? thanks ! the required change in node app port number - use process.env.port value instead of specific numeric in server.js/app.js stated in official /src/samples/express/hello.js (notice last line): var express = require('express'); var app = express.createserver(); app.get('/node/express/myapp/foo', function (req, res) { res.send('hello foo! [express sample]'); }); app.get('/node/express/myapp/bar', function (req, res) { res.send('hello bar! [express sample]'); }); app.listen(process.env.port); also make sure asp.net's web.config have sections node (taken /src/samples/express/web.config ): <configu

Getting first visible element with jQuery -

trying first visible element of list using jquery's :first , :visible pseudo-selectors, suggested here: https://stackoverflow.com/a/830611/165673 it's not working: fiddle: http://jsfiddle.net/fay9q/4/ html: <ul> <li>item a</li> <li>item b</li> <li>item c</li> </ul> <ul> <li style="display:none;">item a</li> <li>item b</li> <li>item c</li> </ul> jquery: $('li:visible:first').css('background','blue'); the first item in each list should turn blue... try using this: $('ul').find('li:visible:first').css('background','blue'); currently code getting first visible li element on page , setting background colour. code selects ul elements finds first visible li within each of them , applies style. here working: http://jsfiddle.net/fay9q/5/

php - In AJAX, do I have to init the class? -

i trying out page refresh (but think way going it, require page refresh. ultimate goal not have one. i have 2 things wrong, 1 basic html, other not understanding ajax. html issue when click link beside element: <label class="checkbox"> <input type="checkbox" name="aisis_options[package_aisis-related-posts-package-master]" value="package_aisis-related-posts-package-master" checked=""> aisis-related-posts-package-master <a href="#">(disable)</a> </label> it executes piece of js: (function($){ $(document).ready(function(){ $('a').click(function(){ var el = $(this).prev('input[type="checkbox"]'); if(el.is(':checked')){ el.prop('checked',false); } }); }); })(jquery); unchecks it, page refreshes , scrolls top. assuming there js way stop or maybe stupi

What is the difference of Ruby's Array#to_a method -

for example: a = [1,2,3,4] b = c = a.to_a a.insert(0,0) #=> [0,1,2,3,4] b #=> [0,1,2,3,4] c #=> [0,1,2,3,4] why output of array b , c same? if want copy of array a , not reference one, method should use? you can b = a.dup old post can try if there no easier way b = a.map {|x| x} it works 1.9.3-p448 :001 > = [1,2,3] => [1, 2, 3] 1.9.3-p448 :002 > b = => [1, 2, 3] 1.9.3-p448 :003 > c = a.map{|x| x} => [1, 2, 3] 1.9.3-p448 :004 > a<<0 => [1, 2, 3, 0] 1.9.3-p448 :005 > b => [1, 2, 3, 0] 1.9.3-p448 :006 > c => [1, 2, 3] but shallow copy though. according this post , a.dup easier way.

xcode - xcodebuild cannot find header in embedded projects -

i have project embed project, , xcode gui build successful, in command line xcodebuild failed such. fatal error: 'ohattributedlabel/ohattributedlabel.h' file not found #import <ohattributedlabel/ohattributedlabel.h> ^ 1 error generated. but had in project header search path (where h located) ${project_dir}/myproject/vendor/ohattributedlabel/source the problem header located in "ohattributedlabel/source" folder, while import statement looking header under ohattributedlabel folder, don't want touch embedded project directory structure, can in case? the best way modify embedded project publish header files: select embedded project in xcode select applicable target. click on build phases expand "copy headers" section , add ohattributedlabel.h file. select main project select applicable target. click on build phases. click on target dependencies. make sure embedded project added dependency. try run

How to auto increment build number in Xcode -

Image
i found many solutions , scripts on site, easiest solution increase build number in xcode is: go build phases in targets section , add run script build phase: change shell /bin/bash , insert following script: #!/bin/bash buildnumber=$(/usr/libexec/plistbuddy -c "print cfbundleversion" "$infoplist_file") buildnumber=$(($buildnumber + 1)) /usr/libexec/plistbuddy -c "set :cfbundleversion $buildnumber" "$infoplist_file" have fun! :) i found tutorial on cocoa factory

django - Why is request.session['django_language'] is being overriden by browser preferred language? -

using django, i'd users able choose site language. it working fine when user preferred language set in browser english. user can switch between english , portuguese expected. however, when change browser preferred language language switcher stops working (i tested in opera, google chrome, firefox , epiphany - couldn't test on ie or safari). i suppose did wrong, cannot figure out what. puzzles me works fine when preferred language set default... django documentation says use following choose language: first, looks django_language key in current user’s session. failing that, looks cookie. failing that, looks @ accept-language http header. header sent browser , tells server language(s) prefer, in order priority. django tries each language in header until finds 1 available translations. failing that, uses global language_code setting. why getting different behavior in language switcher when browser has preferred language when has default? my se

jquery - How to manage multiple ajax request/responses with a for loop and an array -

i trying make ajax request using loop , array in jquery mobile. i trying to: send requests. store responses. after ajax completed, perform action. here's have far doesn't work (that's why i'm here). var req1 = []; var req2 = []; var size = //some number passed here//; //create size number of unique ajax json requests (i = 0; < size; i++) { requesta[i] = // request json datatype //; requestb[i] = $.ajax(requesta[i]); }; (j = 0; j < size; j++) { requestb[j].done (function (response) { if (response[j].results.length > 0) ( requestb[j] = response[j].results; } }); $(document).ajaxstop (function() { // after ajax done // }); try lock array when in callback. something this var isloked = false; // ... if (response[j].results.length > 0 && !islocked) ( islocked = true; requestb[j] = response[j].results;

c - Is it possible to capture localhost packets (127.0.0.1 as destination) in NDIS layer? -

i developing ndis 6 filter driver of win7 , win8 winpcap , nmap. know, nmap network scanner. requirement of nmap capture localhost packets "ping 127.0.0.1", nmap can test local machine itself, too. however, seems localhost packets return in tcp/ip stack , never comes ndis layer. there way resolve issue? adding loopback adapter or what? thanks. you'll need wfp callout capture layer-3 loopback packets. tcpip has fast-path loopback never reaches layer-2 in ndis.

ruby - Difference between passing arguments to define_method and to the following block? -

i confused following code poignant guide : # guts of life force within dwemthy's array class creature # metaclass class def self.metaclass; class << self; self; end; end # advanced metaprogramming code nice, clean traits def self.traits( *arr ) return @traits if arr.empty? # 1. set accessors each variable attr_accessor( *arr ) # 2. add new class method each trait. arr.each |a| metaclass.instance_eval define_method( ) |val| @traits ||= {} @traits[a] = val end end end # 3. each monster, `initialize' method # should use default number each trait. class_eval define_method( :initialize ) self.class.traits.each |k,v| instance_variable_set("@#{k}", v) end end end end # creature attributes read-only traits :life, :strength, :charisma, :weapon end the above code used create new class, in following: class dragon &l

python - porting PyGST app to GStreamer1.0 + PyGI -

i have python audio player based on gstreamer , dbus http://sourceforge.net/p/autoradiobc/code/210/tree/trunk/autoradio/autoplayer/player_gstreamer1.py . works pygst , want port gstreamer 1. following how https://wiki.ubuntu.com/novacut/gstreamer1.0 it's going work but: file "/home/pat1/svn/autoradio/autoradio/autoplayer/player.py", line 826, in position except(gst.queryerror): file "/usr/lib64/python2.7/site-packages/gi/module.py", line 316, in __getattr__ return getattr(self._introspection_module, name) file "/usr/lib64/python2.7/site-packages/gi/module.py", line 135, in __getattr__ self.__name__, name)) attributeerror: 'gi.repository.gst' object has no attribute 'queryerror' it's in part of code: try: pos_int = self.player.query_position(gst.format.time, none)[0] except(gst.queryerror): logging.warning( "gst.queryerror in query_position" ) return none bypassing problem after : if ret == gst.state.ch

How to keep information about an app in Android? -

i want know if possible keep information app in while example. i have app access file , information choices user have made. example: i have button many events (event model), , want know if user clicked in button after application restarts. i know possible keep information login , password. possible other information? use shared preferences . so: create these methods use, or use content inside of methods whenever want: public string getprefvalue() { sharedpreferences sp = getsharedpreferences("preferencename", 0); string str = sp.getstring("mystore","thedefaultvalueifnovaluefoundofthiskey"); return str; } public void writetopref(string thepreference) { sharedpreferences.editor pref =getsharedpreferences("preferencename",0).edit(); pref.putstring("mystore", thepreference); pref.commit(); } you call them this: // when click button: writetopref("theyclickedthebutton"); if (getprefvalue().eq

java - Checking for decimal after 10 digits - substring(i,1) not working -

i have 2 problems: x.substring(i,1) breaks in try/catch because of , possibly other things, can't method work. i'm trying have when user enters decimal, increase max length of edittext , decrease max length original max length if user enters number large. boolean toobig = false; edittext txt = (edittext)findviewbyid(r.id.num1); textview display = (textview)findviewbyid(r.id.display); string x = txt.gettext().tostring(); // string in edittext string str = "didn't work"; try { if (x.contains(".")) { // set max length 15 if (x.length() >= 10) { // see if decimal contained after 10 digits (int = 10; < x.length(); i++) { str = x.subtring(i,1); // breaks here (test) if (x.substring(i,1).equals(".")) // breaks here { toobig = true; } } } if (toobig)

c++ - Vector with custom objects: crash when I want to use one received with .at method -

i have class named cconfig, i'm creating new object: std::vector< cconfig > docs; cconfig newfile( "somefile.xml", "root" ); printf("%s", newfile.gettagvalue( "servername" )); // works docs.push_back( newfile ); when i'm getting object .at method cconfig file = docs.at(0); printf("%s", file.gettagvalue( "servername" )); // crashes where's problem? (im sorry if formatting wrong don't use javascript because bandwidth ended , max speed 1kb/s i'll try fix later) cconfig.h: class cconfig { tixmldocument m_doc; tixmlelement* m_proot; bool m_bisloaded; public: cconfig ( void ) {}; cconfig ( const char * pszfilename, const char * pszrootname ); ~cconfig ( void ) {}; const char* gettagvalue ( const char * pszta

ios - How to calculate area of an organic shape? -

Image
i want know possible calculate area of organic shape. shape im trying calculate looks this: imagine drawn cgpoints is there special function this? im thinking maybe coreimage or quartz or maybe opengl. if boundary path consists of straight line segments , not intersect can use following formula compute area of enclosed region (from https://en.wikipedia.org/wiki/polygon#area_and_centroid ): cgpoint points[n]; cgfloat area = 0; (int = 0; < n; i++) { area += (points[i].x * points[(i+1) % n].y - points[(i+1) % n].x * points[i].y)/2.0; } where points[0], ... , points[n-1] starting points of line segments in counter-clockwise order. for more complicate path segments such bézier curves, can subdivide each segment small parts can approximated line segments.

java - Android AdView NoClassDefFoundError -

i'm beginner in android development. released app found glitches, thought of correcting glitches creating new android project same package name of released app. once finished update app, app not running on phone(debugging). says "unfortunately thisapp has stopped." , im trying incorporate admob time. please me because have publish asap. here's logcat once app crashes : 08-11 18:14:31.063: e/dalvikvm(15877): not find class 'com.google.ads.adview', referenced method com.gamerspitch.easybluetooth.blueactivity.initadview 08-11 18:14:31.254: e/androidruntime(15877): fatal exception: main 08-11 18:14:31.254: e/androidruntime(15877): java.lang.noclassdeffounderror: com.google.ads.adview 08-11 18:14:31.254: e/androidruntime(15877): @ com.gamerspitch.easybluetooth.blueactivity.initadview(blueactivity.java:107) 08-11 18:14:31.254: e/androidruntime(15877): @ com.gamerspitch.easybluetooth.blueactivity.oncreate(blueactivity.java:40) 08-11 18:14:31.254: e/an

c# - Using WPF validation -

i have dialog in project user enters values in , when hits ok add item database. using entity framework , adding database code this: transactionitem _item = new transactionitem(); _item.doctorid = (int)cmbdoctor.selectedvalue; _item.transactioncategoryid = (int)_dlg.cmbcat.selectedvalue; _item.transactionmethodid = (int)_dlg.cmbmethod.selectedvalue; _item.amount = int.parse(_dlg.txtamount.text); _item.documentid = _dlg.txtdocnum.text; _item.info = _dlg.txtinfo.text; _item.date = _dlg.dtedate.selecteddate.tostring(); _db.transactionitems.add(_item); _db.savechanges(); but problem there nothing bind , enable validating. have tried making empty object in window , bind text box it, had own problems , didn't work expected. want when users enter values or when hits ok, check if of fields valid (for example 1 of problems if user didn't

c# - Sorting from earliest to latest date -

how loop every month's first date. public struct stat{ public datetime date; } i have list<stat> have date property. want lowest , newest 1 sorting. first element older , last newer one. i can got first , second order by. what want 1st date of every month in between of both first (oldest ) , newest. string ret = ""; list<datetime> dates = new list<datetime>(); int breaker = datetime.daysinmonth(datetime.now.year, datetime.now.month); stats = stats.orderby(x => x.date).tolist(); datetime old = stats.first().date; datetime @new = stats.last().date; int diffdays = @new.subtract(old).days; datetime loopd = datetime.now; (int = 0; < diffdays; = + breaker) { loopd = loopd.adddays(-breaker); dates.add(loopd); if (loopd < old) console.writeline("date" + old); } (int j = 0; j < dates.count; j++) { if (j == 0) {

joomla3.0 - New user comes disabled but activated -

new installation of joomla! 3. user registration gives me problem cannot figure out how solve: new users got registered , activated not enabled when trying login error messages "login denied! account has been blocked" comes up. checking on shows activated not enabled. i using setting enable user register , use account right away without email confirmation. the setting in user management module are: allow user registration:yes; new user registration group:registered; new user account activation:none; notification mail administrators:none; please specify other component using current site. might plugin disable user while creating new user, try disable user plugin 1 one , check works or not

javascript - Google API Sample not Loading -

i'm trying use sample code from: https://developers.google.com/youtube/analytics/v1/sample-application however, when open html file won't load. firebug says "google not defined" , references line 17 of index.js file, is: google.load('visualization', '1.0', {'packages': ['corechart']}); this leads me believe isn't loading or isn't finished loading time index.js is. read other similar posts talked forcing browser wait scripts load before moving on, i'm novice understand talking about. since i'm copying sample code 3 files (index.html, index.js, index.css) (although add in oauth key in index.js) i'm hoping able replicate , see mean. you need import google jsapi before attempt load visualisation package. make sure following line appears in document: <script type="text/javascript" src="https://www.google.com/jsapi"></script> if copy paste entire contents of the o

ruby - Creating Hash of Hash from an Array of Array -

i have array: values = [["branding", "color", "blue"], ["cust_info", "customer_code", "some_customer"], ["branding", "text", "custom text"]] i having trouble tranforming hash follow: { "branding" => {"color"=>"blue", "text"=>"custom text"}, "cust_info" => {"customer_code"=>"some customer"} } you can use default hash values create more legible inject: h = hash.new {|hsh, key| hsh[key] = {}} values.each {|a, b, c| h[a][b] = c} obviously, should replace h , a, b, c variables domain terms. bonus: if find needing go n levels deep, check out autovivification: fun = hash.new { |h,k| h[k] = hash.new(&h.default_proc) } fun[:a][:b][:c][:d] = :e # fun == {:a=>{:b=>{:c=>{:d=>:e}}}} or overly-clever one-liner using each_with_object : silly = valu

Changing an Activity in Android -

i'm learning android here, , java honest. i'm trying switch different activity via button click, however, keeps crashing. crashes when click button , go make switch. can please me figure i'm going wrong? first activity: package com.example.killacatoe; import android.os.bundle; import android.app.activity; import android.view.*; import android.widget.*; import android.content.*; public class tictactoe extends activity {//start tictacttoe class //constants //variables button mainbutton; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_tic_tac_toe); mainbutton = (button) findviewbyid(r.id.bplaynow); mainbutton.setonclicklistener(new view.onclicklistener(){ public void onclick(view v) { // todo auto-generated method stub intent = new intent(getapplicationcontext(), playermenu.class); startactivity(i); } }); }