Posts

Showing posts from February, 2010

python - How do you find which value occurs the most in a dictionary? -

in dictionary keys , list of values, how find value in lists of values frequently? i'm assuming use loops , append lists unsure of how so. want print value occurring frequently? thank you! please keep in mind i'm new programming , not familiar lambda or other complicated ways solve this. one way use collections.counter from collections import counter >>> d = {'a': 5, 'b': 3, 'c': 5, 'd': 1, 'e': 5} >>> c = counter(d.values()) >>> c [(5, 3), (1, 1), (3, 1)] >>> c.most_common()[0] (5, 3) # value, , number of appearances

symfony - Duplicate index on sqlite, not on mysql -

i have entity definition works on dev , production envs (mysql), not on test (sqlite): /** * invoice * * @orm\table(name="invoice", indexes={ * @orm\index(name="ref_idx", columns={"ref"}), * @orm\index(name="created_at_idx", columns={"created_at"}), * @orm\index(name="paid_idx", columns={"paid"}), * @orm\index(name="is_valid_idx", columns={"is_valid"}), * @orm\index(name="canceled_idx", columns={"canceled"}) * }) * @orm\entity(repositoryclass="appbundle\repository\invoicerepository") */ class invoice // [...] when run doctrine:schema:create or doctrine:schema:update --force on test env, have following error: [doctrine\dbal\dbalexception] exception occurred while executing 'create index created_at_idx on invoice (created_at)': sqlstate[hy000]: gener

angularjs - $compile not compiling templates in Karma/Jasmine -

i have tested both phantomjs , chrome. following this question i'm trying access generated html code in unit tests karma: it('should something', inject(function ($rootscope, $templatecache, $compile) { var scope = $rootscope.$new(); scope.$digest(); var template = $templatecache.get('/app/views/mytemplate.html'); var compiler = $compile(template); var compiledtemplate = compiler(scope); console.log(compiledtemplate); })); what i've found template being fetched correctly, , corresponds raw html file on computer. compiledtemplate never compiled correctly; basically, angular removing ng-tagged divs , replacing them comments, regardless of values should be. for example, <ol ng-repeat = "foo in foos"> <li>foo</li> </ol> will replaced with: <!-- ngrepeat: foo in foos --> even if set scope.foos array in unit test. have tried adding waitsfor , settimeout methods force karma wait 8 seconds, , st

php - symfony2 form, collection of objects, issue updating existing object property -

the form consists of 1 question has several answers, answers can dynamically created each question. stuff works fine: public function buildform(formbuilderinterface $builder, array $options) { $builder ->add('question','textarea') ->add('answers', 'collection', array( 'type'=>new answertype(), 'allow_add'=>true, 'allow_delete'=>true, 'label' => false )) ; } here form code answertype: $builder ->add('answer','text', array( 'attr'=>array( 'class'=>'form-control' ), 'label'=>false )) ->add('isgoodanswer', 'checkbox', array( 'label'=>'good?', 'required'=>false )) ; i using prototype template popula

ruby on rails - How to tell if GIF is animated? -

i have rails app paperclip image uploads -- how check if image animated gif rmagick? you can count scenes associated image. in rmagick means doing this: image = magick::imagelist.new(image_file) if image.scene == 0 #this not animated gif else #this animated gif end

How to check if a non binary tree is a subtree of another -

Image
i'm working trees , need know how check if if non binary tree subtree of another. these trees have n nodes , n levels, , children's order not important. know if tree subtree of another the problem me how recursion , compare both tree @ same time recursion. for create exemple demonstrate want do. i know roots of both tree , i;m trying in ruby on rails, know justa want know pseudo code or logic. someone can me? thanks i try use ideas hash tree or merkle tree : a hash tree or merkle tree tree in every non-leaf node labelled hash of labels of children nodes. hash trees useful because allow efficient , secure verification of contents of large data structures. see hashing tree structure

404 in Chrome, not IE, using asp.net bundles -

the issue when bundles minified , @ network tab in chrome see 404 url : http://localhost:57000/bundles/underscore-min.map no such directory exists. if remove reference underscore.js in bundle 404 url : http://localhost:57000/bundles/angular-sanitize.min.js.map this doesn't happen in ie. i've moved order around , there 1 file, , one, generate 404. here's bundles generate issue. bundles.add(new scriptbundle("~/bundles/scripts") .include("~/scripts/angular/angular.js") .include("~/scripts/angular/angular-resource.js") .include("~/scripts/angular/angular-route.js") .include("~/scripts/angular/angular-animate.js") .include("~/scripts/angular/angular-touch.js") .include("~/scripts/angular/angular-sanitize.js")

r - Assigning to a dynamically created vector -

how assign dynamically created vector? master<-c("bob","ed","frank") d<-seq(1:10) (i in 1:length(master)){ assign(master[i], d ) } eval(parse(text=master[2]))[2] # can access data # how can assign returns error ####################### eval(parse(text=master[2]))[2]<- 900 ok. i'll post code because asked to: > eval(parse(text=paste0( master[2], "[2]<- 900" ) ) ) > ed [1] 1 900 3 4 5 6 7 8 9 10 it's considered bad practice use such method. need build expression" ed[2] < 100 . using paste0 lets evaluate master[2] 'ed' concatenated rest of characters before passing parse convert language object. more in keeping considered better practice: master<-c("bob","ed","frank") d<-seq(1:10) mlist <- setnames( lapply(seq_along(master), function(x) {d} ), master) so changing second value of second item <- : > mlist[[2]][

html - How to scale jumbotron bootstrap on larger monitors? -

i have website uses jumbotron feature bootstrap taken codecademy "how make website" tutorial. in it, uses following html: <div class="jumbotron"> <div class="container"> <h1>heading</h1> <p>tagline</p> <a href="#about"><button type="button" class="btn btn-lg btn-danger">learn more</button></a> <!--<a href="#">learn more</a>--> </div> </div> and following css: .jumbotron { background-image:url("flight.jpg"); height: 500px; background-repeat: no-repeat; background-size: cover; margin-bottom:0px; } .jumbotron .container { position: relative; top:100px; } .jumbotron h1 { color: #cc0000; font-size: 48px; font-family: 'shift', sans-serif; text-shadow:none; } .jumbotron p { font-size: 20px; color: #cc0000;

javascript - d3.js area chart - json data not binding to chart -

i'm stumped trying json data render. thank suggestions below made progress trying solutions not quite there yet. thank you. jsfiddle: http://jsfiddle.net/tommy6s/9dv55t4q/ d3.json("http://www.corsproxy.com/dvl.thomascooper.com/data/kruggerrand.json", function(error, data) { ...fiddle data...} the variable type undefined. it's not necessary. you might want think twice posting auth_token on public web site stackoverflow or jsfiddle.

python - PyQt QApplication.aboutToQuit() -

i'm trying catch global quit signal application class subclasses qapplication. here how attempt set in main. def cleanup(): os.system('rosnode kill -a') sys.exit(0) ## start qt event loop if __name__ == '__main__': app = application(sys.argv) app.abouttoquit.connect(cleanup) app.exec_() the issue doesn't seem catch signal have apparently connected. edit i'm using pyqtgraph, preferably there way catch global window closes? # main application class application(qtgui.qapplication): def __init__(self, args): qtgui.qapplication.__init__(self, args) self.plot = pg.plot(title="uwb") self.raw_signal = self.plot.plot() self.filtered_signal = self.plot.plot() # start main loop self.listen() you can override close event when qmainwindow closed. might useful depending on use case. # override exit event def closeevent(self, event): cleanup() # close win

ruby - will_paginate gem rendering each entry 4 times rails -

i using will_paginate rails 4 , have following code in users controller: def index @users = user.paginate(page: params[:page], :per_page => 10) end and in view: <% provide(:title, 'all users') %> <h1>all users</h1> <%= will_paginate %> <ul class="users"> <% @users.each |user| %> <%= render @users %> <% end %> </ul> <%= will_paginate %> this renders users there 40 per page, not 10. each page has correct users 4 times. example renders users 1 .. 10 1 .. 10 again , on. there 101 users , if set per page limit 1 renders 101 pages 1 user on each page should limit > 1 , breaks. any insight on how fix 10 users appear on each page appreciated. i found mistake. need render @users once. hope works on side. :) <ul class="users"> <%= render @users %> </ul> also need render pagination following code <%= will_paginate @users %>

email - Rails mailer smtp configuration with gmail -

so having trouble setting rails application(openproject, if makes difference). when try send test mail in openproject settings displays message in e-mail sent don’t ever receive @ address. config/configuration.yml production: delivery_method: :smtp smtp_settings: tls: true address: "smtp.gmail.com" port: '587' domain: "smtp.gmail.com" authentication: :plain user_name: "your_email@gmail.com" password: "your_password" development: delivery_method: :smtp smtp_settings: tls: true address: "smtp.gmail.com" port: '587' domain: "smtp.gmail.com" authentication: :plain user_name: "your_email@gmail.com" password: "your_password" test: delivery_method: :test if use: telnet smtp.gmail.com 587 trying 64.233.171.108... connected gmail-smtp-msa.l.google.com. escape character '^]'. 220 mx.google.com esmtp r1sm2094806qam

commenting - Changing block comment styles in Xcode? -

i want have comments work in traditional way in c in apple's xcode. have installed vvdocumentor , how default way comments is, i.e.: /* * comments go here */ /* * multiple * lined * comment */ i hoped able use ccomment , me that, just /* comments go here */ /* multiple lined comment*/ which ugly. vvdocumentor doesn't either because if 1 hits enter result is /* * multiple * lined * comment new comment here */ which unhelpful. i'd modify xcode such behavior of hitting enter takes this. /* * multiple * lined * comment */ to this /* * multiple * line * comment * new comment line here */ i'm aware can block comment, selecting text , pressing ⌘ + /, doesn't achieve i'm looking for, , more importantly when i'm commenting must press again every time press enter. i'm sure else looking since it's pretty common style google-fu has failed far.

Rails 4.2.0 beta4 - Haml with no output -

i have installed haml gem in rails app (v4.2.0 beta4) doesn't seem compile output. i have included gem in gemfile , ran bundle install , made sure changed html.erb files html.haml this 1 of template , see heading "new recipe" . %h1 new recipe = render 'form' = link_to 'back', recipes_path and nothing gets displayed form partial. i've come across similar issue , solution issue making controller inherit applicationcontroller rather actioncontroller . i wonder if need make working. have thought installing haml gem have handled needed working. in gemfile , put gem "haml-rails" and of course bundle install this gem need integrate haml rails app, provides wrappers needed able use ruby logic in haml views. using haml alone not sufficient haml framework independent.

java - The `If statement ` in JGrasp -

how change code.... if (youranswer = numberone + numbertwo) { system.out.println("that correct!"); counter = counter + 1; } else { system.out.println("that incorrect!"); } this not seem working me. can me?. debugger saying: randomnumbersprogramthree.java:21: error: incompatible types: int cannot converted boolean". you cannot associate number boolean value. boolean true or false, not number, can create variable indicates if number represents true or false. entire program? see "youranswer", "numberone", , "numbertwo" stored. write pseudo-program explain theory. import java.util.*; public class exampleprogram { public static void main(string[] args) { system.out.println("please enter 2 numbers"); scanner answer = new scanner (system.in); int youranswer = answer.nextint(); int numberone = 1; int numbertwo = 2; if (youranswer == (numberone +

iphone - How to embed a video in a container in iOS? -

i make container in view controller. container normal ui view controller. i want video (in m4v or mp4 format) play in infinite loop. not want want video have controls , not want video present full screen, size of container. mean video should played modal in container view controller? i tried doing this, video nor container not show up. have tried looking question , did not help: embed video in view controller ios or how should embed animation instead plays in infinite loop.

sql - Oracle : specify a larger or smaller in date data type -

i have table with: two columns : date_1 , date_2 data type date (dd-mm-yyyy) database oracle i want know whether date_1 greater or smaller date_2 . my script: decode (to_char(date_1,'yyyyddmm') > to_char(date_2,'yyyyddmm'), 'greater','smaller') status cmiiw as datatype of both date not need convert date char. select case when date_1 > date_2 'date_1 greater' when date_1 = date_2 'date_1 equal date_2' else 'date_1 smaller' end

xml - XPath for anchor in sibling TD -

i tying work out xpath select tag in 2nd sibling td 1 matches "paypal sale". there many such rows on table wanting first match. here's html <tr> <td class="ref">paypal sale</td> <td class="icon">...</td> <td class="from"><a class="nav" href="http://google.com">click here</a></td> </tr> ... <tr> <td class="ref">paypal sale</td> <td class="icon">...</td> <td class="from"><a class="nav" href="http://google.com">click here</a></td> </tr> so far have not working: //tr[td=\'paypal sale\'][1]/following-sibling::td[2]/a try this: //tr/td[. = 'paypal sale']/following-sibling::td[2]/a

c# - Web API 2 default routing scheme -

this question pops in mind. in startup.cs have: httpconfiguration config = new httpconfiguration(); config.maphttpattributeroutes(); app.usewebapi(config); when have method one: [routeprefix("api/order")] public class ordercontroller : apicontroller { // don't use attribute here public ihttpactionresult helloworld() { ... return ok(); } } is possible access helloworld() ? should get or post or whatever action sent? you can access httpworld() using if rename method as: gethelloworld() . same post renaming posthelloworld() . but prefer using [httpget] , [httppost] , ... attributes, if action methods has "get" or "post" characters in name, avoid possible errors. updated after making tests, realised comments not possible call helloworld not correct. indeed possible call helloworld() method if make post call http://<yourprojecturl>/order . so, default method post and, haven't

c++ - Exclude "README.md" from doxygen's "File documentation" list -

i struggling following problem. use doxygen document c++ code, , use readme.md document main page of code documentation, via input += readme.md use_mdfile_as_mainpage = readme.md in doyxgen configuration file. works, except file readme.md appears in "file documentation" section of generated .pdf out of refman.tex file (it doesn't appear in "file list" section), like 8.24 /users/username/qpp/readme.md file reference . . . . . . 123 this extremely annoying, don't want file appear in file list. there way remove it? cannot add exclude = list, if do, won't used anymore generate main page. as of today, still haven't found elegant solution. can in case don't want readme.md appear in file reference section inside .pdf manually comment line %\input{_r_e_a_d_m_e_8md} in generated refman.tex file, , after compile .tex file produce final .pdf latexmk -pdf refman.tex the issue not appear in html generated documentation, in

java - Outputing duplicate values in 2 arraylists -

hey guys i'm kind of @ cross roads here, have 2 different arraylists of different lengths , different values. i'm trying find common values between 2 , output output text file name "output.txt". know both of arraylist filled values other textfiles, code have right not generating empty output textfile , can't figure out why program isn't outputing duplicate values textfile "output.txt" heres code i'm using right now: public static void duplciates(){ //compares 2 arraylists dictionary , phonewords , adds duplicates duplicates arraylist for(string term: dictionary){ if(phonewords.contains(term)){ duplicates.add(term); } } } public static void openoutputfile (){ try{ writer = new filewriter("e:\\output.txt"); } catch(exception e){ system.out.println("you have error"); } } public static void writearr

javascript - jQuery Multi Select Option - Check if a option is selected or not -

i have html multi select box <form action="form_action.php" method="post"> <select name="cars[]" multiple id="select_id"> <option value="all" id="option_id">all</option> <option value="volvo">volvo</option> <option value="saab">saab</option> <option value="opel">opel</option> <option value="audi">audi</option> </select> <input type="submit"> </form> what trying check if option "all" selected or not in jquery. what have tried <script> $(document).ready(function() { $('#option_id') .click( function() { if ($("#select_id option[value='all']").length == 0) { //value not exist add //do if

database - relationship type,degree, cardinality, optionality terms confusion -

i studying database i've seen degree , cardinality uses same term, or in other degree defined no. of entities involved in relationship , further catogories unary, binary , trenary. some placed degree defined degree of relationship type concerns number of entities within each entity type can linked given relationship type. cardinality minimum , maximun number of entity occurrence associated 1 occurrence of related entity cardinality types 1 1 , 1 many , many many . or min , max cardinality. min degree optionality , maximum degree cardinalty. what difference between degree , cardinaltiy ? in context cardinality number of rows in table , degree number of columns. so i'm suppose write if question asked "define cardinality ?". can explain ? ok here explanation 1.degree. number of entities involved in relationship , 2 (binary relationship) unary , higher degree relationships can exists. 2.cardinality. specifies number of each entity invo

When i am generating pdf form I want to add form number on top left of the pdf using itext java -

hi when generating form using java itext want add form number on top left of document above header.please let me know ways it. pdfptable table = new pdfptable(3); // 3 columns. table.setwidthpercentage(100); pdfpcell cell1 = new pdfpcell(new paragraph("cell 1")); pdfpcell cell2 = new pdfpcell(new paragraph("cell 2")); pdfpcell cell3 = new pdfpcell(new paragraph("cell 3")); cell1.setborder(0); cell2.setborder(0); cell3.setborder(0); table.addcell(cell1); table.addcell(cell2); table.addcell(cell3); how can set table alignment start of page margin. your question confusing. creating form, when form, don't seem referring interactive form, ordinary pdf containing table. you want add number above header , not telling mean header . assuming people reading question can read mind. i guess want use page event add string in top left corner of each page. make question duplicate of itextsharp: how generate report dynamic header in pdf using it

TimeOut Exception while doRpcCall-Importing contacts in TeleGram java API -

i trying add , import contact sending message getting time out exception every time. correct me if wrong. code: tlinputcontact tlic=new tlinputcontact(1, phno, fname, lname); tlvector contacts = new tlvector<>(); contacts.add(tlic); tlrequestcontactsimportcontacts importcontacts = new tlrequestcontactsimportcontacts(contacts, true); tlimportedcontacts importedcontacts = api.dorpccall(importcontacts); tlabsuser recipient=importedcontacts.getusers().get(0); tlinputpeercontact peer = new tlinputpeercontact(recipient.getid()); tlrequestmessagessendmessage sendmessagerequest = new tlrequestmessagessendmessage(peer, "test", rnd.nextint()); tlabssentmessage sentmessage = api.dorpccall(sendmessagerequest); log:: telegramapi#1001:timeout iteration actordispatcher:dispatching action: schedule scheduller actordispatcher:dispatching action: schedule scheduller telegramapi#1001:timeout iteration telegramapi#1001:rpc #3: timeout (15001 ms) exception

How to set params for libvirt python api setBlockIoTune? -

i need set kvm virtual machine's disk iotune using python libvirt. after searching, found method "setblockiotune" @ libvirt.py, call c api virdomainsetblockiotune, int virdomainsetinterfaceparameters (virdomainptr domain, const char * device, virtypedparameterptr params, int nparams, unsigned int flags) here problem, can't find how set value "virtypedparameterptr params" in in python livirt. doc does't talk it. please me, thanks!! orz i call libvirt python api "blockiotune(dev)" result, modify pass setblockiotune. result of blockiotune(dev): {'write_bytes_sec': 0l, 'total_iops_sec': 0l, 'read_iops_sec': 0l, 'read_bytes_sec': 0l, 'write_iops_sec': 0l, 'total_bytes_sec': 0l} hope :)

ios - Getting only those Facebook events which haven't expired graph api -

i trying facebook events haven't expired yet(upcoming events). when use following query events including have expired long ago. fbrequestconnection startwithgraphpath:@"/me/events" parameters:nil httpmethod:@"get" you can make use of since parameter described in https://developers.facebook.com/docs/graph-api/reference/v2.2/user/events/#read https://developers.facebook.com/docs/graph-api/using-graph-api#paging if set timestamp current time, should see future events: /me/events?since=1417508443

android - Making my layout better looking -

Image
i looking design, , feel suggestions based on have - ugly: http://screencast.com/t/mjhawfefnbrb it listview such: * <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" > <textview android:id="@+id/textview1" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margintop="10dp" android:text="@string/news_name_placeholder" android:layout_weight="3" style="?android:attr/listseparatortextviewstyle" android:textappearance="?android:attr/textappearancemedium" /> <textview android:id="@+id/textview2" android:layout_width="0dp" android:layout_margintop="10dp" android:layout_height="match_parent"

Trouble understanding Javascript nested function/closure -

i'm attempting port following javascript code ruby: https://github.com/iguigova/snippets_js/blob/master/pokerin4hours/pokerin4hours.js i think have of sorted, function giving me grief is: var kickers = function(idx){ // http://en.wikipedia.org/wiki/kicker_(poker) idx = idx || -15; var notplayed = math.max(input.length - 1/*player input*/ - 5, 0); return function(all, cardinality, rank) { return (all || 0) + (((cardinality == 1) && (notplayed-- <= 0)) ? rank * math.pow(10, ++idx) : 0); }; }(); and called further down so: k = kickers(k, cardsofrank[i], i); i wondering if explain how works in javascript. fact inner function has 3 parameters , outer has 1 confusing, given called 3 parameters. understand it's trying accomplish, can port code confidence. var kickers = function(idx){ var xyz;//below function in return statement can access , argument idx return function(...) {//this ensures kickers infact funct

javascript - put a spinner while $http.get fetches data from RESTful API in agular js -

i fetching data function in controller: var fetchstoreitems = function () { return $http.get('/enterprises/_store').then(function (response) { $scope.items = response.data; }, function (errresponse) { console.error("error while fetching data") }) }; it working fine , fast enough. if there lots of items fetch?! want put spinner while data being fetched. how can this? in controller, var fetchstoreitems = function () { $scope.loading = true; //define `$scope` variable; show loading image when ajax starts return $http.get('/enterprises/_store').then(function (response) { $scope.items = response.data; $scope.loading = false; //hide loading image when ajax completes }, function (errresponse) { console.error("error while fetching data"); $scope.loading = false; //hide loading image when ajax error }) }; <img src="pathtoloadingima

apache - Error in remote streaming pdf files to Solr -

i trying stream remote files solr indexing using stream.url parameter as curl 'http://localhost:8983/solr/update/csv?stream.url=http://www.artofproblemsolving.com/resources/papers/satont.pdf&stream.contenttype=application/pdf;charset=utf-8' following solution here remote streaming solr . however, solr server throws error <?xml version="1.0" encoding="utf-8"?> <response> <lst name="responseheader"> <int name="status">400</int> <int name="qtime">518</int> </lst> <lst name="error"> <str name="msg">document missing mandatory uniquekey field: id</str><int name="code">400</int> </lst> </response> i tried looking in solr documentation , wiki pages couldn't find single example. appreciated. update here schema.xml file - http://pastebin.com/akmrud9n the problem there 1 field, i.e., id r

mongodb - How to find out key-value which matches to given value for a week using mongo? -

i have following collection structure - [{ "runtime":1417510501850, "vms":[{ "name":"a", "state":"on", },{ "name":"b", "state":"off", }] }, { "runtime":1417510484000, "vms":[{ "name":"a", "state":"on", }, { "name":"b", "state":"off", }] },{ "runtime":1417510184000, "vms":[{ "name":"a", "state":"off", }, { "name":"b", "state":"off", }] },{ "runtime":1417509884000, "vms":[{ "name":"a", "state":"on", }, { "name":"b", "state":"off", }] },{ "runtime":1416905084000, "vms":[{ "name":"

c - Which encryption protocol does Firebase use? -

i'm pretty new firebase. right want modify firebase using embedded client i'm developing in c. encryption i'm using cyassl. the question is, encryption protocol firebase use? format of messages firebase expecting me? i'm developing c embedded client firebase. i'm using cyassl. have succeeded connecting cyassl 3.3.0 aes or des3 cypher. when aes , des3 both disabled (no_des3 , no_aes defined in cyassl\ctaocrypt\settings.h) connection fails. maybe have better answer, asked 7 months ago. comment question still haven't got 50 reputation. regards

c - android internal socket connection fails with a daemon service -

i've gstreamer decoder application written in 'c' decodes h264 frame in android. want camera service communicate application. this, i've used sockets (dgram). creating unix pf_inet socket path "/data/cam_file". now issue is, if run gstreamer application command line (adb shell), able connect camera service , exchange data, if make gstreamer application daemon service (with late_start option), socket connection fails. fails if fork gstreamer application using processbuilder() camera app source. clues? this issue solved. issue permissions of native service. set user 'root' due other services not able connect in init..rc. if set user 'system' other services able connect. remember add 'system' in 'group' settings of service connecting native service. hope beginners.

objective c - iOS - Get File Size of Image Selected From Photo Reel -

i'm building app allows users select photos , videos device , upload them server. trying file size (in bytes) of each item select, can me out? if ([dict objectforkey:uiimagepickercontrollermediatype] == alassettypephoto){ // image file if ([dict objectforkey:uiimagepickercontrolleroriginalimage]){ nsurl* urlpath=[dict objectforkey:@"uiimagepickercontrollerreferenceurl"]; item = [bundleitem itemwithpath:urlpath anddescription:nil]; item.itemimage = [dict objectforkeyedsubscript:uiimagepickercontrolleroriginalimage]; item.itemtype = 1; // image item.itemsize = // need here?? [m_items addobject:item]; } } else if ([dict objectforkey:uiimagepickercontrollermediatype] == alassettypevideo){ // video file if ([dict objectforkey:uiimagepickercontrolleroriginalimage]){ nsurl* urlpath=[dict objectforkey:@"uiimagepickercontrollerreferenceurl"];

php - How would i convert a comma seperated list to a square bracket array -

i have variable $csv = '3,6,7,8'; need convert square bracketed array of form $csv_array = [3,6,7,8]; if explode csv $new_array=explode(",",$csv); ,it not give me array want. this running example http://3v4l.org/kyc0g the code $csv = '3,6,7,8'; $new_csv = '['.$csv.']'; if(is_array($new_csv)){ echo 'true'; } else{ echo 'false'; //this false } echo '<br/>'; $new_array=explode(",",$csv); print_r($new_array); //not looking echo '<br/>'; print_r($new_csv); echo '<br/>'; echo $new_csv; as stated fellow stacker richardbernards - 2 'types' of array same in php. if looking json an example of using json achieve require: to encode : $csv = '3,6,7,8'; $array = explode(",", $csv); $json = json_encode($array); echo $json; to decode $csv normal array provided it: $decoded = json_decode($json, true); var_dump($decoded)

python 2.7 - I want to know how capture RAW data packets in a Queue using Iptables or Nftables -

my doubt want captire raw data packets, can use them built firewall. following script prints short description of each packet before accepting it. netfilterqueue import netfilterqueue def print_and_accept(pkt): print pkt pkt.accept() nfqueue = netfilterqueue() nfqueue.bind(1, print_and_accept) try: nfqueue.run() except keyboardinterrupt: print to send packets destined lan script, type like: iptables -i input -d 192.168.0.0/24 -j nfqueue --queue-num 1 according comment, raw packet mean layer 2. iptables works @ layer 3, need use ebtables instead.

javascript - Convert date in YYYY/MM/DD format in MomentJS -

i using momentjs converting date format. i have date in format 2010/12/01 , want convert 01/12/2010 using momentjs only. i have date in format "12/02/2014" , want convert in "2014/12/02" <!--begin snippet: js hide: false console: true babel: false--> <!--language: lang-js--> var date = moment(new date(2010/12/01)).format("mmm h/mm"); console.log(date); <!--language: lang-html--> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script> <!--end snippet--> how convert them using momentjs you can try this: moment('2010/12/01', 'yyyy/mm/dd').format('dd/mm/yyyy')

javascript - Event binding on dynamically created elements? -

i have bit of code looping through select boxes on page , binding .hover event them bit of twiddling width on mouse on/off . this happens on page ready , works fine. the problem have select boxes add via ajax or dom after initial loop won't have event bound. i have found plugin ( jquery live query plugin ), before add 5k pages plugin, want see if knows way this, either jquery directly or option. as of jquery 1.7 should use jquery.fn.on : $(staticancestors).on(eventname, dynamicchild, function() {}); prior this , recommended approach use live() : $(selector).live( eventname, function(){} ); however, live() deprecated in 1.7 in favour of on() , , removed in 1.9. live() signature: $(selector).live( eventname, function(){} ); ... can replaced following on() signature: $(document).on( eventname, selector, function(){} ); for example, if page dynamically creating elements class name dosomething bind event parent exists, document . $(document

.net - How to use Resource File for html parameters? -

in project using resource files , calling resource file following syntax: @httpcontext.getglobalresourceobject(customersresource, "t_gobackcustomer") where customersresource resource file name , t_gobackcustomer key name. value of key "go previous page". whole value rendering labels , other places without problem. but when use <a title=@httpcontext.getglobalresourceobject(customersresource, "t_gobackcustomer")> first word coming title. i.e while pressing f12 can see `<a title="go" previous page></a>' only "go" coming title. words after space not considered title. same case placeholder. can mistake doing here? i have found solution problem. have use following syntax words spaces. <a title='@httpcontext.getglobalresourceobject(customersresource, "t_gobackcustomer")'> the single quotes did magic. labels , controls no need use single quotes. wh

android - NullPointException in drag and drop of ImageView -

i want move image 1 place another. now image held imageview , drawing drag , drop ondraglistener return null point exception , application got crash there other way implement drag , drop , solution problem. here main activity code: @override public void oncreate(bundle savedinstancestate) { setcontentview(r.layout.activity_main); ima = (imageview)findviewbyid(r.id.iv_logo); ima.settag(imageview_tag); ima.setonlongclicklistener(new view.onlongclicklistener() { @override public boolean onlongclick(view v) { clipdata.item item = new clipdata.item((charsequence)v.gettag()); string[] mimetypes = {clipdescription.mimetype_text_plain}; clipdata dragdata = new clipdata(v.gettag().tostring(), mimetypes, item); // instantiates drag shadow builder. view.dragshadowbuilder myshadow = new dragshadowbuilder(ima); // starts drag v.startdrag(dragdata,

linux kernel - Process Hung due to scheduler time-out in Multi-Core system -

we have isr can executed on of available cores , may result success or failure condition based on whether core busy or free.in handler, queue work on work queues per core using queue_work_on() function.for each core, queue_work_on() function called , based on return values of queue_work_on(), how can pass isr return values irq_handled, irq_none how handle when 1 of queue_work_on function fails , how return isr value. hope provided enough context view on it. edit: scenario more like: have e.g. 1024 queues consumed multiple processes performing offload function host driver. after submitting offload, process gets blocked wait_for_completion() call , ideally should awaken completion notification. in driver offloaded rings enqueued , based on offload success, isr notifies worker threads dequeue rings jobs , trigger completion event. see more no of completion event waiting processes resulting in process hung task_uniterruptible state resulting in scheduler timeout. need pointer

font of downloaded project not recognized by android adt -

Image
i have downladed demo project research of project adt not recocnizing fonts of comments in downladed project.i can't read comments.is there way make these comments redable? as there parts readable (accesstoken , userinfo) bet, these comments in language not use "normal" letters a-z. using of classnames in code snipped found this github repo looking @ files there let see these comments written in chinese or that. to setup eclipse show correct text can change font under window -> preferences -> general -> appearance -> colors , fonts . text still chinese. if don't understand chinese, wouldn't much. ;)

c++ - How can I find a box that encompasses all given boxes? -

i have sequence of boost geometry box types , wish find dimensions of box encompasses of objects. i've noticed boost geometry provides encompass function, seems i'm asking general geometry concepts, don't know how sequence of boxes. basically i've had roll own, wondering if possible turn sequence of boxes "geometry" can apply envelope function. here's i've written: // elsewhere in code: using location = boost::geometry::model::d2::point_xy<double>; using box = boost::geometry::model::box<location>; // calculate smallest box encompasses provided boxes template <template <typename...> class iterablecontainer> box envelope(const iterablecontainer<box>& sequence) { location mincorner( std::n

scala - Using Breeze from Java on Spark MLlib -

while trying use mllib java, correct way use breeze matrix operations? e.g. multiplication in scala ist " matrix * vector ". how corresponding functionality expressed in java? there methods " $colon$times " might invoked correct way breeze.linalg.densematrix<double> matrix= ... breeze.linalg.densevector<double> vector = ... matrix.$colon$times( ... one might need operator instance ... breeze.linalg.operators.opmulmatrix.impl2 exact typed operation instance , parameters used? it's hard. breeze makes very heavy use of implicits, , don't translate java. have java friendly wrappers signal processing, nothing linear algebra. (i'd happily take pull request provided support wrapping things.)

How to wait for the full load of a bootstrap modal-dialog loaded with jquery .load() function -

i have severals bootstraps modals in website, , load them : function modal_density(){ $("#modal-content").load("pages/modals/density_control.php"); $('#all_modal').modal('show'); } then close them : function close_modal(){ $("#modal-content").empty(); $('#all_modal').modal('hide'); } i want put focus in input of modal, think modal not loaded when try : function modal_density(){ $("#modal-content").load("pages/modals/density_control.php"); $('#all_modal').modal('show'); $("#element").focus();//<----added part } how wait full load of elements ? [edit]: tryed , doesn't work : function modal_controle_densite_valid(){ $("#modal-content").load("pages/modals/controle_densite_validation.php", function() { $('#all_modal').modal('show'); $("#codebarre").focus(); })

ffi - Connect prolog code with C# program -

this question has answer here: integrating prolog c# [closed] 8 answers i have prolog code searching book. simple game. want make interfaces c#. don't know how connect prolog c#. please me. how conncet prolog c#. besides answers mentioned on comment link there swi prolog has c# interface. can see here . here example provided aforementioned link: plquery q = new plquery("member(a, [a,b,c])"); foreach (pltermv s in q.solutions) console.writeline(s[0].tostring()); there full documentation .

java - Jackson - serializing a list containing null elements -

i'm using jackson 2.4 serialize objects json. when serialize list of objects, having elements null, result json string contains "null" strings. how prevent "null" elements being serialized? there configuration objectmapper ? have set "setserializationinclusion(include.non_null)" ! here code : list<string> strings = new arraylist<>(); strings.add("string 1"); strings.add("string 2"); strings.add(null); strings.add(null); after serializing got : [string 1, string 2, null, null] how json string without "null"? [string 1, string 2] using @jsoninclude annotation. @jsoninclude(include.non_null) class foo { string bar; } edit also can create own serializer. example : public static void main(string[] args) throws jsonprocessingexception { list<string> strings = new arraylist<>(); strings.add("string 1"); strings.add("string 2

linux - vagrant up fails when destroying and associated drives -

when run vagrant up command give me error while destroying vm , associated drives. amit@amit:/var/www/myhomestead/homestead$ vagrant bringing machine 'default' 'virtualbox' provider... ==> default: box 'hashicorp/precise32' not found. attempting find , install... default: box provider: virtualbox default: box version: >= 0 ==> default: loading metadata box 'hashicorp/precise32' default: url: https://vagrantcloud.com/hashicorp/precise32 ==> default: adding box 'hashicorp/precise32' (v1.0.0) provider: virtualbox default: downloading: https://vagrantcloud.com/hashicorp/boxes/precise32/versions/1.0.0/providers/virtualbox.box ==> default: added box 'hashicorp/precise32' (v1.0.0) 'virtualbox'! ==> default: importing base box 'hashicorp/precise32'... ==> default: matching mac address nat networking... ==> default: checking if box 'hashicorp/precise32' date... ==&g