Posts

Showing posts from February, 2011

c# - DllNotFoundException when web application p/invokes a win32 DLL -

i error when web application p/invokes win32 dll (player.dll) system.dllnotfoundexception: unable load dll 'player.dll': specified module not found. (exception hresult: 0x8007007e) at player.playerproxy.initialize() atrunaware.wpfbrowserapp.player.page1.playfile(object sender, routedeventargs e) the application written in wpf (xbap). i've following info in .manifest file. although .net dlls mentioned in <dependency> tags, win32 dll mentioned in tag. why difference? <file name="win32dll\player.dll" size="620544"> <hash> <dsig:transforms> <dsig:transform algorithm="urn:schemas-microsoft-com:hashtransforms.identity" /> </dsig:transforms> <dsig:digestmethod algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /> <dsig:digestvalue>ewahnz1qpeygmncxuskji4zta78=</dsig:digestvalue> </hash> </file> ...

push notification - Badge on App Icon in Iphone App -

how badge notification in app icon , similar badge notifications in tabbar item.? need notifying new messages. you can set app icon's badge number this: [uiapplication sharedapplication].applicationiconbadgenumber = 3;

geocoding - The most efficient way to query ip ranges in mysql -

i have geoencoding database ranges of integers (ip addresses equivalent) in each row fromip (long) toip (long). integers created ip addresses php ip2long i need find row in given ip address (converted long) within range. what efficient way it? (keys , query) if (the naive solution) select * ipranges fromip <= givenip , toip >= givenip limit 1 , key fromip, toip . case ip address not in given ranges search goes through rows. some more info: explain select * ipranges ipfrom <= 2130706433 , ipto >= 2130706433 order ipfrom asc limit 1| gives me 2.5m rows (total 3.6m in table). key is: primary key ( ipfrom , ipto ) that not seem efficient @ all. (the ip above in none of ranges) your query fine, put index on (fromip, toip) covering index query. table won't have examined @ all, sorted index gets searched, fast can be. the search not go through rows. not go through none of rows, index, won't examine every entry in index e...

openoffice.org - how to create an odt file programmatically with java? -

how can create odt (libreoffice/openoffice writer) file java programmatically? "hello world" example sufficient. looked @ openoffice website documentation wasn't clear. take @ odfdom - opendocument api odfdom free opendocument format (odf) library. purpose provide easy common way create, access , manipulate odf files, without requiring detailed knowledge of odf specification. designed provide odf developer community easy lightwork programming api portable object-oriented language. the current reference implementation written in java. // create text document standard template (empty documents within jar) odftextdocument odt = odftextdocument.newtextdocument(); // append text end of document. odt.addtext("this first odf test"); // save document odt.save("myfilename.odt"); later as of writing (2016-02), told these classes deprecated... big time, , odftextdocument api documentation tells you: as o...

Delphi Emulate Keys/Mouse To a Specific window -

i wondering how target specific window key strokes/mouse clicks able help? (regarding comment question) if button standard button control , find handle , send bm_click message (take note of remarks in documentation when dialog not active).

linux - Different result when executed from Crontab -

i trying number of open files periodically through crontab using lsof|wc -l. returns zero. giving correct result when run directly.any idea strange behaviour?is related pipe size result can quite large?thanks lot. kaka the main difference environment variables. in case might path. lsof found in or /usr/sbin , might in path when run interactivly, while not in path when run cron. try /usr/sbin/lsof|wc -l in cron script. , check local mail, cron output sent there, there might relevant error messages. is related pipe size result can quite large? no.

Access hashmap value by variable in JSP -

i have hashmap, put request: hashmap<integer, string> mymap = ... request.setattribute("mymap", mymap); in jsp have foreach loop <c:foreach items="${list}" var="item" varstatus="status"> <c:out value="${item.description}"/> <c:out value="${mymap[item.id]}"/> </c:foreach> but ${mymap[item.id]} not work. how can access hashmap's value item.id variable ? in el, numbers treated long . change map map<long, string> , it'll work.

browser - Problem loading wordpress blog on Google Chrome -

i doing tweaks header , stuff of wordpress blog. , of sudden realized google chrome having issues browsing blog page. on other hand working fine on firefox. not sure went wrong, following error message receive: warning: cannot modify header information - headers sent (output started @ /home/misspass/public_html/wp-blog-header.php:3) in /home/misspass/public_html/wp-includes/pluggable.php on line 890 the address of blog http://www.misspassiton.com.au i obliged if me out regarding issue. for me can overwrite file: /home/misspass/public_html/wp-includes/pluggable.php

asp.net - How to preserve dynamically created controls? -

i want preserve dynamically created control when postback occurs . protected void page_load(object sender, eventargs e) { } private void createtable() { htmltablerow objhtmltblrow = new htmltablerow(); htmltablecell objhtmltablecell = new htmltablecell(); objhtmltablecell.controls.add(new textbox()); objhtmltblrow.cells.add(objhtmltablecell); mytable.rows.add(objhtmltblrow); this.savecontrolstate(); // this.controls.add(mytable); } protected void button1_click(object sender, eventargs e) { createtable(); } it can achieved calling createtable() in page_load. there alternative way preserve control thanks you can add them list when create them , save list session. on postback (page_load) load them session page.

c# - Building a photography portfolio site in Silverlight - your input wanted! -

i'm .net newbie , want learn more programming silverlight webapp. in spare time photography big passion of mine, thought why not try build myself portfolio website in silverlight nice project focus on , learn from. i've started digging world of silverlight , i'm blown away fact there many frameworks etc can use, caliburn (micro), ria services, wcf data services, etc etc. perhaps can me out choose what's best use (and not). i've made basic list of stuff want have on site: navigator-style interface (some text and/or images click on swap pages) a portfolio page photos grouped in albums a blog comments section (should build myself?) a few textbased pages including graphics, "about me", "gear", etc (nothing special) a guestbook people can drop line (or soooo 1999?) a contact-me page (mailform style) basically, need know need able build site have in mind. should using stuff caliburn micro, ef, etc? hope guys can me on way. thanks o...

I have created one facebook app by which you can play game with each other randomly from all across world -

xmlhttp not supporting in ie ,actually had created 1 facebook app users can play game each other randomly,problem when want test it, login in facebook userid in firefox,and login brother facebook id in chrome connecting each other,do think beacuse of same ip address not connecting or not creating xmlhttprequest object ie , chrome.... function getxmlhttpobject() { var xmlhttp = null; try { // firefox, opera 8.0+, safari xmlhttp = new xmlhttprequest(); } catch (e) { //internet explorer try { xmlhttp = new activexobject("msxml2.xmlhttp"); } catch (e) { xmlhttp = new activexobject("microsoft.xmlhttp"); } } return xmlhttp; ...

Message Box in ASP.NET hindering the layout -

i displaying message in asp.net code-behind using this: response.write("<script>alert('hello')</script>"); when ok button pressed on message box, whole layout of web page shifts little towards right direction. wrong? else added? private void alert(string msg) { response.write("<script language = 'javascript'>window.alert('" + msg + "')</script>"); } try previos method .. if u want cool messages try following link: produce "toast" messages stackoverflow

android - Repackage APK file to contain custom assets - what build tool to use? -

update : old post, , references below broken aapt versions out of date. based on previous feedback, storing custom text fields in assets directory of app. i write app, using default user details in asset file, , client rebuild app each user, including user's details in asset file. (i aware method has serious shortcomings, client still keen in way - see embed login details in apk file, different each user (or other options?) ) this question relates troubles having rebuilding apk file, once have unzipped it, , updated custom asset file. quite convinced missing small, however, documentation , posts have found on these methods not helpful enough newcomer. aapt - android sdk tool: unfortunately android docs on "using aapt" on android docs [link 2 below] limited. console command -help shows bit more info. when trying use add file test.apk, ends deleting original, , creating new file test.apk.zip containing file tried add. have not been able find correct comman...

python - PyQt4 - "See the log file for details" error -

i have made application using python , found can use py2exe make executables windows. the problem library using (xmpppy) produces error deprecationwarning: md5 module deprecated; use hashlib instead and when try run executable dialog appears saying this see logfile 'c:\python26\p2e\myapp\dist\myapp.exe.log' details any ideas how fix that? you can try including following lines down import sys sys.stdout = open(“my_stdout.log”, “w”) sys.stderr = open(“my_stderr.log”, “w”) for more information can read this

java - Strategy Pattern and Dependency Injection in Spring -

i have strategy interface, implemented strategya , strategyb , both of them defined @component 's , have @autowired attribute well, how can obtain instance of 1 of them based on string value? this controller's action, should perform strategy: @requestmapping("/blabla") public void perform (@requestparam string strategyname) { strategy strategy = (strategy) /* concrete strategy based on strategyname */; strategy.dostuff (); } thanks! you can programmatically: private @autowired beanfactory beanfactory; @requestmapping("/blabla") public void perform (@requestparam string strategyname) { strategy strategy = beanfactory.getbean(strategyname, strategy.class); strategy.dostuff(); } you fancier way using custom webargumentresolver , that's lot more trouble it's worth.

bash - Deleting all folders older than a specified date, except some -

i have delete directories in path, older specified date except of them, in bash. i know names of directories shouldn't deleted. use find . here's example should work @ least on freebsd: find . -type d -not -newerct 'x days ago' -not -name dir1 -not -name dir2 -delete

javascript - AJAX with Facebook Authentication -

This summary is not available. Please click here to view the post.

how to load API on Windows 7? -

my intention able sucessfully load .dll file hook windows api. have researched , tried extensively, without success, method load .dll file on 64bit machine running windows 7. 2 solutions have tried include loading path of .dll registry keys: computer/hkey_local_machine\software\microsoft\windowsnt\currentversion\windows\appinit_dlls or computer\hkey_local_machine\software\wow6432node\microsoft\windowsnt\currentversion\windows\appinit_dlls please don't me wrong, there many online resources explaining how load apis registry, none of them have worked me. apologize if answer question obvious, have tried could. time , help! don't use appinit_dlls mechanism dangerous , can lead crashes , loader-lock deadlocks in other applications (see great raymond chen has on subject). if absolutely, positively must use mechanism can only call functions in kernel32.dll. no runtime calls at all . a better option using detours library

asp.net mvc - IIS7.5 not displaying Flash object -

i'm writing mvc web app in asp.net mvc, supposed serving flash object written 1 of colleagues. don't know flash; doesn't know c#/asp.net; hence question goes so! the code on web page looks this: <head> (blah blah blah...) <script type="text/javascript" src="/flashstuff/js/swfobject.js"></script> <script type="text/javascript"> var gp_mlm_flashvars = {}; gp_mlm_flashvars.remote = 'true'; gp_mlm_flashvars.streamprovider = 'localweb'; gp_mlm_flashvars.referer = ''; gp_mlm_flashvars.bgcolor = '#000033'; var gp_mlm_params = {}; gp_mlm_params.menu = 'false'; gp_mlm_params.allowfullscreen = 'true'; gp_mlm_params.salign = 'tl'; gp_mlm_params.scale = 'noscale'; gp_mlm_params.wmode = 'opaque'; gp_mlm_params.bgcolor = '#000033'; var gp_mlm_attributes = {}; gp_mlm_attributes.id = ...

html - Check visibility of an object with JavaScript -

i have variable called "object". how can check javascript if visible? i tried !object.getattribute("dislay", "none")... doesn't work. could me please? thank you! function isvisible(obj) { return obj.offsetwidth > 0 && obj.offsetheight > 0; } as it's implemented in jquery.

Debugging PHP Output -

i have php website on pages adding dot or space before first html tag. can't figure out coming - there way debug code can see coming from? thanks, josh to prevents happening considered practice don't end php file ?> . you possibly have file way (notice space after ?> ): <?php // code // ?> if remove ?> @ end, space @ end of file won't interpreted output. for files contain php code, closing tag ("?>") never permitted. not required php, , omitting it´ prevents accidental injection of trailing white space response. source: http://framework.zend.com/manual/en/coding-standard.php-file-formatting.html

hibernate - multiple levels of nesting component in JPA -

i know using hibernate mapping files can nest 1 component inside another. example: <?xml version="1.0" encoding="utf-8"?> <!doctype hibernate-mapping public "-//hibernate/hibernate mapping dtd 3.0//en" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.hibernaterecipes.chapter3"> <class name="orders" table="book_orders"> <id name="id" type="long" column="id"> <generator class="native" /> </id> <component name="weekdaycontact" class="contact"> <property name="recipient" type="string" column="weekday_recipient" /> <component name="phone" class="phone"> <property name="areacode" type="string" column="weekday_areacode" /> <property name="...

css - IE7 acronym underline in a fieldset legend -

i have acronym inside of fieldset/legend: <fieldset> <legend> <acronym>foo</acronym> </legend> </fieldset> in firefox gets rendered dotted underline signal user there there if mouseover it. in ie dotted underline doesn't show up? i tried forcing in css this: style="border-bottom:1px dotted #000000 !important;" but can't seem show up. ideas? set acronym's display style inline-block let ie7 show border specify in style.

JQuery: 1 datepicker From date to constrain the To date -

the user has enter date field , date field. date field must after date from. how enforce in jquery? current code not work, not giving default date. <script type="text/javascript" language="javascript"> $('#datefrom').datepicker({ dateformat: 'dd-mm-yy', changemonth: true, changeyear:true, yearrange: 'c-1:c+1' }); $('#dateto').datepicker({ dateformat: 'dd-mm-yy', changemonth: true, changeyear: true, yearrange: 'c-1:c+1' }); $('#datefrom').datepicker({ onselect: function (datestr) { $('#dateto').datepicker({ defaultdate: datestr }); } }); $('#dateto').datepicker(); </script> you can use minvalue option of datepicker. sample below: <input type="text" id="from"> <input type="text" id="to"> <script type="text/javascript"> $(function(){ $("#to").datepicker(); ...

ios - Delegates - retain or assign - release? -

i've seen number of posts related delegates, , know proper way reference them. suppose have object declared like: @interface myviewcontroller : uitableviewcontroller { id delegate; } @property (nonatomic, retain) id delegate; @end through lifecycle of myviewcontroller , make calls methods of delegate in response interaction user. when it's time rid of instance of myviewcontroller , delegate ivar need release 'ed in implementation's dealloc method since declared retain ? or conversely, should delegate retained? perhaps should @property (nonatomic, assign) id delegate ? according apple's docs : retain ... typically use attribute scalar types such nsinteger , cgrect, or (in reference-counted environment) objects don’t own such delegates. normally i'd go docs say, i've seen lot of code calls retain on delegate. "bad code?" defer experts here... proper way handle this? you want assign delegates rather retain...

jquery - stopping an onclick event if its the tab already selected -

how can stop following code executing if id 1 selected? any appreciated. //product tabs $('#productinfowrap .tab:first').show(); $('#subselect li').click(function() { var thistop = $(this).position().top; $('#subselect li').removeclass('current'); var li = (this); $('.pointer').animate( {'top': thistop}, function() { $(li).addclass('current'); }); var id = $(this).find("a").attr('href'); $("#productinfowrap > div").fadeout(500).hide(); $(id).fadein(); return false; }); and html <ul id="subselect"> <li class="current"><a href="#overview">overview</a><span class="pointer"></span></li> <li><a href="#applications">applications</a></li> ...

click - Flash Video metrics on the "play" button -

i've been searching around internet while store click counter within flash video. count how many times video viewed instead of page being loaded. i have few restrictions. :( i cannot use server side language. i cannot use database. (i want use text file stored on server) is possible? there simple , effective solution : google analytics api. get analytics account, , can track videos clicks , more, beautiful graphs. you can create dynamic stats javascript or flash, see example. if use flowplayer, hook api track play, pause or event.

asp.net - SharePoint 2010 - login without using AD accounts? -

if create public facing internet site using sharepoint backend, how change login process doesn't use ad / local windows accounts? i want have registration process logins admin approve before giving out access users. you can use forms based authentication users stored in sql server tables. see: http://blog.summitcloud.com/2009/11/forms-based-authentication-sharepoint-2010-fb/

SQL Server 2008 Express (shared hosting) Times Out When Changing Data Type on Field -

i'm changing bad design on table. field i'm trying change holds iis7 session id's long numbers. i'm trying change field nvarchar(20) int. there 349,000 records in table. sql server management studio times out after 35 seconds. however, if check query timeout setting connection set @ 600 seconds (and can't change either). is there timeout setting causing problem? here's error message i'm getting: - unable modify table. timeout expired. timeout period elapsed prior completion of operation or server not responding. i've been able change several other tables no problem. of course, had fewer rows. this database on shared hosting package @ arvixe.com. think part of problem? can try run t-sql script instead of doing using visual designer? alter table dbo.yourtable alter column yourcolumn int now, only work if all rows valid int values! otherwise, it'll bomb out @ point.... to check if rows valid int, run query: select *...

Double value to round up in Java -

i have double value = 1.068879335 want round 2 decimal values 1.07. i tried this decimalformat df=new decimalformat("0.00"); string formate = df.format(value); double finalvalue = double.parsedouble(formate) ; this giving me following exception java.lang.numberformatexception: input string: "1,07" @ sun.misc.floatingdecimal.readjavaformatstring(floatingdecimal.java:1224) @ java.lang.double.parsedouble(double.java:510) can 1 tell me wrong code. finaly need finalvalue = 1.07; note comma in string: "1,07". decimalformat uses locale-specific separator string, while double.parsedouble() not. happen live in country decimal separator ",", can't parse number back. however, can use same decimalformat parse back: decimalformat df=new decimalformat("0.00"); string formate = df.format(value); double finalvalue = (double)df.parse(formate) ; but should instead: double finalvalue = math.round( value ...

error handling - Is there a way of showing variable values in an global ASP.Net exception? -

i have global error trap in application_error method of global.asax writes unhandled exception log file. is there anyway of reporting variable names , values part of exception report? unless tricky aspect-oriented programming, pretty need make sure manually introduce relevant information stack trace when exceptions thrown. example: public void dosomething(int number, string name) { try { ... } catch (exception e) { throw new exception("error occurred while doing something: " + new {number, name}, e); } } this way, number , name included in stack trace when exception trickles top level. edit after reading david stratton's answer, felt need expand on little. sense experienced c# programmers haven't learned of tricks i've learned. first of all, wanted point out exception-handling system in .net designed idea of innerexception purpose (providing additional information @ vari...

Views and Tags (taxonomy) and Tabs in Drupal -

it drupal 6 installation , have content type has few taxonomy vocabularies , terms in tags format. i create views show nodes based on terms, , have views displayed in tabs. for example, 4 nodes: node 1: terma, termb node 2: terma, termc node 3: termb termc node 4: termb, termd i have tabs display have 4 tabs, named terma, termb, termc, termd respectively. when clicking each tab, show nodes associated term. eg: for tab terma, display node1, node 2, tab termd, display node 4 only. any suggestion on how that? thanks have looked @ taxonomy menu . might easier solution doing using views.

iphone - XCode/GDB stops on my auto-continue breakpoints when debugging on Device -

i discovered (thanks helpful post ) can use gdb commands create breakpoints log information gdb console, whether debugging on device or simulator. nslog, nicer in don't have wait console catch up, don't have annoying timestamps, , can turn them on/off @ run time via xcode breakpoint view). very nice, , invested time figuring out how best log messages , variables together. (use gdb command po [nsstring stringwithformat: @"your message: %d %@",variable,[[object expression] description]] ) maximum versatility. everything worked wonderfully in simulator. when got around device debugging, getting messages fine, gdb stopping on every breakpoint despite fact configured them auto-continue checking box in breakpoint view. i tried adding "continue" commmand each breakpoint, , worked gdb started spewing information every breakpoint hit , telling me "continuing" after every line. my questions: does happen you? can change auto-continue works on ...

proxy - We need to migrate SVN to a new server but need to keep original hostname in URL -

the original server hosting several services besides subversion, , cannot change hostname. many existing build scripts have change if use new host name in url. there way use network proxy or redirect svn:// traffic directed @ original host new host? if you're interested in subversion port 3690, simple tcp proxy application such datapipe trick. if you're willing change server name (once), recommend changing logical name such subversion or something, urls read svn://subversion/repo/... . changing location of server changing 1 logical host address.

e commerce - Complex Names with Authorize.net AIM -

how rest of handle complex names when submitting transaction authorize.net using aim? nearly every ecommerce application on planet asks user fill in "name appears on credit card". odd reason, authorize.net wants submit x_first_name , x_last_name however. this fine when you're dealing mary jones or jack smith . becomes real hassle when you've got margret a. jones-robinson , h. william robert van horn, sr. though. is there best practice here? first & middle names in x_first_name field? last name, hyphenated name and/or suffix in x_last_name field? has developed routine parse names accordingly? thanks! have 2 fields on payment form. 1 first name , 1 last name. customer chooses complete form how should submit (and save in database if choose so). fyi, name on credit card not used in processing of credit card not have transmit authorize.net process transaction. should anyway helps keep records accurate , complete handy when doing aud...

Oracle style dates in SQL Server -

we have ssrs report on want show date field in following format dd-mmm-yy in oracle. converts dates 25-jan-11 so in sql final select, use replace (convert (varchar, datetimecolumn,106), ' ', '-') is there better way of doing conversion? within sql server sql server convert: http://msdn.microsoft.com/en-us/library/ms187928.aspx no, specific format not available doing there is. prefer size varchar columns instead of leaving unsized. i notice have 106, dd-mmm-yyyy not dd-mmm-yy. did mean use 6? replace(convert (varchar(9), datetimecolumn, 6), ' ', '-') using ssrs formatting =format(fields!datetimecolumn.value, “dd-mmm-yy”)

ruby on rails - How to have one public/.htaccess per stage using capistrano-ext -

i'm using capistrano multistage (capistrano-ext) deploy staging or production. the problem i'm using passenger in shared hosting , need specify passengerapproot in public/.htaccess file. different between stages. how can keep different "stage-versions" of file? i haven't used capistrano-ext, i'm assuming somewhere in capfile you'll have stage variable. let's assume it's variable 'stage'. let's assume have 2 different versions checked in somewhere in code (public/.htaccess-{production|staging}) you set task symlink (or copy) right file after deploy: desc 'set stage-appropriate .htaccess file' task 'update_htaccess' run "ln -s #{release_path}/public/.htaccess-#{stage} #{release_path}/public/.htaccess" end after "deploy:update_code", "update_htaccess"

jquery - iPad app using JQtouch Help needed -

so 2nd attempt @ creating ipad app using jquery , jqtouch (see other questions) i wondering how can split readily available jqtouch theme app iphone uses 1 window - 2 windows. more suited ipad so when user accesses page, navigation on left, , have main window. when user clicks navigation link on left, div information appears in main window on right transition animation happening in main window , navigation remaining un changed. what have far, menu links displayed on page, when menu link clicked, mennu links slide left reveal selected link. i want menu links on left, when menu link clicked, selected link appears in window on right nice transistion animation. who can me?????? please? any reply appreciated. im not sure if links allowed make this: http://en.myfreeweb.ru/designing-an-ipad-web-application-with-jqtouc how looks far: jqtouch website @import "jqtouch.css"; @import "theme.css"; ...

Formatting PDF table with PHP -

i'm attempting format section of pdf table created php. have 2 tasks thought quite simple, can't figure either 1 out. inside table, have 4 cells need grey background color. thought fill={ {area=cell fillcolor={gray 0.12}} } work (as area=table works fine), i'm mistaken. my other issues deals formatting text within cell. need bold portion of text in middle of string. looking @ how rest of document created, seems though i'm able bold entire cell. there way around this? tia!!! assuming you're on pdflib, can specify macros within textflows allow vaguely html-like markup modify text on-the-fly within string. there's example here in 'case 3'

c# - Deserializing XML element to an Object when the element could be one of many possible elements -

within local framework messages transmitted in xml via pub/sub,i need able consume number of messages, however, messages received simple text , must deserialized objects created xsd tool. the messages derived base messagetype element/object, if deserialize based on so: xmlserializer serializer = new xmlserializer(typeof(messagetype)); xmlreader reader = xmlreader.create(new stringreader(rawmessage)); messagetype message = (messagetype)serializer.deserialize(reader); i receive error says actual element type ("updateparameter" say) not expected. at moment solution can think of use switch statement: xmlreader reader = xmlreader.create(new stringreader(upstring)); reader.movetocontent(); switch (reader.localname.tolower()) { case "updateparameter": serializer = new xmlserializer(typeof(updateparameter)); dostuff((updateparameter)serializer.deserialize(xml)); break; case "updateparameterresponse": serializer = new xm...

ruby - Nokogiri: need to turn markup partitioned by `hr` into divs -

given markup inside html document looks this <h3>test</h3> <p>test</p> <hr/> <h3>test2</h3> <p>test2</p> <hr/> i'd to produce this <div> <h3>test</h3> <p>test</p> </div> <div> <h3>test2</h3> <p>test2</p> </div> what's elegant way with nokogiri? edit : reworked answer bit cleaner. edit2 : small rewrite shorten 2 lines require 'nokogiri' doc = nokogiri::html <<endhtml <h3>test</h3> <p>test</p> <hr/> <h3>test2</h3> <p>test2</p> <hr/> endhtml body = doc.at_css('body') # created parsing html kids = body.xpath('./*') # every child of body body.inner_html = "" # empty body have our nodes div = (body << "<div>").first # create our first container in body...

sql - MySQL query - Before and after rows of a custom ordered results -

i've seen other questions similar in stackoverflow, of them based in auto-increment id, don't have that. i have query like: select field_a, field_b table field_m = '100' , field_n = '200' order field_x that results in this field_a field_b ------------------- john 12 marty 7 peter 2 carl 9 mark 11 bob 10 neil 1 louis 14 so, want complete original query , 1 query take record before , after 1 of them ... let's "carl", it's important in each case different, mean, other times need before , after of "bob" ... so, let's "carl" ... need create sql query in use order field_x described , , take before , after rows when field_a='carl' it rather heavy on big tables, can use ranking , join twice have previous , next record , use filter it. set @rank_prev = 0; set @rank_cur = 0; set @ra...

silverlight - Assigning to an attached property using a child element -

regular (not attached) properties in xaml can assigned either attribute or child element. example: <textblock foreground="blue">some text</textblock> or: <textblock> <textblock.foreground> <solidcolorbrush>blue</solidcolorbrush> </textblock.foreground> text </textblock> since attached properties simple, see examples of assigning them using attribute, example: <textblock grid.row="1">some text</textblock> but possible assign attached property using child element? i have custom control has attached property of complex (class) type. since can't specify value in attribute, i'm not sure how assign xaml. this feature called property element syntax , yes, can set attached properties using element attribute syntax: <textblock> <grid.column>1</grid.column> abc </textblock>

c# - BindingList and ListBox behaviour -

i have listbox bound bindinglist collection. works great. my grief occurs when first item enters collection. default behavior of listbox select item - yet, not raise selectedindexchanged event. assume because selectedindex set null; on becoming null, index isn't changed; rather assigned. how can stop default behavior of selecting (highlighting) first initial item added listbox? if assumption wrong, please shed light? update here core parts of code far. public uavcontrolform() { initializecomponent(); _controlfacade = new uavcontroller.facade.controlfacade(); updateflightuavlistbox(); } private void updateflightuavlistbox() { lsbflightuavs.datasource = _controlfacade.getflightuavtally(); lsbflightuavs.displaymember = "name"; } private static bindinglist<flightuav> _flightuavtally = new bindinglist<flightuav>(); public bindinglist<flightuav> flightuavtally { ...

install - android APK within an APK? -

as stated in question above, possible have apk file within apk? further explain, here situation: i have 2 apps , first 1 calls other through intent.. don't have problem this.. need install 1 apk file instead of two. , first thing came mind put .apk file inside other .apk file.. don't know if possible that's why need take on this. if not possible, hope can tell me best practice doing kind of thing. i can make 1 application, last solution. perhaps android library looking for. place can put common code , include in multiple applications (apks). see documentation on library projects .

python - Are there any good tutorial about using buildout and pip? -

i've been struggling day understand how use buildout , pip. watched bunch of videos etc., still have hard time figuring out , don't of buildout , pip. any help, tutorial, book welcome. is not http://www.buildout.org/ , http://pip.openplans.org/ tutorials helpful? apart that, there couple of tutorials on buildout 1 , pip 2 helpful start. best way start, write small buildout conf , using existing recipe pypi , see how package installs.

python - What's wrong with my PCA? -

my code: from numpy import * def pca(orig_data): data = array(orig_data) data = (data - data.mean(axis=0)) / data.std(axis=0) u, s, v = linalg.svd(data) print s #should s**2 instead! print v def load_iris(path): lines = [] open(path) input_file: lines = input_file.readlines() data = [] line in lines: cur_line = line.rstrip().split(',') cur_line = cur_line[:-1] cur_line = [float(elem) elem in cur_line] data.append(array(cur_line)) return array(data) if __name__ == '__main__': data = load_iris('iris.data') pca(data) the iris dataset: http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data output: [ 20.89551896 11.75513248 4.7013819 1.75816839] [[ 0.52237162 -0.26335492 0.58125401 0.56561105] [-0.37231836 -0.92555649 -0.02109478 -0.06541577] [ 0.72101681 -0.24203288 -0.14089226 -0.6338014 ] [ 0.26199559 -0.12413481 -0.80115427 0.5235462...

Like a Facebook Wall Post - Javascript -

i'm developing facebook application retrieves specific facebook wall posts. want allow user "like" post within application using javascript sdk. know how accomplish this? update: issuing post request likes connection of post object need: you can post issuing http post request post_id/likes connection publish_stream permission. no parameters necessary. example: fb.api("/post_id/likes", 'post',function(response) { if(response === true) { alert("done!"); } }); the above request should return true on success.

ruby on rails - Is it possible to call Git or other command line tools from inside a Thor script? -

i find i'm running sequence of routine 'cleanup' tasks before , after make git commit rails 3 app. i thinking putting these things thor script, 1 thing haven't been able figure out how use thor (or rake) call other tools on system. is possible call command git log thor or rake script, , if like? thanks! just shell out: result = %x(git log) puts result or system('git log') if want pass output terminal. there grit gem abstracts git tools ruby library: require 'grit' repo = grit::repo.new("/path/to/repo") repo.commits.each |commit| puts "#{commit.id}: #{commit.message}" end

asp.net - how to display result in gridview according to textbox only if textbox2 value is greater than textbox1? -

how display result in gridview according textbox if textbox2 date value greater textbox1 ? i have 2 textboxes , gridview ... if type in textbox1 : 2-jan-2011 , in textbox2 : 1-jan-2011 in label1 eroor message display else ..if textbox2 value greater textbox1 value gridview display records according textbox1 , textbox2 database ... how ,,, ? function retrieve date parameters , either show error message or call binding function: private void loaddata() { try { datetime date1 = convert.todatetime(textbox1.text); datetime date2 = convert.todatetime(textbox2.text); if (date1 >= date2) { label1.text = "invalid dates"; } else { binddataingridview(date1, date2); } } catch (exception ex) { // log , report exception } } function bind data: private void binddataingridview(datetime date1, datetime date2) { // logic retrieve data based on date parameters , bind gridview }

struts - servlet action is not available -

a strange thing happening when call servlet using struts, if call local host gets called when deploy on web server throws error saying " servlet action not available " here's web.xml <servlet> <servlet-name>action</servlet-name> <display-name>socialauthdemo</display-name> <description>application socialauth demo</description> <servlet-class>org.apache.struts.action.actionservlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/web-inf/struts-config.xml</param-value> </init-param> <init-param> <param-name>debug</param-name> <param-value>2</param-value> </init-param> <init-param> <param-name>detail...

android - Phonegap adding items to the notification tray -

i learning phonegap , push notifications notification tray on timer. i tried notification function in phonegap api messages boxes in application self. any ideas how send push notifications "notification tray" android system? update: have not worked phonegap long time, , repo no longer managed. here phonegap plugin have written system notifications. https://github.com/saileshmittal/phonegap-system-notification-plugin

javascript - Extend Google Maps Bounds so that div overlay doesn't cover any markers -

in google maps mashup i'm working on, map 100% wide , pretty 100% tall , have horizontal transparent div overlays left side of map using z-index , css. when dynamically add markers, start empty bounds object , extend 1 one contain new latlngs. markers appear under transparent div contains other elements. let's transparent div 250 pixels wide. what i'd once bounds show markers established, i'd extend them 1 more time expand viewport of google map when fit bounds, these markers appear @ least 250 pixels away left border not covered transparent div. i tried playing mapprojection.frompointtolatlng , mapcanvasprojection.fromdivpointtolatlng wasn't able achieve predictable results. any advice or examples appreciated. hopefully quick , dirty solution (it api v3) <html> <head> <style> #over { position: absolute; z-index:99999; width: 250px; height: 600px; opacity: 0.7; top: 0px; border: 2px solid black; left: 0px; background: w...

python - how to send success message if we use django generic views -

i new django (1.2.4). have created crud generic views. how can show "the student added successfully" when student created using django's messaging framework? as far know, there isn't straightforward way of doing using traditional generic views. i've felt documentation on generic views pretty lacking , never used them. in theory use decorator making assumption redirect meant successful submission. so write (none of code has been tested): urls.py : try: functools import wraps except importerror: django.utils.functional import wraps django.http import httpredirectresponse django.contrib import messages django.views.generic import * def add_message(success_message=none): def decorator(func): def inner(request, *args, **kwargs): resp = func(request, *args, **kwargs) if isinstance(resp, httpredirectresponse): messages.success(request, message) return resp return wraps...

php - The results of 2 queries in one while loop -

i want plot 3 dataseries in jquery flot first 2 series snowdepth in last 10 weeks (upper , lower mountain). last 1 snowdepth upper slopes 1 year earlier. use 2 queries exercice , want merge results 1 while loop. have far dataseries stay empty (d1,d2,d5). doing wrong? $yrwk = $curryear . $currweek; $rquery21 = "select wk, yr, snow_valley, snow_mountain sv_cond_vw res_id=$res_id , yrwk<$yrwk order yrwk desc limit 11"; $rresult21 = mysql_query($rquery21); $lyrwk = $lastyear . $currweek; $lquery21 = "select snow_mountain sv_cond_vw res_id=$res_id , yrwk<$yrwk order lyrwk desc limit 11"; $lresult21 = mysql_query($lquery21); while ($rows21 = mysql_fetch_array($rresult21) && $lrows21 = mysql_fetch_array($lresult21)) { $wk = $rows21['wk']; $yr = $rows21['yr']; $wk=date('d-m-y', getdatefromweek($wk, $yr)); $wk = strtotime($wk); $wk=$wk*1000; $snow_mnt = $rows21['snow_mountain']; $snow_val = $rows21['snow_valley'...

javascript - Prototype rewrite of jQuery function -

i'm bit of jquery monkey , i've had site dropped on me need use simple function open links rel="external" in separate window. in jquery this: // make links rel=external open in new window/tab $(function() { $('a[rel*=external]').click( function() { window.open(this.href); return false; }); }); how set same function in prototype triggered unobtrusively on links rel=external attached them? thanks simon edit: following advice of 3 responses below final code is: $(document).on('dom:loaded', function() { $$('a[rel*=external]').invoke('on','click', function(event) { window.open(this.href); event.stop(); }); }); thanks all! event.observe(window, 'load', function() { $$('a[rel*=external]').each(function(item) { $(item).observe('click', function(event) { window.open(this.href); event.stop(); ...

sql - EXECUTE IMMEDIATE in plsql -

how result code execute immediate 'select * ' || table_name through for loop the usual method looks this for items in (select * this_table) loop htp.p(items.id); end loop; if really need select * from dynamic table name , i'd go dbms_sql type record : create type tq84_varchar2_tab table of varchar2(4000); / type result set (which array of records ): create type tq84_varchar2_tab_tab table of tq84_varchar2_tab; / the function select , returns instance of result set : create or replace function tq84_select_star_from_table(table_name in varchar2) return tq84_varchar2_tab_tab stmt_txt varchar2(4000); cur number; columns_desc dbms_sql.desc_tab; column_cnt number; result_set tq84_varchar2_tab_tab; begin stmt_txt := 'select * ' || table_name; cur := dbms_sql.open_cursor; dbms_sql.parse(cur, stmt_txt, dbms_sql.native); dbms_sql.describe_columns(cur, column_cnt, columns_de...

java - How to set the state of a Google Visualization Motion Chart? -

i'm using gwt , google chart tools (aka visualization) 1.1 library of google api libraries gwt . i want display motion chart , set state possible in javascript . has idea how set state? here modified motionchart gwt-getting started page data javascript documentation. didn't test i'm not sure if code works. public class simpleviz implements entrypoint { public void onmoduleload() { // create callback called when visualization api // has been loaded. runnable onloadcallback = new runnable() { public void run() { panel panel = rootpanel.get(); motionchart chart = new motionchart(createtable(), createoptions()); panel.add(chart); } }; visualizationutils.loadvisualizationapi(onloadcallback, motionchart.package); } private options createoption...

django - ForeignKey to multiple Models or Queryset -

it possible make foreignkey more on model. want choose lets say, parts , machines model. i read combine multiple models 1 list: how combine 2 or more querysets in django view? but can foreignkey list somehow? i know asked on year ago, had similar problem , want share link solution future readers. generally the contenttypes framework solves problem, , guess daniel roseman talking about. how use dynamic foreignkey in django?

Glassfish v3 cache and Varnish cached -

i looking way speed site, contain decent amount of small images @ 1 times (so site primary io read). use glassfish v3. in gf v3, specify glassfish cache static resources. sufficient use gf cache? varnish cache me significant improvement on gf cache? do gf work varnish? varnish may better option; rather trying manage it's own set of files in memory , on-disk, works utilize underlying caching system of os instead of fighting against it, why out-performs other caching technologies such squid. i've found varnish simple set-up , have used in past number of client sites survive "slashdottings".

algorithm - In how many ways can you tile a 3xn rectangle with 2x1 dominoes? -

everyday struggle algorithm questions , try ask here can't answer. excuse me, if cause headache. anyway, here problem university of waterloo acm programming contest. in how many ways can tile 3xn rectangle 2x1 dominoes? nirvana : smells recursion spirit you can solve using dynamic programming. check this possible solution.

wpftoolkit - Wpf Toolkit Chart Invert Highlighting -

Image
how can highlight other pieces (columns, bars etc.) in chart created wpf toolkit. using control template style own chart. far used trigger fading effect on element on mouse residing. want invert this; fade other elements (a popular charting visual gimmick) on mouse not pointing. following image shows selected column faded, want other way around . just set default value faded , use trigger bring full opacity. have done other styling here example based on default style: <grid> <grid.resources> <pointcollection x:key="sampledata"> <point>1,20</point> <point>2,40</point> <point>3,30</point> </pointcollection> <style x:key="dimeffectstyle" targettype="{x:type charting:columndatapoint}" basedon="{staticresource {x:type charting:columndatapoint}}"> <setter property="opacity" value=...