Posts

Showing posts from April, 2012

node.js - How does Express/Connect middleware work? -

i learning node.js, , have read tutorials, node beginner book learning core funcionality. more read examples, more doubts start collecting. on further example, obtained tutorial, can see crud 'read' request key /documents/titles.json , returning value: app.get('/documents/titles.json', loaduser, function(req, res) { document.find({ user_id: req.currentuser.id },[], { sort: ['title', 'descending'] }, function(err, documents) { res.send(documents.map(function(d) { return { title: d.title, id: d._id }; })); }); }); on example, function loaduser() used authentication purposes: function loaduser(req, res, next) { if (req.session.user_id) { user.findbyid(req.session.user_id, function(err, user) { if (user) { req.currentuser = user; next(); } else { res.redirect('/sessions/new'); } }); } } what don't understand is: i suppose nod...

My own stopwatch in Android -

i developing simple stopwatch problem when user presses home button thread witch calculates time freezes how can avoid make thread run in background ? a simpler solution record start time of stopwatch using system.currenttimemillis. when activity onresume or onstart() called, update watch show time elapsed time you've saved.

java - JSF selectOneMenu: validation of two dropdown menus -

in .jsp have 2 selectonemenu items give me start/end year. want display error message if choosen start year bigger end year. how can solve this? <h:selectonemenu id="minyear" value="#{statistics.minyear}" style="width: 75px"> <f:selectitems value="#{statistics.yearvalues}" /> </h:selectonemenu> <h:selectonemenu id="maxyear" value="#{statistics.maxyear}" style="width: 75px"> <f:selectitems value="#{statistics.yearvalues}"/> </h:selectonemenu> in backing bean have method returns true/false if range valid or not. public boolean isyearvalid() { return (getmaxyear() >= getminyear()); } normal validation in jsf can validate single elements, need circumvent restriction. there @ least 2 ways cross-field validation jsf. you can aply validator last element (or hidden element behind last) define custom validator/method, lookup elements , valida...

Python: range operation with list -

i have list of elements this: [1/1/9-1/1/13, 1/1/20-1/1/22] and print numbers in range between 9 , 13, 20 , 22 result= [1/1/10, 1/1/11, 1/1/12, 1/1/21 ] the range() method this, how catch them? >>>test = ['1/1/9-1/1/13', '1/1/20-1/1/22'] >>>test = [tuple(x.split('-')) x in test] >>>print test [('1/1/9', '1/1/13'), ('1/1/20', '1/1/22')] >>>result = [x[:x.rfind('/')+1]+str(t) x,y in test t in range(int(x.split('/')[-1])+1, int(y.split('/')[-1]))] >>>print result ['1/1/10', '1/1/11', '1/1/12', '1/1/21'] i guess want.

java - Eclipse does not recognize org.jdesktop.* -

i use jre system library [jre7] , when import org.jdesktop.application.action get the import org.jdesktop cannot resolved i removed build path build path > remove build path , did project > properties > java build path > add library > jre system library , still same error . the org.jdesktop code not part of java se, classes won't in jre. need locate , download jar file containing classes, , add eclipse buildpath. (one place download jar here ... easy own searching if link breaks. go maven central or findjar.)

iphone - Flash : How to write roll over coding for grid in array which is similar colour movieclips nearby? -

flash as3: need know how check condition roll on effect on similar colour movieclips near in group of random colours movieclips in grid whereas using 2d array in flash as3.or need roll on event wrote onboxover event function, in object targetting getting rollover or getting alpha changes. need know how make rollover similar colour nearby. code wrote below reference. flash as3:: package { import flash.display.movieclip; import flash.events.mouseevent; public class playgame extends movieclip { public static var totalrowboxes:number = 13; public static var totalcolumnboxes:number = 12; public static var rowgap:number = 30; public static var columngap:number = 30; public static var totalcolorboxes:number = 8; public static var boxcollection:array = new array(); public static var boxcollection1:array = new array(); public function ...

linux - how to switch to root user without entering password in bash script on RedHat -

i want switch root user in bash script on redhat specifying password in code rather entering it. any highly appreciated. thanks it's not idea store passwords in plain text in script. can use visudo edit sudoers file , allow users run command using sudo without using password.

Plotting vectors in a coordinate system with R or python -

i looking advice on plotting vectors in cartesian plane. task plot points (coordinates) , link them arrow source point (say 0,0). image below should give idea. don't care colours , naming vectors/points, it's plotting arrows in coordinate plane. sure library exists in r (or python) plotting linear algebra vectors , operations. any pointers appreciated! vectors in plane http://mathinsight.org/media/image/image/vector_2d_add.png or can use arrows function in r. plot(c(0,1),c(0,1)) arrows(0,0,1,1)

java - How to access a SharedPreferences field? -

i'm trying access sharedpreferences field declared in activity sax parser class. i tried using getdefaultsharedpreferences(context), unable find context pass argument method sax parser doesn't extend activity. how can access field ? now, let's suppose managed this. have second problem here : sharedpreferences field declared in activity (a class extending preferenceactivity actually). in sharedpreferences field, can store boolean values 2 lists of checkboxes, standing 2 lists of multi choice preferences. i need know value of these lists of preferences "true". how can ? here code :- pref.java public class pref extends preferenceactivity implements onsharedpreferencechangelistener { static sharedpreferences pref; public void oncreate(bundle saveinstancestate) { super.oncreate(saveinstancestate); pref = getpreferencemanager().getsharedpreferences(); pref.registeronsharedpreferencechangelistener(this); int c = pref.getint("numrun...

matlab - getting mean value of sensor for given runs -

given number of sensor values measured @ each of 100 runs. = 8 7 8 9 8 8 8 8 9 8 to display value of specific runs (let every 5 runs) the code is: c= b(1:5:end); c= 8 8 what want store average of 5 runs how that? answer should = 8 8.2 i don't have matlab @ hand, try mean(reshape(b,5,[])) .

jQuery variable saved as JavaScript var unexpected behavior -

in script had following: $('#image-slider').empty(); which emptied image slider element in application. i wanted move directly using id references in function declared variables @ top of script including: var globals = []; globals.markup = []; globals.values = []; globals.markup.image_slider = $('#image_slider'); however when call: globals.markup.image_slider.empty(); the slider not emptied. any ideas i'm doing wrong? edit: a full example: $(document).ready(function(){ var projects = <?= $json; ?>; var globals = []; globals.markup = []; globals.values = []; globals.markup.title = $('#title'); globals.markup.image_slider = $('#image_slider'); function load_project(f) { var potential = window.location.hash.substring(1); $.each(projects, function(i, project){ if (project.permalink == potential) { // manage stats , fields $('#title')....

dns - Zend Hostname Route dispatching defined controller / action -

when domain requested, display page genereted defined controller / action. tried using hostname route (in case requesting www.some-page.de should dispatch transportaction in indexcontroller), this: $hostnameroute = new zend_controller_router_route_hostname( 'www.some-page.de', array( 'controller' => 'index', 'action' => 'transport' ) ); $plainpathroute = new zend_controller_router_route_static(''); $router->addroute('transport', $hostnameroute->chain($plainpathroute)); apparently doing wrong, because isn't working (instead indexaction of indexcontroller being dispatched). hints or ideas how can achieve this? i've got - it's simple , hope practice: in plugin's routeshutdown hook check domain name (using $_server['http_host']) , if desired domain, set action name using following code: $request->setactionname('transport');

jQuery mobile listview outside data-role="page" wrapper -

how can apply jquery mobile listview styles list reside outside data-role="page" wrapper? put list inside page wrapper, after been rendered move want it. $('#page').before($("#menu"));

PHP - File download through fread preserving last modification time -

the following script (just relevant part) let me download file: if ($file = fopen($file, 'r')) { if(isset($_server['http_range'])) { fseek($file, $range); } while(!feof($file) && (!connection_aborted()) && ($bytes_send<$new_length)) { $buffer = fread($file, $chunksize); print($buffer); //echo($buffer); // possible flush(); $bytes_send += strlen($buffer); } fclose($file); } doing this, downloaded file show actual time creation time. i know how preserve last modification file has on server. i know can info filemtime don't know how use in combination script above. before sending output, do header("last-modified: " . gmdate("d, d m y h:i:s", filemtime($file)) . " gmt"); i don't think cause web browser save file locally modification time. think need use type of archive format that, zip.

integrate a function in r (wrong length) -

i facing problem “integrate” command in r , don’t know how solve it, how deal extremely appreciated! i have data have fitted function using nls command. integrate function on range (e.g. 2-20), in case illustrates fluorescence 2-20 meters in water column – in function. the way tried it: depth <- seq(0,100, by=.1) #### first making vector simulates depth (have real once in own data set). flu <- 0.216 + 0.140*depth + (-0.01538*(depth^2)) + 0.0004134*(depth^3) ### fitted function. integrand <- function(depth) {flu} integrate(integrand, lower= 2, upper= 20) when this, r says: error in integrate(integrand, lower = 2, upper = 20) : evaluation of function gave result of wrong length i have tried vectorize flu function , integrate again, doesn’t help. maybe floating points? don’t know how deal this. hope can me - time , in advance!!! søren depth <- seq(0,100, by=.1) flu <- function(depth) {0.216 + 0.140*depth + (-0.01538*(depth^2)) + 0.000...

javascript - How to get rid of the 'progress' cursor? -

i have interval launches ajax call check if there update page (i imagine it's similar mechanism used facebook or stackexchange check new notifications). problem call changes cursor 'progress' or 'busy' cursor (visual problem) , disables option click on links (functional problem). i suppose both problems related. how can rid of effect or @ least minimize consequences? some code: setinterval(function() { try { var mid = $($("ul#alert-messages li.regular")[0]).attr('ref'); call_ajax('/load_alerts', {num:0, id:mid}, function (data) { if (data.ok) { (var i=0; i<data.result.length; i++) { // .... } // ... } }, function() {}, // not show error this!! false); // not change cursor! } catch (e) {} }, 15000); function call_ajax(url, data, fnsuccess, fnerror) { $.ajax({ ...

sql server - sql query to return date range or all records or only null records -

i have sql query can not work correctly here simplified version of query. select * permit inner join bmp on permit.permitnumber = bmp.permitnumber left join bmpinspection bi on permit.permitnumber = bi.permitnumber , bmp.bmpnumber = bi.bmpnumber permit.permitnumber = 's002552' , ( ( @startdate null , @enddate null ) or ( bi.dtactiondate > dateadd(day, -1, @startdate) , bi.dtactiondate < dateadd(day, 1, @enddate) ) or ( bi.dtactiondate > dateadd(day, -1, @startdate) , @enddate null ) or ( @startdate null , bi.dtactiondate < dateadd(day, 1, @enddate) ) ) the desired behavior return records in date range when start date , end date specified return null dates or less end date when start date null , end date has date return null or greater start date when start date has date , end date null return records null date when both start date , end date null ...

c# - How to know WCF service availability? -

i want know whether wcf service available or not before making service call. best way? how using this: bool isserviceup = true; try { string address = "http://localhost/myservice.svc?wsdl"; metadataexchangeclient mexclient = new metadataexchangeclient(new uri(address), metadataexchangeclientmode.httpget); metadataset metadata = mexclient.getmetadata(); // if service down exception } catch (exception ex) { isserviceup = false; } my service using net tcp binding. can use net tcp binding? edit: jaredpar. suppose first call gets succeeded , while second call server down. before making service call check state of proxy in open state , hence make service call gets time out. haven't set open or close time out default takes 1 minute , call gets caught in fault event handler of service in dispose proxy. time ui hangs , shd do? please guide. this type of test not possible. there no way reliably detect if given wcf, or networking call, succ...

Ruby on rails access to model information to an another model -

i have first model contact field :email , need same field :email in model customer value of field :email in model contact . i use mongoid orm here's first model contact class contact include mongoid::document include mongoid::timestamps embedded_in :customer embedded_in :employee embedded_in :restaurant field :city field :street field :zip_code field :country field :phone_number field :email and second model customer class customer include mongoid::document include mongoid::timestamps embeds_one :contact devise :database_authenticatable, :lockable, :recoverable, :rememberable, :registerable, :trackable, :timeoutable, :validatable, :token_authenticatable attr_accessible :email, :password, :password_confirmation field :first_name field :last_name field :password field :gender field :encrypted_password thanks. if using activesupport, delegate should job. in customer.rb delegate :email, :to ...

web - Why the statement exec("php -l $file", $error, $exit) set $exit = 5 while there's no error? -

the file exists. i'm validating syntax of file statement. exec("php -l $file", $error, $exit); it supposed set $exit = 0 if there's no error. in other words, syntax in file right. in case, sets $exit 5 , $error empty array. wonder how case. in advance. also, i'm using mamp. php5.3. $file hash string of file content. $code string of file content gotten file_get_contents() function. don't think $translatedfile , $error matter in question. function validatesyntax($code,$translatedfile, &$error){ $translatedfile = $this->gettranslatedlanguagefile($translatedfile); $file = 'cache/'.md5(time()); file_put_contents( $file, $code); exec("php -l $file",$error,$exit); foreach($error $k=>$v){ $error[$k] = str_replace($file, $translatedfile, $v); } unlink($file); if($retcode==0)return true; return false; } you quoting around of parameter...

objective c - Data doesn't load in UITableView until I scroll -

i trying load parsed data in cells, problem is happening synchronously , uitableview doesn't show until data has finished loading. tried solve problem using performselectorinbackground, data isn't loaded in cells until start scrolling. here code: - (void)viewdidload { [super viewdidload]; // additional setup after loading view, typically nib. [self performselectorinbackground:@selector(fethchdata) withobject:nil]; } - (void)viewdidunload { [super viewdidunload]; // release retained subviews of main view. self.listdata = nil; self.plot=nil; } -(void) fethchdata { nserror *error = nil; nsurl *url=[[nsurl alloc] initwithstring:@"http://www.website.com/"]; nsstring *strin=[[nsstring alloc] initwithcontentsofurl:url encoding:nsutf8stringencoding error:nil]; htmlparser *parser = [[htmlparser alloc] initwithstring:strin error:&error]; if (error) { nslog(@"error: %@", error); return; ...

How to make "universal" getters and setters in an object in perl? -

how make 1 setter method, , 1 getter method manage access fields of object? new subroutine looks this: sub new { $class = shift; $self = {@_}; bless($self,$class); # turns object } creation of new object looks this: $foo = package::new("package", "bar", $currentbar, "baz", $currentbaz, ); this not idea. perl instituted use of use strict; take care of problems this: $employee_name = "bob"; print "the name of employee $employeename\n"; mistyped variable names common problem. using use strict; forces declare variable, errors can caught @ compile time. however, hash keys , hash references remove protection. thus: my $employee[0] = {} $employee[0]->{name} = "bob"; print "the name of employee " . $employee[0]->{name} . "\n"; one of reasons use objects when start talking complex data structures prevent these types of errors: $employee ...

algorithm - Random distribution between evenly sized buckets without repetition -

problem i have n items of various types evenly distributed own buckets determined type. want create new list that: randomly picks each bucket does not pick same bucket twice in row each bucket must have (if possible) equal amount of representation in final list not using language specific libraries (not implemented in language) example i have 12 items of 4 distinct types means have 4 buckets: bucket - [a, a, a] bucket b - [b, b, b] bucket c - [c, c, c] bucket d - [d, d, d] what want a list of above items in random distribution without characters repeating size between 1 , n. 12 items: a, d, c, a, b, a, c, d, c, b, d, b 8 items: c, a, d, a, b, d, c, b 4 items: c, b, d, 3 items: b, c, (skipping d) i trying while loop generates random integers until next bucket isn't equal used bucket, seems inefficient, , hoping else might have better algorithm solve problem. you generate random list of buckets, , randomly pick in order, removing bucket list w...

javascript - Backbone.js - Change Event on Array of Models Doesn't Trigger On Element Change -

i have parent backbone model contains 2 objects. (1) array of backbone models (2) string if bind parent, setting value of string trigger change event, calling set on attribute of 1 of models in array of models not trigger change event on parent. how fix change of models in array triggers parents change event? edit -- added code request var mymodel = backbone.model.extend( { defaults : { models : [], astring: 'foobar' } } ); var foo = new mymodel(); var arrayelement = backbone.model.extend({x: 7}); var arrayelement1 = new arrayelement({x: 7}); foo.set('models', [arrayelement1]); foo.bind('change', function() { console.log('changed!')}); arrayelement1.set('x', 10); //does not trigger console log foo.set('astring', 'barfoo'); //does trigger console log backbone models don't bind attributes foo has no way of knowing changing 1 of attributes behind back. so, when this: foo.set...

c# - Why doesn't my service start after installation? -

i've created windows service, set start automatically. added following code installer: public projectinstaller() { initializecomponent(); serviceprocessinstaller1.afterinstall += new installeventhandler(serviceprocessinstaller1_afterinstall); } void serviceprocessinstaller1_afterinstall(object sender, installeventargs e) { try { var sc = new servicecontroller(serviceinstaller1.servicename); sc.start(); } catch { } } protected override void oncommitted(idictionary savedstate) { try { var sc = new servicecontroller(serviceinstaller1.servicename); sc.start(); } catch { } } the service installed properly, never starts. what cause of this? perhaps need put in temporary diagnostic logging, maybe using system.io.file.writealltext(); . know it's not answer you're look...

javascript - CSS mobile media styles with manual toggling -

so i'm trying build mobile , desktop version of website simultaneously (using mediawiki engine, if interested). since don't have experience mobile device building, looking around mobile development practices. in end, feel media queries need do, because double-publishing on separate domains (like m.foo.com vs foo.com) not possible task. the shortcoming css media queries, seems, apparent inability phone users view site in desktop format whenever want (google or youtube example of when accessed using phone). is there way me freely toggle between desktop , mobile stylesheets developed media queries? using javascript bulky mobile device download? i appreciate suggestions. thanks! edit: clarification, yes, want click link or button on mobile style switch desktop style. i'm 90% sure not possible css alone can accomplished php or javascript . shouldn't bulky use javascript. some examples php style switcher . javascript style switcher jquery style s...

objective c - Do I still have to alloc my object if I'm using a property -

simple question can't seem find fast post for; if have object, lets say: nsstring *mystring_; @property(readwrite, retain)nsstring* mystring; @synthesize mystring = mystring_; when synthesize this, alloc memory object? thanks all @synthesize generate accessors (setter , getter) property , create instance variable same name. added step of using equals sign: @synthesize mystring = _string; ... renames instance variable _string (or whatever name choose, underbar apple convention). practice since having instance variable share same name accessors can problematic. having underbar lets differentiate between two. this generated (assume arc on): // getter - (nsstring*)mystring { return _string; } and // setter - (void)setmystring:(nstring*)mystring { _mystring = mystring; } you can initialize property in init method (using self.propertyname): -(id)init { self.mystring = @"something"; // or use alloc init method in class } ...

c# - Given two dictionaries, how do you overwrite matching items in one with items in the other, leaving the remaining items untouched -

here starting code: dictionary<string,object> dest=...; idictionary<string,object> source=...; // overwrite in dest of items appear in source new values // in source. new items in source not appear in dest should added. // existing items in dest, not in source should retain current // values. ... i can foreach loop goes through of items in source, there shorthand way in c# 4.0 (perhaps linq)? thanks the foreach pretty small. why complicate things? foreach(var src in source) { dest[src.key] = src.value; } if you're going repeat often, write extension method: public static void mergewith<tkey, tvalue>(this dictionary<tkey,tvalue> dest, idictionary<tkey, tvalue> source) { foreach(var src in source) { dest[src.key] = src.value; } } //usage: dest.mergewith(source); as doing "with linq", query part means linq method should have no side effects. having side effects confusing of expect n...

sql - How to include column in resultset without including it in group by clause or performing any aggregation on it? -

given list containing city, empname , salary, sorted city , empname, how output each empname , salary total salary per city? here have got: select empname, sum(salary) table group province; but gives me error have not included empname in group clause and/or not performing aggregation on it. how can achieve desired results? help? if, want, sum of salary in city each employee, have 2 options. first should work in database: select empname, tcity.citysalary t join (select city, sum(salary) citysalary t group city ) tcity on tcity.city = t.city the second way use window function. notably, doesn't work on mysql: select emptname, sum(salary) on (partition city) t

tfs2012 - TFS 2012 Product Backlog ordering per team -

here current project/team setup in tfs 2012: project :myproject teams : team1, team2 so means have 2 separate backlogs - 1 per team - each accessible via appropriate team area path ("myproject/team1" , "myproject/team2"). means have sort of "master" product backlog, accessible @ "myproject" level; place there no delineation of task-by-team. what i'm trying have setup project managers/execs/etc. can see "master" version, , each team has own granular details. , stands, until try backlog sorting @ team level. let's have following backlog: order - taskname - team 1 - task1 - team1 2 - task2 - team2 3 - task3 - team1 4 - task4 - team2 what i'm seeing happening in setup if try re-prioritizing in "myproject/team2" backlog, end putting "task4" higher "task1" in "myproject" backlog, wrong @ macro level. i realize why can happen, i'm wondering if can give better ide...

installation - Installer overhead of wix, InnoSetup, nsis -

what typical package size overhead of installer created wix? same question nsis , innosetup. nsis installer has overhead of 34 kb. inno setup smallest size 350kb (ten times more nsis).

wordpress - Adding new menu page to dashboard -

i'm looking use add_menu_page add new section wordpress dashboard. issue put code? i've looked around @ several tutorials , frustratingly not 1 mentions add code! if tell me: where put add_menu_page code and where register function passed parameter add_menu_page function that appreciated. normally wouldn't answer question doesn't have code you've tried in, seems more abstract question i'll give more abstract answer. 'hacking' wordpress achieved using hooks triggered when actions executed wordpress. when hook reached system checks see if there functions registered called @ point in execution. menu page can registered in functions.php file of theme or in plugin file - doesn't matter long register appropriate action hook. example first need page menu item link (create page anywhere, ideally in theme directory if you're doing theme or plugin directory if you're doing plugin) . called mine settings_page.php , put ...

ruby on rails - Railties update probelm -

i tried run git push heroku , following error displayed in gemfile: rails (= 3.2.3) depends on railties (= 3.2.3) jquery-rails (= 2.0.0) depends on railties (3.2.5) here gemfile: source 'https://rubygems.org' gem 'rails', '3.2.3' gem 'jquery-rails', '2.0.0' gem 'bootstrap-sass', '2.0.0' gem 'bcrypt-ruby', '3.0.1' gem 'faker', '1.0.1' gem 'will_paginate', '3.0.3' gem 'bootstrap-will_paginate', '0.0.5' group :development, :test gem 'sqlite3', '1.3.5' gem 'rspec-rails', '2.9.0' gem 'guard-rspec', '0.5.5' end # gems used assets , not required # in production environments default. group :assets gem 'sass-rails', '3.2.4' gem 'coffee-rails', '3.2.2' gem 'uglifier', '1.2.3' end group :test gem 'capybara', '1.1.2' gem 'fa...

php - My script to deliver emails based on each user's local time -

i'm posting php script hoping opinions , advice. php application needs send individual emails users based on local time. each user has set of time-marks @ chose receive emails. how time-marks field looks in database: 12:00:00, 14:15:00, 16:30:00 . i'm rounding time-marks nearest quarter hour , sending cronjobs every quarter hour check users scheduled email , sending respective emails one-by-one (worried :-/) in loop. my server timezone set america/new_york can't send emails based on time because users in different locations. below developed model should handle issue. solution: collect each user's timezone on each cronjob each user's localtime in php using timezone data create array of user's time-marks. example: 12:00:00, 14:15:00, 16:30:00 array ( [0] => 12:00:00 [1] => 14:15:00 [2] => 16:30:00 ) if user's localtime matches 1 of his/her time-mark send email update database date sent php script: //loop through user...

javascript - How do you stop a dropdown menu from going up? -

i have dropdown menu that's towards top of page screen sizes, on smaller screens, such laptop, menu in middle of screen, , because of this, dropdown list going above selector. want dropdown consistently go down, no matter on page is. @ possible? drop-downs rendered browser/os. cannot control type of behaviour using css or javascript.

asp.net mvc - Cosuming JSON with JavaScriptSerializer returns NULL object -

my json string: jsonstring ="{"getstatusresult":[{"casecompleteind":"n","casenbr":"999999","insurgerynowind":"y","inroomnowind":"n"}]}"; my classes: public class getstatusresult { public list<casemodel> casedetails { get; set; } } public class casemodel { public string casecompleteind { get; set; } public string caseconfirmnbr { get; set; } public string insurgerynowind { get; set; } public string inroomnowind{ get; set; } } } my code: getstatusresult caseinfo = new getstatusresult(); javascriptserializer jsserializer = new javascriptserializer(); caseinfo = jsserializer.deserialize<getstatusresult>(jsonstring); my problem: the object returning null , casemodel details not being populated. json string has data, feel class structure somehow messed root level class. appears similar other examples posted here , elsewh...

why my php code create unneccesary spaces? -

Image
this php code. creating html codes below. foreach($sorular->sorucek($_get["kategori"]) $data) { $kontrol = $sorular->cevapcek($data["id"]); if($kontrol) { echo $data["soru"] . '<br/>'; foreach(@$sorular->cevapcek($data["id"]) $veri) { ?> <input type="radio" name="soru<? echo $data["id"]; ?>" value="<? echo $veri["id"]; ?>"/><? echo $veri["cevap"]; ?> <? echo "<br/>"; } echo "<br/>"; } } result: php templated language. spaces outside of php tags sent browser. <?php $a = 'foo';?> <input type="string" /> <?php $b = 'bar';?> input indented many spaces. regarding 'formatting' html mar...

javascript - How to structure nested Models and views? -

using backbone.js: i have collection of modela contains several attributes , 1 "node" holds several modelb. modelb contains several attributes. collectiona modela attribute 1 . . attribute n "node" modelb attribute 1 attribute 2 modelb attribute 1 attribute 2 modela attribute 1 . . attribute n "node" modelb attribute 1 attribute 2 modelb attribute 1 attribute 2 i'm still working on views main idea views should structured in similar way. (collection view holds several view holds several view b). same modelb never shared between multiple viewb. q1: design make sense or obvious flaws should consider? (this first try backbonejs). q2: best way set "node"? right i'm using array of modelbs. possible have collection of modelb on each modela instead? approach better? any guidelines appriciated! i point out i've read this excel...

vb.net - .Net Asynchronous Delegate Abortion -

background: application used execute tests using selenium rc servers, , i'm running problem when call selenium command doesn't return response rc server - ends blocking thread executing test. sample code: private delegate function docommand_delegate(byval command string, byval args() string) string ... asynccommand = new docommand_delegate(addressof server.docommand) asyncresult = asynccommand.begininvoke(command, args, nothing, nothing) try ... (i have use asyncwaithandle wait periods of 10 seconds 2 minutes. @ end of each period runs checks common problems block selenium returning response (modal dialogs) - don't think part relevant question, it's necessary.) result = asynccommand.endinvoke(asyncresult) ... at time endinvoke called, worker delegate has either finished or needs aborted. of time has response works fine, on rare occasion selenium rc's docommand doesn't return, thread sits there locked. finally, question: there resource-fr...

expressionengine - EE2 Embedded Template with Playa fields -

hopefully has simple solution. pretty sure close. here goes... code first. {exp:channel:entries channel="client" url_title="{embed:client_name}"} <tr> {exp:playa:parents channel="project"} <td> {proj_name} </td> <td> {proj_job_number} {job_number} {/proj_job_number} </td> <td> {entry_date format="%m/%d/%y"} </td> <td> {proj_producer} {producer_name} {/proj_producer} </td> <td> {proj_vendor} {vendor_name} {/proj_vendor} </td> <td> <a href="{proj_folder_zip}"><i class="icon-download"></i></a> </td> {/exp:playa:parents} </tr> {/exp:channel:entries} this code embedded template using. trying return each project channel entry along other playa field values project ...

asp.net mvc - MVC vs ASPX dynamic page render -

i have cms website written in aspx 2.0 allows users build pages dropping controls on page , setting properties (reflection on server side) , events (client side js). render engine knows property call on each control find out save database. went through pitfalls of control re-hydration , lack of proper ids on controls , struggled make solution seo friendly partial @ best. suffer viewstate getting huge have started @ mvc better way forwards next version. final design of page set when user decides promote live, , may make many changes per day. a typical page may have many textbox controls, radio button groups, checkbox groups, dropdownlists , images. have few of our own controls reflect @ runtime solution. from initial research mvc, looks have been written avoid these types of issues , not try hide html looks promising giving final markup more cross browser friendly. now question - since requirements generate dynamic pages dynamic html controls, step far mvc , should stick...

Sesame concurrent connections -

i using sesame rdfstore. wondering how many incoming concurrent requests (connections) sesame can support. is there jetty/sesame configuration can change support more? the number of concurrent connections webapp determined jetty, not sesame. sesame supports multithreaded access on of backends, you're limited number of resources each thread consumes (e.g. might run out of memory if have serialize x large query results concurrently).

Android eclipse - Making box increase in size with text -

i displaying following rule in eclipse code. rule taking care of type of phones. problem if text bigger in case wrapping around inside box. there way make box bigger automatically increase in text? textview rule1 //add rule 1 rule1=new imageview(this); rule1.setbackgroundresource(r.drawable.rules); if(w<340) { layout_params=new relativelayout.layoutparams(width(310), height(44)); layout_params.leftmargin=width(5); layout_params.topmargin=height(30); }else if(w<=500) { layout_params=new relativelayout.layoutparams(width(469), height(64)); layout_params.topmargin=height(40); layout_params.leftmargin=width(6); }else { layout_params=new relativelayout.layoutparams(width(774), height(92)); layout_params.leftm...

python - In celery how to get task position in queue? -

i'm using celery redis broker , can see queue redis list serialized task items. my question is, if have asyncresult object result of calling <task>.delay() , there way determine item's position in queue? update: i'm able position using: from celery.task.control import inspect = inspect() i.reserved() but bit slow since needs communicate workers. the inspect.reserved()/scheduled() mention may work, not accurate since take account tasks workers have prefetched. celery not allow out of band operations on queue, removing messages queue, or reordering them, because not scale in distributed system. messages may not have reached queue yet, can result in race conditions , in practice not sequential queue transactional operations, stream of messages originating several locations. is, celery api based around strict message passing semantics. it possible access queue directly on of brokers celery supports (like redis or database), not part of public a...

netbeans - Compiling c++ with Armadillo library at NeatBeans -

i going compile c++ program contains armadillo library. issue feasible via command line command: g++ '/arm.cpp' -o example -o1 -larmadillo but when add -o1 -larmadillo compile options of netbeans project considerable amount of errors. i got these errors: "/usr/bin/make" -f nbproject/makefile-debug.mk qmake= subprojects= .build-conf make[1]: entering directory `/home/atx/netbeansprojects/armadillo' "/usr/bin/make" -f nbproject/makefile-debug.mk dist/debug/gnu-linux-x86/armadillo make[2]: entering directory `/home/atx/netbeansprojects/armadillo' mkdir -p dist/debug/gnu-linux-x86 g++ -o3 -o dist/debug/gnu-linux-x86/armadillo build/debug/gnu-linux-x86/main.o build/debug/gnu-linux-x86/main.o: in function `gemv<double>': /usr/include/armadillo_bits/blas_wrapper.hpp:79: undefined reference `wrapper_dgemv_' /usr/include/armadillo_bits/blas_wrapper.hpp:79: undefined reference `wrapper_dgemv_' /usr/include/armadillo_bits/bla...

SQL Injection at CakePHP 2.0 -

when execute url @ website data @ "post" table deleted: http://mysite.com/posts/getposts/29;set foreign_key_checks = 0;delete posts; or http://mysite.com/posts/getposts/29;set foreign_key_checks = 0; currently function @ postcontroller this: public function getposts($iduser, $return = true){ $iduser = sanitize::clean($iduser); //calling post model... $posts = $this->post->getposts($iduser); } and yeah... im sorry have sql sentence @ post model called "getposts". (but can not change now...) i thought sanitize enought... how can solve it?? there equivalent mysql_real_escape_string @ cakephp when work own sql functions? thanks. cakephp 2.x protect against sql injection long use built-in query builders find , save . if table ids integer there quick , easy hack makes security. use php's integer type converter on parameter. either convert correct id value or zero. there no need sanitize integer value. publ...

regex - How regular expression ANDY X - XXXXX - XXXXX -

i trying create regular expression formate. x integers , n 1 or more[1 infinity]. andy can lower or upper case andy n: xxxxx - xxxxx /^[\iandy]\s[\d]{1,}\s[0-9]{4}\s-\s[0-9]{4}$/ may know how make n more 0 regular expression? , there anyway improve it? if want make sure it's more 0 use this: [1-9]\d* as in 1 digit between 1 , 9, followed number of digits between 0 , 1.

coming back to Java (IntelliJ IDEA or Eclipse) -

i had experience java earlier, , on , off java development. involving complex projects soon. looking suggestions ide. new eclipse, intellij idea. better start intellijidea or eclipse suffice? do guys think intellijidea smoother start dont have go through several plug-ins , custom configuration eclipse? pretty work web services, spring framework (no ui development) , little bit of jsp. is intellij idea community edition support spring framework , web services? dev. env: windows 7, jboss, weblogic app server the paid version of intellij better java development environment. free version doinking not real business ide, imo. many of goodies missing. eclipse ok, worse.

android - EXTRA_LANGUAGE_PREFERENCE for SpeechRecognizer? -

forcing particular language recognizerintent straightforward described in this answer . intent.putextra(recognizerintent.extra_language_preference, "en-us"); but works if intent instantiated of type recognizerintent . in application use lower-level speechrecognizer , i.e.: intent intent = new intent(speechrecognizer.results_recognition); and trying force language decribed above doesn't work. what proper way of programmatically setting language preference speechrecognizer ? is possible @ all? the language preference should work. please post more of code. you should still create intent this: intent intent = new intent(recognizerintent.action_recognize_speech); not this: intent intent = new intent(speechrecognizer.results_recognition); then have call speechrecognizer class directly. are doing that? for reference, see code 's recognizespeechdirectly() method.

css - jQuery: Tooltip Positioning -

i'm trying figure out how center tooltip under link (so it's not positioned in line link). [link] [tooltip should appear this] [link] [tooltip should not appear this] i'm trying figure out why tooltip not fading in. http://jsfiddle.net/fj4xz/ there : $('a.tooltip').hover(function() { var title = $(this).attr('title'); var offset=$(this).offset(); var width=$(this).outerwidth(); var height=$(this).outerheight(); $content=$('<div class="tooltip">' + title + '</div>').fadein(); $(this).append($content); var middle = offset.left+(width-$content.outerwidth())/2; // middle = math.max(offset.left,offset.left+(width-$content.outerwidth())/2 ); $content.offset({ top: offset.top+height, left: middle }); $('div.tooltip').hover(function() { $(this).fadeout('fast'); }); }...

ruby on rails - Sortable Table Row with Nested Resource -

in rails app, timesheet has_many entries , entry belongs_to timesheet. class timesheet < activerecord::base has_many :entries, order: 'position', dependent: :destroy end class entry < activerecord::base belongs_to :timesheet end i'm following railscast 147 sortable lists (the updated version). in development log notice params hash correctly updates sort order, on reload doesn't save positions correctly. furthermore, request being processed create action instead of custom sort action. here's controller. class entriescontroller < applicationcontroller before_filter :signed_in_user before_filter :find_timesheet def index @entries = @timesheet.entries.order("position") @entry = @timesheet.entries.build end def create @entry = @timesheet.entries.build(params[:entry]) @entry.position = @timesheet.entries.count + 1 if @entry.save #flash[:notice] = "entry created" #redirect_to timesheet...

Which these conditional has a better performance in php? -

i think first approach has better performance. <?php if(cond) { $var = 'v1'; } else { $var = 'v2'; } ?> or <?php $var = (cond)?'v1':'v2'; ?> thanks. edit: mean server performance wasting less ram ... no performance difference. readability issues. stop giving importance such tiny details , focus on bigger picture!

unit testing - Clojure equivalent to Python doctest? -

python doctests associate simple tests source code (in python in function documentation). more info , examples here . is there similar clojure? i aware of unit tests clojure.test , looking more closely integrated source (typically unit tests in different files; here want have test "inside" defn ). searching around found this , seems un-lispy (the tests in actual text, python - surely macro extends defn preferable?). or perhaps there other way solve general problem, have tests (generally simple things demonstrate basic properties of function) better included documentation (i using marginalia ) in separate unit test files. update here's example: have function calculates (manhattan) distance (in pixels) rectangle of pixels centre of image. sounds simple, complicated things difference in meaning of "centre" images odd or numbers of pixels on sides, or part of block measure from. had write tests code straight. , @ docs , best if docs included tes...

ios - Setting rootViewController on UIWindow changes UIScrollView with paging layout -

Image
update it turns out code below not problem. in app delegate doing: - (bool)application:(uiapplication *)application didfinishlaunchingwithoptions:(nsdictionary *)launchoptions { self.window = [[uiwindow alloc] initwithframe:[[uiscreen mainscreen] bounds]]; self.viewcontroller = [[viewcontroller alloc] init]; self.window.rootviewcontroller = self.viewcontroller;// <-- not work //[self.window addsubview:self.viewcontroller.view]; // <-- works [self.window makekeyandvisible]; return yes; } if remove statement "self.window.rootviewcontroller = self.viewcontroller" , add viewcontroller's view window, works. can explain this? setting rootviewcontroller on window constrain child's bounds? have tried go through docs, doesn't mention this. original post i having trouble adding padding pages in uiscrollview. trying setup simple scroll view shows uiviews in different pages separated predefined padding (kind of photos app wit...

http - programatically browse remote website with php -

how go programatically use php access secure site of website , pull image? there website can login username/password. once logged in, have go few different pages before image available download. trying download pod (proof of delivery) image carriers website. can done curl? unfortunately, cannot access image directly because: a) in password protected area b) think there session variables being set browse, if browse pod of consignment, there no request variables added image, thinking previous page must set sesion variable "this consignment looking at". also- there ethical restrictions guys can see in doing this? if company lets login website, can't see why care if doing physically or programatically. i use simpletest's php scriptable web browser such tasks. regarding "ethical" question, if you're not breaking laws , getting information personal purposes, nobody should care. don't abuse it.

flex - Is it possible to use outside "<mx:script>" in "<mx:canvas>"? -

i got new project. , part of it, flex exist. <mx: application xmlns:mx=...> <mx:script> import... function a() { } </mx:script> <mx:linkbar...> <mxviewstack ...> <mx:canvas id="1st" ...> **[here]** </mx:canvas> <mx:canvas id="2nd" ...> ... </mx:canvas> <mx:canvas id="3rd" ...> ... </mx:canvas> ** when viewstack calls canvas sequentially, a() has work. is possible use function a() in **here**] ? or please let me know possible function or tag can used. below example may you: - <?xml version="1.0" encoding="utf-8"?> <s:application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" minwidth="955" minheight="600"...