Posts

Showing posts from July, 2011

angularjs - Convert all falsey values in a Javascript object to blank string -

is there way convert undefined, nan, etc. values in javascript object blank string (so it's @ least defined). ex: javascriptobject = defineundefined(javascriptobject) something works that. one idea might check if value nan, , set equal 0 (or value of choosing). if (isnan(x)) x = 0; for more information on isnan, can take here: https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/isnan

Wordpress Meta Field - Finding the values of a select meta- field -

i have created custom field ( select box) post type - flavors. custom field type can have flavors vanilla, chocolate etc.. set @ run-time administrators. i have requirement, need list values @ run time has been set custom field type choices. how do this? get_post_meta return value set particular post id. if understand requirement right (and tbh i'm not sure), following code should need. global $wpdb; $flavors=$wpdb->get_col('select `meta_value` `' . $wpdb->prefix . 'postmeta` `meta_key`=\'flavor\' group `meta_value`;'); if (count($flavors) > 0) { foreach ($flavors $flavor) { //do whatever need $flavor (meta_value) } }

Enhance MediaWiki Search -

i wondering if can enhance search facility in mediawiki, returning suggested result set closest search key instead of return 0 results page. for eg. have created ff: articles, guidelines database management guidelines sql reporting but when try search entering guidelines , instead of showing me or suggesting me close, returns 0 results prompting me if want create it. would little suggestive, can make little suggestive? try installing lucene in place of default mediawiki search engine, merely mysql full-text indexing. lucene not solve above problem, work if you'd mistyped "guidlines" , ask, "did mean 'guidelines'?" http://www.mediawiki.org/wiki/extension:lucene-search http://www.mediawiki.org/wiki/extension:mwsearch lucene nontrivial install, results worth it.

c# - Value cannot be null. Parameter name: entity -

this question has answer here: asp.net mvc: why view passing null models controller? 2 answers i have following view (basic "edit" template) @model successstories.models.testimonials @using (html.beginform()) { @html.antiforgerytoken() <div class="form-horizontal"> <h4>testimonials</h4> <hr /> @html.validationsummary(true, "", new { @class = "text-danger" }) @html.hiddenfor(model => model.id) <div class="form-group"> @html.labelfor(model => model.testimonial, htmlattributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @html.editorfor(model => model.testimonial, new { htmlattributes = new { @class = "form-contro...

c++11 - C++ run time with different loops -

why both of these loops take same amount of time, shouldn't if statement make first single loop slower? // example program #include <iostream> #include <string> #include <vector> using namespace std; int main() { int counter = 0; #ifdef single cout << "one loop\n"; for(int =0;i<10000000;i++) { if(i != 50000) counter+=i; } #else cout << "two loops\n"; for(int = 0;i<50000;i++) { counter+=i; } for(int = 50001;i<10000000;i++) { counter+=i; } #endif return 0; } i get, time, following results: time ./test 1 loop real 0m0.004s user 0m0.001s sys 0m0.002s and two loops real 0m0.004s user 0m0.001s sys 0m0.002s i did research , said cause of branching i'm not sure if reason, compiled g++ -std=c++11 -o3 test.cpp -dsingle -o test the overall loop bare...

osx - automating zsh shell scripts within OS X -

is there way automate task (zsh shell script) using type of scheduler. if so, how? for example, if running zsh shell script within system named zshprogram1.zsh within directory /users/myname/zshtest , want run @ 1:35 pm hst daily, how go doing that? also, i'm assuming work if laptop on. work if it's on in sleep mode? check out crontab or launchctl . for example, crontab run crontab -e terminal , paste following line editor comes up 35 13 * * * /users/myname/zshtest/zshprogram1.zsh to have zshprogram1.zsh run @ 1:35 pm every day. launchctl bit more complicated configure, apple recommends on crontab future, might worthwhile check out.

Javascript check if transparent image on canvas has been clicked -

i have canvas, , drew image transparent, , has polygon shape. need check if image has been clicked. i have cords { x:30, y:20, w:100, h:100 } i check box or circle click if rigid polygon there pixel click test or convex algorithm(but don't want have specify edges)? thank you. one solution implement pixel detection secondary canvas used map. draw shape onto scene canvas. draw exact shape onto second canvas, set color rgb(0,0,0). store color reference in sort of map reference first 'shape' e.g. var pixelmap = { '000' : 'rectangle 1', '001' : 'rectangle 2' }; every time draw new shape canvas, increase rgb 1. unless have on 16.7 million shapes (256^3), method should suffice. heres example implementation : https://jsfiddle.net/mikeschultz/nbtnxpf2/

javascript - What does a function with multiple return statements return? -

this exercise out of head first javascript programming book. function findcarinlot(car) { (var = 0; < lot.length; i++) { if (car === lot[i]) { return i; } } return -1; } var lot = [chevy, taxi, fiat1, fiat2]; i'm not going write code chevy, taxi, etc, objects , function assigned 1 of 4 objects , value give variable in exercise. question going on with: return -1; so doesn't returned when function completes? or negated when return i; happens? or both values returned? sort out poor brain , tell me rules here. depending on return hits, thing returns function findcarinlot(car) { (var = 0; < lot.length; i++) { if (car === lot[i]) { return i; // if if statement true return here , function end , never make next return } } return -1; // called if above if s...

javascript - How to highlight current id element in HTML -

i want highlight current '#id' fragment: like if url : http://localhost:4321/store/zapakshop/#943 then id=943 should highlighted.. i have tried not working: $(document).ready(function () { $(window.location.hash).effect("highlight", { color: "#ff0000" }, 3000); }); help me... yes working changing color permanently want flash... – user2217267 snook has nice example of doing css3. here working example, adapted page: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <style type="text/css" media="all"> :target { -webkit-animation: target-fade 3s 1; -moz-animation: target-fade 3s 1; } @-webkit-keyframes target-fade { 0% { background-color: rgba(0,0,0,.1); } 100% { background-color: rgba(0,0,0,0); } } @-moz-keyframes target-fade { 0% { background-color: rgba(0,0,0,.1); } 100% { background-color: rg...

ios - Why the Alamofire return early? -

alamofire.request(.get, gaode, parameters: ["location": location,"key":key]) .responsejson { response in guard response.response?.statuscode == 200 else{ return } js = json(response.result.value!) guard js["infocode"].string! == "10000" else { return } print("json: \(js)") guard js["regeocode"]["formatted_address"].string != nil else{ return } print(js["regeocode"]["formatted_address"].string) } return js["regeocode"]["formatted_address"].string! the code execute return js["regeocode"]["formatted_address"].string! before response. why?i want json before return. how solve problem? the return outside response block, being returned totally separately network reque...

javascript - What is OWASP ? why we need that? -

i read documents said owasp used security purpose web application. not clear that. can 1 tell me purpose, difference normal app(without owasp) & secure app(with owasp) , why need that. can give me runable angularjs example following things 1)a2: cross-site scripting (xss) 2)a3: broken authentication , session management 3)a4: insecure direct object references 4)a5: cross-site request forgery (csrf) 5)a6: security misconfiguration 6)a7: insecure cryptographic storage 7)a9: insufficient transport layer protection to put it, owasp community highlighting security threats web application. hence, provides information on top security threats (owasp top ten) , whole bunch of guidelines , best practices when developing web applications keep secure. difference whether developer followed said guidelines , best practices. to give example: cross site scripting when user tries execute javascripts in web apps input fields, allowing rogue client-side script executed ...

Decode base64 string C# -

i tried decode following base64 string in c#: pglmcmftzsbzcmm9imh0dha6ly9lbwjlzc5yzwr0dwjllmnvbs8\/awq9mzg1njamymdjb2x vcj0wmdawmdaiigzyyw1lym9yzgvypsiwiib3awr0ad0indm0iibozwlnahq9ijm0ncigc2nyb2xsaw5n psjubyigywxsb3dmdwxsc2nyzwvupjwvawzyyw1lpg== but i'm getting error: the input not valid base-64 string contains non-base 64 character, more 2 padding characters, or illegal character among padding characters. even if remove last = in string above still same error. here code use: byte[] decodedbytes = convert.frombase64string(embedcode); string decodedtext = encoding.utf8.getstring(decodedbytes); why that? thank you. the correct base64string is: pglmcmftzsbzcmm9imh0dha6ly9lbwjlzc5yzwr0dwjllmnvbs8/awq9mzg1njamymdjb2x vcj0wmdawmdaiigzyyw1lym9yzgvypsiwiib3awr0ad0indm0iibozwlnahq9ijm0ncigc2nyb2xsaw5n psjubyigywxsb3dmdwxsc2nyzwvupjwvawzyyw1lpg== well not valid base64string. base64string can not have \ character. remove character , work

JavaFX HTTP Live Streaming Not Working -

i trying create media-player plays local media files/media on http live streaming using javafx version 2.0. i able play local media files in media player. when try play media files on http live streaming, not working. getting white-blank screen shown below when try play media files using http live streaming. click here see screenshot and following code play media on http live streaming: public class remotemultiplefilestreaming extends application { private static final string media_url = "http://youtu.be/uvcuo8dpwfs?list=plrqujcu2azg-amedjxa7p7ylymon5imls&t=2"; @override public void start(stage primarystage) { gridpane root = new gridpane(); scene scene = new scene(root); primarystage.setscene(scene); primarystage.setmaximized(true); primarystage.show(); media media = new media(media_url); mediaplayer mediaplayer = new mediaplayer(media); mediaplayer.setautoplay(true); med...

c++ - RTTI check fails on remote Linux machine -

i use c++/qt project , facing strange issue. my application runs fine on native linux machine , windows. problem appears when use remote linux machine execute program , use x windows server (i use xming) view/use it.the debugger points line dynamic_cast fails object pointer(the cast returns nice null) instead of actual object wanted. i suspect configuration issue must missing enable these runtime checks. anyone has faced such issues, pointers towards solution welcome. how have linked? had similar problem our java plug-ins. if dynamic_cast in different dll dll object constructed, rtld_global must set in call dlopen when dlls loaded. if dlls loaded implicitly, whether set depend on how set dll triggering load (which means may have no control on it). in end, had ensure no .so loaded implicitly (by having java load special loader dll, loaded explicitly, in dependency order). note may not problem; i'm guessing, since don't have enough information. had...

desire2learn - getting random 404 errors using Valence -

when make api calls server, i'm getting 404 errors various data -- grades, role ids, terms -- won't on next time call it. data's there on server, viewable same user, , returned successfully, not every time. same user context return data other calls. any ideas causing this? i'm using valence api python client library , our 9.4.1 sp18 instance of desire2learn in non-interactive script. more detail: text returns on bad 404s " errorthe system cannot find path specified." it enormously gather data case: packet traces can show successful calls client alongside unsuccessful calls, in particular, useful see. if quite (and see no reason shouldn't description) you're forming calls in right way each time make them, kind of behaviour you're noticing seem speak wider network or configuration issue: calls getting through web service layer, , not -- seem therefore not down way you're using api in way service able receive request. i enc...

javascript - Unable to click button in iframe using Webdriver which has property <em unselectable="on"> -

i need click on 'show in full screen mode' button present in our application. following html content found using firebug <iframe class="gwt-frame" src="/designer/editor/?uuid=1cca23be-5a43-4506-962e-b9124d463469&profile=jbpm" domain="bg-sipstage1" style="width: 100%; height: 580px;" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"> <!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd"> <html class=" ext-strict x-viewport x-viewport" xmlns="http://www.w3.org/1999/xhtml" xmlns:b3mn="http://b3mn.org/2007/b3mn" xmlns:ext="http://b3mn.org/2007/ext" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:atom="http://b3mn.org/2007/atom+xhtml"> <head profile="http://purl.org/net/erdf/profile...

Android Datagram Sockets not working -

i trying implement basic datagram sockets in android. starting 1 of samples available on web: string messagestr="hello android!"; int server_port = 54372; try { datagramsocket s = new datagramsocket(); inetaddress local = null; local = inetaddress.getbyname("192.168.100.127"); int msg_length=messagestr.length(); byte[] message = messagestr.getbytes(); datagrampacket p = new datagrampacket(message, msg_length, local, server_port); s.send(p); } catch (socketexception e) { e.printstacktrace(); } catch (unknownhostexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } i have enables internet permissions in androidmanifest.xml: <uses-permission android:name="android.permission.internet"/> the program dies when hits s.send(p) command. what missing? must obvious. you getting error not catch-ing: networkonmainthreadexception. should networking staff in thread or asynctask. for exampl...

Can I optionally include one element in a list without an else statement in python? -

i know can in python: >>> conditional = false >>> x = [1 if conditional else 2, 3, 4] [ 2, 3, 4 ] but how this? >>> conditional = false >>> x = [1 if conditional, 3, 4] [ 3, 4 ] that is, don't want substitute 1 number. want omit if conditional false. use concatenation: x = ([1] if conditional else []) + [3, 4] in other words, generate sublist either has optional element in it, or empty. demo: >>> conditional = false >>> ([1] if conditional else []) + [3, 4] [3, 4] >>> conditional = true >>> ([1] if conditional else []) + [3, 4] [1, 3, 4] this concept works more elements too, of course: x = ([1, 2, 3] if conditional else []) + [4, 5, 6]

c# - Generating zip files in azure blob container --getting corrupted -

here trying zip contents of azure blob directory using dotnetzip here code use this. zip files getting created corrupted. in blob container 'myfiles' ,i want create zip file named "mymusic.zip" reading files , folders within mymusic folder while retaining same folder structure inside zip file. following code creates zip file, zip file getting corrupted .any suggestions resolve ? string ofurl = @"http://myxyzstorage.blob.core.windows.net/myfiles/mymusic"; string ofblob = @"http://myxyzstorage.blob.core.windows.net/myfiles"; dblob = new cloudblob(blobclient.getblobreference(ofblob)); using (var zipfile = new zipfile()) { byte[] filebytes = dblob.downloadbytearray(); using (var filestream = new memorystream(filebytes)) { filestream.seek(0, seekorigin.begin); zipfile.addentry("myzipfiles"+".zi...

How can I filter the entire spreadsheet in Excel VBA instead of the specific rows the macro discovered? -

here's minimal example. show rows particular element empty. here's excel macro generator gives me. sub showempties() selection.autofilter activesheet.range("$a$1:$m$4922").autofilter field:=6, criteria1:="=" end sub instead of a1-m4922, specific particular sheet, how can have filter entire sheet no matter how many rows there are? usedrange revers range of worksheet contains data: activesheet.usedrange.autofilter field:=6, criteria1:="="

javascript - Is their any responsive lightbox with slideshow that has proper swipe? -

i have been search hours jquery type plugin responsive , has proper swipe animation during gesture. http://www.photoswipe.com/ 99% there except dosent support single image lightbox mode, geared towards grouping images swipable galleries, brilliantly. however , may want few images on page have no relation each other. id rather have default class, when used images opened in single image lightbox. photoswipe automatically groups images given same class. if able set option plugin hide prev/next images on call, have been perfect. important though, plugin must use full screen photoswipe does. many responsive plugins seem waiste screen unrequired image chrome. intended slide show or light box should viewing gallery on smartphone - again photoswipe this. fall in being able have non related instances. there couple out there appear inline want. never understood why developers create "responsive" galleries, waste space padding or decretive chrome elements. i thi...

PHP 5.5 - using yield with PDO transactions, is it possible? -

i want make use of generators handle on chunks of data database query while using minimum ammount of memory @ same time (one of advantage generators). the problem i've found while using generators associated piece of code: if (!empty($this->attributes["queries"])) { if (!empty($query)) { if (!empty($this->attributes["queries"][$query])) { $this->attributes["queries"][$query]->output(); } } else { foreach ($this->attributes["queries"] $query) { $query->output(); } } } optimizations aside, code is: checks if have allocated sql query checks if specific sql query given execute (ignore other) in case specific sql query given , exists, execute output() if no specific sql query given, traverse sql queries , execute them output() the problem works flawlessly kind of sql query except used one: select . the problem lies within piece of code: if ...

url for - Rails: generate URL from class name and ID -

so, i've got situation have big array includes references objects like: array=[['vendor',1],['comment',2]] i'd able create link objects in array. seems me since know class name , id should able generate link, far haven't figured out how without instantiating object. i know do: array.each |i| = link_to i[0].constantize.find(i[1]) end ... that's tons of overhead. suggestions on how build link class name string , id? you use inflections , dynamically compute path helper : array.each |i| = link_to 'show', send( "#{i[0].underscore}_path", i[1] ) end but won't work if have nested or namespaced resources.

mysql - find database rows that start with a character using PHP -

how can grab data database using mysql query rows start string, example; $string = 'ws'; mysql_query("select * `table` `name` starts '$string'"); something above you mean like select * `table` `name` 'ws%'

How to maintain scroll in ASP.NET MVC -

i need how can maintain scroll position in asp.net mvc during server calls or postbacks i agree nick berardi in answer question :- actually there no standard way of handling this, microsoft hack support post model. needed because every control did post > > , user pushed top of page.

python - Django model with relationships -

i know, questions of kind have been asked @ least bunch of times here, kind of starting django , having tough time apply solutions similar questions , put stuff together. i think model should have 3 classess: class guild(models.model): name = models.charfield(max_length=50) class battle(models.model): guild1 = models.foreignkey(guild, related_name="guild_one") guild2 = models.foreignkey(guild, related_name="guild_two") # tournament = models.foreignkey(tournament) ??? class tournament(models.model): name = models.charfield(max_length=50) ???? a battle war between 2 guilds , takes place during tournament . there can many battles in tournament . guild can participate in several tournaments . i want able search guild (to see every battle of theirs, every tournament have taken part in), tournament see battles have been played out plus have access through tournament see guilds have ever participated. above code (plus line commenet...

Tokenize a string in C# which delimeters contains some parts of other delimeters -

i want tokenize string using regular expressions based on operators. operators inlude others string. such as >= , > , [ eg. >= contains >] suppose have string (3>=4)!=(3>4) [ operators >= , != , >] how tokenize correctly? is there reason have regular expressions? would easier if used string split function on it. if start complex operators (>=) don't have worry later splitting on >. edit: adding example below //put operators in order of 'complexity'. since >= contains > , =, comes before them string[] operators = new string[] {">=", "!=", ">", "="}; string expression = "(3>=4)!=(3>4)"; foreach (string operator in operators) { //perform logic of creating expression tree here } so basically, inside loop it's going break down expression. you'll need construct expression tree inside here based on order of operations.

scala - Is blocking within a future still blocking? -

blocking bad, async good, blocking within future still blocking? keep coming to; consider following pseudo-code: def queryname(id:id):future[string] def queryeveryonesnames:future[seq[string]] = { val everyonesids:future[seq[id]] = getids val everyonesnames:future[seq[future[string]]] = { everyonesids.map(seq.map(id=>queryname(id))) } // i'm trying understand impact of i'll below everyonesnames.map(seq=>seq.map(fut=>blocking(fut, 1 s))) } queryeveryonesnames in last line turned future[seq[future[string]]] (notice future within future ) future[seq[string]] blocking on inner future . blocking on future within future feels redundant, @ least here, yet having future within future feels redundant well. can propose smarter way of getting rid of inner future? do think blocking on future inside future bad? if why , under circumstances? yes, future blocking blocking, should avoid that, resources blocked wait result, if in thread. if und...

c++ - Converting UINT32 color format from AaBbGgRr to AaRrGgBb -

i trying convert uint32 color format aabbggrr aarrggbb in c++. aa = alpha, bb = blue, gg = green rr = red. converting mean switching values of bb , rr. know how can achieve ? you can use mask , bit shifting achieve this: uint32_t newvalue = oldvalue; newvalue = newvalue & 0xff00ff00; // open new space insert bits newvalue = ((oldvalue & 0xff)<< 16) | newvalue; // change bb newvalue = ((oldvalue & 0x00ff0000) >> 16) | newvalue; // change rr

printing - If i could print across network, why can't i scan? -

i purchased hp deskjet wifi-enabled printer (model no. 3515). set both me (in same network printer) person few miles apart me (having different isp mine) print wirelessly successfully. the printing across network (printing network other printer connected) has been set-up , tested both through google cloud print , hp eprint software. however, when comes scanning across network, or cloud scan may call it, none of these 2 support, or about, it. talking hp customer care executive fruitless expectedly got no better answer 'it not possible'. also, unfortunately, have not found worthwhile on internet regarding either. what understand - if printing done wirelessly across network, scanning. after all, in both same thing in opposite direction. is, in layman's terms, if not wrong, in printing convert digital information hardcopy document, , in scanning other way round. please correct me if assuming many things wrong. hp eprint email based, i.e. printer acts email...

visual studio 2012 - For unit tests written in F# with mstest in vs2012, how do I assert that an exception is raised? -

i'm writing unit tests in f# using mstest, , i'd write tests assert exception raised. 2 methods can find doing either (1) write tests in c# or (2) don't use mstest, or add test package, xunit, on top of it. neither of these option me. thing can find on in msdn docs, omits f# examples. using f# , mstest, how assert particular call raises particular exception? mstest has expectedexceptionattribute can used, less ideal way test exception has been thrown because doesn't let assert specific call should throw. if method in test method throws expected exception type, test passes. can bad commonly used exception types invalidoperationexception . use mstest lot , have throws helper method in our own asserthelper class (in c#). f# let put assert module appears other assert methods in intellisense, pretty cool: namespace fsharptestspike open system open microsoft.visualstudio.testtools.unittesting module assert = let throws<'a> f = let m...

activerecord - Rails, including more than one relationship in the scope of a model -

i have following scope returns products have branch_id = 1, , have attribute enabled set true. scope :enabled_product, -> {includes(:products).where("products.branch_id = ?", 1).where(products: {enabled: true})} product has many many relationship category. how can include categories each product in scope? includes(:products => [:categories])

jquery - Update individual span tags counting upwards from x seconds -

i have several <span> tags hold seconds. example: <span class="timeout">27</span> <span class="timeout">58</span> i trying increment them 1 second each time, having difficulties, namely, puts wrong data in <span> tags. i must doing wrong, below code trying use.. must wrong , full of mistakes, well, i'm still trying learn ;-) function timer() { var self = $(this); var idx = $("span.timeout"); var sec = parseint(self.find('span.timeout').text()) var interval = setinterval(function() { idx.each(function() { idx.text(sec++) }); }, 1000); } thanks in advance, - robert. you want way: function timer() { var self = $(this); var idx = $("span.timeout"); //console.log(self.find('span.timeout').text()); //gets nothing var interval = setinterval(function () { idx.text(function (_, txt) { //use...

android - Intent to launch a website from activity doesn't work after 2-3 times -

i have webview activity , button open website in default browser after user clicks on show more button.i destoy webview activity after launching browser intent shown in code below. intent intent = new intent(intent.action_view, uri.parse(url)); intent.addflags(intent.flag_activity_new_task); context.startactivity(intent); finish() my problem is, i) after launching 2-3 websites using intent stops loading website in browser ii) launches browser on click of button loads previous url opened in browser. iii)i tried setting intent.flag_activity_clear_top intent not help. let me know doing wrong.

mysql - SQL Select only rows with Max Value on a Column revisited -

same old question: i have table. want rows max value field, grouped set of fields. not need max value , group fields, need full row (all other fields, can't do: select max(field1), field2 table group field2; as said, need field3, field4, ... , fieldn. this has been treated before, , found excelent answer here: sql select rows max value on column basically, says should join between original table, getting fields there, , subquery gets me max , group fields. , cases, works. my issue for particular case not sure approach works, because of data types involved. let me give example. consider gives me max values want, grouped field want: select max(field1) maxf1, field2 f2 mytable group f2 the above link suggest trying like: select mt.field1, mt.field2, mt.field3, ... , mt.fieldn mytable mt inner join ( select max(field1) maxf1, field2 f2 mytable group f2 ) sq on sq.maxf1 = mt.field1 , sq.f2 = mt.field2 for particular case, field1 , field2 may of type ...

Trying To Find The Cause Of Very Slow LEFT JOIN MySQL Query -

i appreciate trying find cause of slow return times on basic query table joins. i having trouble turned on profiling , query took 19.7903 sec return showed following profile details: profiling status time starting 0.000044 opening tables 0.000067 system lock 0.000002 table lock 0.000006 init 0.000009 optimizing 0.000005 statistics 0.000011 preparing 0.000014 executing 0.000031 sending data 0.000050 end 0.000004 end 0.000003 query end 0.000002 freeing items 0.000009 closing tables 0.000003 removing tmp table 0.000011 closing tables 0.000003 logging slow query 0.000002 cleaning 0.000003 showing rows 0 - 29 (2,200 total, query took 19.7903 sec) i don't understand why profile times not add "19.7903 sec". are 'profile' time , 'total, query' time, add up? <<<<<<< the query was: select owner.id owner_id, owner.last_name ...

javascript - AngularJS Trigger ng-animate when binding value change -

i have directive content bound via ng-html-bind-unsafe . have transition when content changes. can use jquery fade out, change content value , fade in. is there more elegant way angularjs ? in angular 1.2.0 can use directive watches content changes , adds removes classes. can tie animation class adds , removes triggers fading effect looking for. module.directive('contentchange', function(){ return { scope: { content: '=' }, template: '<span ng-bind-html="mycontent"></span>', link: function(scope, element, attrs){ scope.$watch('content', function(){ //add fader class element scope.mycontent = content; //remove fader class element }); }; }); here's popular article on 1.2 animations: http://www.yearofmoo.com/2013/08/remastered-animation-in-angularjs-1-2.html

git - Ruby + Compass: Permission Issues -

i have been having sorts of permission issues using scss + compass after pulling git repo project contains this. works great if created own sass project scratch. inside git repo project, sass lies, run: compass watch ...and get... >>> change detected to: print.scss errno::eacces on line 25 of /library/ruby/gems/1.8/gems/sass-3.2.10/lib/sass/../sass/cache_stores/filesystem.rb: permission denied - /applications/mamp/htdocs/dt/resources/slice/html/.sass-cache/f2469bce8a00b9f9dd394c466620079eaa696535/print.scssc so logged in root user , ran... chmod 777 /library/ruby ...with no luck. when first installed ruby, used sudo install gem *** . seems use read bad idea. (such case) tried installing fresh copy of ruby while logged in normal admin user , don't have permissions install it. fetching: compass-0.12.2.gem (100%) error: while executing gem ... (gem::filepermissionerror) don't have write permissions /library/ruby/gems/1.8 directory. which why...

R convert vector of numbers to skipping indexes -

i have vector of widths, ws = c(1,1,2,1,3,1) from vector i'd have vector of form: indexes = c(1,2,3,5,6,7,9,11,12) in order create such vector did following loop in r: ws = c(1,1,2,1,3,1) indexes = rep(0, sum(ws)) counter = 1 counter2 = 1 last = 0 for(i in 1:length(ws)) { if (ws[i] == 1) { indexes[counter] = counter2 counter = counter + 1 } else { for(j in 1:ws[i]) { indexes[counter] = counter2 counter = counter + 1 counter2 = counter2+2 } counter2 = counter2 - 2 } counter2 = counter2+1 } the logic follows, each element in ws specifies respective number of elements in index. example if ws 1, respective number of elements in indexes 1, if ws > 1, let 3, respective number of elements in index 3, , elements skipped 1-by-1, corresponding 3,5,7. however, i'd avoid loops since tend slow in r. have suggestions on how achieve such results vector operations? or more crantastic solution? thanks! here...

Java Junit4 testing; protected methods -

i'm working test chunk of code - it's class called mazebuilder. problem of methods protected, can't access them in tests... so thought test should focus on run(), accesses lot of other methods. i'm concerned impossible sort of cohesive testing done operating 1 method. additionally, proper way test 2 constructors ( mazebuilder() , mazebuilder(boolean deterministic) )? stands, i'm testing object formed not null - i.e. they're being built @ all. there more expansive way of testing constructor i'm unaware of? package falstad; public class mazebuilder implements runnable { // given input information: protected int width, height ; // width , height of maze, maze maze; // reference maze constructed, results returned calling maze.newmaze(..) private int rooms; // requested number of rooms in maze, room area no walls larger single cell int expectedpartiters; // user given limit partiters // produced output in...

mongodb - Mongo DB, PHP add or update a field in a document -

i have following document: { "_id": objectid("5241f1d79b7e7aed05000000"), "description": { "nl": "hallo", "en": "hello" }, "name": "marc" } now need update update 1 existing field or add new field description. in php use update function mongo , following code: $new_data = array( '$set' => array( "description" => array( "de" => "hallo" ) ) ); what removes other fields , insert "de" field. tried replacing $set $push (which thought made this) no result $setoninsert not anything. how can solve problem can either add new field (if not exist) or update if exist. thanks just make update {$set: {"description.de": "hello"}} i guess in code be: $new_data = array( '$set' => array( "description.de" => "hallo" ) )...

php - How to upload larger sized images -

so wrote code below if($_files!=null && $_post!=null){ $file = $_files["image"]["tmp_name"]; if(!isset($file)){ echo "please upload image"; }else{ $image = addslashes(file_get_contents($_files['image']['tmp_name'])); $image_name = addslashes($_files['image']['name']); $type=$_post['type']; $image_size = getimagesize($_files['image']['tmp_name']); if($image_size==false) echo "that's not image."; else { if(!(mysql_query("insert store (name,image,type) values ('$image_name','$image','$type')"))) echo "problem uploading image"; else { $lastid = mysql_insert_id(); echo "image uploaded. <p /> image: <p /> <img id='imageid' src=get.php?id=$lastid>"; } } } } when try up...

ios - Changing the frame of UISearchBar's cancel button -

i have uisearchbar have been trying long customise. have changed appearance (using custom images backgrounds) of both cancel button , uitextfield . not able change frames of these views using [uiview setframe:] command. idea why might not changing?

sql - Returning a set of the most recent rows from a table -

i'm trying retrieve latest set of rows source table containing foreign key, date , other fields present. sample set of data be: create table #tmp (primaryid int, foreignkeyid int, startdate datetime, otherfield varchar(50)) insert #tmp values (1, 1, '1 jan 2010', 'test 1') insert #tmp values (2, 1, '1 jan 2011', 'test 2') insert #tmp values (3, 2, '1 jan 2013', 'test 3') insert #tmp values (4, 2, '1 jan 2012', 'test 4') the form of data i'm hoping retrieve is: foreignkeyid maxstartdate otherfield ------------ ----------------------- ------------------------------------------- 1 2011-01-01 00:00:00.000 test 2 2 2013-01-01 00:00:00.000 test 3 that is, 1 row per foreignkeyid showing latest start date , associated other fields - primaryid irrelevant. i've managed come with: select t.foreignkeyid, t.startdate, t....

c++ - condition_variable::wait_for always waits? -

i have code in unit test waits until vector sufficiently big: bool waitforoutwardmessages(size_t size, int millis) { std::unique_lock<std::mutex> lock(mutex); return ready.wait_for(lock, std::chrono::milliseconds(millis), [=]{ return this->messages.size() >= size; }); } std::mutex mutex; std::condition_variable ready; easy enough. except when run test, i'm expecting the vector in question should fill on order of milliseconds after make call on other thread. maybe 10ms, maybe 100ms, within 1s. when pass in 5000 millis argument, function always waits 5 seconds. on 1 hand, fine, because don't care how long test takes anyway. on other hand, thought supposed wait duration if condition variable wasn't notified... not always? is there way return earlier? check calling signal or broadcast on ready . there's possible race if you're not careful can signal condition before wait on (which cause wait until timeout).

c# - Exit my while loop at a specific day and time -

i have while loop continually processing information on weekend. on monday @ 8:00 process stop. i have running inside while loop: datetime currentdate = datetime.now; if (currentdate .dayofweek == dayofweek.monday) { runloop = false; } this should correctly stop loop turns monday right? how enable continue until 8:00 on monday morning? it sounds me it's simple as: datetime currentdate = datetime.now; if (currentdate.dayofweek == dayofweek.monday && currentdate.hour >= 8) { runloop = false; }

python - Best way to reference the User model in Django >= 1.5 -

what best way reference user model in django >= 1.5? after reading referencing user model , i've started using (1) while: (1) from django.conf import settings django.db import models class article(models.model): author = models.foreignkey(settings.auth_user_model) but following zen of python, readability counts, why not this: (2) from django.contrib.auth import get_user_model django.db import models user = get_user_model() class article(models.model): author = models.foreignkey(user) update: of django 1.11, get_user_model can called @ import time, in modules define models. that means this: models.foreignkey(get_user_model(), ...) original answer (django <= 1.11) you might experience circular reference issues if use get_user_model @ module level. option importing auth user model is: from django.conf import settings auth_user_model = getattr(settings, 'auth_user_model', 'auth.user') # models class article(model...

ruby on rails - CanCan and ability block -

i have piece of code defines cancan's user permissions, don't understand conditions inside block ? class ability include cancan::ability def initialize(user) user.permissions.each |permission| can permission.action.to_sym, permission.thing_type.constantize |thing| thing.nil? || permission.thing_id.nil? || permission.thing_id == thing.id end end end end so, lines of code bugging me: permission.thing_type.constantize |thing| thing.nil? || permission.thing_id.nil? || permission.thing_id == thing.id end i understand block used define complex conditions , guess permission.thing_id == thing.id there permission granted selected objects don't see purpoose of thing.nil? || permission.thing_id.nil? .what's for? so, according cancan docs , when pass block can (which what's going on here), permission given if block returns true. object pas...

javascript - jQuery Validate: Validate that one field, or both fields of a pair are required -

i have form trying validate has 2 fields: <div class="entryform"> <div class="formfield"> <label for="fieldemailaddress">email address:</label> <input type="email" name="fieldemailaddress" id="fieldemailaddress"/> </div> <div class="formfield"> <label for="fieldmobilenumber">mobile number:</label> <input type="text" name="fieldmobilenumber" id="fieldmobilenumber"/> </div> </div> here's jquery validation wireup: <script type="text/javascript"> $(document).ready(function () { $('#form1').validate({ rules: { fieldmobilenumber: { phoneus: true } } }); }); </script> what i'd add additional validation rule says: the form not valid if both fieldemailaddress , fieldmobilenumber blank. in other words, ...

Regex: Python First Occurrence After Return or Newline -

i'm trying match set of data, , while can create regex correctly, python returns no match. i'd know if i'm formatting regexes in python correctly. i'm trying match date after \r or \n. can of following: date/time sep 12 11:13:42 date/time sep 12 11:13:42 date/time sep 12 11:13:42 date/time sep 12 11:13:42 and using (?<=date/time\s)(\r*[\w :]+) works far validator concerned. i input date = re.findall("(?<=date/time\s)(\r*[\w :]+)", content) never matches returned. the regex formatted correctly. question whether regex formatted incorrectly far python concerned (illegal characters, etc.)? but... works: content = """\ date/time sep 12 11:13:42 date/time sep 12 11:13:42 date/time sep 12 11:13:42 date/time sep 12 11:13:42""" import re re.findall("(?<=date/time\s)(\r*[\w :]+)", content) #>>> ['sep 12 11:13:42', ' sep 12 11:13:42', 'sep 12 11:13...

linux - While read line is very slow -

i want create thumbs large list of images. problem is, appears while read line slow large lists. 1 solution can think of create files contain max 500 lines , read them 1 one. there smart solution problem? while read line; if [ -e "$line" ] && [ ! -z "$line" ]; ... fi } done <<< "$imageslist" your problem you're using here string read in these lines via <<< . slow if here string large. if $imgagelist file, can file redirect , lot faster: while read line if [ -e "$line" -a ! -z "$line" ] ... fi done < "$imageslist_file" # redirect file. you might able this: echo "$imageslist" | while read line if [ -e "$line" -a ! -z "$line" ] ... fi done but, worried overloading command line. in linux/unix systems, defined in /usr/include/sys/syslimits.h or /usr/include/syslimits.h . it's 102...

java - log4j2 - Root contains an invalid element or attribute -

trying use sample xml file "sample 1 / log4j 2 xml configuration" page: http://logging.apache.org/log4j/2.x/manual/migration.html but gives: 2013-09-25 02:22:59,182 error root contains invalid element or attribute "appenderref" any ideas? i using dependency in pom.xml, <dependency> <groupid>org.apache.logging.log4j</groupid> <artifactid>log4j-core</artifactid> <version>2.0-beta8</version> </dependency> and use inside class: private static final logger logger = logmanager.getlogger(app.class.getname()); and specify config file follows: java -dlog4j.configurationfile=log4j2.xml -jar target/project-jar-with-dependencies.jar this error 2.0-beta8, not present on 2.0-beta9 here output using beta9 log.debug("log4j impl test started..."); log.warn(" log4j impl test warn..."); log.info(" log4j impl test info..."); lo...

python - int has no len error Help me please? -

i have problem program , it's annoying me keep getting error don't know why can please me? i keep getting builtins.typeerror: object of type 'int' has no len() error when gets password verfication stage , cannot figure out problem is.. #program asking username, password , security pin #written cole johnston #19/08/13 - #declare/initialize variables sfirstname = "" #user's input of first name (the minimum 2 characters) (string) slastname = "" #user's input of last name (the minimum 4 characters) (string) spassword = "" #user's input of password (it must have minimum length of 6 characters , maximum length of 10 characters. must contain @ least 2 numbers in password, case sensitive) ipinno = 0 #user's chosen input of security pin (it must 4 characters long , contain numbers single digit , range between 0-9) icount = 0 #the amount of times user enters invalid username (integer) smessage = "" #message us...