Posts

Showing posts from April, 2015

actionscript 3 - How to count numbers in string -

i have string contains numbers this: 2243. need total of these numbers. using example numbers in string converted integers , i'd able this: 2+2+4+3 = 11. not having coded in quite while find myself bit stumped on (probably) quite easy task. all appreciated! you can : var number:string = "2243"; // represents original string number var result:int = 0; (var i:int = 0; < number.length; i++) { result += parseint(number.charat(i), 10); } // result var contain sum

sql - MySQL how to return concatenated name and lastname of a user -

i need mysql query return " value " , " label " field name. i have " value " id of user , " label " " name lastname " or "*name_first_letter lastname*" directly query. lets have table this: id name lastname 1 john johhanson 2 peter petterson 3 jeff jefferson i id "value" simple query: select id value . "j. johhanson" or "p. petterson" " label ". update sorry bothering. tried concat , concat_ws . unsuccessfully, managed results easily. in case query worked needed: select concat_ws(' ', name, lastname ) users name "%peter%" thank you. select id value, concat(left(name, 1), '. ', lastname) label table;

Automatically rebuild external cmake project after edit_cache -

i have main cmake project has project_include_path cached variable. pass variable cmake_args parameter external project add using externalproject_add(). the problem is, when change value of project_include_path using 'make edit_cache' external project not reconfigured. is there way make external project reconfigured , built automatically when cached variable changed in main project? i re-run cmake after modifying cmakecache.txt (not often). update externalproject_add call in case. probably safer option here avoid make edit_cache , , re-run cmake command line parameter of -dproject_include_path:path=<updated value> .

hibernate - SQL Injection Issue -- getHibernateTemplate().delete(getObject(objectClass,objectId)) method -

i fixing code audit report security issue-- sql injection. in code following method used extensively delete records. method defined in base class , extended every other dao level class in module. public void delete(class objectclass, long objectid)throws daoexception{ try{ gethibernatetemplate().delete(getobject(objectclass,objectid)); }catch(exception e){ throw new daoexception(e); } } and, method call gethibernatetemplate().delete(getobject(objectclass,objectid)); is reported prone sql injection. reported like "injection of data received servlet request ("getobject(objectclass,objectid)") user defined dangerous". how fix issue. have done sufficient homework , had fixed more sql injection issue prepared statement in hql. thanks in advance. answer -- method in use binding parameters , can verified log4j api. have verified logs binding parameters , sql injection issue not feasible

mcc - How to run external .m code in a MATLAB compiled application? -

this question has answer here: is possible execute compiled code both within , out of matlab environment? 2 answers i've got matlab project, compile in order have single executable file, using mcc. then want know if it's possible external programmer execute of .m files within .exe, without re-compiling whole project. the point provide application in other developpers add "plug-ins", written in matlab. i've searched way of running external .m files inside compiled matlab application (like thread : running .m file matlab-compiled function ) doesn't fit purposes here, altough it's working fine using eval(). but eval() "trick" isn't sufficient, doesn't allow define new functions or classes. instance, external .m files new classes (inherited compiled "interfaces" in executable). is there way dynamically l...

drupal - Taxonomy list with content counters -

using drupal 7, i have content type: movie, it has taxonomy of actors: keanu reeves, christian bale, milla jovovich, etc. i'd build view lists actors taxonomy count of content matching taxonomy term, example: keanu reeves (4) christian bale (8) milla jovovich (2) i'm not sure how build view, i've set view use aggregation, filter: =published, content type=movie, lang=users language, fields: count(content: actors) it doesn't seem accomplish goal, please help! couldn't find way implement via view, here's custom block code replace view. $vid = 3; //vocabulary id $num_term = 8; //limit maximum terms $query = "select tid, name, count ( select td.tid tid, name, count(td.tid) count taxonomy_term_data td join taxonomy_index tn on td.tid = tn.tid join node n on n.nid = tn.nid td.vid = ". $vid ." , n.status = 1 group td.tid order count desc limit ". $num_term . " ) t order name asc"; $result = db_quer...

linqpad - Is there a way to get an XML document instead of HTML from an entity dump? -

i love linqpad. there way xml document instead of html entity dump? i wanted use linqpad.util create xml doc instead of html doc on linqtosql changeset. have tried many ways serialize changeset unsuccessfully. linqpad util createxhtmlwriter works great prefer xml document. ideas on how quickly? right there's nothing in linqpad dump arbitrary object graph xml. however, should able describe quite extension method. go my extensions in linqpad , write method this: public static xelement toxml (this changeset cs) { return new xelement ("changeset", new xelement ("inserts", cs.inserts.select (e => entitytoxelement (e))), new xelement ("updates", cs.updates.select (e => entitytoxelement (e))), new xelement ("deletes", cs.deletes.select (e => entitytoxelement (e)))); } static xelement entitytoxelement (object o) { return new xelement ( o.gettype().name, o.gettype().getfie...

scalaz - Is Validation a SemiGroup/Monoid : using |+| does not work -

i uder impression validation used monoid/semigroup tried following code under scala 2.9.2 , scalaz 7 snapshot import scalaz._ import scalaz._ val success1 = 1.success val success2 = 2.success val failurea = "a".fail val failureb = "b".fail success1 |+| success2 <console>:16: error: diverging implicit expansion type scalaz.semigroup[scalaz.validation[nothing,int]] starting method validationsemigroup in trait validationinstances success1 |+| success2 ^ <console>:16: error: value |+| not member of scalaz.validation[nothing,int] success1 |+| success2 i expecting success(3) then failurea |+| failureb gives res1: scalaz.validation[java.lang.string,nothing] = failure(ab) expected and success1 |+| failurea fails expected with <console>:16: error: diverging implicit expansion type scalaz.semigroup[scalaz.validation[nothing,int]] starting method validationsemigroup in trait validationinstance...

Asp.net Email Control -

i'm in beginning stage of building asp.net email control. i'm big fan of asp because developer can drop control onto page , functionality bundled it. so, goal develop emailcontrol encapsulates send/recieve single server control. i appreciate if has tips or technical references regarding topic. of wondering, doing research of own of may have additional sites check out. thanks to let users send, need basic form elements , code on page below send mail. sending email system.net.mail .net doesn't have native pop3/imap support there multitude of libraries available, such as: .net pop3 mime client (this answer assumes "send/receive" referring implementing mail client opposed mail server.)

Windows Live Login API SSL issue - Python -

i'm writing program invite several windows live contacts web application, in django 1.4. i'm experiencing following problem. i'm able log user in windows live using account credentials through windows live rest api using piece of code def hotmail(request): auth_params = { 'client_id': settings.hotmail_key, 'scope': 'wl.basic', 'response_type': 'code', 'redirect_uri': 'http://my_testing_comain/hotmail/process' } auth_url = settings.hotmail_auth_url % urllib.urlencode(auth_params) return httpresponseredirect(auth_url) then, receive authorization code exchange access token (according oauth protocol) piece of code use process windows live's response: def hotmail_process(request): if request.method == 'get': parameters = { 'code': request.get['code'], 'grant_type': 'authorization_code', ...

c# - WPF: Raise an Event when Item is added in ListView -

i working on wpf , using listview, , need fire event when item added it. have tried this: var dependencypropertydescriptor = dependencypropertydescriptor.fromproperty(itemscontrol.itemssourceproperty, typeof(listview)); if (dependencypropertydescriptor != null) { dependencypropertydescriptor.addvaluechanged(this, itemssourcepropertychangedcallback); } ..... private void itemssourcepropertychangedcallback(object sender, eventargs e) { raiseitemssourcepropertychangedevent(); } but seems working when entire collection changed, have read post: event-fired-when-item-is-added-to-listview , best answer applies listbox only. tried change code listview wasnt able that. i hope can me. thank in advance. note works wpf listview! after research have found answer question , it's easy: public mycontrol() { initializecomponent(); ((inotifycollectionchanged)listview.items).collectionchanged += listview_coll...

ruby on rails 3 - Hostname was not match with the server certificate while opening pdf with prawn -

i'm using prawn build pdfs. i'm having trouble opening existing pdf uploaded amazon s3. i've got model called format has file_name attribute has associated uploader. when try open existing pdf template: pdf.start_new_page(:template => open(@format.file_name_url)) the following error occurs: hostname not match server certificate when go @format.file_name_url myself, don't have issues, means url correct. going on? thanks!

How to compile and link together object files in C++ using the same header file? -

i'm having issue gcc compiler seems failing when comes linking 2 object files have together. both object files foo1.cc , foo2.cc include classes header file called foo1.hh . in addition, header file foo.hh has external declaration of object instance appears in foo1.cc . it should noted header file foo.hh defined once between 2 source files foo1.cc , foo2.cc . when compile source files using following command, seems work: g++ foo1.cc foo2.cc the above command produce executable called a.out . when try compile source files object files independently: g++ -c foo1.cc g++ -c foo2.cc g++ -o foo1.o foo2.o the gcc compiler complains there undefined references functions in foo2.cc . these functions should defined in foo1.cc ; however, linker doesn't recognize that. i wondering if there way around issue gcc compiler. there no issue, you've got error in gcc syntax. g++ -c foo1.cc g++ -c foo2.cc g++ -o foo foo1.o foo2.o the -o parameter accepts ...

ruby - Michael Hartl Rails Tutorial chapter 7 error Action not found in UsersController -

i'm following michael hartl's rails tutorial @ moment , i've managed 7.22 without major hitches. i'm stumped output testing says: failures: 1) userpages signup invalid information should not create user failure/error: expect{click_button submit }.not_to change(user, :count) abstractcontroller::actionnotfound: action 'create' not found userscontroller # (eval):2:in `click_button' # ./spec/requests/user_pages_spec.rb:29:in `block (5 levels) in <top (required)>' # ./spec/requests/user_pages_spec.rb:29:in `block (4 levels) in <top (required)>' 2) userpages signup valid information should create user failure/error: expect{click_button submit}.to change(user, :count).by(1) abstractcontroller::actionnotfound: action 'create' not found userscontroller # (eval):2:in `click_button' # ./spec/requests/user_pages_spec.rb:42:in `block (5 levels) in <top (required)>...

python - Custom Timer to get the seconds to the next start time/date -

i have project have assigned days of week running, while other days not included should skipped. eg: days on: mon (0), tues (1), wed (2), thurs (3), fri (4) days off: sat (5), sun (6) i have settings saved within registry days on, when settings pulled referenced weekday number. if want put app sleep on fri (4), , have wake on mon (0), how can go doing so? have no way state sure whether days off consistent, might have sun/mon off instead of sat/sun. ideally need @ current weekday number, see if within list of days on , if not, have calculate number of seconds until next day on begins. scenarios: i set script go sleep on friday june 8th, , sat/sun off days, how calculate seconds sleep 2 days starts again on mon 11th? i set script go sleep on wed june 6th, , need wake on fri june 8th, turn off on friday night have start again on monday morning. because days on variable, function must able accommodate it; running problems. any appreciated, big in advance! c...

c# 4.0 - Better way to query a page of data and get total count in entity framework 4.1? -

currently when need run query used w/ paging this: //setup query (typically more complex) var q = ctx.people.where(p=>p.name.startswith("a")); //get total result count prior sorting int total = q.count(); //apply sort query q = q.orderby(p => p.name); q.select(p => new personresult { name = p.name }.skip(skiprows).take(pagesize).toarray(); this works, wondered if possible improve more efficient while still using linq? couldn't think of way combine count w/ data retrieval in single trip db w/o using stored proc. the following query count , page results in 1 trip database, if check sql in linqpad, you'll see it's not pretty. can imagine more complex query. var query = ctx.people.where (p => p.name.startswith("a")); var page = query.orderby (p => p.name) .select (p => new personresult { name = p.name } ) .skip(skiprows).take(pagesize) .groupby (p ...

.htaccess - Symfony2/ get variable from subdomaine and htaccess -

i using symfony2. what best practice variable url. using subdomain city. ex: paris.website.com how paris variable. believe need play kernel , htaccess, haven't figured out how. thanks if can put me on right tracks that. cheers, pierre. you should read documentation of symfony. 1 of basis components of symfony routing provides need : www.mysite.com/paris/ using subdomain not solution, can play .htaccess rewrite subdomain paris.mysite.com www.mysite.com/paris (if web server allows it) after having configured route in symfony.

internationalization - GWT i18n and images -

is there way internationalize images (using g:image , imageresource) in gwt? can see, possible internationalize src attribute of img element, using: <img src="http://www.images.com/englishversionofimage.png" alt=""> <ui:attribute name="src" description="image internationalized"/> </img> and changing src value in appropriate localizableresource_xxxx.properties file. however, technique not seem applicable <g:image resource="{resources.myimageresource}"/> elements. should simple other source types ( https://developers.google.com/web-toolkit/doc/latest/devguideclientbundle#i18n ). in simple words, if use text labels: messages.properties messages_fr.properties messages_de.properties , try same technique images: logo.jpg logo_fr.jpg logo_de.jpg the proper file should have been chosen depending on current locale. so, considering example https://developers.google.com/web-toolkit/do...

Android DownloadManager ETag support -

there info android's downloadmanager support etags. okay, have server etag support (e.g. dropbox). when i'm trying download file downloadmanager creates new 1 , appends number local filename (e. g. file.zip, file-1.zip, file-2.zip etc.). there way not download existing file same etag? app will downloading huge files don't want reload them every time. is there way not download existing file same etag? you 1 requesting downloads. need determine files should , should not downloaded. afaik, downloadmanager uses etag interrupted downloads -- not store etag information indefinitely.

performance - When does java JIT have wrong optimization? -

jit method optimization (-xx:+printcompilation) after 10k invocations , can configure -xx:compilethreshold. read reason not lower threshold jit optimization might wrong or optimize infrequently used code. have few questions regarding area: i think wrong optimization (ie: on-stack-replacement) due lazy classloading of polymorphic methods. after 3 implementations (i think) found, jvm index table lookup. of course, speed suffers if have more polymorphic impl. polymorphic method cause or major cause wrong jit optimization? if not, others? what if force loading classes @ astartup jvm can build such index tables upfront, isn't better overall optimization upfront? what's wrong optimize-all approach? what's cost if goal speed? comparing c++, if source closed means no 3rd party lib, low-latency system, there way force optimization upfront increase performance closer of c++? peter lawrey mentioned in oracle magazine article can kick-in jit artificially run enough test data ...

postgresql - SQL, select in tables -

hey don't know how it.... its homework: list code , consumers bought cars 'argentina' country. table sell: customer | resell | veicle | date | value ---------+---------+-----------+------------+---------- 02 | 01 | 03 | 2010-02-05 | 17500.00 04 | 02 | 01 | 2010-01-07 | 28000.00 01 | 03 | 08 | 2010-02-15 | 28000.00 02 | 03 | 02 | 2010-03-12 | 42000.00 03 | 04 | 06 | 2010-02-06 | 11500.00 03 | 02 | 05 | 2010-01-25 | 22100.00 01 | 01 | 04 | 2010-01-21 | 15500.00 table customer: cod | name | lastname --------+------------+------------ 01 | jose | alves 02 | paulo | cunha 03 | maria | dpaula 04 | joana | silveria table veicle: cod |manufacturer| model | year | country | price --------+------------+-----------------+------+-----------+---------- 01 ...

.net - Strange Error Message Submitting from InfoPath to WCF Service -

i'm building infopath form (infopath 2010) , in custom code i'm calling wcf service programatically part of submit action below: driverhours.driverhours allhours = new driverhours.driverhours(); bool spec; xpathnavigator mynav = this.maindatasource.createnavigator(); string alldata = mynav.outerxml; alldata = alldata.replace("my:", ""); result = allhours.savedriverhoursbystring(alldata); savedriverhoursbystring takes string of xml data, saves database on backend via wcf. when submit block executes, following error shows on last line: system.web.services.protocols.soapheaderexception formatter threw exception while trying deserialize message: there error while trying deserialize parameter http://tempuri.org/:xml. innerexception message 'there error deserializing object of type system.string. maximum string content length quota (8192) has been exceeded while reading xml data. quota may increased changing maxstringcont...

css - How does one do a simple inner container in Twitter Bootstrap? -

here's image of i'm trying accomplish: http://i.imgur.com/xkpuv.png i want outside container border , inner container gray background. within inner container 2 blocks: text on left, image on right (the elements on either side of no importance - can whatever). pretty basic stuff. with code below, have 2 div's span 6 columns breaking apart (here's looks like: http://i.imgur.com/beivl.png ). what's best way fix issue? <div class="container" style="border: 1px solid gray;height:490px;margin-top:20px;"> <div id="inner-container" style="background:gray;margin:5px;"> <div class="row"> <div class="span6"> <p style="margin:5px;"> lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. ut wisi enim ad minim veniam, quis nostrud exerci tat...

No output for ssh host "awk '{print $0}' /path/to/log.txt" -

i'm trying pull data out of logs on remote machines using awk, , have noticed if ssh machine , run awk '{print $0}' /path/to/log.txt i expected output (containing log messages, stack traces, etc.), if run ssh host "awk '{print $0}' /path/to/log.txt" then output looks following: 0 1 0 0 1 1 1 1 1 1 any ideas why may happening? escape dollar sign. ssh host "awk '{print \$0}' /path/to/log.txt" because single quotes don't protect $0 on local side, gets substituted befor it's sent remote side. you try: ssh host 'awk "{print \$0}" /path/to/log.txt' that protects $0 on remote side, takes more changes command.

assembly - ASM to C - Can someone explain me what structure this is? -

i having following asm code (ollydbg) should contain structure developed in c. can tell me how structure looks in c programming language? maybe little explanation how figured out stored in structure , on... thank much! cpu disasm address hex dump command comments 6a27f058 /$ 68 e9a6286a push 6a28a6e9 ; entry point 6a27f05d |. 64:ff35 00000 push dword ptr fs:[0] 6a27f064 |. 8b4424 10 mov eax,dword ptr ss:[esp+10] 6a27f068 |. 896c24 10 mov dword ptr ss:[esp+10],ebp 6a27f06c |. 8d6c24 10 lea ebp,[esp+10] 6a27f070 |. 2be0 sub esp,eax 6a27f072 |. 53 push ebx 6a27f073 |. 56 push esi 6a27f074 |. 57 push edi 6a27f075 |. a1 e067336a mov eax,dword ptr ds:[6a3367e0] 6a27f07a |. 3145 fc xor dword ptr ss:[ebp-4],eax 6a27f07d |. 33c5 xor eax,ebp 6a27f07f |. 50 push eax 6a27f080 |. 8965 e8 mov dword ptr ss:[ebp-18],esp 6...

Create windows service with current user account using sc.exe -

i trying write batch file creates windows service runs user running batch file. in other word, if i, user_x runs batch file, created service log on me, user_x. since user must logged in run batch file, hoping there way create service without entering user's password. so far i've been using sc.exe create "local system" windows service, , works great. don't understand how same current user. idea? no, cannot create service runs user without knowing user's password, if logged in user in question. because system has save copy of user's password in registry (using reversible encryption) in order configure service run user.

javascript - How to get POST variables in jQuery -

possible duplicate: how get , post variables jquery? i have following html: <form action='.' method='post'>{% csrf_token %} <div class="parameters"> show <select name="earnings_filter"> <option value="all">total earnings</option> <option value="hd">hd earnings</option> <option value="sd">sd earnings</option> </select> <input type="submit" name="submit" class="submit float-right" value="submit" id="submit_financials"/> </div> </form> i need ajax call this, i'm triggering on: $("#submit_financials").live('click', function(){ ... }); is there way variables submitted in post, example option selected (and there 10 other variables need get). or need use jqu...

sql server - storing time and day of week -

challenge : have requirement in have implement recurring events. storing day of week , time , date range event reoccur. possible solution: storing time , day of week string , enumeration. storing current , setting time , day day ? question : best practice on storing time , day of week ? edt: using sql server database this best approach might dependson database using. but, there 2 general approaches, both quite reasonable. the first store dates , times in native format database. databases have functions extract day of week , time date time type. write queries using these functions. typically, store these 1 field, might want separate date , time portions. the second have calendar table. calendar table have date or dateid key, , contain columns want know it. day of week obvious column. a calendar table preferred solution in situations. instance, if going internationalize application, being able day of week table makes easier string english, greek, chines...

java - Using Map of Futures, how do I notify() a single element within? -

i'm attempting hold static list of futures, , @ later time either cancel() or notify() futures in progress. callable class associated these futures has wait() within it, each 1 must notified outside source continue. however, calls notify() appear ignored, callables never past wait statement. class list of futures looks this: private static map <string, future<object>> results = new hashmap <string, future<object>>(); executorservice taskexecutor; public void dostuff() { taskexecutor = executors.newcachedthreadpool(); // loop inifinitely - external processes modify conditions within while(!shutitdown) { if (<condition1>) { // condition 1 dictates kick-off of new callable future<object> future = taskexecutor.submit(new mycallable(id)); results.put(id, future); } else if (<condition2>) { // condition 2 represents callable in wait status needs ...

android - Disabling the notification tray -

a little background first. i'm developing application corporate devices running on android platform. won't distributed on play store , thus, unavailable general public. devices owned company , purpose run application. accessing home screen/notifications/application history/ app drawer unnecessary , in fact want focus user experience directly on application. the current problem i'm facing preventing access notification tray. making application full screen not solution. need see status bar. it's easiest way provide network,gps , battery status information user. so far research has turned 1 solution, go full screen (again, not solution problem,i need status bar visible). know there's number of lock screen apps able there must way. haven't found yet. i not sure, can't lock notification bar application level. android app isolated operating system , apps, not able lock os features. solution came head make app fullscreen , create own status bar b...

python - Sphinx and argparse - autodocumenting command line scripts? -

i'm building python package, , using sphinx create docs. aside package code, include lot of command line python scripts, use argparse. wondering if there way sphinx autodocument these scripts? end goal pretty-printed list of scripts, associated print, arguments , options. , clear, i'm looking pre-existing way this, not way implement myself. this isn't specific of question ask on s.o., if there more appropriate s.e. site post question, please let me know. thanks. you can use sphinxcontrib.programoutput include messages command line in documentation. this not specific argparse can used document script printing messages command line.

java - Sorting String objects -

i'm trying see if there easy way sort list of string objects. problem i'm facing right collections.sort(...) method not working me. this original list, requirement purposes sorted: list<string> values = new arraylist<string>(); values.add("section_1"); values.add("section_2"); values.add("section_3"); values.add("section_4"); values.add("section_5"); values.add("section_6"); values.add("section_7"); values.add("section_8"); values.add("section_9"); values.add("section_10"); values.add("section_11"); values.add("section_12"); values.add("section_13"); and after doing collections.sort(values), order broken: section_1 section_10 section_11 section_12 section_13 section_2 section_3 section_4 section_5 section_6 section_7 section_8 section_9 is behavior because of lexico...

Javascript preformatted text with cross-browser line breaks -

i have preformatted strings line-breaks , multi-spaces , want append them text node. <pre id="bar"></pre> <script> var string = "preformatted" + "\n" // \r, \r\n, \n\r or else? + "multispace string"; var text = document.createtextnode(string); document.getelementbyid('bar').appendchild(text); </script> i tried adopt line breaker: \n breaks lines in browsers, in ie (i'm testing on 7) becomes space \r breaks lines in ie \r\n works in browser in ie space @ beginning of second line horror \n\r ok in all, in ie space @ end of first line inacceptable layout. i can't use <br> , innerhtml because ie collapses multi-spaces. jquery .text(string) has same behavior of .appendchild(createtextnode(string)) how can insert cross-browser line breaks? eventually, how can detect if browser supports \n or \r ? this seemed work in browser...

c# - read hidden file -

is possible read file attribute hidden in program? know path file. for example, if copy file place , set attribute hidden: file.copy("sender.exe", path+"system.exe"); file.setattributes(path + "sender.exe", fileattributes.hidden); can run hidden .exe file code (if know path)? function run(path, lang, city) { var shell = new activexobject("wscript.shell"); shell.run(path + " " + city + " " + lang); } yes; that's possible.

ruby on rails - Using the Command-line Command to launch Sublime Text 2 on OS X -

i started reading michael hartl's book on rails , i've run across problem in setup phase. hartl keeps referring making file in home directory, i'm not quite sure how this. example, when try setup command line sublime text instructions tell me this: assuming you've placed sublime text 2 in applications folder, , have ~/bin directory in path, can run: ln -s "/applications/sublime text 2.app/contents/sharedsupport/bin/subl" ~/bin/subl my problem don't know how put ~/bin directory in path. know real basic appreciation. create or edit ~/.profile (works both bash , zsh) add following export path=$path:$home/bin the line above saying, overwrite path environment variable , set previous path plus ~/bin now when try run command, bash in colon separated paths in path environment variable executable. to see entire path , type echo $path in terminal. or better yet, type env see environment variables.

php - Count number of rows -

hello here code $query['2'] = mysql_query("select distinct site logs") or die(mysql_error()); while ($row = mysql_fetch_assoc($query['2'])) { if (!$row['site'] == null) { echo "<a href='http://".$row["site"]."' target='_blank'>".$row["site"]."</a> <a href='./" . basename($_server[php_self]) . "?site=" . $row["site"] . "'> (view logs)</a> <a href='./" . basename($_server[php_self]) . "?action=exportall&site=" . $row['site'] . "'>(dump file)</a> <a href='./" . basename($_server[php_self]) . "?action=delete&site=" . $row['site'] . "'>(delete)</a> <br>"; } } this gives output of test.com (view logs) (dump file) (delete) i this www.iraceonline.com (view logs) (d...

linq - OrderBy Parent object by Nested Collection -

simple public class timeline { public string name {get;set} public list<milestone> milesstones {get;set} } public class milestone { public string name {get;set} public datetime time {get;set} } i tried: from t in dataaccess.timelinecollection.orderby(c=>c.milesstones.orderby(z=>z.milestonedate)) select t; got error "at least 1 object must implement icomparable." i need order timeline milestone.time. first project in list 1 has eraliest time property in milestone collection. need link. it sounds might want var query = dataaccess.timelinecollection .orderby(t => t.milestones.min(m => m.time)); in other words, each timeline , find earliest milestone, , use ordering. of course if milestones in order, use: var query = dataaccess.timelinecollection .orderby(t => t.milestones.first().time); both of these fail if timeline has no milestones.

xpath - XSLT position before and after -

<parent> ... <child>foo</child> <child current="true">current</child> <child>bar</child> ... </parent> how values of children before , after @current child (i.e. output foo , bar)? i'll outputting prev/next links using values. thanks! child[@current='true']/preceding-sibling::child[1] child[@current='true']/following-sibling::child[1]

python - How can I configure Pyramid's JSON encoding? -

i'm trying return function this: @view_config(route_name='createnewaccount', request_method='get', renderer='json') def returnjson(color, message=none): return json.dumps({ "color" : "color", "message" : "message" }, default=json_util.default) because of pyramid's own json encoding, it's coming out double-encoded this: "{\"color\": \"color\", \"message\": \"message\"}" how can fix this? need use default argument (or equivalent) because it's required mongo's custom types. it seems dictionary being json-encoded twice, equivalent of: json.dumps(json.dumps({ "color" : "color", "message" : "message" })) perhaps python framework automatically json-encodes result? try instead: def returnjson(color, message=none): return { "color" : "color", "message" : ...

python - Getting links to wikipedia images -

i'm trying extract links images in wikipedia, without losing image names , alt tags. got know how link image on wikipedia infobox? that querying: http://en.wikipedia.org/wiki/file:filename.jpg however, need filenames of images. clues? thanks! this gives list of image urls , file names in page http://en.wikipedia.org/w/api.php?action=query&titles=world&generator=images&gimlimit=10&prop=imageinfo&iiprop=url|dimensions|mime&format=json change title= part

ms word - How to convert a webpage (from an intranet wiki) to an Office document? -

i have set of wiki pages (mediawiki style) on company's intranet convert microsoft office word documents (or can import in it). looking has: requirements keep formatting as can does not require change on server hosts wiki (no plugin can added nor configuration files can modified side) the solution can programmatically (as developer too), in flavor of python/c#/c++ , like exclusions does not solution "wiki acrobat pdf pro microsof office word" (as not have acrobat pdf pro). actually, non-pro version (that allows "save microsoft word online" option) not available in company (very old version of adobe suite). however, can still export page pdf, wiki have, not (because element big, a4 format, , parts scraped out of produced pdf. them included anyway , able play "bad" formatting within word eventually as intranet wiki, online solutions out of scope solutions implies copy db of wiki , operation elsewhere (at home example) out of scope ...

php - Jquery .clone() causing $.post to fail -

i copied html using .clone(true, true) because want keep jquery event handlers. when pass php via $.post post fails , gives me following error in firebug uncaught exception: [exception... "could not convert javascript argument" nsresult: "0x80570009 (ns_error_xpc_bad_convert_js)" location: "js frame :: jquery-1.7.2.js :: <top_level> :: line 7740" data: no] i want somehow keep html , jquery event handlers because working on writing script save state user in. update (added code) //save html w/ jquery gsavestate = new object(); gsavestate['html'] = $('#content').clone(true, true); $.post("decopostate.php", { savedstate: gsavestate}, function(data){ alert("test"); } ); the problem code try send dom element - cannot obvious reasons. assuming want send html code of element, use $('#content').html() var gsavestate = { html: $('#content').html(); ...

c# - lambada expression how to express or? -

i want use lambada expression search status equals 1 or 2. code following: return database.find<patient>(p=>(p.id==id && p.status ==1)||(p.id==id && p.status==2)); i know it's not right, understand want above code. i use c# update: sorry guys, realize not reason of syntax, it's reason of third party api use data db. please close question. return database.find<patient>(p=>p.id==id && (p.status ==1 || p.status==2));

windows - How to retrieve start address of a thread using its ID? -

i want start address of thread using it's id. possible? well, not trivial following reason: in win32 subsystem all threads have same start address. in windows (but not including) vista inside kernel32.dll (named basethreadstartthunk according official symbols). in windows versions starting vista, common start address rtluserthreadstart in ntdll.dll (and basethreadstartthunk got renamed basethreadinitthunk , seemingly win32-specific tasks now). however, attempt suspend thread, retrieve context (using getthreadcontext ) , traverse stack top investigate parameters there. require reverse-engineering of each implementation of kernel32.dll thread start routine, should doable. an alternative use undocumented native api ntqueryinformationthread threadquerysetwin32startaddress . there an msdn page function, far complete.

java - Using a Timer to break a loop -

i trying build timeout call/response ping. determine commport use in auto-connect sequence. when send call_signal byte[], expect "fu" in reply. how determine device. sscce below (sorry length, is shortened version) import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import java.util.enumeration; import java.util.timer; import java.util.timertask; import javax.comm.commportidentifier; import javax.comm.commport; import javax.comm.portinuseexception; import javax.comm.serialport; public class pingtest { public static final long ping_timeout = 1000; // in millis public static final byte[] call_signal = {70, 68, 73, 68}; public boolean ping(commportidentifier cpi) { system.out.println("pinging " + cpi.getname()); commport port = null; inputstream input = null; outputstream output = null; //initialization test try { port = cpi.open("pingtest", 50...

SOLR refuses to bring exact matches, How? -

i have following field type (notice no filters, no tokenizers) <fieldtype name="text_names" class="solr.strfield" /> i create field in schema using type: <field name="exact_type" type="text_names" indexed="true" stored="true" /> now, search q=*:*&fq=exact_type:aa&fl=exact_type still results have other 'aa' in exact_type field. missing here? also behaves same: q=exact_type:aa&fl=exact_type i don't think "q=*:*" works dismaxhandler , believe using ,the correct syntax both queries should be: q=&fq=exact_type:aa&fl=exact_type fq=exact_type:aa&fl=exact_type

What tools can provide scheduled backups of Azure blob storage? -

i'm looking best way prevent accidental deletion - perhaps copying disk or separate azure storage account or amazon. tools can this? redgate cloud services seems closest fit want seems require config per container. know of other tools cloud storage studio , azure sync tool exist don't think support scheduled backups of blob storage. windows azure storage backed geo-replication means there total 6 copies of data @ given time. there no built-in service available in windows azure backup data on azure storage outside azure storage or user defined location. windows azure azure manged restful interface 3rd party vendors have created application such purposes. besides above had chance use gladinet cloud backup solution useful in case. based on experience, there few backup tools available , not single 1 perfect match expectation.

java - Transaction with request scope with MyBatis and Spring -

is there way setup mybatis springmvc have 1 transaction whole http request? there hibernate opensessioninviewfilter in mybatis or should write own filter fulfill such behavior? you confused notions "session" , "transaction". osiv opens session, in 1 session several transactions may coexist. should put @transactional attributes services used controllers, depending on business requirements. moreover, 1 big transaction anti-pattern. ideally have read-write transaction user's actions, , read-only transaction build response user. saves resources, because database locks taken inserts/updates released earlier.

javascript - How to construct a complete HTML table using jQuery? -

i wish construct complete table using jquery. i try learn or copycat question create table jquery - append but no luck. what want create is <table> <thead> <tr> <th>problem 5</th> <th>problem 6</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2</td> </tr> </tbody> </table> the jquery code created is var $table = $('<table/>'); var $thead = $('<thead/>'); $thead.append('<tr>' + '<th>problem 5</th>' + '<th>problem 6</th>' + '</tr>'; $table.append(thead); var $tbody = $('<tbody/>'); $tbody.append( '<tr><td>1</td><td>2</td></tr>' ); $table.append(tbody); $('#grouptable').append($table); but failed r...

debugging - C#: Enumerating SessionState keys in QuickWatch window -

while debugging in visual studio 2010, there way view keys of httpsessionstate in quickwatch window? there must better method exiting debugging session, coding loop on session.contents.keys object, breakpointing , stepping through loop - see keys defined. i suspect i'm going in entirely incorrect manner. , hints or advice appreciated. httpsessionstate ienumerable , long system.core dll loaded in process you're debugging, can evaluate system.linq.enumerable.toarray(system.linq.enumerable.cast<object>(myhttpsessionstate)) in quickwatch window. if current code file has using system.linq statement, can write shorter expression: myhttpsessionstate.cast<object>().toarray() if you're having @ httpsessionstate objects often, may want try bugaid , , define above expression custom expression on httpsessionstate class, won't forced type in long expression each , every time. full disclosure: i'm co-creator of bugaid.

php - JSON object is not returned with ajax -

i beginning play around json, , keep running trouble neither google nor have helped me with. have simple php script: <?php $email = $_request['email']; if ( strpos($email,'@') !== false ) { $data = array('status' => 1 , 'msg' => 'sent') ; echo json_encode( $data ) ; } else { $data = array('status' => 0 , 'msg' => 'failed send') ; echo json_encode( $data ) ; } ?> i have following ajax call: $('.submit').click(function() { $('div.load').html('<img src="images/load.gif" alt="loading..." id="loading" />'); //edit //creation of variables send var name = $('#name').val(); email = $('#email').val(); phone = $('#phone').val(); $.ajax({ type: "post", datatype: "jason", data: { name: name, email: ...

apache - Is Apache2 (HTTPD) Location tag a wildcard match? -

good news i've solved problem, bad news don't understand issue! url: http://host:port/a/b httpd.conf <location /a> proxypass server.... </location> <location /b> proxypass other server </location> in setup, request http://.../a/b takes me "some other server" instead of expected "server" i able expected behavior forcing more "regex-y" behavior, , using starts expression (aka: <location ~ "^/a"> proxypass server.... </location> if that's how have it, that's fine. docs seemed rather unclear on situation. documentation sources: httpd docs on location tag http://httpd.apache.org/docs/2.0/mod/core.html#location seem imply location matching in non-regex manner (aka, no ~) not use wildcards (that's why have section explaining how use wildcards , regexs). slash discussion @ end doesn't imply uses wildcards either. so, i'm left assume i've uncovered bug in ver...

how to convert itk image file to vtk with python? -

i'm trying read nrrd file itk , show vtk. have trouble on convert itk vtk. import itk file_name = '/home/yao/workspace/test/1.nrrd' image_type = itk.image[itk.uc, 2] reader = itk.imagefilereader[image_type].new() reader.setfilename( file_name ) reader.update() itk_vtk_converter = itk.imagetovtkimagefilter[image_type].new() itk_vtk_converter.setinput(reader.getoutput()) itk_vtk_converter.update() and got message traceback (most recent call last): file "ex1.py", line 11, in <module> itk_vtk_converter = itk.imagetovtkimagefilter[image_type].new() file "/usr/lib/insighttoolkit/wrapitk/python/itklazy.py", line 14, in __getattribute__ value = types.moduletype.__getattribute__(self, attr) attributeerror: 'lazyitkmodule' object has no attribute 'imagetovtkimagefilter' i'm using itk3.20, python2.7. how can fix it? regards. yao c++ filter itk::imagetovtkimagefilter not wrapped can use itk.vtkimagei...

php - How to friend a test user that does not have app installed? -

using facebook developers site editing roles of test user, able make friends using 2 test users, 1 app installed , 1 without. i have created 2 facebook test users using graph api. if both users have app installed can make friend connections between them using graph api , user's access tokens. if create 1 test user app installed , 1 without app installed user without app installed not have user access token. how can friend these 2 users programmatically without them both having accesses token? for api work, need access token each test user. see http://developers.facebook.com/docs/test_users/ making friend connections you can use api make friends connections test user other test users of app. provide api creating friend request accepting friend request. enables developers create several friend connections between test users via api itself, without having log-in test user accept requests. api https://graph.facebook.com/test_user_1_i...

hadoop - Lifespan of mapper class instance -

a mapper class instance created , used 1 inputsplit (or mapper task)? or multiple mapper class instances can handling 1 inputsplit (or mapper task)? each input split handed mapper, , mapper process single input split. however if have mapper speculative execution turned on, input split can run 2 mappers on different nodes in parallel (there conditions trigger speculative execution, should able google them). also, if map task fails, input split scheduled run on cluster node map task.

css - Trying to change the colour of submenu links -

i have navigation hidden sub menus display when ever parent menu link hovered over. i' bit stuck on how target links list of parent navigation item. here code: <nav id="nav"> <ul> <li><a href="#">home</a></li> <li><a href="#">about</a></li> <li> <a href="#">categories</a> <ul> <li><a href="#">12" vinyl album</a></li> <li><a href="#">12" vinyl single</a></li> <li><a href="#">7" vinyl album</a></li> <li><a href="#">7" vinyl single</a></li> <li><a href="#">cd</a></li> <li><a href="#">dvd</a>...

Automated backup to Google Cloud Storage - Google App Engine Datastore with cron.yaml -

so, trying automate our gae datastore backups using cron.yaml. furthermore, use google cloud storage destination our backups. have created bucket , set acl. manual backups work datastore admin console. can cron work. but, push same codebase 3 different environments: dev, staging, production. so, separate backups in different buckets based on application name. i staging datastore go myapp_staging_bk bucket, dev in myapp_dev_bk bucket, , live myapp_live_bk. cron.yaml: cron: - description: daily backup url: /_ah/datastore_admin/backup.create?name=backuptocloud&kind=logtitle&kind=eventlog&filesystem=gs&gs_bucket_name=whitsend schedule: every 12 hours target: ah-builtin-python-bundle all of super easy if figure out way pull application name in above url. this: url: /_ah/datastore_admin/backup.create?name=backuptocloud&kind=logtitle&kind=eventlog&filesystem=gs&{myapp}_bk=whitsend schedule: every 12 hours where {myapp} name of app th...

mysql - Both “INSERT IGNORE” and “… ON DUPLICATE KEY UPDATE” what happens? -

what mysql both insert ignore , … on duplicate key update ? this not question differences . ask because talend etl behind ui , i'm worried have side effects if don't want update , this: string insertignore_tmysqloutput_10 = "insert ignore `" + "employees" + "` (`name`,`jobtitle`) values (?,?) on duplicate key update `name` = ?"; ignore acts kind of error-suppressor, making fatal errors act warnings instead. on duplicate key update doesn't trigger error, ingore has no effect on it. therefore, ignore has no effect on duplicate keys when on duplicate key update used well. however , if different error occur ignore indeed have effect.

ansi - Representing individual bits in C -

if have 16 bits represent 3 pairs of values, each 5 bits long, , 1 other 1 bit value, in order, safe use bitfield describe this? ansi c guarantee bits in order specify? struct { unsigned v1 : 5; unsigned v2 : 5; unsigned v3 : 5; unsigned v4 : 1; } test; if not, there other data structure can use represent this? or should store 2 8 bit char s , manipulate them programmatically assured of portability? the relevant quote find 6.7.2.1(1), c99: an implementation may allocate addressable storage unit large enough hold bit- field. if enough space remains, bit-field follows bit-field in structure shall packed adjacent bits of same unit. if insufficient space remains, whether bit-field not fit put next unit or overlaps adjacent units implementation-defined. order of allocation of bit-fields within unit (high-order low-order or low-order high-order) implementation-defined. alignment of addressable storage unit unspecified. i think unsigned isn't...