Posts

Showing posts from September, 2010

filesystems - Tips on improving performance of fuse based file system -

i comparing fusepy , java based nfs server , native. see native file system 4 times faster , surprisingly java based nfs server twice faster compared fusepy based loopback system. tips improve performance of file systems written based on fusepy or fuse-python. running them on linux kernel 2.6.9 , fuse binding version 2.6.5. check if python code blocking anywhere?

objective c - How to wake from sleep programmatically? -

i want wake system sleep programmatically, there way this? i have read following link: http://developer.apple.com/mac/library/qa/qa2004/qa1340.html this talk getting notification , not sure there way wake system sleep? i appreciate thread information... update: as per suggestion tried iopmschedulepowerevent code have used: nscalendardate *timeintervalsincenow = [nscalendardate datewithtimeintervalsincenow:40]; ioreturn result = iopmschedulepowerevent ((cfdateref)timeintervalsincenow, null, cfstr(kiopmautowake)); result: it fails in macbook if lid closed am doing thing wrong or solution? you can schedule wake events iopmschedulepowerevent through power manager. may able schedule immediate wake up. pmset command line wrapper power manager. can prevent sleep iocancelpowerchange in cases. you may able prevent sleep or wake generating mouse or key event. 1 way generate events cgpostkeyboardevent. edit: normal sleep different clamshell closed sle...

Why is it considered bad practice to use cursors in SQL Server? -

i knew of performance reasons in sql 7 days, same issues still exist in sql server 2005? if have resultset in stored procedure want act upon individually, cursors still bad choice? if so, why? because cursors take memory , create locks. what doing attempting force set-based technology non-set based functionality. and, in fairness, should point out cursors do have use, frowned upon because many folks not used using set-based solutions use cursors instead of figuring out set-based solution. but, when open cursor, loading rows memory , locking them, creating potential blocks. then, cycle through cursor, making changes other tables , still keeping of memory , locks of cursor open. all of has potential cause performance issues other users. so, general rule, cursors frowned upon. if that's first solution arrived @ in solving problem.

asp.net mvc - Is it i possible to prevent certain PartialViews from being served if requested directly? -

i'm working on site has routes actions render partial views. lot of these partial views components make complete page. for instance on search page i'm working on has text box, list of tabs, , table. seach of these can accessed url similar to /search/searchpanel /search/tabs/{searchterm} /search/resultstable/searchterm?tab=[currently selected tab] and these rendered on renderpartial on index page. when page loads, display each of these components way want it. @ moment there's nothing stopping user going directly url /search/tabs to render tab control meaningless outside context of rest of elements on page. is there way me prevent this? have tried marking controller method private ? private partialviewresult mypartialresultmethod() this should allow call within code build pages , disallow public access such through url. i'm testing make doubly sure answer correct i'll update test. in tabs example restrict access using second contro...

How do I get the external IP of a socket in Python? -

when call socket.getsockname() on socket object, returns tuple of machine's internal ip , port. however, retrieve external ip. what's cheapest, efficient manner of doing this? this isn't possible without cooperation external server, because there number of nats between , other computer. if it's custom protocol, ask other system report address it's connected to.

ASP.NET How to change Page controls via custom UserControl? -

i have on page label control , custom usercontrol. want that, when appears in usercontrol, shoud change e.g label's text property (as mentioned, label doesn't belong usercontrol). how ? your best bet use sort of event notify containing page usercontrol updated. public class mycontrol : usercontrol { public event eventhandler somethinghappened; private void somefunc() { if(x == y) { //.... if(somethinghappened != null) somethinghappened(this, eventargs.empty); } } } public class mypage : page { protected void page_init(object sender, eventargs e) { myusercontrol.somethinghappened += myusercontrol_somethinghappened; } private void myusercontrol_somethinghappened(object sender, eventargs e) { // it's business time } } this basic example, recommend using designer interface specify user control's event handler assignment gets handled in designer code-behi...

How do you create an event log source using WiX -

i'm creating installer website uses custom event log source. our wix based installer create event log source during installation. does know best way using wix framework. wix has out-of-the-box support creating event log sources. assuming use wix 3, first need add reference wixutilextension either votive project or command line. can add eventsource element under component : <wix xmlns="http://schemas.microsoft.com/wix/2006/wi" xmlns:util="http://schemas.microsoft.com/wix/utilextension"> <component ...> ... <util:eventsource log="application" name="*source name*" eventmessagefile="*path message file*"/> ... </component> if .net project, can use eventlogmessages.dll in framework directory message file.

How to use hibernate criteria to return only one element of an object instead the entire object? -

i'm trying list of id of object bob example instead of list of bob. it's ok hql request, know if it's possible using criteria ? an example : final stringbuilder hql = new stringbuilder(); hql.append( "select bob.id " ) .append( bob.class.getname() ).append( " bob " ) .append( "where bob.id > 10"); final query query = session.createquery( hql.tostring() ); return query.list(); i think projections, like criteria.forclass(bob.class.getname()) .add(restrictions.gt("id", 10)) .setprojection(projections.property("id")) );

.net - Interview questions: WPF Developer -

what should every wpf developer know? entry level strong .net 2.0 background & willing learn! explain dependency properties? what's style? what's template? binding differences between base classes: visual, uielement, frameworkelement, control visual vs logical tree? property change notification (inotifypropertychange , observablecollection) resourcedictionary - added a7an usercontrols - added a7an difference between bubble , tunnel routing strategies - added carlo why did microsoft introduce yet markup language? xaml mid-level routed events & commands converters - added artur carvalho explain wpf's 2-pass layout engine? how implement panel? interoperability (wpf/winforms) blend / cider - added a7an animations , storyboarding clickonce deployment skinning/themeing custom controls how can worker threads update ui? datatemplate vs hierarchicaldatatemplate itemscontrol vs itemspresenter vs contentcontrol vs contentpresenter diffe...

actionscript 3 - Is there a way to truly extend a Flex component? -

i need create extension of flex component, (obviously) means new component should able used whenever parent used. don't see way it, flex offers 2 ways of extending component, defining class extending parent or creating mxml file uses parent component root element; in both cases can’t use nested elements configure child parent. e. g. package components { import mx.controls.advanceddatagrid; public class fixeddatagrid extends advanceddatagrid { public function fixeddatagrid() { super(); } } } this valid mxml <mx:advanceddatagrid> ... <mx:columns> ... this not valid mxml <mx:fixeddatagrid> ... <mx:columns> ... it doesn't seem valid is-a relation. when defining properties via new mxmltag, property must contain specified in same namespace tag. so this: <mycomp:fixeddatagrid columns="somearray"> without issues. if use mxml tag syntax define columns array property, need this: <myco...

ado.net - How do I access an Excel named table via ADO/ODBC? -

i have workbook multiple sheets, , have created named tables (not ranges) in work book. illustrative purposes, these table names tbla, tblb, , tblc. unable find way query these tables via ado or odbc. can access named ranges, not work needs. thanks! i don't know if can done directly interested see if comes working method. getschema collection of ado seems pick sheetnames , named ranges not listobjects named tables are. below workaround means opening excel find header/data range of table. it's pointless using ado or similar can copy data directly suppose convert named range before saving one-off task? option explicit sub test() dim wb workbook, ws worksheet, strexcelfile string, strsheetname string dim strtablename string, objlistobj listobject, headerrange string dim strsql string, datarange string strexcelfile = "c:\users\osknows\desktop\new folder\test.xlsm" strsheetname = "sheet1" strtablename = "tablename" set wb = geto...

How does display tooltip for the questions?

while ask question, shows related questions. if hover on questions content displayed tooltip contains linebreaks, indentations etc. technique uses it? how display tooltips wit formatting? other than, jquery/javascript there simple way achieve it? was wondering, should ask on meta? it title attribute on hyperlink, plain , simple. <a href="..." title="the value approximately 3.14159265 simplicity can round 3.0">what value of pi?</a> in ie, chrome & safari, honors line breaks bit more strictly firefox or opera.

ipad - Need help with an activity indicator -

i can't activity indicator work. here's i've got- -(void)viewwillappear:(bool)animated{ [super viewwillappear:yes]; //create instance of activity indicator view uiactivityindicatorview * activityindicator = [[uiactivityindicatorview alloc] initwithframe:cgrectmake(0, 0, 20, 20)]; //set initial property [activityindicator stopanimating]; [activityindicator hideswhenstopped]; //create instance of bar button item custome view of activity indicator uibarbuttonitem * barbutton = [[uibarbuttonitem alloc] initwithcustomview:activityindicator]; //set bar button navigation bar [self navigationitem].rightbarbuttonitem = barbutton; //memory clean [activityindicator release]; [barbutton release]; } the part of code supposed started , ended-- ... else if ([theselection isequaltostring: @"update statistics"]) { [self starttheanimation]; [updatestatistics updatethe2010statistics]; [self stoptheanimation]; } ... -(void)startthean...

asp.net - All controls are still null after calling EnsureChildControls()? -

the way page laid out, of data loaded @ page_init . well, have custom control having problems though. i have on page so: <cc:somecontrol... /> and set value @ page_init using mycontrol.value="blah"; simple stuff.. the value accessor , has similar this: public string value{ get... set{ ensurechildcontrols(); myhiddenfield.value=value; } } and here have problem. says myhiddenfield null. page_init this? or there other function need call? the fix changing using namespace reference customcontrol using src filename changing this: <%@ register assembly="myproduct" namespace="myproduct.customcontrols" tagprefix="cc" %> to this: <%@ register src="/customcontrols/mycontrol.ascx" tagname="mycontrol" tagprefix="uc2" %>

ruby - Rails Model, View, Controller, and Helper: what goes where? -

in ruby on rails development (or mvc in general), quick rule should follow put logic. please answer in affirmative - do put here , rather don't put there . mvc controller : put code here has working out user wants, , deciding give them, working out whether logged in, whether should see data, etc. in end, controller looks @ requests , works out data (models) show , views render. if in doubt whether code should go in controller, shouldn't. keep controllers skinny . view : view should contain minimum code display data (model), shouldn't lots of processing or calculating, should displaying data calculated (or summarized) model, or generated controller. if view needs processing can't done model or controller, put code in helper. lots of ruby code in view makes pages markup hard read. model : model should all code relates data (the entities make site e.g. users, post, accounts, friends etc.) lives. if code needs save, update or summarise data related e...

c# - Checkbox in listview control -

can have multicolumn listview control 1 of columns checkbox? example code or links appreciated. i using visual studio 2005 allan anderson created custom control let this. can find here: http://www.codeproject.com/kb/list/aa_listview.aspx here's example code control: glaciallist mylist = new glaciallist(); mylist.columns.add( "column1", 100 ); // can added // through design time support mylist.columns.add( "column2", 100 ); mylist.columns.add( "column3", 100 ); mylist.columns.add( "column4", 100 ); glitem item; item = this.glaciallist1.items.add( "atlanta braves" ); item.subitems[1].text = "8v"; item.subitems[2].text = "live"; item.subitems[2].backcolor = color.bisque; item.subitems[3].text = "mlb.tv"; item = this.glaciallist1.items.add( "florida marlins" ); item.subitems[1].text = ""; item.subitems[2].text = "delayed"; item.subi...

mod rewrite - mod_rewrite equivalent for IIS 7.0 -

is there mod_rewrite equivalent iis 7.0 that's a) more or less complete b) suitable production environment, i.e. battle-tested/dependable/secure do have experience-based recommendation? check out url rewrite module iis 7 created microsoft

sql server - SQL Select Bottom Records -

i have query wish retrieve oldest x records. @ present query following: select id, title, comments, createddate mytable createddate > @olderthandate order createddate desc i know remove 'desc' keyword switch order of records, in instance still want records ordered newest item first. so want know if there means of performing query such oldest x items sorted such newest item first. should add database exists on sql server 2005. why not use subquery? select t1.* (select top x id, title, comments, createddate mytable createddate > @olderthandate order createddate) t1 order createddate desc

The best way to start a project -

when starting personal programming project, first step? i'm trying start project thats idea @ moment. lots of these , dive right code , after while lose interest , or forget project. when starting, first step? plan out project? make diagram? write code on paper? how start project in manner know succeed? the thing works me: create smallest possible implementation of that's somehow usable , use it.

visual studio 2010 - How do I keep MSDeploy from deleting extra folders in my project? -

i using msbuild runner in team city build , deploy project staging environment. works except fact keeps removing repository folder located in root of project. in visual studio 2010 there check box in publish profile dialog says "leave files on destination (do not delete)" is there way accomplish same thing msbuild? <target name="deploy" dependsontargets="build;test"> <msbuild projects="myproject.sln" properties="configuration=$(configuration); username=username; password=password; deployonbuild=true; deploytarget=msdeploypublish; msdeploypublishmethod=wmsvc; msdeployserviceurl=https://devweb01:8172/msdeploy.axd; deployiisapppath=myproject.$(configuration); allowuntrustedcertificate=true;"/> </target> found answer! all need add following property properties attribute: skipextrafilesonserver=true;

javascript - Passing Class Variables to Class Method in Prototype via addEventListener -

i have following class file i'm attempting build. i'd pass multiple variables method way of eventlistener code have below doesn't work, due scoping. not sure should change though. advice appreciated. var myclass= new class.create(); myclass.prototype = { initialize: function(id,name,top,left){ try{ this.id = id; this.name = name; this.currenttop = top; this.currentleft = left; $(id).addeventlistener("mousedown",function(event,this.id,this.name){ this.grabobj(event,this.id,this.name); },false); } catch(error){alert(error);} }, grabobj:function(event,myid,myname){ // here myid , myname } }; your syntax wrong. instead, should make separate variable hold real this , this: var myclass= new class.create(); myclass.prototype = { initialize: function(id,name,top,left){ try{ this.id = id; ...

Web in a desktop application: Good web browser controls? -

i've been utlising "web browser control" in desktop based applications (in case windows forms .net) number of years. use create familiar flow-based user interface allows seamless transition internet required. i'm tired of ie browser control because of poor quality html generates on output. also, guess ie7 behind scenes , has many of browser "issues". despite this, quite powerful control , provides rich interaction desktop app. so, other alternatives ie browser control there? looked @ mosaic equivalent year ago disappointed number of unimplemented features, maybe has improved recently? hmm..interestingly mozilla seems provide activex control k-melon gecko based browser control

iphone - Deleting multiple (not yet loaded) rows in UITableView -

i'm having bit of trouble trying delete rows haven't been loaded (or not visible) uitableview. my setup follows - there 2 sections in tableview , each element in section 1 associated multiple elements section two. to give example (the data isn't related i'm trying do, believe example doesn't require explanation) section 1 bmw acura merc section 2 328i 335i rx lx tx c300 c550 my internal model goes - nsmutablearray cars[] nsmutablearray models[] cars[0] = "bmw" cars[1] = "acura" cars[2] = "merc" each element in models[] vector , conents listed below models = [ ["328i", "335i"], ["rx", "lx", "tx"], ["c300", "c550"] ]; so functionality i'm trying build. if user clicks delete , tries delete bmw, app needs remove entry bmw section 1 , entries 328i , 335i in section two. however, user free delete single row of section 2 independe...

android - Padding in different phones -

say add linear layout top padding of 20. mean layout rendered 20 pixels of padding in phones? or scale according height/width/density of phone? in java code going pixels on devices. if want make density respected (like using 20dp or 20dip) can use: float density = context.getresources().getdisplaymetrics().density; setpadding(20 * density, blah, blah, blah); that density var 1.0 on medium phones, or more or less depending on density of screen.

osx - Installing PDO-drivers for PostgreSQL on Mac (using Zend for eclipse) -

how can pdo work on mac (os x 10.5)? i'm using built in php , php in zend/eclipse. can't seem find useful drivers @ all. i had install pdo_pgsql driver on leopard, , ran across multitude of problems. in search answers, stumbled across question. have installed, , so, though question quite old, hope i've found can others (like myself) undoubtedly run similar problems. the first thing you'll need install pear , if haven't done already, since doesn't come installed on leopard default. once that, use pecl installer download pdo_pgsql package: $ pecl download pdo_pgsql $ tar xzf pdo_pgsql-1.0.2.tgz (note: may have run pecl superuser, i.e. sudo pecl .) after that, since pecl installer can't install extension directly, you'll need build , install yourself: $ cd pdo_pgsql-1.0.2 $ phpize $ ./configure --with-pdo-pgsql=/path/to/your/postgresql/installation $ make && sudo make install if goes well, should have file called " p...

virtualization - Replacing Virtual PC/Server with VMWare Fusion/Server for Development Environments -

i develop exclusively on vms. run boot camp on macbook pro , development on series of virtual pc vms many different environments. post andrew connell litterally changed way work. i'm thinking switching fusion , running in os x wasn't able answer following questions vm fusion/workstation/server. i need know if following features virtual pc/server exist in vmware counter parts. differencing disks (ability create base vm , provision new vms add deltas on top of base [saves ton of disk space, , makes easy spin new vms base set of funcitonality]). (not available fusion, need workstation [$189]) undo disks (ability rollback changes vm within session). (available in both workstation , fusion [$189/$79.99 respectively]) easily nat out different subnet vm sit in. (in both fusion/workstation). share vms between vm player , vm server. i'd build vm locally (on os x/fusion) , move server (win2k3/win2k8 , vm server) , host there vm server. (in both fusion/workstation). an e...

asp.net - How do I detect new aspx file and get information from them? -

i'm developing website has modular section. when new aspx (and aspx.cs) file placed in subdirectory of application can ask class information... the idea when file placed in directory new menu item added menu. need "ask class" name, icon, description, etc. is there way determine class defined in codebehind file , instantiate instance of it? i know , parse config file each plugin rather not have go route. the "standard" method config file mention, in form of sitemap. you'll lot of features out of doing way, breadcrumbs , forth. know answer asked not get, there anyway. if insist, though, there's nothing stopping using mappath , searching disk .aspx files, parsing them pull out info (like class name), , doing whatever like. but sitemap better, unless have strange requirement. note sitemap can come database or dynamic source, doesn't have xml file.

jailbreak - Programatically installing the application in iPhone -

hi, i install .app programatically application. hope can done through jailbrokken iphones. can share knowledge regarding this. found application called "callme" in cydia store. application programatically installs other one. or how install iphone applications (.app) file in iphone terminal. if programatically execute system commands, hope s possible install application programatically in jailbroken iphones. awaiting reply. - mohammed sadiq. as far know, need download (somehow) , put unpacked application in /var/mobile/applications on phone. @ existing structure (with terminal, on jailbroken phone) , follow it.

c++ - Compile errors for double linked list code -

i have tried implement doubly linked list in c++. here code, #include <iostream> using namespace std; //double linked list class link{ public: long data; link *next; public: link(long d) { data=d; } void displaylink() { cout<<data<<" "<<"\n"; } }; class firstl { private: link *first; link *last; public: firstl() { first=null; last=null; } public: bool empthy() { return (first==null); } public: void insertfirst(long dd) { link *newlink=new link(dd); if (empthy) last=newlink; newlink->next=first; first=newlink; } public : void insertlast(long dd) { link *newlink=new link(dd); if (empthy) first=newlink; else ...

Endless loop in JavaScript that does not trigger warning by browser -

i'm displaying set of images overlay using google maps. displaying these images should in endless loop most browsers detect this, , display warning. is there way make endless loop in javascript isn't stopped or warned against browser? try setinterval or settimeout edit: in simple example: http://n0p.com/so/63011.php

Hidden features of Ruby -

continuing "hidden features of ..." meme, let's share lesser-known useful features of ruby programming language. try limit discussion core ruby, without ruby on rails stuff. see also: hidden features of c# hidden features of java hidden features of javascript hidden features of ruby on rails hidden features of python (please, one hidden feature per answer.) thank you from ruby 1.9 proc#=== alias proc#call, means proc objects can used in case statements so: def multiple_of(factor) proc.new{|product| product.modulo(factor).zero?} end case number when multiple_of(3) puts "multiple of 3" when multiple_of(7) puts "multiple of 7" end

.net - Can I suppress FX Cop code analysis violations globally? -

when use visual studio's code analysic (fxcop), , want suppress message there 3 options. suppress violation in code. suppress violation in globalsupression.cs file. disable violation check in project file (via project -> properties -> code analysic). the later hard review when checking in source control, , hard overview of disabled violations. use option 2. the problem option 1 , 2 1 suppression line each violation. e.g like: [assembly: suppressmessage("microsoft.design", "ca1020:avoidnamespaceswithfewtypes", scope = "namespace", target = "company.project.namespace2")] [assembly: suppressmessage("microsoft.design", "ca1020:avoidnamespaceswithfewtypes", scope = "namespace", target = "company.project.namespace1")] we love ing globalsuppressions.cs: [assembly: suppressmessage("microsoft.design", "ca1020:avoidnamespaceswithfewtypes")] but possible? su...

css - Why not use tables for layout in HTML? -

it seems general opinion tables should not used layout in html. why? i have never (or honest) seen arguments this. usual answers are: it's separate content layout but fallacious argument; cliche thinking . guess it's true using table element layout has little tabular data. what? boss care? users care? perhaps me or fellow developers have maintain web page care... table less maintainable? think using table easier using divs , css. by way... why using div or span separation of content layout , table not? getting layout divs requires lot of nested divs. readability of code i think it's other way around. people understand html, few understand css. it's better seo not use tables why? can show evidence is? or statement google tables discouraged seo perspective? tables slower. an tbody element has inserted. peanuts modern web browsers. show me benchmarks use of table slows down page. a layout overhaul easier without tables, see css zen garden . most web sites ...

performance - Periodically check if android GPS has new data -

i have been getting gps data through registerlocationlistener() , onlocationchanged() methods. problem speed reading of app freezes if there no more gps data (e.g. when go indoors, enter tunnel, etc). behavior want app user somehow notified speed reading not accurate due lack of fresh data (set speed zero, blink speed reading, etc). how can that? though of checking periodically whether gps unit detecting satellites, i'm not sure how force periodic checks. maybe start periodic timer. if timer sees last gps fix old displays notification. application should remember when last fix was.

audio - iPhone AudioSession properties -

i'm developing app should have following properties regarding audio: can record , play sound @ same time can mix audio output other app, e.g. ipod audio output @ speaker when earphone not plugged in audio output @ earphone when plugged in i used following code. avaudiosession *audiosession = [avaudiosession sharedinstance]; nserror *audiosessionerror; [audiosession setcategory:avaudiosessioncategoryplayandrecord error:&audiosessionerror]; uint32 mix = 1; audiosessionsetproperty(kaudiosessionproperty_overridecategorymixwithothers, sizeof(mix), &mix); uint32 route = kaudiosessionoverrideaudioroute_speaker; audiosessionsetproperty(kaudiosessionproperty_overrideaudioroute, sizeof(route), &route); [audiosession setactive:yes error:&audiosessionerror]; however, can achieve 1-3 failed @ 4. when earphone plugged in, audio still comes through speaker. tried setting kaudiosessionproperty_overridecategorydefaulttospeaker instead of kaudiosessionproperty_...

html - Navigation on Website Positioned Incorrectly -

i'm converting portfolio mock html/css , i've come across has confused me. http://www.mozazdesign.co.cc/ as can see, navigation text positioned in wrong place; want inline markers. i've looked through code loads , looked @ other websites can't figure out why it's not working.. this exact code: <head> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <link href="styles.css" rel="stylesheet" type="text/css" /> <title>mozazdesign portfolio</title> </head> <body> <div id="container"> <div id="header"> <div id="logo"> </div><!--end logo--> <div id="nav"> <ul id="main_nav"> <li><a href="#">home</a></li> <li><a href="#">about me<...

Can anyone recommend a simple Java web-app framework? -

i'm trying started on i'm hoping relatively quick web application in java, yet of frameworks i've tried (apache wicket, liftweb) require set-up, configuration, , trying wrap head around maven while getting whole thing play nice eclipse, spent whole weekend trying point write first line of code! can recommend simple java webapp framework doesn't involve maven, hideously complicated directory structures, or countless xml files must manually edited? haven't tried myself, think http://www.playframework.org/ has lot of potential... coming php , classic asp, it's first java web framework sounds promising me.... edit original question asker - 2011-06-09 just wanted provide update. i went play , asked for. requires little configuration, , works out of box. unusual in eschews common java best-practices in favor of keeping things simple possible. in particular, makes heavy use of static methods, , introspection on names of variables passed ...

c++ - STL like container typedef shortcut? -

a common pattern stl containers this: map<key, value> map; for(map<key, value>::iterator iter = map.begin(); iter != map.end(); ++iter) { ... } so in order avoid writing declaration of template parameters can somewhere: typedef map<key, value> tnicenameforamap; but if map used in single function or single iteration annoying overhead. is there way around typedef? not sure mean "overhead". if simplifies way write code, use it, otherwise stick longhand. if it's used in restricted scope, put typedef in same scope. doesn't need published, or documented, or appear on uml diagrams. example (and don't claim best code ever in other respects): int totalsize() { typedef std::map<key, value> deduplicator; deduplicator everything; // run around universe finding everything. if encounter key // more once it's added once. // compute total int total = 0; for(deduplicator::iterator = everything.b...

sql - AIR Sqlite: SQLEvent.RESULT not firing, but statement IS executing properly -

ok looks likes have stumbled upon strange timing issue... made quick sql wrapper class executing sql statements. after .execute() called, sqlevent.result event never fired, new entry in db created should be. really odd part if put settimeout() after calling execute() event fires expected.. hope i'm missing obvious here... here link example air app: http://www.massivepoint.com/airsqltest/airsql.zip and here code wrapper class: if down @ line 51 in sqlrequest class, see commented out settimeout() method. make work, uncomment line.. me doesn't make sense... anyone have thoughts? i'm totally stumped here... package com.jac.sqlite {//package import flash.data.sqlconnection; import flash.data.sqlstatement; import flash.events.eventdispatcher; import flash.events.sqlerrorevent; import flash.events.sqlevent; import flash.utils.settimeout; public class sqlrequest extends eventdispatcher {//sqlrequest class private var _callback:function; private var _...

browser - Using same cache from different static servers -

i'm thinking adding static server web app, i'd have static1.domain.tld , static2.domain.tld. the point use different domains in order load static content faster ( more parallel connections @ same time ), 'troubles' me "how user's browser see static1.domain.tld/images/whatever.jpg , static2.domain.tld/images/whatever.jpg same file" ? is there trick accomplish headers or i'll have define file on server? no, there's no way tell browser 2 urls same -- browser caches full url. what can make sure use same url same image. ie. images start a-m go on server 1, n-z go on server 2. real implementation, i'd use hash based on name or that, there's libraries kind of thing you.

Best way to find if an item is in a JavaScript array? -

this question has answer here: how check if array includes object in javascript? 39 answers what best way find if object in array? this best way know: function include(arr, obj) { for(var i=0; i<arr.length; i++) { if (arr[i] == obj) return true; } } include([1,2,3,4], 3); // true include([1,2,3,4], 6); // undefined function include(arr,obj) { return (arr.indexof(obj) != -1); } edit: not work on ie6, 7 or 8 though. best workaround define if it's not present: mozilla's (ecma-262) version: if (!array.prototype.indexof) { array.prototype.indexof = function(searchelement /*, fromindex */) { "use strict"; if (this === void 0 || === null) throw new typeerror(); var t = object(this); var len = t.length >>> 0; if (len === 0) return -1; var n = 0; ...

ASP.NET GridView postback not setting posted controls' values -

when adding edititemtemplate of complexity (mulitple fields in 1 template), , parsing controls rowupdating event, controls manually entered user have no values. guess there going on when data bound, i've had instances adding , attribute control in codebehind started behavior , removing code made code work. work-around, can request(controlname.uniqueid) it's value, rather hack. edit when access value so textbox txtvalue = gvwsettings.selectedrow.findcontrol("txtvalue") textbox; the text box found, .text not user input. did turn off viewstate? did add control programmatically in template? if so, did create them @ correct stage?

php - When to use self over $this? -

in php 5, difference between using self , $this ? when each appropriate? short answer use $this refer current object. use self refer current class. in other words, use $this->member non-static members, use self::$member static members. full answer here example of correct usage of $this , self non-static , static member variables: <?php class x { private $non_static_member = 1; private static $static_member = 2; function __construct() { echo $this->non_static_member . ' ' . self::$static_member; } } new x(); ?> here example of incorrect usage of $this , self non-static , static member variables: <?php class x { private $non_static_member = 1; private static $static_member = 2; function __construct() { echo self::$non_static_member . ' ' . $this->static_member; } } new x(); ?> here example of polymorphism $this member functio...

css - Could I get in legal trouble for copying a website's stylesheet? -

i simplistic , design of of microsoft blogs. alas, can't join microsoft dev party , create own development blog on blogs.msdn.com page because don't work @ microsoft, , have own wordpress blog. i looking have blog styled 1 of default looking themes shown here: http://blogs.msdn.com/jmeier/default.aspx could microsoft take legal action against me if used stylesheet page? if made page 'based' off stylesheet, e.g. written ground up, copyright infringement? could microsoft take legal action against me if used stylesheet page? absolutely, since infringed copyright. on other hand, it's debatable whether stylesheet alone constitues sufficient threshold of originality justify legal actions 1 . @ least, taking without asking considered rude. ;-) 1) no. doesn't . sophisticated design will.

c# - Efficient way of logging to txt file from a console program -

what efficient way of recording log (.txt) console program on c# , .net 2.2? program loops multiple times outputting different data based on user wants, i'm searching efficient way achieve this. i know can reopen stream , close it, everytime writing 1 line, next time around (seconds later) program reloops , needs tor write again. in opinion, doesn't seem resourse friendly. i'm using multiple threads have output data want log (opening/closing same file or accessing same file on different threads might bad). "holds reference stream writer auto-flushes" sounds idea, don't know how that. you hook tracing framework forms part of clr. using simple class like: http://www.chaosink.co.uk/files/tracing.zip can selectively log diagnostic information. use add class application. create inistance of tracer in class like: private tracing trace = new tracing("my.namespace.class"); and call using: myclass() { trace.verbose("entered my...

php - Best way to get result count before LIMIT was applied -

when paging through data comes db, need know how many pages there render page jump controls. currently running query twice, once wrapped in count() determine total results, , second time limit applied results need current page. this seems inefficient. there better way determine how many results have been returned before limit applied? i using php , postgres. pure sql things have changed since 2008. can use window function full count , limited result in 1 query. (introduced postgresql 8.4 in 2009 ). select foo ,count(*) over() full_count bar <some condition> order <some col> limit <pagesize> offset <offset> note can considerably more expensive without total count. rows have counted, , shortcut taking top rows matching index not possible. doesn't matter small tables, matters big tables. consider sequence of events : where clause (and join conditions, not here) filter qualifying rows base table(s). ( group by , ...

.net - C# - Xml serializing ambiguous complex types -

i have problem can perhaps solved in more efficient or clean way, current solution. over past days have gotten understanding of how xml serialization can controlled via attributes, 1 part of xml structure obscure, have not been able find smart solution. i have been handed xml schema, cannot altered, , must create c# class. the code bugs me following: <xs:complextype name="datareftype"> <xs:sequence> <xs:element name="data" type="datatype"/> <xs:sequence minoccurs="0" maxoccurs="unbounded"> <xs:element name="separator" type="xs:string"/> <xs:element name="data" type="datatype"/> </xs:sequence> </xs:sequence> </xs:complextype> <xs:complextype name="datatype"> <xs:choice> <xs:sequence> <xs:element name="dataowner" ty...

c++ - Visual Studio 2008: Use external Debug-DLL for Debug-Run and external Release-DLL for Release-Run -

short version: if running program vs2008 in release mode, want use patha\externaldll.dll . if running program vs2008 in debug mode, want use pathb\externaldll.dll long version: have programm linked against external dll-files (vtk). have built external application myself in both debug , release mode. external dll-files located this: <some path>\debug\externaldll.dll <some path>\release\externaldll.dll (so called same, have different folders). i want step external code debug builds, want release builds use release dlls testing execution time (i process big datasets). linking according dlls easy, have project settings that. when executing, visual studio takes first dll finds within path environment variable. cumbersome solution idea: having path variable like: path=;%currentdllpath%; , setting currentdllpath in post-build-step. there no solution built-in vs2008? actually there built-in , easy way: the "environment"-variable within ...

iphone screenshot specific area -

i have view including toolbar , webview uiview uitoolbar uiwebview now make screenshot webview with: uigraphicsbeginimagecontext(articlewebview.window.bounds.size); [articlewebview.window.layer renderincontext:uigraphicsgetcurrentcontext()]; uiimage *screenimage = uigraphicsgetimagefromcurrentimagecontext(); uigraphicsendimagecontext(); but imagecapture starts top of screen. includes toolbar (even 20 empty pixel @ top statusbar) how can capture image thats actual in uiwebview? thanks chris your uiwebview backed own layer, should able grab displayed contents it: uigraphicsbeginimagecontext(articlewebview.bounds.size); [articlewebview.layer renderincontext:uigraphicsgetcurrentcontext()]; uiimage *screenimage = uigraphicsgetimagefromcurrentimagecontext(); uigraphicsendimagecontext();

php - IFrame Comet response contains no data -

i'm experimenting comet , i'm stuck implementing via hidden iframe ("forever frame". this index.html: <!doctype html> <html> <head> <script type="text/javascript"> cometresponse = function() { var debugout = document.getelementbyid('debugoutput'); return function(response) { debugout.innerhtml = response.number; } } </script> </head> <body> <div id="debugoutput"></div> <iframe src="comet.php"></iframe> </body> </html> and comet.php file: <?php set_time_limit(0); header('content-type: text/html'); header('cache-control: no-cache, must-revalidate'); header('expires: mon, 26 jul 1997 05:00:00 gmt'); header('transfer-encoding: chunked'); flush(); ob_flush(); $response = '<script type="text/javascript"> parent.cometresponse...

kernel - What is the difference between an nanokernel and an exokernel? -

i understand both supposed small, key differences between two? exokernel operating system mit (and class of it's variants) handles relatively little hardware abstraction. in exokernel, low-level responsibilities of controlling hardware (particularly memory allocation ) left in hands of developer. many developers prefer have os take more responsibility of such low-level tasks, because developers writing applications. an exokernel allocates physical hardware resources programs . allows program use library operating systems, linked in provide of abstraction exokernel isn't providing. developer can choose between abstraction models, or roll own. given application, may have great performance benefits. if don't know you're doing, can write programs explode when crash. most kernels more abstract physical hardware resources kind of theoretical model . developer interfaces model, handles finer points of dealing hardware internally. the term nanokern...

java - How to make junit testing to stop after first failing test -

is there way make running junit test stop after test fails? yes ... ability (or lack of it) built various testrunners (console, awt, swing, ant, maven or 1 built eclipse, etc). you'll have control in documentation specific platform you're using.

ruby on rails - ActiveRecord serialization problem -

i have db column serialized hash : class foo < activerecord::base serialize :bar end when store hash inside of bar few levels deep, deeper levels not seem deserialize when need them. objects 1 level deep deserialzed fine. however, objects 2 or more levels deep remain yaml classes. i tried manually deserializing using yaml::load() got error saying argument wasn't instance of io. does know why complete ruby object doesn't deserialize? edit : after further investigation, problem seems stem fact i'm calling virtual attribute serialized yaml. class foo < activerecord::base serialize :bar end class bar < activerecord::base attr_accessor :enabled end @bars = @foo.bar[:bars] @bars.each |bar| puts bar.enabled end yields: nomethoderror: undefined method `enabled' #<yaml::object:0xb6f11844> (irb):12 (irb):11:in `each' (irb):11 :0 does mean deserialization isn't "real", ie, yaml object acts simila...

C# delegate dictionary add -

i want create method this: private static void addorappend<k>(this dictionary<k, multicastdelegate> firstlist, k key, multicastdelegate newfunc) { if (!firstlist.containskey(key)) { firstlist.add(key, newfunc); } else { firstlist[key] += newfunc; // line fails } } but fails because says can't add multicast delegates. there i'm missing? thought delegate keyword shorthand class inherits multicastdelegate. firstlist[key] = (multicastdelegate)delegate.combine(firstlist[key],newfunc); with test: var data = new dictionary<int, multicastdelegate>(); action action1 = () => console.writeline("abc"); action action2 = () => console.writeline("def"); data.addorappend(1, action1); data.addorappend(1, action2); data[1].dynamicinvoke(); (which works) but tbh, use delegate in place of multicastdelegate ; largely hangover never worked. o...

linux - appname: /lib/libc.so.6: version `GLIBC_2.8' not found (required by appname) -

ldd -v appname linux-gate.so.1 => (0x00949000) libpthread.so.0 => /lib/libpthread.so.0 (0x00cea000) libm.so.6 => /lib/libm.so.6 (0x00a83000) libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0x00ba1000) libc.so.6 => /lib/libc.so.6 (0x0015c000) /lib/ld-linux.so.2 (0x0012f000) libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x00b93000) version information: appname: libm.so.6 (glibc_2.0) => /lib/libm.so.6 libc.so.6 (glibc_2.8) => not found libc.so.6 (glibc_2.2) => /lib/libc.so.6 libc.so.6 (glibc_2.3.2) => /lib/libc.so.6 libc.so.6 (glibc_2.7) => not found libc.so.6 (glibc_2.4) => /lib/libc.so.6 libc.so.6 (glibc_private) => /lib/libc.so.6 libc.so.6 (glibc_2.1) => /lib/libc.so.6 libc.so.6 (glibc_2.1.3) => /lib/libc.so.6 libc.so.6 (glibc_2.2.4) => /lib/libc.so.6 libc.so.6 (glibc_2.3) => /lib/libc.so.6 libc.so.6 (glibc_2.0) => /lib/libc.so.6 libstdc++.so.6 (cxxabi_1.3) => /usr/lib/libstdc++.so.6 ...

xml - Need advice for XMLText usage in C# -

i writing output module visualize data on program. if inspect code, add point coordinates string , add string textnode element. problem number of points can more 500000 is there better way write lot of text xml or ok? xmlelement points = doc.createelement("vtk", "dataarray"); string str = ""; (int = 0; < sim.numberofparticles; i++) { str += sim.pposx[i].tostring() + " " + sim.pposy[i] + " " + sim.pposz[i] + "\n" } xmltext coordinates = doc.createtextnode(str); points.appendchild(coordinates); for amount of data, use xmlwriter instead of xmldocument . streams , resources no problem more.

sql - how to exclude rows that have duplicates in one field -

i have simple task, cannot find solution. have 2 tables, 'articles' , 'categories' my article table this: id | cat_id | title | content 1 1 blah content 1 2 1 blah2 content 2 3 2 blah3 content 3 my categories table this: id | title 1 category 1 2 category 2 you see have 2 articles have same cat_id. not want duplicate cat_id field. cannot use distinct, because articles, because want fields out. so if use distinct this: select distinct a.id, a.cat_id, a.title, a.content articles a i out, want output this id | cat_id | title | content 2 1 blah2 content 2 3 2 blah3 content 3 can me please !!! this query select first article (lowest id) each category select a.* article left join article a2 on a.id<a2.id , a.cat_id=a2.cat_id a2.id null it outer join other articles. join clause joins articles same category , smaller id. when there no matches (a2.id null), have ...

What needs to go in order to fully remove a MAMP install from OSX? -

for reasons won't discuss, have determined mamp pile of crap haunts system, , unless remove fully, live in shame. i've done obvious thing , removed mamp directory applications folder, however, don't wandering files, , have itching feeling mamp put .sock files somewhere, or otherwise made mess in file system. what files mamp add system when it's installed, , they? if have proof mamp doesn't put files anywhere (besides /mamp dir), that's answer any! from help page : to "uninstall" mamp, have delete mamp directory , returns original state (mamp not alter on "normal" os x).