Posts

Showing posts from January, 2011

Bash read file to an array based on two delimiters -

i have file need parse array want brief portion of each line , first 84 lines. line maybe: >mt gi... and want mt entered array. other times might this: >gl000207.1 dn... and need gl000207.1 i thinking might able set 2 delimiters (one being '>' , other being ' ' whitespace) not sure how go it. have read other peoples posts internal field separator not sure of how work. think perhaps might work though? desiredarray=$(echo file.whatever | tr ">" " ") x in $desiredarray echo > $x done any suggestions? how about: head -84 <file> | awk '{print $1}' | tr -d '>' head takes first lines of file, awk strips off first space , after it, , tr gets rid of '>'.

mongoid - Why is 'Delayed::Job.all' not being recognized in the Ruby on Rails console? -

i'm trying check see in delayed job queue when run delayed::job.all in console, nameerror: uninitialized constant delayed error. according readme on github page, should able run normal delayed_job commands. i'm using delayed_job_mongoid gem version 1.0.8. here gemfile: gem 'rails', '3.2.6' gem 'unicorn' gem 'mongoid', '3.0.0.rc' gem 'bson_ext' # mongoid-related gem 'bcrypt-ruby' # encryption gem 'jquery-rails' gem 'haml' gem 'delayed_job_mongoid', :git => 'https://github.com/asavartsov/delayed_job_mongoid.git' group :assets gem 'uglifier', '>= 1.0.3' end group :development gem 'rspec-rails' gem 'guard-rspec' end group :test gem 'cucumber-rails', require: false gem 'capybara' gem 'database_cleaner' gem 'factory_girl_rails' gem 'mongoid-rspec' gem 'spork' gem 'guard-...

iphone - How to set high score and only changes if it is surpassed -

like game helicopter or left 4 dead survival mode want score stay , change if score surpassed. here code have far. ./m file _score = 0; _oldscore = -1; self.scorelabel = [cclabelttf labelwithstring:@"" dimensions:cgsizemake(100, 50) alignment:uitextalignmentright fontname:@"marker felt" fontsize:32]; _scorelabel.position = ccp(winsize.width - _scorelabel.contentsize.width, _scorelabel.contentsize.height); _scorelabel.color = ccc3(255,0,0); [self addchild:_scorelabel z:1]; if (_score != _oldscore) { _oldscore = _score; [_scorelabel setstring:[nsstring stringwithformat:@"score%d", _score]]; } and .h file int _score; int _oldscore; cclabelttf *_scorelabel; i tried put _score = [[nsuserdefaults standarduserdefaults] integerforkey:@"score"]; [[nsuserdefaults standarduserdefaults] setinteger:_oldscore forkey:@"score"]; ...

classpath - Flyway not finding the migrations in a jar file -

i implemented flyway in number of applications support , worked dream. however deployed applications test environment migrations stopped working. after investigation found migrations not being located flyway when loaded jar file, when not zipped (like when working in eclipse or if extract jar classpath) works expected. due plugin architecture of applications not in position use "default" setting , such setting flyway object this: flyway flyway = new flyway(); flyway.setdatasource(datasource); flyway.setbasedir("za/co/company/application/plugin1/db/migration"); flyway.settable(tablename); flyway.setbasepackage("za.co.company.application.plugin1.db.migration"); flyway.init(); flyway.migrate(); if 1 unzip jar file sql files located in: za/co/company/application/db/migration as mentioned know migrations work, not when in jar file. code above executes perfectly, it's there no sql files found run part of migration. although originaly develo...

html output formatting php -

i trying format html output db using php , here's problem: how should formated: ... <li> <div class="row-wrapper"> <div class="some-class-1">array-element-1</div> <div class="some-class-1">array-element-2</div> <div class="some-class-1">array-element-3</div> <div class="some-class-2">array-element-4</div> </div> <div class="row-wrapper"> <div class="some-class-1">array-element-5</div> <div class="some-class-1">array-element-6</div> <div class="some-class-1">array-element-7</div> <div class="some-class-2">array-element-8</div> </div> <div class="row-wrapper"> <div class="some-class-1">array-element-9</div> <div class="some-cl...

html - two div boxes [1st float, 2nd clear], margin on 2nd doesn't seem to push off first -

in code below have 2 div boxes. first float:left, second has clear:left sits below first. question why margin-top:20px not push off first div? <head> <style> div { width:100px; height:100px; background-color:green; } #box1 { float:left; } #box2 { background-color:red; clear:left; margin-top:20px; } </style> </head> <body> <div id="box1"></div> <div id="box2"></div> </body> yeah, it's confusing. read css spec on collapsing margins . specifically, "if top , bottom margins of element clearance adjoining, margins collapse adjoining margins of following siblings resulting margin not collapse bottom margin of parent block." to effect you're looking need apply margin element doesn't have clearance, in case first div, this: http://jsfiddle.net/6bfyu/

jsf - Semantics of "?faces-redirect=true" in <commandlink action=...> and why not use it everywhere -

i understand semantics behind appending "?faces-redirect=true" in action property of <h:commandlink> tag in jsf2.0. whether or out it, application indeed navigates target page specified in action. @ first glance seems effect cosmetic, i.e. provide feedback user (if looking @ browser's visited url) has moved new page. if innocuous , side-effects-free cannot see why not default behaviour. suspect has post-based mechanism of jsf2.0. 've noticed when browsing through jsf application urls 1 sees @ browser (when ?faces-redirect=true not used) ones of "previous" "page". meta-nb. behind firewall , plagued "so requires external javascript domain" issue apologize absence of formatting. provide feedback on answers in few hours, when can access domain. page-to-page navigation should not performed using post @ all. should using normal <h:link> or <h:button> instead of <h:commandlink> or <h:commandbutton...

php - Collapse on unique value which adding up the second in 2D array -

i have loop adds array of 2 values main array. how can merge of arrays in main array have same first values while @ same time add values of second? $maindata = array() ; //loop... $cres = $dbh->query("select overdue _credit_control_overdue entityid = $entityid") ; $currentowed = $cres->fetchcolumn() ; $dbh->exec("replace _credit_control_overdue (entityid, overdue) values ('$entityid', '$remaining')") ; $totalremaining += $remaining ; array_push($maindata, array($entityid, $remaining)) ; //end of loop in many cases $entityid same, , $remaining different. now need function similar array_unique leave me unique $entityid $remaining values added up, left e.g. 2339, 83572.60. hope have explained clearly! this output desire: array ( [0] => array ( [0] => 2499 [1] => 5314.50 ) [1] => array ( [0] => 639 [1] => 75.00 )) i.e array ( [0] => uniqueid [1] => sum ) the...

java - how to set JSESSIONID cookie as secure using Spring security 2 and Apache Tomcat 7 setting -

how set jsessionid cookie secure using spring security 2 , apache tomcat 7 setting. have put in code below in web.xml , deosn't seem working. <cookie-config> <secure>true</secure> </cookie-config> thanks use following: <session-config> <cookie-config> <secure>true</secure> <http-only>true</http-only> </cookie-config> </session-config>

.net - How do I lazy load a property? -

i have poco class built through service. hit service info, dto , use build parts of object. i'm trying lazy load of bigger properties they're filled on demand. thought way it: private list<user> _directreports; public list<user>directreports { { if (this._directreports == null) { setdirectreports(); } return this._directreports; } private set { this._directreports = value; } } private void setdirectreports() { using (var client = new adsclient()) { this._directreports = client.getdirectreports(this.guid); } } here's problem, , maybe i'm chasing ghosts, when step through debugger , @ guts of object after instantiating it, fields have information in it, , shouldn't @ stage...

wpf - How to know if the UserControl is active other than using IsFocused -

i working on wpf project, , trying fire event every time usercontrols active or inactive. these usercontrols have many other controls inside of them. i tried achieve using usercontrol events gotfocus , lostfocus , these events not working in way need since usercontrol loses focus when work controls inside of it. so, question is: is there way mantain usercontrol active while user works controls inside of it, and, when user goes usercontrol first 1 gets inactive ??? thank in advance. i solve problem thank comments of @lpl , @rachel. i had use event uielement.iskeyboardfocuswithinchanged , worked perfectly. at first had problem callback method being raised infinitely, actual problem was showing messagebox every time event iskeyboardfocuswithinchanged raised, so, caused iskeyboardfocuswithin property changed , created infinite loop. rachel's advice figure out how solve it.

JQuery Isotope plugin not allowing custom css animations -

i working on project , using isotope library jquery. prior incorporating isotope, created basic css class contained code perform css transform rotate element. used jquery apply class onclick , fire transform. when attempt apply class trigger transform on element within isotope container, transform not apply. able add/remove other classes transform classes have no effect. can tell within isotope not allowing transform fire , hoping might able tell me a)what might , b)if/how might turn off (if option) thanks

c# - How do you get the name of a new file created using FileSystemWatcher? -

i'm monitoring folder using filesystemwatcher. if download file there, how name of downloaded file? example, if downloaded file named textfile.txt, how have return string? assuming work 4 triggers (changed, created, deleted, renamed)? have includesubdirectories set true, should able that. on oncreated event, add code: private void watcher_oncreated(object source, filesystemeventargs e) { fileinfo file = new fileinfo(e.fullpath); console.writeline(file.name); // you're looking for. } see fileinfo class @ msdn

Solving Dinesman's multiple-dwelling example using clojure's core.logic/core.match -

after watching sussman's lecture http://www.infoq.com/presentations/we-really-dont-know-how-to-compute , inspired give core.logic , core.match go. examples know constraint problem solvers used kid. 1 example used in sicp course being mentioned in talk: baker, cooper, fletcher, miller, , smith live on different floors of apartment house contains 5 floors. baker not live on top floor. cooper not live on bottom floor. fletcher not live on either top or bottom floor. miller lives on higher floor cooper. smith not live on floor adjacent fletcher's. fletcher not live on floor adjacent cooper's. live? i found on rosettacode site: http://rosettacode.org/wiki/dinesman%27s_multiple-dwelling_problem#picolisp but not sure how translates clojure. hoping can provide example of solving using core.logic or core.match here's solution in core.logic. it's not equivalent picolisp algorithm because don't have same primitives available, it's same general id...

How do I get listed in the "featured for tv" section of google play on GTV -

i've built app google tv, , published google play store. expected listed in "featured tv" section since customized google tv, doesnt seem case. if search app name listed in results, how can show in "featured tv" section? any appreciated! first, not technical app development related question, should not asked here. featured apps staff picks. however, if want review app, please join 1 of hangouts on air google tv developers page , tell more app. app reviews in hangouts on air once in while.

cocos2d iphone - Registering touches on CCSprite characters of a CCLabelBMFont label -

the problem encounter positions of cclabelbmfont label , 1 of ccsprite characters composing label seem different cannot manage touch events... to test more in details issue tried : -(id)init { if ((self = [super init]) { cclabelbmfont *label = [cclabelbmfont labelwithstring:"welcome" fntfile:@"arial.fnt"]; cgsize size = [[ccdirector shareddirector] winsize]; label.position = ccp(size.width/2, size.height/2); [self addchild: self.label]; self.istouchenabled = yes; } return self; } -(void)cctouchesbegan:(nsset *)touches withevent:(uievent *)event { uitouch *touch = [touches anyobject]; cgpoint touchlocation = [touch locationinview:[touch view]]; touchlocation = [[ccdirector shareddirector] converttogl:touchlocation]; nslog(@"point touched: x:%f, y:%f", touchlocation.x, touchlocation.y); (ccsprite *character in [label children]) { ...

JQuery AJAX call to the php SLIM framework calls the error function, without no error message? -

i have server side slim code: require 'slim/slim.php'; $app = new slim(); //$app->config('debug', true); $app->get('/hello', 'hello'); //$app->post('/addconsultant', 'addconsultant'); $app->run(); function hello() { echo '{"hello": ' . json_encode("merp") . '}'; } pretty bare bones right? mean 1 single get. now, have client side javascript code: var rooturl = "http://somabsolutions.se/dev/index.php/"; $('#btnhello').click(function() { $.ajax({ type: 'get', url: rooturl + '/hello', datatype: "text json", success: function(data){ alert("something " + data); }, error: ajaxfailed }); return false; }); function ajaxfailed(xmlhttprequest, textstatus, errorthrown) { alert("xmlhttprequest=" + xmlhttprequest.responsetext + "\ntextstatus=...

javascript - tinymce autoresize with chrome when readonly -

hi guys tried full day, did not it. i use tinymce editor , in browsers works fine, except in * * chrome. use autoresize in readonly mode , have problem in chrome editor iframe ~20px small, text missing. i not jquery or javascript crack , did not find solution it. there row setting style h.setstyle(h.get(a.id + "_ifr"), "height", k + "px"); when add +20 have problem in editor mode adds 20 px when keydown. not solution. add pixeld css? how access iframe element? maybe of have idea can here add there pixels. edit ok seems no 1 has interest workaround. in plugin file following, maybe helps people, having same problem: if (tinymce.iswebkit && tinymce.activeeditor.settings.readonly == true) { then can add pixels, in case 20px. maybe there better solutions, works. i had similiar problem chrome, tinymce 3.5.6 , autoresize plugin. helped manually calling resize plugin in init_instance_callback . i'm calling tinymce (jquery ve...

c# - Transforming repeating group into several text lines -

i wanted transform repeating group sample xml 2 delimited text lines. here current code version: string orderxml = @"<?xml version='1.0' encoding='utf-8'?> <order id='79223510'> <status>new</status> <shipmethod>standard international</shipmethod> <tocity>tokyo</tocity> <items> <item> <sku>sku-1234567890</sku> <quantity>1</quantity> <price>99.95</price> </item> <item> <sku>sku-1234567899</sku> <quantity>1</quantity> <price>199.95</price> </item> </items> </order>"; stringreader str = new stringreader(orderxml); var xslt = new xmltextreader(new stringreader( @"<?xml version='1.0' encoding='utf-8'?>" + "<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/xsl/transform'>" + ...

android - setting raw resource as a ringtone -

i have read these 2 posts link1 , 1 link2 code not seem work me. here code: file newsoundfile = new file("/sdcard/media/ringtone", "myringtone.oog"); uri muri = uri.parse("android.resource://com.pack.android.myapp/r.raw.song1"); contentresolver mcr = main.this.getcontentresolver(); assetfiledescriptor soundfile; try { soundfile= mcr.openassetfiledescriptor(muri, "r"); } catch (filenotfoundexception e) { soundfile=null; } try { byte[] readdata = new byte[1024]; fileinputstream fis = soundfile.createinputstream(); fileoutputstream fos = new fileoutputstream(newsoundfile); int = fis.read(readdata); while (i != -1) { fos.write(readdata, 0, i); = fis.read(readdata); ...

php - PDO multiple queries -

as of php version 5.3 pdo_mysql driver has been repleaced in favour of pdo_mysqlnd . introduced support multiple queries. though, can't figure out how both result sets if more 1 select query has been passed. both queries have been executed, can't second 1 dumped. $db->query("select 1; select 2;")->fetchall(pdo::fetch_assoc); returns: array(1) { [0]=> array(1) { [1]=> string(1) "1" } } it turns out need use pdostatement::nextrowset . $stmt = $db->query("select 1; select 2;"); $stmt->nextrowset(); var_dump( $stmt->fetchall(pdo::fetch_assoc) ); this return result second query. it bit odd implementation. easier if multi-query statement return both results sets under 1 array. however, advantage implementation allows fetch every query using different fetch styles .

c# - verbosity of yield syntax -

i have interesting question. according msdn yield syntax : yield return <expression>; // yield value yield break; // exiting iterator why not just: yield <expression>; // yield value return; // exiting iterator to me second form less verbose , still have same meaning first. question - why first form chosen .net designers ? reasons may caused ? potential design problems second form has ? here's 1 possibility: create technical ambiguity (remember yield contextual keyword, not reserved keyword)... unlikely, but: struct yield {} then yield x; is variable declaration. "yield return x;", valid 1 way. no idea if true. thought.

cocoa touch - Getting location of sprite within array cocos2d` -

i need able touch specific moving sprite in array , perform action on it. when perform moveto action, sprite location doesn't update. help! array: int numbreds = 7; redbirds = [[ccarray alloc] initwithcapacity: numbreds]; for( int = 1; i<=numbreds; i++){ int xvalue = ((-50*i) + 320); int yvalue= 160; if (i==4) { ccsprite *parrot = [ccsprite spritewithfile:@"taco.png"]; [birdlayer addchild:parrot]; [self movement]; //the action moves array horizontally parrot.position = ccp(xvalue,yvalue); parrot.tag=100; touch -(void)cctouchesbegan:(nsset *)touches withevent:(uievent *)event { uitouch *touch = [touches anyobject]; cgpoint location = [touch locationinview:[touch view]]; location = [[ccdirector shareddirector] converttogl:location]; ccsprite *mark = (ccsprite *)[birdlayer getchildbytag:100]; if (cgrectcontainspoint([mark boundingbox], location)) { cclog(@"yay!"); } the problem...

c# - Why does empty controllerName property work when the default action is empty? -

i reading on urls , routes chapter in pro asp.net mvc 3 , tried see happens when object defaults contain empty values. route have @ moment. routes.maproute("myroute", "{controller}/{action}", new { controller="home", action="index" }); following observations made possible combinations of values of object defaults. ( in each case, urls in bold not accessible. ) case 1 new { controller="home", action="index" }); http://mywebapp.net/ http://mywebapp.net/home/ http://mywebapp.net/home/index/ case 2 new { controller="home", action="" }); http://mywebapp.net/ error: routedata must contain item named 'action' non-empty string value. http://mywebapp.net/home/ error: routedata must contain item named 'action' non-empty string value. http://mywebapp.net/home/index/ the above error 2nd url because routing system couldn't find default action name. cas...

Display random element from XML in TextView of iPhone -

i working on daily verse bible, , i'd random. have xml of verses looks this: <bible translation="kjv"> <testament name="old"> <book name="genesis"> <chapter number="1"> <verse number="1">in beginning god created heaven , earth.</verse> <verse number="2">and earth without form, , void; , darkness upon face of deep. , spirit of god moved upon face of waters. </verse> <!-- rest of xml here --> </chapter> </book> </testament> i use parser create nsstring of text 1 of verses, listed there several of each of elements, , named differently. suggestions how this? you use plist instead of xml implementation. find plists easy implement , manage. you load plist dictionary , randomly select there.

iphone - How do you detect when a file is changed in iCloud? -

when file changed in icloud (whether added, deleted, or content changed), call method created ( [self methodname] ) can update table view names of new files. how notified of file change? need listen nsnotification (if so, it?) or have check manually? thanks. the name of nsnotification have listen nsmetadataquerydidupdatenotification . how did it: [[nsnotificationcenter defaultcenter] addobserver:self selector:@selector(querydidupdate:) name:nsmetadataquerydidupdatenotification object:query]; ... -(void)querydidupdate:(nsnotification *)notification { //something changed, reload (nsmetadataquery, create nspredicate, rerun query, etc.) }

jquery - JavaScript not working when moved to an external .js file -

i had working java script in html page.now moved script external js file. here script(jful.js) <script type="text/javascript"> $(function() { // grab initial top offset of navigation var sticky_navigation_offset_top = $('#catnav').offset().top; // our function decides weather navigation bar should have "fixed" css position or not. var sticky_navigation = function(){ var scroll_top = $(window).scrolltop(); // our current vertical position top // if we've scrolled more navigation, change position fixed stick top, // otherwise change relative if (scroll_top > sticky_navigation_offset_top) { $('#catnav').css({ 'position': 'fixed', 'top':0, 'left':0 }); } else { $('#catnav').css({ 'position': 'relative' }); } }; // run our function on load sticky_navigation(); // , run...

c# - How to pass an argument to the EventHandler -

no it's not kind of basic question. doing application , got scenerio like, file downloaded uploaded ftp server, local copy deleted, 1 entry placed in dictionary filename. so, code below public void download_this_webpage(string url, string cookies_string, string local_saving_file_name_with_path) { webclient wb = new webclient(); wb.headers.add(httprequestheader.cookie, cookies_string); // below want pass local_file _path event handler wb.downloadfilecompleted += new system.componentmodel.asynccompletedeventhandler(wb,); wb.downloadfileasync(new uri(url), local_saving_file_name_with_path + ".html"); } public void data_download_completed(object sender, system.componentmodel.asynccompletedeventargs args) { //use file name upload file ftp } public ftp_completed { // delete file } but, dont know how pass filename event handler of download_completed. can guide me in this edit: thank answers "darin" , "frederic". ...

asp.net mvc - DevExpress MVC GridView: Multiple gridviews loaded via AJAX -

i have page multiple devexpress gridviews late-loaded via ajax. problem after each ajax load last-loaded gridview functional, others dead , i.e. sorting, filtering , paging not working. i've pinpointed problem fact on each ajax load web-request made dxr.axd, returns new global devexpress js objects (like aspx = new { }; ) overwriting old objects, causes previously-loaded grid stop working (this does not happen if multiple gridviews present @ initial page load, each callback loads grid content, no dxr.axd). as last resort could load gridviews hosted in iframes guess solve problem, it's messy (iframe sizing issues) , i'd avoid if possible. this issue resolved starting version 12.1 see this thread more information.

How to increment a numeric string by +1 with Javascript/jQuery -

i have following variable: pageid = 7 i'd increment number on link: $('#arrowright').attr('href', 'page.html?='+pageid); so outputs 7, i'd append link 8. if add +1: $('#arrowright').attr('href', 'page.html?='+pageid+1); i following output: 1.html?=71 instead of 8. how can increment number pageid+1? try this: parseint(pageid, 10) + 1 accordint code: $('#arrowright').attr('href', 'page.html?='+ (parseint(pageid, 10) + 1));

c# - Ajax Accordion Panes: separate required field validators only triggered by a button in its pane -

i have ajax accordion, using c# asp.net, few panels. in first panel have 2 required fields , have validation when user clicks button. want more in pane, if make them required field, button click causes validation them shows message first panel well. is there away separate out validators in each panel? missing obvious? if code helpful edit , include requested code. thank advice able provide. you want use validationgroup s this. basically, can set "validationgroup" property on each of validation controls want group same value (kind of css class). then, set "validationgroup" property of button want group tied same string. specifically, you'd set of validation controls in panel1 container same group (so add validationgroup="panelonegroup" markup). then, add same attribute button want validate panel. something this: <ajaxtoolkit:accordion id="myaccordion" > <panes> <ajaxtoolkit:accordionpane...

Group Video Chat using Mono for Android -

i need write group video chat app using mono android. have written same app using adobe air. works on high end phones. so, let me know start. have had @ sipdroid, that's in java , google voice users. best regards, ram

Rails Many to Many SQLite3 error -

i created many-to-many relationship in rails, here's models , migrations class channel < activerecord::base has_and_belongs_to_many :packages validates_presence_of :name end class package < activerecord::base has_and_belongs_to_many :channels validates_presence_of :name end class createchannelspackages < activerecord::migration def change create_table :channels_packages, :id => false |t| t.references :channel t.references :package t.timestamps end add_index :channels_packages, :channel_id add_index :channels_packages, :package_id end end then have multiple select, when try save error sqlite3::constraintexception: constraint failed: insert "channels_packages" ("package_id", "channel_id") values (1, 1) i tried remove indexes migration didn't solve it, did else have problem? btw i'm using rails 3.2.6 , sqlite3 1.3.6 i don't know if reason of problem, has_and_be...

Ruby: how to find the next match in an array -

i have search item in array , return value of next item. example: a = ['abc.df','-f','test.h'] = a.find_index{|x| x=~/-f/} puts a[i+1] is there better way other working index? a classical functional approach uses no indexes ( xs.each_cons(2) -> pairwise combinations of xs ): xs = ['abc.df', '-f', 'test.h'] (xs.each_cons(2).detect { |x, y| x =~ /-f/ } || []).last #=> "test.h" using enumerable#map_detect simplifies litte bit more: xs.each_cons(2).map_detect { |x, y| y if x =~ /-f/ } #=> "test.h"

c# - Implementing async timeout using poor mans async/await constructs in .Net 4.0 -

motivation c# 5.0 async/await constructs awesome, unfortunately yet microsoft shown release candidate of both .net 4.5 , vs 2012, , take time until these technologies adopted in our projects. in stephen toub's asynchronous methods, c# iterators, , tasks i've found replacement can nicely used in .net 4.0. there dozen of other implementations make possible using approach in .net 2.0 though seem little outdated , less feature-rich. example so .net 4.0 code looks (the commented sections show how done in .net 4.5): //private async task processmessageasync() private ienumerable<task> processmessageasync() { //var udpreceiveresult = await udpclient.receiveasync(); var task = task<udpasyncreceiveresult> .factory .fromasync(udpclient.beginreceive, udpclient.endreceive, null); yield return task; var udpreceiveresult = task.result; //... blah blah blah if (message bootstraprequest) { var typ...

c++ - Non-virtual interface? (Need a very performant low level abstraction) -

i'm trying micro-optimize code @ low level point in application architecture. here concrete scenario: i have parser class parses graph file (nodes, edges, adjacency entries etc.) the file format versioned, there exist parsers each version implemented separate classes (parserv1, parserv2, ...). the parsers provide same functionality upper layer in application. thus, implement same " interface ". in c++, i'd implement such interface abstract class functions being pure virtual . as virtual functions need memory lookup , can't bound statically @ compile time , -- more important -- not allow inlining of small methods in parser classes, using classical sub-classing idiom wouldn't lead best performance can achieve. [before describing possible solutions, want explain why i'm doing micro-optimization here (you may skip paragraph): parser class has lot of small methods, "small" means don't much. of them read 1 or 2 bytes or 1 bit cache...

python - django: don't log out when there is an error in view with `request.session.set_exipry` -

i'm developing app django, , every time have error when rendering view or template, session gets logged out. ends being pretty annoying. how disable 'feature'? note don't logged out if there's error when code loaded/parsed (e.g. if decorator on view fails), if there's error within view. edit: tested , yes, raise exception in view cause this. all views wrapped decorator, which, among other things, does: def needs_base_index_dict(func): def wrapper(request, *args, **kwargs): request.session.set_expiry(30*60) #... if comment out set_expiry line, don't behavior. when fix errors, still logged in. if line not commented out, error in view - including raise exception() - logs session out. django writes session database everytime there change it. since updating session state in view decorator, means there should session write db. however, if on database transaction management when view fails database write gets rolled bac...

Adding a line break to code blocks in R Markdown -

i using knitr package r markdown create html report. having trouble keeping code on separate lines when using '+'. for example, ```{r} ggplot2(mydata, aes(x, y)) + geom_point() ``` will return following the html document ggplot2(mydata, aes(x, y)) + geom_point() normally fine, problem arises once start adding additional lines, want keep separate make code easier follow. running following: ```{r} ggplot2(mydata, aes(x, y)) + geom_point() + geom_line() + opts(panel.background = theme_rect(fill = "lightsteelblue2"), panel.border = theme_rect(col = "grey"), panel.grid.major = theme_line(col = "grey90"), axis.ticks = theme_blank(), axis.text.x = theme_text (size = 14, vjust = 0), axis.text.y = theme_text (size = 14, hjust = 1.3)) ``` will result in code coming out in 1 line, making harder follow: ggplot2(mydata, aes(x, y)) + geom_point() + geom_line() + opts(panel.background = the...

Read multiple incoming sms's in blackberry -

i have code datagramconnection _dc =(datagramconnection)connector.open("sms://"); datagram d = _dc.newdatagram(_dc.getmaximumlength()); _dc.receive(d); //receive sms byte[] bytes = d.getdata(); string address = d.getaddress(); //the address of sms put on string. string msg = new string(bytes); does above code listen incoming sms's on continuous basis, or listen 1 sms? if listens 1 sms can please provide me code listen sms's on continuous basis. your code reads single sms. if need read every sms delivered, need loop 1 posted in the official knowledge base article : datagramconnection _dc = (datagramconnection)connector.open("sms://"); for(;;) { datagram d = _dc.newdatagram(_dc.getmaximumlength()); _dc.receive(d); byte[] bytes = d.getdata(); string address = d.getaddress()...

php - A click on module header in my joomla website to lead to an article -

i m using pause scrolling news module, got joomla extensions. http://kksou.com/php-gtk2/joomla/pausing-up-down-scroller-module.php it has relevant plugin installed, when both module , plugin installed & enabled works. yes works in site !! but requirement when click module heading must lead article, unfortunately module not have option. need play code. please instruct me steps code in module. wonderful if me. this content plugin. you can edit code in folder : your_joomla_site\plugins\content\pausing_up_down_scroller

java - What are the implications of running a query against a MySQL database via Hibernate without starting a transaction? -

it seems me have code not starting transaction yet read-only operations our queries via jpa/hibernate straight sql seem work. hibernate/jpa session have been opened our framework few spots in legacy code found no transactions being opened. what seems end happening code runs long not use entitymanager.persist , entitymanager.merge. once in awhile (maybe 1/10) times servlet container fails error... failed load resource: server responded status of 500 (org.hibernate.exception.jdbcconnectionexception: last packet received server 314,024,057 milliseconds ago. last packet sent server 314,024,057 milliseconds ago. longer server configured value of 'wait_timeout'. should consider either expiring and/or testing connection validity before use in application, increasing server configured values client timeouts, or using connector/j connection property 'autoreconnect=true' avoid problem.) as far can tell few spots in our application code not have transactions started ...

config - how to display context of .cfg file in php? -

i have .cfg file contains code. display whole .cfg in php page. code my_config.cfg here: # ata/ide/mfm/rll support # account_name=changl # # ide, ata , atapi block devices # config_blk_dev_ide=y config_blk_dev_idedisk=y config_blk_dev_idecd=n now wrote php code checks condition , display write in echo. instead of want display file. here php code: <?php $config_file = "my_config.cfg"; $comment = "#"; $fp = fopen($config_file, "r"); while (!feof($fp)) { $line = trim(fgets($fp)); if ($line && !preg_match("/^$comment/", $line)) { $pieces = explode("=", $line); $option = trim($pieces[0]); $value = trim($pieces[1]); $config_values[$option] = $value; } } fclose($fp); if ($config_values['account_name'] == "changl") echo "account_name changl"; else echo "account_name not changl"; ?> the code working properly. want display data in file. please appreciated...

comparing strings in c# which calls C dll -

(day 2 of learning c#) passing buffer c dll c#. c func copies string "text" buffer. in c# code, compare "text" what's in buffer , doesn't compare equal. missing? extern "c" __declspec( dllexport ) int cfunction(char *plotinfo, int buffersize) { strcpy(plotinfo, "text"); return(0); } c# using system; using system.collections.generic; using system.linq; using system.text; using system.runtime.interopservices; namespace consoleapplication1 { class program { [dllimport("mcdll.dll", callingconvention = callingconvention.cdecl, charset=charset.ansi)] public static extern int cfunction(stringbuilder thestring, int bufsize); static void main(string[] args) { stringbuilder s = new stringbuilder(55); int result = cfunction(s, 55); console.writeline(s); ...

scala - Pattern matching Type as a parameter for functions, methods, etc -

i making progress scala's pattern matching (amazing btw) until tried make dynamic function match "instance of" , in future part of object maybe save [type] later. understand how use pattern class matching case x:int => .... but why (below) seem work passed it?? further more can't seem work [type] , object? can't print or val = , etc.. thought trying work java.class associated doesn't seem correct. advise appreciated, thank you! class parent class child extends parent object testtypes { def testrelate[type](o:any) = { o match { case o:type => println(" o matching type") case _ => println(" o fails") } // val save = [type] .. why can't this? } def main(args: array[string]): unit = { val p = new parent val c = new child testrelate[int](c) // why match??? testrelate[parent](c) // } } --- update clarify (and thank answers) how can accomplish pattern mat...

list - Is a.insert(0,x) an o(n) function? Is a.append an O(1) function? Python -

i trying move numbers in array front , odd numbers of array. problem asks in linear algorithm , in place. i came this: def sort(a): in range(0,len(a)-1): if a[i]%2==0: a.insert(0,a.pop(i)) return the issue that, told me technically, a.insert o(n) function technically considered non-linear algorithm (when including for in range part of function). since forum asked question couple months old, couldn't ask explanation. basically believe said "technically" because since inserts @ front, not check n number of elements in array, therefore making run practical purposes @ o(n) , not o(n^2). correct assessment? also, on forum used a.append modify above , changed odd numbers. no 1 replied wondering, a.append not o(n) function since moves end? o(1)? thanks explanations , clarifications! insert @ 0th index of list requires shifting every other element along makes o(n) operation. however, if use deque operation o(1). append ...

plugins - Is there a way to capture user input in maven and assign it to a maven property? -

is there way pause maven execution flow provide command prompt user can input text. then provided text stored in maven properties. if user input masked bonus. this useful avoid storing passwords in pom. many you can catch user input using maven-antrun-plugin . following example show how ask current user new project version. <profile> <id>change-version</id> <build> <defaultgoal>validate</defaultgoal> <plugins> <plugin> <groupid>org.apache.maven.plugins</groupid> <artifactid>maven-antrun-plugin</artifactid> <version>1.7</version> <executions> <execution> <id>catch-new-version</id> <goals> <goal>ru...

python - Turtle module has no attribute color? -

when try run first piece of sample code python documentation on turtle : from turtle import * color('red', 'yellow') begin_fill() while true: forward(200) left(170) if abs(pos()) < 1: break end_fill() done() i nameerror : nameerror: name 'color' not defined tweaking import , manually specifying module doesn't work either: import turtle turtle.color('red', 'yellow') turtle.begin_fill() while true: turtle.forward(200) turtle.left(170) if abs(turtle.pos()) < 1: break turtle.end_fill() turtle.done() i using python v3.2.3, contains turtle.color , per documentation. python installed tkinter support well, because import tkinter works well. the full trace is: traceback (most recent call last): file "<path name contains no spaces>/turtle.py", line 1, in <module> turtle import * file "<path name contains no spaces>\turtle.py", line 2, ...

flash - the import * - slows the application? -

when write: import flash.display.*; // importing classes of display import flash.display.movieclip; // importing 1 class and likewise other classes, question is: if import classes package application work more if import needed classes? is true or false? that false. importing more classes namespace should not affect speed of application not cause more code run.

unix - How to CD inside a SFTP connection where the connection is established using - Shell script -

in script - create sftp connection. i read directory value user earlier , once sftp connection established, try cd dir got user. but not working, bec prompt goes inside server sftp connection established. in case how make work ? if script does, state somewhere in page, sftp $user@$host cd $directory and tries else, like: sftp $user@$host foo that command foo not executed in same directory $directory since you're executing new command, create new connection sftp server. what can use "batchfile" option of sftp, i.e. construct file contains commands you'd sftp on 1 connection, example: $ cat commands.txt cd foo/bar put foo.tgz lcd /tmp/ foo.tgz then, able tell sftp execute commands in 1 connection, executing: sftp -b commands.txt $user@$host so, propose solution be: with user's input, create temporary text file contains commands executed on 1 sftp connection, then execute sftp using temporary text file "batch file...

permissions - Unable to delete deployed file during installation with WIX installer -

in our wix installer project, need generate new file, let's call fileb, based on deployed file, called filea in managed custom action function. in word, in component declaration, declare filea. while in custom action (which happens @ commit phase), need generate fileb based on filea. after that, since filea no use anymore, want delete in same custom action. and here comes problem: default installation folder, program files, normal user not allowed add file (generate fileb) folder in custom action (i not 100% sure right, case in test. , if install in folder, there no problem @ all). think need give permission of creating file. in order that, add createfolder element component includs filea. whole component declaration this: <component id='component_name' guid='my_guid'> <!--other files in component--> ... <createfolder directory='installdir'> <permission createfile='yes' user='everyone' genericall...