Posts

Showing posts from September, 2011

time - Previous Hour or X Minutes in TSQL Snapping to Window -

in tsql, how can can previous hour snapping hour. so example, if 2:33, how fields creationdate (a datetime field) greater or equal 1:00 , less 2:00. i to 10 minute intervals (snapping previous :00 - :10 if :14 example, or example, :50-:00 if :06). this start , end of current hour: select dateadd(hour, datepart(hour, getdate()), dateadd(day, 0, datediff(day, 0, getdate()))) , dateadd(hour, 1+datepart(hour, getdate()), dateadd(day, 0, datediff(day, 0, getdate()))) explanation: dateadd(day, 0, datediff(day, 0, getdate())) gets start of today. add current hour that. along same lines previous 10 minute block: select dateadd(minute, datepart(minute, getdate()) / 10 * 10 - 10, dateadd(hour, datepart(hour, getdate()), dateadd(day, 0, datediff(day, 0, getdate())))) , dateadd(minute, datepart(minute, getdate()) / 10 * 10, dateadd(hour, datepart(hour, getdate()), datead

android - How to pass database adapter to another activity? -

i'm having trouble understanding search dialog in android sdk. the "main activity" of application provides button. if user clicks button search dialog called. search done in async task might need time. far good. the main activity creates database adapter object used initialize database, perform queries, etc. how can use adapter object in searchable activity? main activity // init database databaseadapter dba = new databaseadapter(); dba.init(); // open search dialog if (buttonclick) onsearchrequest(); searchable activity get intent , receive query search dialog -> ok how can use database adapter again perform query? do have create new object? can pass somehow min activity searchable activity, [...]? thanks, robert an option use singleton , provide access databaseadapter via static method. ex: private static databaseadapter swritableadapter = null; private static databaseadapter sreadableadapter = null; public static databaseadapte

web application architecture -

we have existing app jsp based front end , java/dao based end connecting oracle db. enterprise level trading application. recently our management gave directive use gwt have more modern , feel our front end pages. have migrated few existing pages gwt brand new development in gwt. gwt being used both rendering front end server side communications , ajax. however, concerned embracing gwt client side architecture of rendering logic processing happens on client side. is concern justified? what other architectures recommend? spring mvc/webflow? else? i'd start service architecture. keep processing in can swap uis in , out without rewriting end. they can soap or rest. need not make them heavy. best not depend on jsp or gwt processing. ever hope make available on ipad? it'd able without rewriting whole thing. start coarse-grained services match use cases.

tsql - SQL Server unique GUID -

i understand in sql server guids unique, , likelihood of collision remote, yet @ same time must win lottery feel makes sense prepare possibility. which faster/better practice using technique assign new guid directly inserting row , checking error (@@error <> 0) , repeating until don't error [which suppose in theory @ worst once...] or using approach this declare @myguid uniqueidentifier select @myguid = newid() if exists(select * tablename userid=@myguid) and looping on till find 1 not in use. i 2nd approach because can have guid use later on in stored procedure i'm leaning towards one. to answer question , not debate merit of question/perceived problem. the first implementation 1 want use 2 reasons: running check exists before doing insert every single record dealing in end result in more resources being dedicated extremely unlikely happen. (also database ensure constraint on column if collide data wont committed) if have error on first one

java - Do I need to put a serialVersionUID on ancestors of a Serializable class? -

do need put serialversionuid on ancestors of serializable class? or on serializable class itself? you not need put serialversionuid @ all. java automatically determine appropriate serial id classes based on fields, methods, etc. the appropriate time have serialversionuids when storing objects file , need load them later, after have changed code. or, if transferring data across wire between components using different versions of library. 90% of time people need serialization, real-time, , library version matching on both sides guaranteed. in these cases, not need set serialversionuid, , can cause problems, if have 2 library versions incompatible have not changed sid. start getting weird errors since java thinks they're serially compatible, when actually, they're not. look @ these questions well: is there reason use real serialversionuid? why generate long serialversionuid instead of simple 1l? what serialversionuid , why should use it? edit add:

numpy - Python: universal import -

can explain 'import' universal, don't need write example: from numpy import * import numpy import numpy np numpy.linalg import * why not import numpy or from numpy import * incude "numpy"? i'm not sure mean "all numpy", should never need use more 1 form of import @ time. different things: option one: import import numpy bring entire numpy module current namespace. can reference moudule numpy.dot or numpy.linalg.eig . option two: from ... import * from numpy import * bring of public objects numpy current namespace local references. if package contains list named __all__ command import every sub-module defined in list. for numpy list includes 'linalg', 'fft', 'random', 'ctypeslib', 'ma', , 'doc' last checked. so, once you've run command, can call dot or linalg.eig without numpy prefix. if you're looking import pull every symbol every submodule in package nam

SQL Server returns different record after insert on linked MS Access table -

we upgraded our backend database sql server 2000 sql server 2008. since switch we've had intermittent (read: impossible consistently reproduce) , strange problems, seem related somehow. in 1 case, our users add new record table via bound form. as record saved, different (much older) record displayed in place. pressing shift + f9 force requery of form brings newly added record (the form filtered show single record). we have managed isolate specific instance of problem based on logging occurs on different form. in beforeupdate event of form timestamp correctly filled in on record being inserted. in afterupdate event of same form history record created in table includes autonumber id of first table. about 1 in 10 of these history records created wrong autonumber id. has witnessed sort of behavior or have explanation it? edit: additional thoughts: the backend database part of merge replication the access front-end versions 2000 , 2002 (other versions not tested

java - Multiple Regression -

in order combine 3 different estimators of same variable need implement multiple regression method in java (therefore 3 independent variables , 1 dependent variable). i'm looking simple method (as simple multiple regression method can be). search i've done, think least squares method should adequate approach know if suggest other method. wasn't able find documentation regarding implementation of least squares method in multi-variable context, grateful if can point me information/source can use. take @ library: http://www.ee.ucl.ac.uk/~mflanaga/java/regression.html you find source code links in answer question: weighted linear regression in java you can read math (with full example) handbook university of delaware: http://udel.edu/~mcdonald/statmultreg.html or statsoft textbook: http://www.statsoft.com/textbook/multiple-regression/

c# - How to unit test with a recursive object -

i have object takes in parameter of same type in constructor: public class person { private person theparent; private string thename; public person(string aname, person aparent) { if(aparent == null) { thrown new argumentnullexception("aparent"); } theparent = aparent; thename = aname; } } in unit test have create new person object constructor requires person object passed in. overcome problem in application getting person object pass in database (using nhibernate , magic)*. don't want tie database access test not testing database functionality. should mock parent object (i'm using rhino mocks in of other tests) or there better way approach this? *there guaranteed 1 record in databse can retrieve make parent object. i assume @ point expected reach top node? correct value aparent then? my guess null , , mean person first in it's line (whatever means application, per

rest - How to post links with the twitter API? -

i'm using twitter api, when post links showing text , not links. haven't been able find documentation showing how post link works. if don't keep prefix (http://) , post www.google.com, link won't picked up.

windows - Watch for newly created files from command line -

i wondering if there way e.g. program or code, can monitor new files created within folder or not? yes possible works different on different operating systems. for example https://github.com/guard/guard implements mainstream systems can check source code. for windows notifications see http://msdn.microsoft.com/en-us/library/aa365261(vs.85).aspx . for mac os x notifications see http://developer.apple.com/library/mac/#documentation/darwin/conceptual/fsevents_progguide/introduction/introduction.html for linux see http://www.kernel.org/pub/linux/kernel/people/rml/inotify/readme .

Addressing multi-page table header rows in LiveCycle Designer -

i trying dynamically hide table column in livecycle designer. table spans multiple pages, , there header row @ top of each page. when set presence of header row cell "hidden", cell on first page hidden. how hide header row cells on subsequent pages? i accomplished creating additional section own sub-record detail house span multiple pages , left original section house header record. so breakdown looked in hierarchy pane: mainform +-masterpage (main layout) +-subform (layer on main page) +-subformdetail (sub on layer) +-maintable (primary table) +-headersection (section display first page header) +-detailsection (section display multi-page rows) +-detailrows (rows display each records data) although admittedly may not best method accomplish trying do, worked needs. hope helps.

Django Markdown or WYSIWYG editor -

i have user generated context extends multiple paragraphs. i'd enable user create paragraphs, possibly change font-weight, nothing huge. i've seen tutorial uses python-markdown module. recommend or should go wysiwyg plugin? i've seen plugins admin have not yet seen applied general django template. thanks brendan i have used django tiny-mce tinymce in comment app , working. defining plugins wysiwyg editor easy , comes specifying name of plugin in settings.py , js file.

asp.net mvc - Controllers in seperate assembly and getting a 'The controller for path "/controllerName/" was not found or does not implement IController.' error -

i doing work on project , trying development environment working. project written in asp.net mvc 2. have asp.net mvc 3 installed. controllers have been moved seperate project namespaced projectname.web.controllers. of controllers inherit system.web.mvc.controller. when try hit controller following: [httpexception]: controller path '/controllername'; not found or not implement icontroller. if make controllers folder in web project contains views, copy controllers there , recompile, works fine. you need add new project namespace defaultnamespaces collection on current controllerbuilder controllerbuilder.current.defaultnamespaces.add("projectname.web.controllers");

What is the best way to display a mouseover with an ellipsis showing the remaining text in GWT? -

i'm tasked creating mouseover ellipsis extends missing characters field. started looking @ api's , narrowed down popup panel or dialog box. better or there widget work better? thanks, james if mouseover (no clicking) popup more better choice. check out uiobject#settitle()

.net - How to add text to icon in c#? -

i want display icon [a .ico file] in system tray text added @ runtime. there native wpf way it? or snippet gdi+ grateful. thank you. here code worked me, public static icon geticon(string text) { //create bitmap, kind of canvas bitmap bitmap = new bitmap(32, 32); icon icon = new icon(@"images\pomodomo.ico"); system.drawing.font drawfont = new system.drawing.font("calibri", 16, fontstyle.bold); system.drawing.solidbrush drawbrush = new system.drawing.solidbrush(system.drawing.color.white); system.drawing.graphics graphics = system.drawing.graphics.fromimage(bitmap); graphics.textrenderinghint = system.drawing.text.textrenderinghint.singlebitperpixel; graphics.drawicon(icon, 0, 0); graphics.drawstring(text, drawfont, drawbrush, 1, 2); //to save icon disk bitmap.save("icon.ico", system.drawing.imaging.imageformat.icon); icon createdicon = icon.fromhandle(bitmap.gethicon());

ios - what control/approach for selection of an integer in an iPhone app? -

any recommendations re approach useability perspective user configure 1 preference app, number of weeks - make sense allow anywhere 2 through 25 say. options come mind include: type in - need validation have list pick (i assume pushing on tableview uinavigationstack) - 25 rows not sure (e.g. row 1 = "week 1", row 2 = "week 2" etc) uipicker wheel - doesn't sound good other??? thanks i advice uipickerview shows when tap edit

java - How to make HtmlUnit's WebClient accelerate execution of javascript to be triggered by window.setTimeout? -

i using java library htmlunit create regression test suite web app. i have "onload" handler hooked in body of pages of app redirect timeout page after session have expired. handler javascript of form: window.settimeout( function() { window.location = 'timout.html'; }, 3600000); i test redirect fired when time arrives, closest thing can find wait entire duration of time (say hour in example above), suggested java sample below: webclient webclient = new webclient(); ... webclient.waitforbackgroundjavascript( 3600000); i know if possible trick script execution engine behaving if time has passed, without having wait minutes or hours "real time" test suite run. ideally, 1 tell engine/client/interpreter x milliseconds had passed (to emulate wait), or perhaps set kind of "time dilation" factor , poll page see how being updated. i don't think can easily. way can see possible mocking rhino method handles settimeout in tests..

How to read an xml file using Silverlight using c#? -

i trying figure out if there way read xml file (like c:\test.xml) in silverlight application? want read xml file xmldocument. help? have text box read xml file path. want read xml xmldocument as link russ provided mentions, can't directly access file on hard drive silverlight. typically need use openfiledialog retrieve file stream. if silverlight application out-of-browser application elevated permissions have access user's documents folder. also, xmldocument not available in silverlight. you'll want use xdocument class, newer way work xml in latest versions of .net. here's example of using xdocument, in relation xmldocument: http://blogs.msdn.com/b/xmlteam/archive/2009/03/31/converting-from-xmldocument-to-xdocument.aspx msdn docs on xdocument: http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument(v=vs.95).aspx

asp.net mvc - MVC - UTC date to LocalTime -

we have mvc project , need display utc date converted users local time. in model passing utc date , in view trying following: <%: html.displayfor(m=> m.somedate.tolocaltime()) %> this throws exception. can point me in correct direction on how convert utc date local datetime display @ customer end. storing dates utc , @ display time these dates need converted local machine equivalent. you need store users timezone server side , use (although should done in controller, not view): @timezoneinfo.converttimefromutc(model.createdon, timezoneinfo.findsystemtimezonebyid("e. australia standard time"))

javascript - What's wrong with my JQuery syntax here? -

this code throwing me syntax error: $("body").live("click", (function(){ if ((! mouse_is_inside) && ($("div#notification_box").is(":visible"))) { $("div#notification_box").hide(); $("p.exclamation").removeclass("exclamation_hover"); $.ajax("/videos/update_box.js"); } }); remove ( before function . have mismatched parentheses.

how to call a function of a same class from other functions of the same class-Objective C -

but i'm getting errors when declaring this. @implementation data -(void)swapendian:(uint8_t*)pdata withboolvalue:(bool)bisalreadylittleendian { data* datas = [data alloc]; [datas swapendians:(uint8_t)&pdata[nindex] withsize:(sizeof(uint32_t)); } -(void)swapendians:(uint8_t*)pdata withnbytesize:(int const)nbytesize { nslog(@"swapendians!!"); } @end how call function other function inside same class? you can use self keyword achieve this. [self yourfunctionname];

Define CSS class's on tables in Sitecore -

in 1 of sitecore solutions user needs have predefined css class's can put on tables created in richtext editor office. when go table wizard can see css class dropdown list, option that's available 1 called "clear class". how can define more class's in drop down list? thanks. /kim you want find following setting in web.config : <!-- web site stylesheet css file html content of sitecore database. file pointed webstylesheet setting automatically included in html , rich text fields. using it, can make content of html fields same actual web site --> <setting name="webstylesheet" value="/default.css" /> whatever css file is, that's 1 can add new classes. once change it, clear browser cache , re-open browser. rte should new classes.

Maximum line length for BufferedReader.readLine() in Java? -

i use bufferedreader's readline() method read lines of text socket. there no obvious way limit length of line read. i worried source of data can (maliciously or mistake) write lot of data without line feed character, , cause bufferedreader allocate unbounded amount of memory. is there way avoid that? or have implement bounded version of readline() myself? the simplest way implement own bounded line reader. or simpler, reuse code this boundedbufferedreader class . actually, coding readline() works same standard method not trivial. dealing 3 kinds of line terminator correctly requires pretty careful coding. interesting compare different approaches of above link sun version , apache harmony version of bufferedreader. note: i'm not entirely convinced either bounded version or apache version 100% correct. bounded version assumes underlying stream supports mark , reset, not true. apache version appears read-ahead 1 character if sees cr last charact

c# - Calling a method in the controller -

i'm newbie asp.net mvc 3, have simple question. possible call controller method cshtml (razor) page? example: xxxcontrol.cs: public string bla(testmodel pmodel) { return ... } index.cshtml: @bla(model) <-- error thanks. update: thanks @nathan. isn't idea on way. goal is: need formatting string field of model. put code return formatting string in case? it considered bad practice view call methods located on controller. controller action populates model , passes model view. if needed formatting on model write html helper. public static class htmlextensions { public static ihtmlstring bla(this htmlhelper<testmodel> htmlhelper) { testmodel model = htmlhelper.viewdata.model; var value = string.format("bla bla {0}", model.someproperty); return mvchtmlstring.create(value); } } and in view: @html.bla()

opengl es - How to emulate GL_DEPTH_CLAMP_NV? -

i have platform extension not available ( non nvidia ). how emulate functionality ? need solve far plane clipping problem when rendering stencil shadow volumes z-fail algorithm. since you're using opengl es, mentioned trying clamp gl_fragdepth, i'm assuming you're using opengl es 2.0, here's shader trick: you can emulate arb_depth_clamp using separate varying z-component. vertex shader: varying float z; void main() { gl_position = ftransform(); // transform z window coordinates z = gl_position.z / gl_position.w; z = (gl_depthrange.diff * z + gl_depthrange.near + gl_depthrange.far) * 0.5; // prevent z-clipping gl_position.z = 0.0; } fragment shader: varying float z; void main() { gl_fragcolor = vec4(vec3(z), 1.0); gl_fragdepth = clamp(z, 0.0, 1.0); }

php - Debugger is not hitting, though Xdebug is installed -

Image
i have enabled xdbug php.ini. how enable debugging eclipse. set debugger in eclipse never hit, each time when ever try debug new configuration created. debugger setting: looks debugger session running. that's why you're getting message. eclipse switches debug perspective when hit debug. can manually switch clicking on open perspective button. if you're working vhosts, make sure create new server hostname. go windows -> preferences , php -> debug . select php servers option , create new server vhost. after that, create new run configuration newly created server. once you've created configuration, can run it. can quick access going run -> debug history . show in history once you've run @ least once.

design - What data structure to pick for genericity but safety? -

say have long data structure definition data = { x1 :: string , x2 :: string ... , x50 :: string } now have 3 tasks: create draft instance of { x1 = "this x1", ... } create instance of other data structure create data instance instance of a the 3 tasks involve tediuous copying of lables x1, ..., x50. better solution generic list [ foo "x1" avalue1 , foo "x2" avalue2 ... ] because make traversal , creating draft easier (the list definition draft already). downside mapping other data structures , more dangerous, since lose static type checking. does make sense? there generic safe solution? edit : give better idea, it's mapping business data textual representation forms , letters. e.g.: data taxdata = taxdata { taxid :: string , income :: money , taxpayed :: money, , ismarried :: bool ... } data taxforma = taxforma { taxid :: text , ismarried :: text ... } data taxformb = taxformb { taxid :: text , taxpayedrounded

networking - Move file onto network share (via impersonation) C# -

i have been working on project in c# (.net4). project pretty allows people upload files local machine network share. network share secured. accessible user called "proxy" created in active directory. i did research , found class used impersonation. using system; using system.collections.generic; using system.linq; using system.text; using system.runtime.interopservices; using system.security.principal; namespace datacom.corporatesys.utilities { public class impersonateuser { [dllimport("advapi32.dll")] public static extern int logonusera(string lpszusername, string lpszdomain, string lpszpassword, int dwlogontype, int dwlogonprovider, ref intptr phtoken); [dllimport("advapi32.dll", charset = charset.auto, setlasterror = true)] public static extern int duplicatetoken(intptr htoken, int impersonationlevel, ref intptr hnewtoke

ios - Force Hide keyboard in iPad Safari -

i have form in order; textbox dropdown now when user moves focus textbox dropdown, keyboard still remains , kind of hides dropdown options... how make keyboard hide (onblur of textbox) i have tried window.blur , not work. please me. thank you. you can try focus() on non-text element. or $("#yourtextfield").blur(); //jquery

android - I'm having trouble loading email addresses from the Phone's contacts -

i trying generate list of emails phone's contacts have having trouble getting emails. can names , phone numbers not emails. arraylist sizes both 0 @ end of loop. can spot doing wrong, or tell me how emails differ phone numbers, names , other information? contentresolver cr = getcontentresolver(); cursor emailcur = cr.query( contactscontract.commondatakinds.email.content_uri, null, contactscontract.commondatakinds.email.contact_id + " = ?", null, null); arraylist<string> emails = new arraylist<string>(); arraylist<string> emailtypes = new arraylist<string>(); while (emailcur.movetonext()) { // allow several email addresses // if email addresses stored in array string email = emailcur .getstring(emailcur .getcolumnindex(contactscontract.commondatakinds.email.data)); string emailtype = emailcur .getst

javascript - backbone.js events are not bound after model change? -

here's code in view initialize: var self = this.model.bind('change', function () { self.render(); }); i have bunch of events defined: events: { "click #blah": "blah", }, but after changing model , rerendering view events no longer bound? i can bind them putting this.delegateevents() in render, don't think that's doing correctly. am doing wrong? thanks. did set el property in view? events delegated el.

database - Locating the SQLite DB file on Android -

i working on android application. have implemented sqlite. whenever run app on emulator can check db file under data folder , can check values inserted it. but when run app on real device can not find db file situated. have set permissions in manifest uses-permission android:name="android.permission.internet" please me find db file when run app on real device. thanks the database in same location on emulator. data map not visible on phone. work emulator test databases.

ios - Loading app after phone call -

i trying make speed dial app various numbers user might enter. loading phone after clicking uitableviewcell - (ibaction)dialer:(id)sender{ nsurl *url = [ [ nsurl alloc ] initwithstring: @"tel:09-410-7078" ]; [[uiapplication sharedapplication] openurl:url]; } that loads phone dialer , dials number.. i'm woundering if after phone call has ended possible load app exited phone call.. or if there better way trying do? actually should keep in mind application can unloaded @ moment. when application being unloaded app delegate gets messages ( applicationwillterminate , applicationwillresignactive , applicationdidenterbackground ). should read this post . in methods should save parameters of application (current page, settings, etc.) , use them when application launched or become active again. if want start application manually shouldn't so. user surprised such behavior.

python - What is a complete list of Exceptions that can be thrown by shutil.rmtree -

i using rmtree method shutil in python (2.7). what possible exceptions can occur while calling method? according implementation, you'll have check oserror . can use argument ignore_errors=true on call to...ignore errors ;) or give callback onerror check exceptions during execution of file removal. ( cf shutil.rmtree documentation )

internet explorer - Javascript code not accepted by validator (JSHint) -

i've written code display bookmarks in ie8. check i've used jshint , following errors : var files=new enumerator(favfolder.files); 'enumerator' not defined. (line 14) enumerator(favfolder.subfolders); 'enumerator' not defined. (line 34) activexobject("scripting.filesystemobject"); 'activexobject' not defined. (lines 46) activexobject("wscript.shell"); 'activexobject' not defined. (line 50) does know why ? my code : var i=0; var favstring=""; var fso; function getfavourites(folder) { var favfolder=fso.getfolder(folder); //gets favourite names & url's given folder. var files=new enumerator(favfolder.files); for(; !files.atend() ;files.movenext()) { var fil=files.item(); if(fil.type=="internet shortcut") { var textreader=fso.opentextfile(fil.path,1,false,-2); var favtext=textreader.readall(); var start=favtext.indexof("url",16); var stop=favtext.indexof("\n",star

javascript - Get textbox within a form of an iframe -

how can textbox in form , form in iframe javascript? simplified code is: <!-- other code --> <div id="login_panel_div"> <iframe id="popuploginscreen" src="login.jsp" name="popupcontent"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> </head> <body> <form id="loginform" method="post" name="loginform"> <h2>login account</h2> <label>username:</label> <input id="username" type="text" name="j_username"> <label>password:</label> <input id="password" type="password" name="j_password"> <button id="submitloginbtn" v

PHP Error: Undefined index: event_list when I think its already defined. -

i complete noob in php , programming well. new programming question might stupid, please patient. i having undefined index error in think defined. i have here codes. index.php <?php include('functions.php'); ?> <?php $yr = $_get['year_list']; $evnt = $_get['event_list']; ?> <html> <head> <script type="text/javascript" src="myscripts.js"></script> </head> <body> <div> <form name="myform" > select year: <?php echo hspacer(1); ?> <select id="year_list" name="year_list"> <?php for($year = (date('y') - 100); $year <= (date('y') + 100); $year++ ) { if ($year == date('y')) echo "<option value='$year' name='$year' selected='' >" . $year . "</option>"; else echo "<option value='$year' name='$year'

c# - Rhino Mocks - Raise Event When Property Set -

i want raise event on stub object whenever property set using rhino mocks. e.g. public interface ifoo { int currentvalue { get; set; } event eventhandler currentvaluechanged; } setting currentvalue raise currentvaluechanged event i have tried mystub.expect(x => x.currentvalue).whencalled(y => mystub.raise... doesn't work because property settable , says i'm setting expectations on property defined use propertybehaviour. aware abuse of whencalled i'm none happy about. what correct way of achieving this? you created stub, not mock. difference stub has property behavior default. so full implementation following: ifoo mock = mockrepository.generatemock<ifoo>(); // variable self-made property behavior int currentvalue; // setting value: mock .stub(x => currentvalue = arg<int>.is.anything) .whencalled(call => { currentvalue = (int)call.arguments[0]; mystub.raise(/* ...*/); }) // getting value m

xml - Python regex issue -

i'm trying extract phone screen resolutions wurfl xml file below python script. problem first match, though. why? how matches? the wurfl xml file can found @ http://sourceforge.net/projects/wurfl/files/wurfl/latest/wurfl-latest.zip/download?use_mirror=freefr def read_file(file_name): f = open(file_name, 'rb') data = f.read() f.close() return data text = read_file('wurfl.xml') import re pattern = '<device id="(.*?)".*actual_device_root="true">.*<capability name="resolution_width" value="(\d+)"/>.*<capability name="resolution_height" value="(\d+)"/>.*</device>' m in re.findall(pattern, text, re.dotall): print(m) first, use xml parser instead of regular expressions. you'll happier in long run. second, if insist on using regexes, use finditer() instead of findall() . third, regex matches first entry last 1 (the .* greedy, , have se

c# - Can ASP.NET module be uploaded on PHP domain? -

i have website in php. now, trying publish separate admin panel (which in asp.net) on same server in different virtual directory. can work? if web server windows running iis, yes, can have asp.net , php co-existing on same server. you have problems if intend share between them -- eg cookies, , session data; you'll have keep them separate , provide separate logins, etc them. on other hand, if server isn't windows, or isn't running iis - if you're running linux server apache - won't able install asp.net, since tied platform. [edit] discussion on official microsoft iis forum, same question asked, , positive answer given: http://forums.iis.net/t/1154462.aspx also, might help: http://www.joshholmes.com/blog/2010/11/11/asp-net-and-php-on-iis-together/

How do simplify megamenu this jQuery code? -

hi i'm trying simplify code can't think way it, ideas? mega mega $(function() { $('#globalnavigation').find("a").bind({ click: function() { if (".submenu:hidden") { $(".submenu").css("display", "block"); } if ($('a[href$="#a-menu"]')) { $(this).addclass("active"); $("#services-menu").css("display", "none"); $("#innovations-menu").css("display", "none"); $("#insights-menu").css("display", "none"); $("#professionals-menu").fadein(750); } if ($('a[href$="#b-menu"]')) { $(this).addclass("active"); $("#professionals-menu").css("display", "none&q

scala - Defining an ordering on traits with abstract types which compiles only for compatible types? -

assume following trait: trait { type b } is there way of making ordered type, a's same b's can compared, , enforced in compile time? yes, via implicit (with type alias make things little more dry), type aa[t] = { type b = t } implicit def aisordered[t](a : aa[t]) = new ordered[aa[t]] { def compare(that : aa[t]) = 0 } sample repl session, scala> val ai1 = new { type b = int } ai1: java.lang.object a{type b = int} = $anon$1@1ec264c scala> val ai2 = new { type b = int } ai2: java.lang.object a{type b = int} = $anon$1@1a8fb1b scala> val ad = new { type b = double } ad: java.lang.object a{type b = double} = $anon$1@891a0 scala> ai1 < ai2 res2: boolean = false scala> ai1 < ad <console>:16: error: type mismatch; found : ad.type (with underlying type java.lang.object a{type b = double}) required: aa[int] ai1 < ad ^ edit ... thanks implicit definitions in scala.math.lowpriorityorderingimplic

c# - PLINQ for DataTables -

is possible apply plinq next code: var query = x in table1.asenumerable() join y in table2.asenumerable() on x.field<string>("field1").tolower() equals y.field<string>("field1").tolower() (x.field<bool>("field2") == false) select x; foreach (var row in query) row.setfield<bool>("field2", true); any improving advances appreciated lot.

javascript - Dynamic table generation in jQuery -

how can dynamically generate html <table> variable number of rows? the number of rows depend on number of properties exist within javascript object. function showtable(trnum) //number of table rows passed in { // how? // $("#elem").foo // #elem - element container table } function showtable(trnum) { var tablecode = "<table>"; (var i=0; i<trnum; i++) { tablecode += "<tr>" + "stuff inside each tr ?" + "</tr>"; } tablecode += "</table>"; $("#elem").append(tablecode); }

java - How many messages can be queued up in a JMS topic? -

for web app, have jms topic receiving many messages @ given time. have mdb processes messages , updates database based on message data. had been getting org.hibernate.exception.lockacquisitionexception when topic receiving multiple messages @ same time changed maxsessions attribute mdb 1 , made singleton. now not seeing hibernate exceptions anymore, have concerns performance. how large can expect topic before start seeing problems? using jboss 4.3 eap , tried searching how configure nothing turned up. topic size grow until java runs out of memory or can configured in jboss? by default, jboss messaging store messages in embedded hypersonic database. if topic starts filling up, memory consumption shouldn't increase linearly, sooner or later database fill (from recall, hypersonic has 40,000 row limit, in configuration @ least). more generally, if you're producing messages faster you're consuming them, have problem. either need produce them more slowly, consu

Drupal Calendar, I want each user sees his own events only -

i installed drupal 6 calendar module , it's working fine, shows events users, want restrict show events user viewing now so want user see own events only, not other users events, how can ? try adding filter in view of user: current . restrict events current user created.

Performance of StringTokenizer class vs. split method in Java -

in software need split string words. have more 19,000,000 documents more 30 words each. which of following 2 ways best way (in terms of performance)? stringtokenizer stokenize = new stringtokenizer(s," "); while (stokenize.hasmoretokens()) { or string[] splits = s.split(" "); for(int =0; < splits.length; i++) if data in database need parse string of words, suggest using indexof repeatedly. many times faster either solution. however, getting data database still more expensive. stringbuilder sb = new stringbuilder(); (int = 100000; < 100000 + 60; i++) sb.append(i).append(' '); string sample = sb.tostring(); int runs = 100000; (int = 0; < 5; i++) { { long start = system.nanotime(); (int r = 0; r < runs; r++) { stringtokenizer st = new stringtokenizer(sample); list<string> list = new arraylist<string>(); while (st.hasmoretokens()) list.a

html - Button:hover not working in Firefox -

i haveing problem hover not working in firefox! working in chrome, ie 9, ie 8 , ie 7. somewone know problem , how fix it? the css : .row button span:hover { background-position : left bottom; border : 1px solid #2b2b2b; } the html : <button type="submit"><span>button</span></button> it looks hover event isn't getting fed down span. try selecting button:hover span instead of button span:hover here's jsfiddle works okay doing above: http://jsfiddle.net/3j7g5/

bash - Problem with suspending and resuming job -

i have driver script manages job string can run jobs in parallel or sequentially based on dependency graph. example: job predecessors null b c d b e d, c f e the driver starts in background , waits complete suspending itselfusing bash built-in suspend . on completion, job sends sigcont driver start b , c in background , suspend again, , on. the driver has set -m job control enabled. this works fine when driver started in background. however, when driver invoked in foreground, first call suspend works fine . second call seems turn ' exit ' reports " there stopped jobs " , does not exit . third call suspend turns ' exit ' , kills driver , children [as should considering second converted call ' exit ']. and question: is expected behavior? if so, why , how work around it? thanks. code fragments below: driver: step

javascript - Problem in getting the parseInt(data) return NaN -

i having peculiar problem getting integer ajax response. whenever call following code, parseint(data) returns nan despite data being string. function(data) //return information jquery's request { $('#progress_container').fadein(100); //fade in progress bar $('#progress_bar').width(data +"%"); //set width of progress bar based on $status value (set @ top of page) $('#progress_completed').html(parseint(data) +"%"); //display % completed within progress bar } from looks of line: $('#progress_completed').html(parseint(data) +"%"); it seems trying insert percentage html #progress_completed element. mentioned data string, why converting integer concatenating string (the % string)? parseint(data) + "%" this statement above creates string. if data string, need be: $('#progress_completed').html(data +&q

Changing default url to static-media in Flask -

i've made website using flask , have no problems getting things work on built-in development server. i've been able things running on production server under mod_wgsi. however, host static media static/cgi/php-5.2 application , can't flask 'see' without manually changing urls in html files. the problem seems basic flask setup expects static files within flask application. see here details. essentially, think need change url of 'static' portion of following 1 liner: <link rel="stylesheet" href="{{url_for('static', filename='css/print.css')}}" type="text/css" media="print"/> it looks can change in init .py, instructions here , defining static_path follows doesn't seem work. app = flask(__name__, static_path = '/web_media') to clear, if manually define url this: <link rel="stylesheet" href="/web_media/css/print.css" type="text/css" med

How to write lists "one by one" to a binary file in python? -

i have piece of code generates quite large lists in each iteration. save memory want write each list binary file in each iteration after list has been generated. have tried text files(even setting parameter "wb" in linux). "wb" seems not have effect file written in binary or text format. moreover, written file huge , don't want this. sure if can write these lists in binary format file smaller. thanks since mentioned need compressibility, i'd suggest using pickle gzip module compress output. can write , read lists 1 @ time, here's example of how: import gzip, pickle output = gzip.open('pickled.gz', 'wb', compresslevel=9) x in range(10): output.write(pickle.dumps(range(10)) + '\n\n') output.close() and use generator yield lists 1 @ time: def unpickler(input): partial = [] line in input: partial.append(line) if line == '\n': obj = ''.join(partial)

xml - select XElements with xmlns -

how select element xmlns specified? need select include/fragment element. i've tried adding http://schemas.microsoft.com/wix/2006/wi before element names, doesn't work. in xmldocument there namespacemanager functionality, don't see same stuff in xdocument. how select element xmlns? <include xmlns="http://schemas.microsoft.com/wix/2006/wi"> <fragment/> </include> i've tried: ienumerable<xelement> fragments = d.element("include").elements("fragment"); and const string xmlns="http://schemas.microsoft.com/wix/2006/wi/"; ienumerable<xelement> fragments = d.element(xmlns+"include").elements(xmlns+"fragment"); you need make xmlns variable xnamespace (instead of string): xnamespace xmlns = "http://schemas.microsoft.com/wix/2006/wi"; ienumerable<xelement> fragments = doc.element(xmlns + "include").elements(xmlns + "fragment&qu

javascript - How do I pass a an element position to jquery UI dialog -

i have list of elements , when clicking on each 1 jqueryui dialog box pop next to list element clicked on. $( "#selector" ).dialog({ draggable: false, width: 250, autoopen: false, position: [e.pagex,e.pagey] }); $(".opendialog").click(function(e){ console.log('i need cooridnates x:'+e.pagex+' , y:'+e.pagey+'to passed dialog box'); $( "#selector" ).dialog("open"); }); i can coordinates need, i'm having trouble passing them dialog init. would love insight this. thanks in advance! since want show dialog next clicked element, should defer setting dialog's position until information becomes available, i.e. in event handler: $("#selector").dialog({ draggable: false, width: 250, autoopen: false }); $(".opendialog").click(function(e) { $("#selector").dialog("option", "position&quo

sql server - Using function as a parameter when executing a stored procedure? -

this question has answer here: incorrect syntax near ')' calling storedproc getdate 2 answers i'm testing stored procedure , wanted submit 'getdate()' function in place of parameter: declare @return_value int exec @return_value = my_store procedure @myid = 1, @mydatefield = getdate() select 'return value' = @return_value go sql server 2005 complains following error: incorrect syntax near ')'. anybody care shed light on matter? per msdn execute stored procedure or function [ { exec | execute } ] { [ @return_status = ] { module_name [ ;number ] | @module_name_var } [ [ @parameter = ] { value | @variable [ output ] | [ default ] } ] [ ,...n ] [ recompile ] } [;]

WPF Data Binding of Width Property -

i'm trying bind width property of canvas width property of shape instance. shape width should updated when canvas width gets new value i want in code, without xaml, because create these elements on runtime. i tried this, didnt work (the code inside of canvas): binding binding = new binding(); binding.mode = bindingmode.onetime; binding.source = this; binding.path = new propertypath("width"); shape.setbinding(frameworkelement.widthproperty, binding); thanks lot help! ksman onetime looks wrong. think want use oneway or twoway . check the bindingmodes edit since oneway , actualwidth didn't fix problem, should recommend use tool debugging bindings. use snoop because free, there others. debugging wpf without tool can painful.

javascript - AJAX vs PHP Directly into JS -

i have little bit of conundrum. i'm developing wysiwyg editor plugin jquery web application. 1 of features inserting inline image tooltip based on images user has uploaded. example: hello there name [i="profile_pic.png"]a. username[/i] the part i'm having issue is, when defining images available user, whether should insert php array directly javascript so: var available_images = "<?=json_encode($user->profile->images)?>"; or go ajax returns encoded array of image sources? think inline php makes more sense since removes need unnecessary ajax call didn't think inserting inline php javascript terribly form? any suggestions? there's nothing wrong inserting data collected php js, how else js data? reason should consider ajax call be, if users upload new images while editing . mean information needs updated, make ajax call more appealing static json on page load.

c# - How to detect height of web page without using a browser control -

i need rendered height of web page when rendered in ie. i'm using webbrowser control load html page , find document's clientheight (or scrollheight, forget which). works well. the problem is, need code run web service result of api call , launching windows form based control load in webbrowser control ugly , (i assume) incredibly resource hungry. so, there headless browser implementation out there allow me figure out height of rendered html? know wouldn't work iframes, divs scroll etc, , doesn't need super accurate (within 200px fine). the html pages test range around 700px high many thousands of pixels high, figuring out rough height perfect. html used tends quite simple, these pages html emails, extracted email , sent web browser. this depends on browser , rendering engine. have use renderer. if html standard one, should able use htmlayout's in-memory rendering capability , results similar other browsers. it has .net wrapper @ http://code

php - Redirecting to mobile subdomain in a CI application -

i have web app of create mobile version jquery mobile. existing application built in codeigniter; i'll using same controllers, models can; (especially models since i'll needing same data anyway, might have write new controllers). i'm bit confused how started. want put mobile version on subdomain ( m.myhost.tld ), however.. since app @ www.myhost.tld , don't feel copying on folder , maintain two, i'm bit confused. i know can use user agent library in codeigniter detect mobile browsers , load views accordingly; don't know how working subdomain. need customize app/config/routes.php file here, or can fix .htaccess magic? have next none experience .htaccess though. thing know how remove index.php ci apps, , that's copypasta snippet. edit: wonder if can use tutorial this one want do? seems doing more or less same thing, dynamic usernames instead of simple 'm.' edit 2: more information, guess. say detect mobile browsers using user agent l

sql server 2005 - Recursive CTE with non-numeric hierarchy data -

i have (simplified) table: orgname | hierarchy ---------|------------ org1 | org2 | aa org3 | ab org4 | aba an organization child of organization if: the child's length 1 greater parent the parent's hierarchy code matches first len(parent.hierarchy) of child's code so in table: org2 , org3 children org1 org4 child of org3 , grandchild org1 my question how write recursive hierarchy find descendants of particular organization? of cte examples i've read have numeric conditions of join (like employee.managerid = cte.empid ). here's have far: delcare @search varchare = 'a' org_cte (orgname, hlevel, recursionlevel) (select o.orgname, o.hierarchy, 0 recursionlevel orgtable o o.hierarchy = @search union select o.orgname, o.hierarchy, recursionlevel + 1 orgtable o inner join org_cte on ???) select orgname, hlevel, recursion org_cte i'm new cte, help! edit: this should it. overlooked s

concurrency - How to make multiple parallel web html requests in a Chrome Extension? -

i'd retrieve , parse multiple html pages within chrome extension. using web workers each request seemed simple way make them execute in parallel. possible? attempt failed, perhaps because it's known permissions bug . as workaround, guess have main extension page multiple asynchronous xmlhttprequests, have callback send result page web workers parallel parsing. method raises question of how many asynchronous parallel requests can chrome make @ once? question has been asked here , without answer. the chrome extension i'm writing browser action. code worker: // triggered postmessage in page onmessage = function (evt) { var message = evt.data; postmessage(message.count + " started"); update(message.count, message.url); }; // parse results page function parseresponse(count, url, resp) { var msg = count.tostring() + " received response "; postmessage(msg); } // read buganizer url , parse result page var update = function(co

sharing a link on facebook: how to get thumbnails? -

i've put in page's header following <link rel="image_src" href="http://fractalsoft.s3.amazonaws.com/sfondo.jp2" /> but thumb not showing up. i think problem image located outside site. is there way solve this? thanks! ok, added inside tag , done: <meta property="og:image" content="http://s3.amazonaws.com/andrea/photos/activities/26/medium.jpg?1304082168"/> and there other useful tags: <meta property="og:title" content="..."/> <meta property="fb:app_id" content="..."/> <meta property="og:type" content="activity"/> <meta property="og:url" content="..."/> <meta property="og:image" content="..."/> <meta property="og:site_name" content="..."/> <meta property="og:description" content="..."/> hop

c# - Dynamic table names -

i have database program query. it has 3 tables same structure: table1, table2 table3 how can write linq query query each of these table, dynamically specifying tablename? in addition this. solution must work if additional tables added database. though when writing code table4 did not exist may added. try this: dataset s = new dataset (); datatable t1 = new datatable (); t1.columns.add ("a", typeof (int)); t1.columns.add ("b", typeof (string)); s.tables.add (t1); t1.rows.add (1, "t1"); t1.rows.add (2, "t1"); datatable t2 = new datatable (); t2.columns.add ("a", typeof (int)); t2.columns.add ("b", typeof (string)); s.tables.add (t2); t2.rows.add (1, "t2"); t2.rows.add (2, "t2"); t2.rows.add (3, "t2"); var result = t in s.tables.oftype<datatable> () r in t.rows.o

java - Compare the current EST to 2PM EST? How? -

so have piece of code return current est date easterntime = new date(); dateformat format = new simpledateformat("h:mm a"); format.settimezone(timezone.gettimezone("est")); return format.format(easterntime); let return x = 12:15pm i want compare x 3:00pm est see if x before or after 3:00pm est, and/or x between 3:00pm - 6:00pm est. there way this. we dont have use java.util.date . take solution calendar well i definitely in joda time instead. if really want built-in api, need use calendar find local time in particular time zone - joda make simpler. you'd use datetime in specific time zone, , possibly take localtime compare localtime s you've hard-coded (or read configuration file etc).

events - Java networking: evented Socket/InputStream -

i'm implementing event-oriented layer on java's sockets, , wondering if there way determine if there data pending read. my normal approach read socket buffer, , call provided callbacks when buffer filled on given amount of bytes (which 0, if callback needs fired every time arrives), suspect java doing buffering me. is available() method of inputstream reliable this? should read() , own buffering on top of socket? or there way? shortly put, no. available() not reliable (at least not me). recommend using java.nio.channels.socketchannel connected selector , selectionkey . solution event-based, more complicated plain sockets. for clients: construct socket channel ( socket ), open selector ( selector = selector.open(); ). use non-blocking socket.configureblocking(false); register selector connections socket.register(selector, selectionkey.op_connect); connect socket.connect(new inetsocketaddress(host, port)); see if there new selector.select(); if &qu