Posts

Showing posts from August, 2010

jsf - ViewExpiredException after upgrade to jsf2 -

we upgraded major platform jsf 1.2 2.0. after upgrading we're getting several viewexpiredexception errors each hour. reading on topic seems expected exception when sessions expire, we've reviewed access logs , getting these exceptions when requests 5 minutes apart in cases. my questions follows: 1) other session expiration, other conditions might cause viewexpiredexception? 2) exception we're logging doesn't contain detail exact condition causing exception (missing session, corrupt session, unable restore particular component). there way introduce additional logging find out specific situation triggering exception in each case? mojarra 2.0.4-b09 tomcat 6 using memcached session manager session replication any appreciated. thanks! other session expiration, other conditions might cause viewexpiredexception? the enduser has requested/created views within session , submitting old view. default max views per session 15. in other words, if enduser...

c# - Column Values Customisation- Export Excel in ASP.NET -

i have export gridview in excel sheet 2003. code can export data excel sheet directly. if there null value column, how replace empty string in excel sheet. there date column null, there event handler occurs between export button click , loading data excel. if there 1 can compare values in database , can replace null value empty string. in evnt handler. please point me in right direction. thank you on click of export button, can iterate through grid rows , replace whatever need. example, code below replace : . : protected void btnexport_click(object sender, eventargs e) { stringwriter sw = new stringwriter(); htmltextwriter htw = new htmltextwriter(sw); string attachment = "attachment; filename=summaryreport" + datetime.now.tostring() + ".xls"; response.clearcontent(); response.addheader("content-disposition", attachment); response.contenttype = "application/ms-excel"; foreach (gridviewrow grdrow...

cocos2d extend touch area from a button -

i got radiobuttons toucharea small. toucharea depends on image size. there elegant way extend touch area cocos2d without using bigger image or make own touch areas cgrect? setcontentsize want. unfortunately image moves left bottom corner of contentsize. set anchorpoint moves contentsize around image stays in left bottom corner. ccmenuitem* pickeasy = [ccmenuitemimage itemfromnormalimage:@"radiobutton_off.png" selectedimage:@"radiobutton_on.png" target:self selector:@selector(pickeasytapped:)]; pickeasy.position = ccp(ss.width * 0.40, ss.height * 0.78); [pickeasy setcontentsize:cgsizemake(50, 50)]; thanks in advance. you need override rectinpixels method - (cgrect)rectinpixels { cgsize s = [self contentsize]; return cgrectmake(0, 0, s.width, s.height); } - (bool)containstouchlocation:(uitouch *)touch { cgpoint p = [self converttouchtonodespace:touch]; cgrect r = [self rectinpixels]; return cgrectcontainspoint(r, p); } - (bool)cctou...

javascript - How to access a variable state from the defining function rather than the calling object -

eg: func = (){ var i_want_this = "yes"; var callback = function(){ // want access value of i_want_this here // preferably single variable without whole scope }; obj.subfunc(some_stuff, callback); }; obj = { subfunc = function(stuff, callback){ // stuff callback(); } }; func(); you can use variable in callback; work way want to. this called closure .

Any ideas on how to create a local customised AVI player in Flash that will play from a USB drive? -

i'm looking create solution enable me have folder of avi files on usb drive, packaged along custom designed player (probably built in flash). creare packaged flash file in way autorun on inserting drive if @ possible. solution need platform agnostic (hence thinking flash best bet). has come across tutorial achieving similar above? i've been trawling through google not getting luck. any can provide gratefully received. thanks in advance, jh you don't want videos avi files if wanna work cross platform. why? flash has no support avi files. macs miss avi support. using avi blocks using authoring application adobe director uses underlying os video playback. if still want use flash suggest taking @ h264/mp4 codec/container.

c++ - std::unique_ptr usage -

std::unique_ptr<int> p1(new int); std::unique_ptr<int> p2(new int); p2=p1; it seems here p1 no longer "unique" since p2 refer also it legal c++ ? unique_ptr have copy_semantics ? if no, , if has move semantics, p1 set null after assign p2 ? edit: ok correct version is p2=std::move(p1) according that, after assign, p1 not valid ? , difference auto_ptr here? more safe explictly specfiy transfer of ownership implicitly case auto_ptr guess std::unique_ptr non-assignable , non-copyable. need use std::move(); so p1 = std::move(p2); have here more info.

sql - does an index provide order by itself? -

lets have create table mytable( varchar(200) b varchar(200) c varchar(200) ) create index on mytable (b) if select select a, b, c mytable; would sorted b? there 2 main types of indexes: clustering , non-clustering. the clustering index determines physical row order in table. inserting table (or updating respective field) causes database engine re-order data field clustering index on sorted correctly. that's why there can 1 clustering index on table. non-clustering indexes copies of columns, ordered desired. exist separately, , physical row order not connected them. that's why there can many non-clustering indexes want. most simple select on single table returns rows in physical order, not surprising receive them sorted way the clustering index is. however, not guaranteed , should not rely on it. always include order clause if result set order of concern. if order clustering index, there not work db engine, intent clear. if order non-cluste...

testing - How to mock a class in Python? -

i'm new python, used work ruby. i'm trying tests python can't figure out how mock class test. let's have real class: from database import db class foo: def do_it(self): x = {'key': 'value'} db.save(x) # other stuff x return x now, want test if i'm doing x returns me right result, , want test if db.save called x parameter, don't want save x database. see if db.save being called, can use mock framework, how can tell foo class need use mock object , not real db object? thank you. edit: sorry, example wasn't enough need accomplish. let's see new example: from database import db class foo: db.connect() def do_it(self): x = {'key': 'value'} db.save(x) # other stuff x return x and instance, let's database down. when import foo, raises connection error , not have time mock db. what should do?? the answer is, don't write classes that. it's strange...

php - Firefox automatically adding closing form tag too early - IE and Chrome OK -

can tell me why firefox close form adding </form> ? closes form before submit button - form won't submit. the whole code form bit long post here. works fine in chrome , ie, firefox seems close form , removes later </form> . the html being output php. not sure if make difference? editing in firebug doesn't work either. ideas appreciated. thanks when browser closes form or div unexpectedly, it's because there's kind of mistake in code - closing div instead of opening one. i suggest feed code w3c validator , , fix errors.

c# - Updating through LINQ in different DataBase -

i have db looks this: 1st: commissionsv2 (table = entity_product_point) dbml has 1 table. 2nd: webenroll (table = planmaster) dbml has 1 table in it. now through linq adding row in has query this: commissionsv2datacontext cv = new commissionsv2datacontext(); entity_product_point ev = new entity_product_point(); ev.entity_id = getentity; ev.product_id = tr.first(); ev.hicommissionold = (double)firststyrcomp; ev.lowcommissionold = (double)recurringcomp; ev.hicommission = (double)finalfirstyrcomp * 100; ev.lowcommission = (double)finalrecurringcomp * 100; ev.datecreated = system.datetime.now; cv.entity_product_points.insertonsubmit(ev); cv.submitchanges(); now update statement this: protected v...

objective c - IOS: UITableViewCell -

in project create table view 10 row, these 10 rows must uitableviewcell customizable. suggest links can find suggest code? the table view programming guide ios has 3 different approaches: programmatically adding subviews cell’s content view, loading custom table-view cells nib files , subclassing uitableviewcell. have @ this tutorial well.

model view controller - ASP.NET MVC: Nesting ViewModels within each other, antipattern or no? -

i have project viewmodels nested within each other such string-typed replication of domain hierarchy. example, if our domain has following relationships: organization has 1 many environments environment has 1 many machines then there organizationviewmodel has 1 many environmentviewmodels in it, , environmentviewmodel have 1 many machineviewmodels themselves. style of hierarchy reused throughout app, 1 of 5 viewmodels of type. (e.g. environmentviewmodel used multiple pages, machineviewmodel many of them well, depending on level of hierachy being viewed...i've simplified purposes of discussion hierachy little larger 3 above). now, as i'd come down above , condemn practice, haven't been able find information on this. can point me more details established practice? anecdotes share? (my own bias these viewmodels shouldn't nested within each other way, , viewmodels should correspond views, not domain objects. find pretty messy maintainability issues. ...

c# - How do I add a folder to a program's namespace? -

i converted visual studio 2006 project visual studio 2010. conversion went on fine, somewhere along line namespace got corrupted, , result, parts of codebase throwing errors (because objects they're referencing, etc. no longer being imported). i can manually locate folder relevant files, can't seem reference file using clauses (or i'm botching using entirely). there function in visual studio can use import requisite files directly? for physical files can click show files button @ top of solution explorer, locating folder, right click , choose include in project.

javascript - Controlling HTML5 video and short code approach -

i use approach catch “ended” event of <video> element: var v = document.getelementsbytagname("video")[0]; v.onended = function(e) { /* handle event */ } but doesn’t fired under safari 5.0.4 (6533.20.27). if use addeventlistener , works, there more code: var v = document.getelementsbytagname("video")[0]; v.addeventlistener("ended", function(e) { /* handle event */ }); i saw first example in w3c, i’m wondering why doesn’t work? maybe i’m doing wrong? addeventlistener correct way of listening event. direct onended should theoretically work if other code elsewhere use method listen override listening , not notified. so anyway: onended - single use, can overridden without noticing it. addeventlistener - can support unlimited number of listeners

c++ - Data in Vectors -

i have 2 vectors both of different types i.e. 1. std::vector<project3::vertex<vertextype, edgetype>> vertice2; //contains list of vertices 2. std::vector<std::string>temp12; my requirement want store data vertice2 temp12. tried out lot many different ways, getting error. type casting didn't work out me. latest tried temp.assign(g1.vertice2.begin(), g1.vertice2.end()); error: 'std::basic_string<_elem,_traits,_ax>::basic_string(const std::basic_string<_elem,_traits,_ax> &)' : cannot convert parameter 1 'project3::vertex<vertextype,edgetype>' 'const std::basic_string<_elem,_traits,_ax> &' c:\program files (x86)\microsoft visual studio 10.0\vc\include\xmemory 208 1 project_3_revised you have vector of apples you're trying store in vector of oranges. apples aren't oranges, , that's basic problem. either need make temp vector<vertex...> , or need convert each vertex...

c++ network serialization -

i'm looking solution serializing of c++ packets network stream. i have seen many posts here refering people to: ace google protocol buffers boost::serialization qt ::qdatastream my requirements/ constraints: the solution must unaware of litteendian/bigendian. machine architecture x86/x64 , platform independant. the foot print (ram & rom) of first 3 solution big platform,and fourth conflicting next requirement. the solution won't require lot of boilerplate code (there 200+ packet serialized). thanks, koby meir if find out google protocol buffers heavy (i can agree because compiled library take more 1 mb), maybe try lite version of protobuf. lite version few times smaller. support lite version enabled in *.proto inserting following line option optimize_for = lite_runtime; more found here http://code.google.com/intl/pl-pl/apis/protocolbuffers/docs/reference/cpp/google.protobuf.message_lite.html but if need protobuf solution minimal overh...

Casting long to byte in Java -

i unable understand following: in java, long l = 130l; byte b = (byte)l; if print value of b, why -126? bit representation of long l? bytes signed in java - range of values -128 127 inclusive. the bit pattern 130 long, when truncated 8 bits, bit pattern -126 byte. as example: int x = 255; byte b = (byte) x; // b -1

mysql - Database design for user medias -

i creating site users can upload images , videos on facebook. have 2 ideas , wonder better: 1) usermedias{userid, mediaid...} medias{mediaid,mediatypeid,name,url...} mediatypes{mediatypeid,name...} 2) userimages{userid, imageid...} image{imageid,name...} uservideos{userid,videoid...} videos{videoid,name...} first implementation has following pros: as khez said, allow faster join it not require change schema if want include audio later on. both video , photo have same attributes other fact physically different.

c# - Windows Shell: How to associate different xml-files with different apps? -

i have many kinds of xml-files (all extension .xml) different root element name , namespace. want associate each type different application , make possible have different file-icons each type. can done using c# .net? the way handle in similar way visual studio uses handle .sln files visual studio version selector . application 1 gets associated .sln files , handles providing icon , eventual process handle specific .sln file. assuming have visual studio installed, take in registry @ hkey_classes_root\visualstudio.launcher.sln see how it's done. so need to: write executable can decide .xml files register process 1 responsible handling .xml files place logic in executable, or in configuration executable consumes, decides on per file basis. for icons, take @ subkey shellex\iconhandler . you'll see points (on x64 machine visual studio 2010 installed) hkey_classes_root\wow6432node\clsid\{9a2b23e4-2a50-48db-b3c3-f5ea12947cb8} lists under inprocserver32 d...

c++ - How do I run a class from another project? -

i new c++ , trying figure out best way run class project in solution. lets have 2 projects in solution: proj_a , proj_b. now create instance of class in proj_b inside proj_a. have tried including headers , source files proj_b proj_a. problem source files in proj_b have lot of dependencies , keep out of proj_a. because feel that merging 2 projects together. maybe going things wrong way. (i have c# background, looking equivalent adding reference project) please me out here. =) in c++, have 2 options splitting application modules. can use libraries, linked directly executable, or can use dlls, familiar c#. it sounds using dlls. if case, need export classes dll (proj_b) want use in main executable (proj_a). http://www.codeproject.com/kb/cpp/howto_export_cpp_classes.aspx since worried exposing dependencies, suggest consider option 3 code project article. i've used 3 approaches described in article, , option 3 has become preferred method.

c# - Get a list of elements by their ID in entity framework -

how can elements in list id? eg; have list roles; i'd roles database in this list id. i'm using code-first. i did , threw error: var roles = db.roles.where(r => user.roles.any(ur => ur.roleid == r.roleid)); roleid of type int. error: unable create constant value of type 'samplemvc.domain.role'. primitive types ('such int32, string, , guid') supported in context. var listofroleid = user.roles.select(r => r.roleid); var roles = db.roles.where(r => listofroleid.contains(r.roleid));

flex zend amf - display results in different labels -

i've got simple app getting information form database , displaying content datagrid. instead of having information displayed in datagrid, i'd display in couple of labels (first name, last name, phone, etc.), i'm not sure how to. currently on creationcomplete call php query function - looks this. public function getpeople() { return mysql_query("select * tbl_people order pers_name asc"); } then i'm putting results datagrid <mx:datagrid id="empdg" x="22" y="184" dataprovider="{amfcall.getpeople.lastresult}" click="showname()"> <mx:columns> <mx:datagridcolumn headertext="id" datafield="pers_id" editable="false"/> <mx:datagridcolumn headertext="name" datafield="pers_name"/> <mx:datagridcolumn headertext="image" datafield="pers_img"/> <mx:datagridcolumn...

c# - .NET - Dynamically get Web Root URL of another project -

i have 4 webforms projects in solution. want able url redirects page in webforms project. currently have set url/port number in project web settings, set url in web config app setting, read , handle redirecting. this real pain , makes deployments various environments obnoxious. there way dynamically handle via code? to make above more complication may have projects mapped in iis such: www.mydomain.com/project1 www.mydomain.com/test/project2 www.mydomain.com/test/project3 but, shouldn't matter because can web root url server want redirect to: httpcontext.current.request.applicationpath; i not sure if handling web config route best option or if can dynamically? thanks assistance. this pretty standard pattern here , believe or not, convention , configuration ways handle -- iis can lie, or iis might not know want , can give wrong answer. so, saying: convention: got sort of standard relationship urls within app? regards dev, ci , qa typically frequent...

regex - How to add a rewrite condition to only pass URL's with one folder depth? -

i have rewrite rule needs applied urls go no further in depth 1 folder example.com/a >> rewrite me and not example.com/a/b >> don't rewrite me so need rewrite urls depth of 1. greater depth allowed needs go through unaltered. how doing mod_rewrite condition statement? , can have personal rewrite rule written. thank you! rewriteengine on # matches urls equal to: "", "<text>", or "<text>/" # if matches, rewrite engine not attempt match more patterns rewriterule ^[^/]*/?$ - [l] # if above doesn't match, meaning it's depth more one, # forbids content being delivered rewriterule .* - [f]

android - Custom layout weird bug -

i'm facing weird bug , if remove first layout(id = firstlayout) second layout(id = user_home_buttonsllay) works fine borders , when put buttons border disappear . strange working fine before . help. my layout : <linearlayout id="@+id/firtlayout" style="@style/headerllay"> <imageview style="@style/header_left_img" /> <textview android:id="@+id/user_home_headertitulo" android:text="usuário" style="@style/header_titulo" /> <imagebutton android:id="@+id/user_home_headerimgbtinfo" style="@style/header_right_img" /> </linearlayout> <linearlayout android:id="@+id/user_home_buttonsllay" style="@style/user_home_buttonsllay"> <button android:id="@+id/user_home_bt_novocliente" style="@style/user_home_button" android:text="@string/user_home_novocliente" /> <bu...

c++ - Efficient way to compute p^q (exponentiation), where q is an integer -

what efficient way compute p q , q integer? exponentiation squaring uses o(lg q ) multiplications. template <typename t> t expt(t p, unsigned q) { t r(1); while (q != 0) { if (q % 2 == 1) { // q odd r *= p; q--; } p *= p; q /= 2; } return r; } this should work on monoid ( t , operator* ) t constructed 1 identity element. includes numeric types. extending signed q easy: divide 1 result of above absolute value of q (but usual, careful when computing absolute value).

version control - Teach me git commit -

Image
i don’t understand git commit @ all. it’s been week since i’ve been using git , these git –a, -m, new files, untracked etc making me totally confused. tortoisegit saving me moment, understand essence , use in way it’s totally easy. when in git command line, it’s rather difficult selectively commit files , keep rest commit. how make easy? it quite simple. need add changes want the index first: git add file1 file2 then git commit if removed file, add that. add means " add change " though removal. if want add changes: git add -a the -a parameter on commit says add changes of tracked files , commit them. so git commit -a will not commit new file created. must explicitly add this. the -m parameter allows avoid opening editor edit commit message , use put in following -m option: git commit -m "use message , don't open editor" sometimes not idea. if tried merge , had conflicts , git caches nice message once resolve...

Ruby on Rails website to iPhone app -

this going generic question , i'm sorry. lets have website wrote using ruby on rails , wish turn native iphone app, downloadable app store. can point me in direction of useful tools/tutorials or helpful? thanks checkout http://railscasts.com/episodes/199-mobile-devices

javascript - How to save a web page snapshot with all its elements (css, js, images, ...) into one file -

how possible programmatically save web page snapshot elements (css, js, images, ...) 1 file? i need archive web pages regularly. however, saving html code useless - not because of images missing esp. because absence of css on today's pages can turn web page unrecognizable mess. i remember .mht format worked this, required manual saving, , feature of ie. believe there open-source solution can achieve programmatically, despite hours of searching cannot find on web. httrack , -%m

Authenticating Users via Restful WCF services on Azure IIS Server -

i'd write mobile location based application (iphone, andorid , blackberry) , post data web server (hosted on azure iis) via wcf restful services. what best way authenticate users? rest authentication can done custom (like api key auth), or using basic auth or oauth. depends on interaction want. can use acs pretty secure rest based service. however, depends again on think have in terms of interaction. as starting point, here @ least (http://acs.codeplex.com/) see how use acs , started.

Shell ps command under Ubuntu -

i have question regarding shell scripts. trying specific possible. so, have write monitoring shell script in have write in file users running vi command more, 1 minute. don't have idea approach, except should use ps command. have this: ps -ewo "%t %u %c %g" | grep '\< vi >' with times , users run vi command. problem don't know how parse result of command. can help, please? answers appreciated. thanks i use awk: ps eo user,etime,pid,args --no-heading -c vi | awk '{min=int(substr($2,0,2)); printf "minutes=%s pid=%d\n", min, $3; }' note, dont have grep "vi", can use "ps -c procname".

python - Logging Handlers: How do I make sure I am not making two? -

edit: ended answering beef of question can have working logging module. however, still have related question. see answer below. i trying implement logging logging temporary directory of whatever os in. have written following function. import logging, tempfile, os, sys def getlog(logname, filename = 'python.log', directory = none): '''returns logger logname print filename , directoryname.''' if directory == none: fd, fname = tempfile.mkstemp() directory = os.path.dirname(fname) fullpath = directory + '/' + filename mylog = logging.getlogger(logname) hdlr = logging.filehandler(fullpath) formatter = logging.formatter('l:%(name)s m:%(module)s t:%(asctime)s > %(levelname)s: %(message)s') hdlr.setformatter(formatter) mylog.addhandler(hdlr) mylog.setlevel(logging.info) mylog.info('new logger started') return mylog if __name__ == '__main__': log = getlog('testi...

Testing an iPhone app on an iPad -

i'm working on iphone app iphone died , buying 1 testing prohibitively expensive. if i'm not using iphone specific features making calls, use ipad 2 testing or there differences in architecture cause iphone-specific bugs go uncaught? i've still got simulator working on layouts , general testing. it should fine, although borrow iphone or testing before final release.

iphone - How to set conditional breakpoint in Xcode? -

my situation here (gdb) info break num type disp enb address 1 breakpoint keep y 0x0000db8f in -[instrument getformattedpricestring:] @ instrument.m:195 condition not yet parsed: (bool)[[self name] hasprefix:@"7_"] breakpoint hit 1 time current language: auto; objective-c (gdb) p (bool)[[self name] hasprefix:@"7_"] $1 = false (gdb) po name 2_year despite fact condition evaluates correctly, breakpoint breaks execution every time. see peculiar statement condition not yet parsed here. why gdb wouldn't parse condition? btw use xcode 3.2.6. xcode4 doesn't evaluate conditions a==1 consider temporary assert() or nsassert(). it's more reliable debugger-based expression evaluation. remove assert() call once don't need breakpoint anymore. syntax is: #include <assert.h> assert( !(expression_on_which_to_break));

xslt - Exists function in XSL When Statement -

i using xsl when clause transform 1 xml file xml file. need use "exists" function in when test. here's example source xml: <people> <person personid="1" location="us" fullname="john doe"/> <person personid="2" location="us" fullname="jane doe"/> </people> <nicknames> <nickname personid="1" nname="johnny d"/> </nicknames> here's example xsl: <xsl:element name="hasnickname"> <xsl:choose> <!-- if nickname exists in source xml, return true --> <xsl:when test="boolean exists function" <xsl:text>true</xsl:text> </xsl:when> <xsl:otherwise> <xsl:text>false</xsl:text> </xsl:otherwise> </xsl:choose> </xsl:element> can exists part? suppose variable $personid contains @pe...

security - "Access is Denied" accessing a subpage in ASP.net (hosting with IIS) -

i'm getting current error when trying go page other index: server error in '/' application. access denied. description: error occurred while accessing resources required serve request. server may not configured access requested url. error message 401.2.: unauthorized: logon failed due server configuration. verify have permission view directory or page based on credentials supplied , authentication methods enabled on web server. contact web server's administrator additional assistance. version information: microsoft .net framework version:4.0.30319; asp.net version:4.0.30319.1 there no login system site. 1 small database. does have ideas? thanks if can! if can hit root page not others i'd concerned ntfs permissions. check out tip anon user p.campbell suggesting. think you'll find you're ok anonymous @ iis level, granted appropriate file permissions "index" page , need propagate permissions re...

silverlight - WP7: navigate twice back -

is there way navigate 2 pages in windows phone 7? know uri, i'd clear navigation stack. yes can programmatically walk stack. recommend reading guidance doc on topic: http://windowsteamblog.com/windows_phone/b/wpdev/archive/2010/12/13/solving-circular-navigation-in-windows-phone-silverlight-applications.aspx thanks, stefan wick - microsoft silverlight

forms - Flex - How to bind (two-way) an integer to a TextInput Field -

how two-way bind integer input field in flex/fb4? is_admin integer : <s:textinput id="textuserisadmin" text="@{user.is_admin}" width="5"/> i receive: 1067: implicit coercion of value of type string unrelated type int. is there different input type, or have bind different way? short answer, can't 2 way binding when trying change nature of object you're binding. have same or won't work. said, there workaround: <s:textinput id="textuserisadmin" text="{user.is_admin}" restrict="0-9" change="user.is_admin = int(textuserisadmin.text)"/> as can see here, i'm binding original value model, when user types change event dispatched , textinput value casted , saved. added 'restrict' numbers can typed in.

couchdb - Couchapp directory structure, updates? -

when generating new couchapp, structure: appname ├── _attachments │   └── style ├── evently │   ├── items │   │   └── _changes │   └── profile │   └── profileready │   └── selectors │   └── form ├── lists ├── shows ├── updates ├── vendor │   └── couchapp │   ├── _attachments │   ├── evently │   │   ├── account │   │   │   ├── adminparty │   │   │   ├── loggedin │   │   │   ├── loggedout │   │   │   ├── loginform │   │   │   │   └── selectors │   │   │   │   └── form │   │   │   └── signupform │   │   │   └── selectors │   │   │   └── form │   │   └── profile │   │   ├── loggedout │   │   ├── noprofile │   │   │   └── selectors │   │   │   └── form │   │   └── profileready │   └── lib └── views └── recent-items now, since structure meant reflect json structure of couchdb _design document, figured out: [_attachments] attachments stored...

loading modules from cron job -

i've got cronjob executed shell script inside shell script module load tww/perl but gives me module: command not found what can do? have @ least 10 modules need load it seems script depends on environment setting, such initial path modules, cron doesn't know about. default cron environment quite austere, or on *nix systems use.

asp.net - Umbraco Freeze / Hang on Plesk Server -

my umbraco site occiasionally seems hang. on plesk server , of sudden, see "no content" pages (the default splash page) or browser hangs on "loading". the way site going again restart iis app pool , recopy bin folder ftp. annoying. sometimes, have right click , choose "re-publish entire site" option editor page content back. there doesn't seem tell tale signs or errors in log files or direct cause. last "hang" seemed caused while google trawling site. way see gap in error logs (the not index items error) site "down" any ideas?

Java Meta Annotations at Runtime -

i have java meta annotation such @retention(value = retentionpolicy.runtime) @target(value = { elementtype.annotation_type }) public @interface qualifier { } i have annotation: @qualifier @retention(value = retentionpolicy.runtime) @target(value = { elementtype.type }) public @interface leafentity { string name() default ""; } at runtime can extract leafentity annotation using getclass().getannotation(leafentity.class); however, know if possible access qualifier? mean purpose of annotations on annotations if can't access them? i have tried of following: getclass().getannotation(qualifier.class); getclass().getannotation(leafentity.class).getclass().getannotation(qualifier.class); getclass().getannotation(leafentity.class) instanceof qualifier.class; if knows how access qualifier annotation appreciate example.. the reason important have base annotation called qualifier. allow users define annotation applying qualifier annotation it. scan class an...

Node.js throw e error -

i messing around in node.js trying replicate simple chat server floating around. this javascript source file: var net = require('net'); var carrier = require('carrier'); var connections = []; var server = net.createserver(function(conn) { connections.push(conn); conn.on('close', function() { var pos = connections.indexof(conn); if (pos >= 0) { connections.splice(pos, 1); } }); conn.write("hello, welcome chat server!\n"); conn.write("please input user name:\n"); var username; carrier.carry(conn, function(line) { if(!username) { username = line; conn.write("hello " + username + "!\n"); return; } if(line == 'quit') { conn.end(); return; } connections.foreach(function(one_connection) { one_connection.write(line); }); })...

android - ways for a client to identify the specific access point it is connected to within a single SSID? -

the problem follows - there's university campus wide wifi connection single ssid, "campus-wifi". user freely roams around campus, , usual hand-off between access points occurs. question is, there information @ layer of network stack allows client identify (any unique identifier fine) specific access point they're connected to, rather fact connected "campus-wifi"? if it's relevant, i'd able mobile devices (android/ios primarily). you can bssid of access point connected to. like: wifimanager wifi = (wifimanager) getsystemservice(context.wifi_service); wifiinfo info = wifi.getconnectioninfo(); string bssid = info.getbssid(); not 100% you'll bssid since i've never used -- should uniquely id base station -- wikipedia seems indicate you'll mac of ap (near bottom): http://en.wikipedia.org/wiki/service_set_(802.11_network)#basic_service_set_identifier_.28bssid.29 -- dan edit: according android docs, mac address: ...

xcode4 - GHUnit Code Coverage on iPhone -

i've been learning how write unit tests using ghunit iphone. however, have no idea on how set code coverage work this, via xcode 4. the googletubes have (somehow) not been particularly helpful in matter. i covered how code coverage ghunit in this blog article (disclaimer: author) to summarize briefly, ghunit need to: enable 2 build settings ‘generate test coverage files’ , ‘instrument program flow’ in test target of project in xcode add code fopen$unix2003 , fwrite$unix2003 functions in main.m file of test target, not in appdelegate. how main.m file looks like: #import <uikit/uikit.h> int main(int argc, char *argv[]) { @autoreleasepool { return uiapplicationmain(argc, argv, nil, @"ghunitiosappdelegate"); } } file *fopen$unix2003(const char *filename, const char *mode) { return fopen(filename, mode); } size_t fwrite$unix2003(const void *ptr, size_t size, size_t nitems, file ...

iphone - what are some good 3rd party tools you have found useful in ios development? -

specifically looking 3rd party tools free/commercial have reduced development time. you can use phonegap,titanium etc if u google cross platform mobile..but wont give correct output..if u learn each technology, better...see link

python - UnboundLocalError: Decorator with default parameters -

here decorator code. i'm getting unboundlocalerror reason couldn't find it. >>> def validate(schema=none): def wrap(f): def _f(*args, **kwargs): if not schema: schema = f.__name__ print schema return f() return _f return wrap >>> @validate() def some_function(): print 'some function' >>> some_function() traceback (most recent call last): file "<pyshell#27>", line 1, in <module> some_function() file "<pyshell#22>", line 4, in _f if not schema: unboundlocalerror: local variable 'schema' referenced before assignment >>> so, thought maybe it's better post here. might missing something. thanks. the compiler can't determine schema 's proper scope. either use nonlocal schema (3.x) within _f() or change definition of _f() slightly: def _f(s...

django template: iterate and print just items with index for example 3,6,9 -

is there way iterate through list in django template , print items index example 3,6,9 , on... let's imagine have list this: ({'title':'first'}, {'title':'second'}, {'title':'third'}, .... {'title':'ninth '}) and in template want see just: third sixth ninth i know how pass variable template, construct in view, need way how iterate through them in template , print want. or need construct list (or dictionary maybe) somehow differently? using latest django. thanks, ignas the slice filter allow slice sequence in python. {{ mylist|slice:"2::3" }}

vb.net - C# and VB in C# -

i have c# , vb .net solution. need use c# form inside vb form tab. how can this? you create 1 of forms in separate class library or user control in separate class library , reference within application. each project in solution can either vb.net or c#, works both ways... in simple example solution have following projects myapp.csharpcontrols - project in c# myapp.vbcontrols - project in vb.net myapp.ui - project in either c# or vb.net can reference either of other control projects edit i'm presuming winforms??

How to use jQuery WYSIWYG HTML editor in ASP.net page -

i working in blog application , want integrate html editor of jquery in asp.net application.although have easier option of using asp.net ajax toolkit editor , not lightweight, want go jquery html editor. can suggest tutorial helps so. thanks in advance. i'm using 1 http://premiumsoftware.net/cleditor/ a 1 :-bd

java - Calling a class having its name as a string -

i have string specifies name of call. how can call particular class using string.am trying in java. function return me list of strings class names.now task make call class using string. you can using code: class clazz = class.forname(yourstring); as class name should use full class name including packages. can't call class. can initialize class , call method of class. http://docs.oracle.com/javase/8/docs/api/java/lang/class.html#forname(java.lang.string

xforms - Currency field constraint check done before rounding off -

hi unit testing currency field , found issue can considered bug. <xforms:bind id="amount" nodeset="instance('form')/data/amount" constraint="if(.!='') number(.) >0 , string-length(.)&lt;20 else ."/> ... <fr:currency bind="amount" xxforms:maxlength="50" incremental="true"> <xforms:alert>value should below $ 9,999,999,999,999,999,999.99</xforms:alert> </fr:currency> the condition trying achieve in above case is, put max value check < "9999999,999999999.99" has 19 characters total. (i had tried constraint="if(.='') true() else number(.)<10000000000000000" instead of length check, later seeing bug in number check switched string-length check) now issue in case of string length if enter "9,999,999,999,999,999.991" following happens 1. constraint check performed. returns 'false' "9999999999999999.991" = 2...

c++ - using exec to execute a system command in a new process -

i trying spawn process executes system command, while own program still proceeds , 2 processes run in parallel. working on linux. i looked online , sounds should use exec() family. doesn't work quite expected. example, in following code, see "before" being printed, ,but not "done". i curious if issing anything? #include <unistd.h> #include <iostream> using namespace std; main() { cout << "before" << endl; execl("/bin/ls", "/bin/ls", "-r", "-t", "-l", (char *) 0); cout << "done" << endl; } [update] thank guys comments. program looks this. works fine except @ end, have press enter finish program. not sure why have press last enter? #include <unistd.h> #include <iostream> using namespace std; main() { cout << "before" << endl; int pid = fork(); cout << pid << endl; if (pid==0...

how to write PHP module in C -

how can write own module in c ? possible ? yes, possible. here's old article used when wrote first extension: http://web.archive.org/web/20110222035803/http://devzone.zend.com/article/1021 things may have changed since then, may want search similar tutorials additional references. oh, , should useful: http://www.php.net/manual/en/internals2.php

javascript: How to check if an element is clickable or not -

my naive approach following: function isclickable(id){ elem = document.getelementbyid(id); if (elem.nodename.tolowercase() == 'a' || typeof(elem.click) != 'undefined'){ return true; }else{ return false; } } is there better can do?

php - htaccess redirect add querystring -

i'm triying redirect www.myweb.com www.myweb.com/?lang=en try made redirect traffic in website or creates loop. help? i thinkg should easier set variable lang 'en' in php, rather redirecting... in code, before handling lang variable, try: if (!isset($_get['lang'])) { $_get['lang'] = 'en; }

can i create java servlet as rest web service -

can use java servlet rest web service? , how request using curl servlet? thank sure can use (raw) servlet create rest service. work knowing there exists standard api (jax-rs jsr-311) , many frameworks implementing : http://www.jboss.org/resteasy http://cxf.apache.org/docs/jax-rs.html http://jersey.java.net/

Getting n most recent emails using IMAP and Python -

i'm looking return n (most 10) recent emails email accounts inbox using imap. so far i've cobbled together: import imaplib email.parser import headerparser m = imaplib.imap4_ssl('my.server') user = 'username' password = 'password' m.login(user, password) m.search(none, 'all') in range (1,10): data = m.fetch(i, '(body[header])') header_data = data[1][0][1] parser = headerparser() msg = parser.parsestr(header_data) print msg['subject'] this returning email headers fine, seems semi-random collection of emails gets, not 10 recent. if helps, i'm connecting exchange 2010 server. other approaches welcome, imap seemed appropriate given wanted read emails not send any. the sort command available, not guaranteed supported imap server. example, gmail not support sort command. to try sort command, replace: m.search(none, 'all') with m.sort(search_critera, 'utf-8', 'all...

android - Create Folder that can not accessible by any other application -

i want create 1 folder can not accessible other application. is possible ? if yes give me solution how achieve functionality. use internal storage so: string filename = "hello_file"; string string = "hello world!"; fileoutputstream fos = openfileoutput(filename, context.mode_private); fos.write(string.getbytes()); fos.close();

java - Display multiple lines within a Jlist cell -

how can display multiple lines within single cell of jlist. in jtable, achieved adding jtextarea table cell renderer. similiarly, there code add custom cell renderer jlist holds textarea? if yes, can please give me code snippet same? or think there other better method display multiple lines within cell of jlist instead of using textarea? please me!! beside usage of html code in swing component (like jigar says), can specify listcellrenderer uses textarea, in jtable.

java - Compare two html files -

hi want compare code of 2 html files. how achieve this? if can use tool; there lot of compare-tools available ultracompare . if want build yourself; please let know. edit: there java library available this.

.net - c# - using : bad practice to use? -

i have read more year ago there few bad practice use using (some code) { } . explain me these bad practice? thanks. why think it's bad practice? can (or best) practice since object disposed after using block.

mongodb - nodejs chat example does not work -

i've come across node chat example on github, when try run it, see following error: error connecting mongo perhaps isn't running ? i've installed mongo 0.9.2, nodejs 5.2 pre, npm 3.0 , other dependencies. example can found here: https://github.com/gregstewart/chat.io i can not determine whether if example not works or didn't run right. please help. did install , start mongo-db on system? error because of missing mongo instance running on local machine. check out follwing code excerpts chat.io. main.js: /** * configure user provider (mongodb connection user data storage) */ var userprovider = new userprovider('localhost', 27017); creates new userprovider object using host , port database (localhost:27017, mongo-db default). userprovider.js: userprovider = function(host, port) { this.db = new mongo.db('node-mongo-chat', new server(host, port, {auto_reconnect: true}, {})); this.db.addlistener('error', func...

google chrome - capybara with selenium wait for onchange event -

i have form field onchange event inserts text page. fill_in "password", :with => 'test' # should trigger onchange inserts text below page page.should have_content('very insecure') now when test cucumber/ capybara/ selenium firefox works without problems. using selenium chrome, capybara complains text not found in document. now wonder how fix this. need manually invoke event (which real hacky imo)? or have wait events being processed (how?) between fill_in , should have_content methods? if feel issue need wait longer, throw in "sleep 3" before page.should. there raw selenium commands best avoid them.

javascript - Change ID of an element where Class is X -

i'm trying change id of div via ajax. because id has dynamic value added class div. my php code: echo '<div id="pagemenu"> <ul id="tabpanel">'; $tel = 0; while($totaalklanten > -4) { $tel++; echo '<li><a href="#'.$tel.'" name="'.$tel.'" onclick="listklant(\'klant.php\',this.name)">'.$tel.'</a></li>'; $totaalklanten = $totaalklanten - 5; } echo '</ul>'; echo '<div class="changeme" id="default">'; //lots of query of php stuff here execute echo '</div> the div class 'changeme' victim. my ajax code far: xmlhttp = new xmlhttprequest(); function listklant(serverpage, pagenum) { xmlhttp.open("get", serverpage); document.getelementsbyclassname('changeme').id = pagenum; alert(document.getelementbyid(pagenum)); ...

iphone - Current and Updating time in iOS? -

i'm developing tool car driving saves gps data, accelerometer data , time later use. acceleration least priority, though. all need little code example can current system time printed updating clock in xcode because want save data fast , possible :> thanks in advance answers :) h4wkeye to current system time use nsdate* currentdate = [nsdate date]; and string representation of nsdate - (nsstring *)description then use below nsstring* dateinstring = [currentdate description];

How to set default values for fields in records in Clojure? -

i creating records in clojure , set fields default value. how can this? you can pass initial values record pretty when construct though extension map: (defrecord foo []) (def foo (foo. nil {:bar 1 :baz 2})) in light of this, create constructor function merges in default values (which can override want): (defn make-foo [values-map] (let [default-values {:bar 1 :baz 2}] (foo. nil (merge default-values values-map)))) (make-foo {:fiz 3 :bar 8}) => #:user.foo{:fiz 3, :bar 8, :baz 2}

Vector option in Java -

i using vector of object. issue removal vector expensive operation( o(n^2)). replacement of vector in java. in uses addition , removal extensively happens. i c++ person don't know java well, vector class shouldn't used. there many containers available in java. few of them: arraylist random access, bad inserting or removing middle of list. linkedlist bad random access, fair iterating , adding/removing elements middle of container.

c++ - TCP packet simulation + omnet -

lets have function todo() , want implement function on packet sent node destination among routers. so want packet goes through tcp via ethernet(could anything) , while going want process packet calling todo() on it. i trying simulate on omnet , wanted advice on it... do need implement entire tcp stack first or there inbuilt feature simulation in , if there allow me thing mentioned ?? i beginner in using omnet please provide me guidelines on how this.... lot ... your question little confusing. routers process ip packets. dont care payload, might contain tcp segment. you have scenario this: client -> router -> server so client create on l7 packet , gives tcp module. there can add function. example in sendtoip function packet goes ip , goes out via ethernet router. router looks @ destination ip address , send out interface configured in routing table. server receive packet. goes through tcp module (their can add todo() function) , gives application mod...

how many threads is too many in iphone/objective-c dev -

i have complex sync job several asyncronous calls content on http. each time content received, asks next bit , on. these daisey-chained in big over-all sync job data on server. there 12 steps in job chain. seems stuck after around 5th async request, request never comes , hangs ever waiting it. think may have many threads being spawned because if fire off 1 hangs @ at beginning returns fine. in way imagine in head, main thread asks async content a. when comes in own asynchronous time spawns new thread asks aync content b. when comes in own sweet time spawns new thread asks content c. isn't new thread being created everytime async request returns result? am daisy-chaining these requests right? quite @ threads in java development i'm bit confused on how work in obj-c. need use thread pool of 3 threads , reuse these? sorry high-level question i'm sure experts can clear cloud of mystery around this. nsoperationqueues built on top of grand central dispatch. i...

PHP - Manipulate user picture in active directory -

is possible retrieve , update user's picture in active directory using php? if so, how accomplished? here setup: php 5.3 on iis 7.5 domain controller windows 2008 i told pictures-in-active-directory i don't think user image stored inside active directory default. user images stored in user profile , not in active directory. it possible extend active directory schema include images, not used user image when logging in example.

asp.net - Returning an output value via C# WCF service -

i'm looking return string value client via http post service on wcf. i can return status code okay via following: weboperationcontext.current.outgoingresponse.statuscode = httpstatuscode.ok; ... i'm not entirely sure how return string value client. any pointers appreciated. thanks nick namespace textwcf { [servicecontract] public interface ishortmessageservice { [webinvoke(uritemplate = "invoke", method = "post", bodystyle = webmessagebodystyle.wrappedrequest)] [operationcontract] void postsms(stream input); } } [operationbehavior] public void postsms(stream input) { streamreader sr = new streamreader(input); string s = sr.readtoend(); sr.dispose(); namevaluecollection qs = httputility.parsequerystring(s); string user = convert.tostring(qs["user"]); string password = qs["password"]; string api_id = qs["api_id"]; string...

json - What is the best way in WebMatrix to query WCF services? -

i have asp.net project using razor view engine queries various databases directly webmatrix.data.database.open. i'm trying migrate direct database access web services using wcf consistent business logic. in doing this, have enabled wcf service "httpgetenabled". allows me use excel macros query same web service. my question is, best way query these web services razor/webmatrix page? should json enable wcf service , use webmatrix json helper? or should using jquery xml? i assume former best way, how json enable wcf service? remember seeing video allowed me specify additional query parameter wcf request json, can't find again. any thoughts or pointers in right direction appreciated. kind regards. edit: i've seen on stack overflow : client side binding using converting wcf services json on following this, went msdn article referred around webhttpbehavior. have since added "automaticformatselectionenabled=true" webhttp element in...

oop - python __init__ method in inherited class -

i give daughter class attributes without having explicitly call new method. there way of giving inherited class __init__ type method not override __init__ method of parent class? i have written code below purely illustrate question (hence poor naming of attributes etc). class initialclass(): def __init__(self): self.attr1 = 'one' self.attr2 = 'two' class inheritedclass(initialclass): def __new__(self): self.attr3 = 'three' def somemethod(self): print 'the method' = inheritedclass() each in a.__dict__: print each #i output be: attr1 attr2 attr3 thank you as far know that's not possible, can call init method of superclass, this: class inheritedclass(initialclass): def __init__(self): initialclass.__init__(self) self.attr3 = 'three'

c# 4.0 - Find nearby postcode with a base postcode -

this reference question: find uk postcodes closest other uk post codes matching post code string --user wants postcodes nearby b193sh -- postcode = 'b193sh' -- latitude = 52.488460 -- longitude = -1.895690 select [housenumber], [street], [area], [postcode], [latitude], [longitude], [dbo].[address] ([latitude] between ( 52.488460 - 0.100000 ) , ( 52.488460 + 0.100000 )) , ([longitude] between ( -1.895690 - 0.100000 ) , ( -1.895690 + 0.100000 )) order [postcode] go executing query, couple of results. question stands difference (meters/miles) +/- 0.100000 lat/lon makes? should try find close postcodes using first 3 letter of base postcode, i.e., 'b19'? please see reference question full detail of scenerio. thanks! given approximate radius of earth being 6378.1 km. latitude (and longitude, when along equator) 2 * pi * 6378.1 * 0.1 / 360 = 11.1319 km (4 d.p.) ...

python - Django template iterating over list -

i have list created in django view: list = [ elem1, elem2, ..., elemn ] the list variable length: can contain 0-6 elements. want iterate on list in template, loop run 6 times, yielding none or empty string non-existing elements. i tried this: {% in "0123456" %} {{ list.i }} {% endfor %} but doesn't work. know in view, have in template. is possible? you can add if statement checking if 6th time through loop. {% item in somelist %} {% if forloop.counter <= 6 %} {{ item }} {% endif %} {% endfor %} http://docs.djangoproject.com/en/1.3/ref/templates/builtins/#for in docs. of course, if list long not optimal. suggest processing list in views.py , passing template. logic should stay in views if possible. this gives control on number of loops done. solve problem need addtional logic see note above regarding this.

java - pimp up a plain jar to be a maven jar with internal pom.xml for Artifactory -

i need use xyz.jar wich generated ant. hence, transitive dependencies missing. had idea, modify xyz.jar add internal meta-inf/maven/groupid/artifactid/pom.xml , pom.properties files. when deployed artifactory, ignored them , generated it's own pom.xml without dependencies. what has 1 do, artifactory deploys pom.xml lying in same folder xyz.jar file? lost way time on allready... chances artifactory skips deployment of internal pom because cannot read pom's physical size archive (done historical reasons); can verify looking @ log warning message along lines of: "found pom.xml file size -1 inside zip. ignoring" if you've gone lengths of creating customized pom file, can paste it's contents in pom content editor of artifact deployer or deploy independently; though first option give benefit of auto detecting deployment coordinates jar file.

problem facing with android application on two different android platform O.S. device -

i have build 1 android application in androids version(2.2) , have specified minimum sdk version in android manifest file 3 i.e (version-1.5) .so have make sure application should run on api leval of device having 3 i.e version(1.5) 8 version(2.2but since contact content provider android api platform "leval(4)" , "leval(8)" different,and in application using contact content provider,i facing exceptions "illegal argument","null pointer","uncought exception" @ runtime. on other side if build application version(1.6),it not gives runtime exception when tried contact details device e.g(phone number,email),it gives null value "null pointer" exception. do have proper solution this.please replay.. if want ship 1 version of app, should use android.os.build.version determine api level, , right api use. hope helps, phil lello