Posts

Showing posts from February, 2011

sql - find out list of inverted hierarchy in mysql -

imagine have table (mysql myisam) child->parent relationship (categories , multiple levels of subcategories) +--------+---------+ | id |parent_id| +--------+---------+ | 1 | null | | 2 | 1 | | 3 | 2 | | 4 | 7 | | 5 | 1 | | 6 | 5 | +--------+---------+ how find children of id, querying id 1 output : 2,5,3,6 ? (order has no importance) so in other words, how reverted children lookup on parent_link ? at moment, cycle in php , query parent_id, again , concatenate results in string while there results, slow... create table my_table( id int, parent_id int ); insert my_table values (1,null), (2,1), (3,2), (4,7), (5,1), (6,5); this stored procedure children of given id delimiter $$ drop procedure if exists get_children$$ create procedure get_children(in v_key int) proc: begin declare vid text; declare oid text; declare count int; create temporary table temp_child_nodes( id int );

ios - set navigation bar back to default -

in app's uiapplicationdelegate customizing background of navigation bar code: [[uinavigationbar appearance] setbackgroundimage:[uiimage imagenamed:myimage] forbarmetrics:uibarmetricsdefault]; everything working fine, when launching example image picker, set navigation bar default, , when user has picked picture, restore custom background. possible? i have tried setting backgroundcolor property nil nothing. instead of changing appearance uinavigationbar (which affect every navigation bar), make subclass of uinavigationbar, use in appearance code. then in navigation controller, set navigation bar class of 1 subclassed.

Java create bat file and escape spaces -

my app creating .bat file in users startup directory able auto run when users logs in. this how creating .bat : file startupfile=getstartupfile(); printwriter out=new printwriter(new filewriter(startupfile)); out.println("@echo off"); out.println("start " + system.getproperty("user.dir") + fileseparator +"myapp.exe"); out.println("exit"); out.close(); } btw: startupfile location startup directory the problem seems system.getproperty("user.dir") contains spaces in path. example second line can be: start c:\program files (x86)\myapp\myapp.exe and breaks .bat file when tries find application run. any ideas how can make .bat understand find application? no matter been installed? quoting file location in every case (with or without space) should work out.println("start \"" + system.getproperty("user.dir") + fileseparator +"myapp.exe\"");

selenium - Two elements with same parent element -

i using selenium ide test tree. i having 2 elements same parent element, 1 check box , other text. my question is, can use text element make selenium click on check box?! in way, can connect 2 elements each others how?!! as me right click on browser webpage want test. , can chose show available command. note when right click on browser need open selenium-ide . hope helpful.

winapi - How to interpret the "code" passed to CallNextHookEx -

i'm wondering values 2nd parameter (code) of callnexthookex function may take, unfortunately msdn documentation quite vague parameter: the hook code passed current hook procedure. next hook procedure uses code determine how process hook information. i assume values code parameter may take defined somwhere among " hook structures " how can interpret values correctly? am allowed manipulate value or expected pass code received it? the value explained in documentation of hook procedure. e.g. getmsgproc : specifies whether hook procedure must process message. if code hc_action , hook procedure must process message. if code less zero, hook procedure must pass message callnexthookex function without further processing , should return value returned callnexthookex. the documentation code parameter similar above (all?) procedures. that means should process calls code equal hc_action . otherwise, should call callnexthookex original p

java - Where am I wrong in this program? -

this program reverse array. now, how create function print reversed array? public class question1 { public static void main( string [] args ) { char[] myname = { 'h', 'a', 's', 'h', 'i', 'm' }; reverse(myname); } public static void reverse(char[] array) { (int = 5; >= 0; i--) { char reversearray = array[i]; } } } you try using charat method: class reversestring { public static void main(string args[]) { string original, reverse = ""; scanner in = new scanner(system.in); system.out.println("enter string reverse"); original = in.nextline(); int length = original.length(); ( int = length - 1 ; >= 0 ; i-- ) reverse = reverse + original.charat(i); system.out.println("reverse of entered string is: "+reverse); } }

shell - How to get the duration of a file in milliseconds -

i trying duration of audio file (.wav) in milliseconds. i have seen command lines using ffmpeg , library deprecated (remplaced avconv ) on ubuntu version, , didn't find on it. i can duration running avconv -i <file> looking result in milliseconds . wrote small stand-alone .sh file: file="$1" info=$(sox $file -n stat 2>&1) full_length=$(echo "$info" | sed -n 's#^length (seconds):[^0-9]*\([0-9.]*\).*$#\1#p') seconds=$(echo $full_length | cut -f1 -d.) if [ -n "$seconds" ]; milliseconds=$(echo $full_length | cut -f2 -d. | cut -c -3) result=$(($seconds * 1000)) result=$(($result + $milliseconds)) echo "$result" exit fi echo "0" exit call like new-file.sh test.wav to result (duration in ms) 1337 (you can find full code sources used on github )

c++ - How to push_back an integer to a string? -

right now, i'm preparing homework assignment first sorting out i'm going in methods. 1 of them, have prepare list of names added list in form a1, b2, c3 ... etc. testing right way add them via loop. please note not doing whole thing yet, i'm ensuring items made in correct form. have following code: list<string> l; //the list hold data in form a1, b2, etc. char c = 'a'; //the char value hold alphabetical letters for(int = 1; <= 5; i++) { string peas; //a string hold values, pushed backed here peas.push_back(c++); //adds alphabetical letter temp string, incrementing on every loop peas.push_back(i); //is supposed add number represents temp string l.push_back(peas); //the temp string added list } the letter chars add , increment value fine (they show b c etc.), problem having when push_back integer value, doesn't push_back integer value, ascii value related integer (that's guess -- returns emoticons). i'm thinking solution

basic haskell: Comparing a set of Ints and a set of set of ints -

is there easy way in can check if 2 lists contain common elements. ie set1 = [1,2,3,4] set2 = [[1,5,7],[1,2,3,8]] would there way potentially isolate elements in set1 not in of sets in set2? best way add x-amount of sets in set2 have 1 big set (using concat) compare set1 or waste of time? much appreciated advice. import data.set set foldl (\x y -> set.difference x (set.fromlist y)) (set.fromlist set1) set2 gives following output: fromlist [4] and give members of set1 not in of sets within set2 - seems question.

What's the difference between ASCII and Unicode? -

can know exact difference between unicode , ascii? ascii has total of 128 characters (256 in extended set). is there size specification unicode characters? ascii defines 128 characters, map numbers 0–127. unicode defines (less than) 2 21 characters, which, similarly, map numbers 0–2 21 (though not numbers assigned, , reserved). unicode superset of ascii, , numbers 0–128 have same meaning in ascii have in unicode. example, number 65 means "latin capital 'a'". because unicode characters don't fit 1 8-bit byte, there numerous ways of storing unicode characters in byte sequences, such utf-32 , utf-8.

java - JSF property not found -

i have little trouble simple jsf page, trying different solutions find here none of them work. me discover, why can't make simple example of jsf work? this pom.xml <project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelversion>4.0.0</modelversion> <groupid>com.mkyong.core</groupid> <artifactid>primefaces</artifactid> <packaging>war</packaging> <version>1.0-snapshot</version> <name>primefaces maven webapp</name> <url>http://maven.apache.org</url> <repositories> <repository> <id>prime-repo</id> <name>primefaces maven repository</name> <url>http://repository.primefaces.o

javascript - How to workaround jQuery UI droppable bug where over/out do not fire if draggable element is dragging before droppable bound -

Image
i have list of draggable objects , droppable target. view housing droppable target gets created , rendered when dragging starts. i've attached images highlighting desired action bottom of post. the issue jquery ui appears have bug. post: droppable items not displaying hoverclass if shown during drag operation seems corroborate belief. i have code enables draggable-ness: this.$el.find('.videosearchresultitem ').draggable({ helper: function() { var helper = $('<span>', { text: videosearchresultitems.selected().length }); return helper; }, appendto: 'body', containment: 'dom', zindex: 1500, cursorat: { right: 20, bottom: 30 }, start: function (event, ui) { var draggedvideoid = $(this).data('videoid'); var draggedvideo = videosearchresultitems.get(draggedvideoid); draggedvideo.set('selected', true); $(ui.

java - What is an ImageObserver? -

when draw image requires image observer. understand far bufferedimage image observer. question is, defines image observer , do? i'm quite confused. first of all, imageobserver interface . according docs : an asynchronous update interface receiving notifications image information image constructed. in other words, it's object-oriented way use images can modified before created. method imageupdate(image img, int infoflags, int x, int y, int width, int height) called time image modified. returns true if wants notified further changes , false otherwise. method can used force size, resolution, colours etc. gives control of errors ( error flag). more info see this . the observer may process important information image - example if we're drawing image on screen , change bigger 1 before rendering complete, there has way inform whatever we're drawing on dimension has changed (allocate more space) , has deal changes. fact imageobserver asynchronous e

stl - What is multi-pass guarantee per C++ ISO standard? -

reading working draft n3337-1, standard programming language c++, 24.2.5 forward iterators, page 806. from draft: two dereferenceable iterators a , b of type x offer multi-pass guarantee if: — a == b implies ++a == ++b and — x pointer type or expression (void)++x(a), *a equivalent expression *a . [ note: requirement a == b implies ++a == ++b (which not true input , output iterators) , removal of restrictions on number of assignments through mutable iterator (which applies output iterators) allows use of multi-pass one-directional algorithms forward iterators. —end note ] could re-interpret in easier terms ? understand forward iterators multi-pass, don't understand how accomplished per c++ standard requirements. the terms states all, i'd think: can pass through sequence multiple times , remember positions within sequence. long sequence doesn't change, starting @ specific position (iterator) you'll traverse on same objects want in same ord

python - Function not producing intended results? -

i having trouble trying figure out why 1 of functions isn't producing results expect. pretty sure has converting equation code can't pinpoint wrong exactly. this given formula: d=radius * arccos(sin(x1)sin(x2)+cos(x1)cos(x2)cos(|y1-y2|)) http://img42.com/yftmc+ here code: part1 = math.cos(abs(y1 - y2)) part2 = math.cos(x1) * math.cos(x2) part3 = math.sin(x1) * math.sin(x2) d = radius * math.acos(part3 + (part2 * part1)) return d you're giving values in degrees instead of radians math.sin , etc. functions expect. try converting values radians math.radians(degvalue) .

polymorphism - JavaScript: Use parent methods from child class? -

i'm trying use method parent class inside child class. in other languages, have use extends , methods parent can used in child, in javascript, seems different. function svg() { this.align = function(value) { if(value === 'left') return 0; } } function graph() { // want align text left console.log('<text x="' + align('left') + '"></text>'); } graph = new graph(); graph.prototype = new svg(); graph.prototype.align.call(); http://jsfiddle.net/cbmqg/9/ i understand code below doesn't 'extend' in other oop languages. take function/class property - can call it's methods directly. furthermore, haven't used javascript prototyping demo. <script> function svg() { this.align = function( align ) { if( align == 'left') return 'left'; else return 0; } } function graph() {

php - Being redirected to login page after being already logged in -

i have login form , i'm logging myself in correct credentials. when logged in did redirect "about" page (used page test functionality). did above following snippet $input = input::all(); $login = auth::attempt([ 'username' => $input['username'], 'password' => $input['password'] ]); if($login){ return redirect::to('about'); } else{ dd('not logged in!'); } this snippet working in route page add ->before('auth'); if i'm not logged in i'm going redirected login page , if i'm logged in continue. code snippet: route::get('about', function(){ $title = 'about'; return view::make('about')->with('title', $title); })->before('auth'); but adding ->before('auth'); , i'm being redirected logging page after logging in correct

javascript - jQuery toggle div: have below content to slide "gently" -

i use script toggle div animation. works charm, except content below div toggle moves jumpy when .click triggered. $('.toggle').click(function() { var $toggled = $(this).attr('href'); $($toggled).siblings('.gallery:visible').hide(); $($toggled).toggle("slide", {direction: 'up'}, 750); return false; }); how can have content below slide "gently" (as content of toggled div does)? in advance! :-) i can't understand call .toggle regards the documentation . order of parameters, values, don't match documentation. i have tried use .slidetoggle() - works perfectly.

php - Updating a row number which has been randomised -

so have random number being generated in php , want know how go updating row number in selected table. code below: $sxiq = mysql_query("select * `starting_eleven` `team_id`=$uid"); $sxir = mysql_fetch_row($sxiq); $first = rand(1,11); $stat_changed = rand(11,31); $up_or_down = rand(1,2); if ($up_or_down == 1) { $player_name = explode(" ", $sxir[$first]); $fn = $player_name[0]; $ln = $player_name[1]; $statq = mysql_query("select * `players` `first_name`=$fn , `last_name`=$ln , `user_id`=".$_session['user_id']); $statr = mysql_fetch_row($statq); $stat = $statr[0]; } i update row $stat_changed database, i'm not sure if possible without doing long if statement, telling code if $stat_changed = 13 $stat = pace or along lines, if way must done i'll have to. thought i'd see if there other simpler ways of doing this. thanks in advance if ($stat_changed == 13) { //insert update statement here }

storyboard - Having a zombie issue on UISearchDisplayController -

i having zombie while using uisearchdisplaycontroller uitableview. the uisearchdisplaycontroller (and rest of view) set via interface builder (storyboard on xcode 5 , using arc , ios 7 only). the searchdisplaycontroller used these 2 methods -(bool)searchdisplaycontroller:(uisearchdisplaycontroller *)controller shouldreloadtableforsearchstring:(nsstring *)searchstring { [self filtercontentforsearchtext:searchstring scope: [[self.searchdisplaycontroller.searchbar scopebuttontitles] objectatindex:[self.searchdisplaycontroller.searchbar selectedscopebuttonindex]]]; return yes; } -(bool)searchdisplaycontroller:(uisearchdisplaycontroller *)controller shouldreloadtableforsearchscope:(nsinteger)searchoption { [self filtercontentforsearchtext:self.searchdisplaycontroller.searchbar.text scope: [[self.searchdisplaycontroller.searchbar scopebuttontitles] objectatindex:searchoption]]; return yes; } instruments giving me information # event type ∆ refct re

python - Return sublists of List of lists -

well, have example: mylist = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]] it list of lists. want keep first 5 points of each sublist. if simple list called mylist[:5] , that's all. now, simpliest method imagine iterate through mylist , copy first 5 points of each sublist new list. newlist = [] in mylist: newlist.append(i[:5]) but happen if list has length 10.000+. know faster way? well, same using list comprehension @ least bit shorter. return [x[:5] x in mylist] or if making function generator instead, yield individual elements: for x in mylist: yield x[:5]

python - BeautifulSoup does not parse content of the tag like first-name that contains '-' -

hi have response below <?xml version="1.0" encoding="utf-8" standalone="yes"?> <person> <first-name>hede</first-name> <last-name>hodo</last-name> <headline>python developer @ hede</headline> <site-standard-profile-request> <url>http://www.linkedin.com/profile/view?id=hede&amp;authtype=godasd*</url> </site-standard-profile-request> </person> and want parse content returned linkedin api. i using beautifulsoup below ipdb> hede = beautifulsoup(response.content) ipdb> hede.person.headline <headline>python developer @ hede</headline> but when do ipdb> hede.person.first-name *** nameerror: name 'name' not defined any ideas ? python attribute names can not contain hypen. instead use hede.person.findchild('first-name') also, parse xml beautifulsoup, use hede = bs.beautifulsoup(content, 'xml') or if have

Python 3 cannot find pygst module -

i'm using ubuntu 13.04 , have python 2.7 , 3.3.2 installed. have started using python 3, when trying import "pygst" gstreamer module, error: importerror: no module named 'pygst' in python 2.x works fine python 2.7.4 (default, apr 19 2013, 18:32:33) [gcc 4.7.3] on linux2 type "help", "copyright", "credits" or "license" more information. >>> import pygst >>> exit() python 3.3.2 (default, oct 6 2013, 01:42:16) [gcc 4.7.3] on linux type "help", "copyright", "credits" or "license" more information. >>> import pygst traceback (most recent call last): file "<stdin>", line 1, in <module> importerror: no module named 'pygst' how can module import in python 3? thank in advance! if have ubuntu 13.04, why don't use gstreamer 1.0 through introspection, can import : from gi.repository import gst

regex - Find location of $ in string -

based on advice here: find location of character in string , tried this: > gregexpr(pattern ='$',"data.frame.name$variable.name") [[1]] [1] 30 attr(,"match.length") [1] 0 attr(,"usebytes") [1] true but didn't work; note: > nchar("data.frame.name$variable.name") [1] 29 how find location of $ in string? the problem $ end-of-string marker in regex. try instead: > gregexpr(pattern ='\\$',"data.frame.name$variable.name") [[1]] [1] 16 attr(,"match.length") [1] 1 attr(,"usebytes") [1] true ... gives right answer - i.e. 16 .

DFS on undirected graph complexity -

let's have undirected graph v nodes , e edges.if represent graph adjacency lists,if have representation of edge between x , y,i must have representation of edge between y , x in adjacency list. i know dfs directed graphs has v+e complexity.for undirected graphs doesn't have v+2*e complexity ,because visit each edge 2 times ?sorry if it's noobish question..i want understand think.thank you, the complexity expressed o(|v| + |e|) , isn't affected factor of 2. but factor of 2 there. 1 undirected edge behaves line 2 directed edges. e.g. algorithm (for connected undirected graph) is visit(v) { mark(v) each unmarked w adjacent v, visit(w) } the loop consider each edge incident each vertex once. since each undirected edge incident 2 vertices, considered twice! note undirected dfs doesn't have worry restarting sources. can pick vertex.

asp.net - Azure site only works when running locally with remote database -

i have site that's running off windows azure , have hooked database via linked resource , looks site should using database. i've included proper connection string in web.config file. when run website locally , use azure database's connection string default connection, works , i've seen updating data local machine reflected in remote database. whenever try access page makes database hits (ie, logging in or looking @ basic index (from scaffolded out views)), 500 error. tried turning on custom errors 500 error get. tried debug local machine didn't @ since worked when running site locally , connecting azure database. i have pulled down web.config files , web.configs on both sides identical. i figure has configuration issue, i'm not sure what. is there maybe i'd have asp.net mvc 5 make work windows azure? looks .net framework set on azure .net 4.5. i'm guessing has fact azure doesn't know should using database supplied in web.config. here

jquery - Showing notification independently of the current view PhoneJS? -

i'm using phonejs make mobile web app. requires login, , i'd show 'toast' message result (error, success, etc) if login successful, shows 'success' toast message, , navigates main view of app. problem is, toast message hidden main view loaded. i'd show full 3 seconds, not stop view loaded. so basically: login successful show toast message ("welcome, john!") while loading main view main view loaded, continue showing toast message until time (3 sec) here's javascript run if there successful login: devexpress.ui.notify("welcome, logged in", "success", 3000 );//i've tried , dxtoast, same result both appnamespace.app.navigate("main", { root: true }); the namespace , view correct, , i've tried both ways show notification. show replaced "main" view. want notification show view loading, , continue show after view loaded (until 3 seconds). the toast message seems part of 'l

javascript - creating new instances of createjs object returns the same instance every time -

i'm have strange problem. have object extends createjs.container so: (function() { var door = function(label, color) { this.initialize(label, color); } var m = door.prototype = new createjs.container(); // inherit container m.container_initialize = m.initialize; m.initialize = function() { console.log(this); } window.door = door; }(window)); whenever try , create new version of object anywhere, console.log output gives me same object everytime. if this: var door1 = new door(); var door2 = new door(); i console output of: door {id: 10, _matrix: c, children: array[0], container_initialize: function, initialize: function…} door {id: 10, _matrix: c, children: array[0], container_initialize: function, initialize: function…} ... both have same id. i'm not sure have wrong here make happen? i missing 1 simple line m.initialize method: this.container_initialize(); solved problem!

Jquery Tokeninput Use search results instead of hint -

i'd tokeninput skip text , search tokens right away. i have pretty short list of tokens, i'd display them user, rather have user try , guess right tokens choose. seem's there's not option looks i'll have hack it? any hints method need override , how? line 195ish there's show_dropdown_hint() , want replace. you'll need replace populate_dropdown(query,results) , show_dropdown() . for populate_dropdown() parameters, should use empty string query - relates section of string bolded in text, , results should json array (?) of tokens. not tested @ all, that's rough guess, hope can figure else out!

javascript - Get custom data attribute of clicked listview item; popup; jqm -

i have dynamically generated listview. each list element assign custom data attribute. when listitem clicked calls popup. <a href="#popupmenu" data-name='.$myrow[id].' data-rel="popup">view</a> //mypopup <ul data-role="listview" data-inset="true" data-theme="b"> <li data-role="divider" data-theme="a">options</li> <li><a id="one" onclick="func1();" href="#">function one</a></li> <li><a id="two" href="#">remove</a></li> <li><a id="three" href="#">cancel</a></li> </ul> i know correct method retrieve custom data attribute of listview item called popup. //myjavascipt var func1 = fu

c++ - How do I stop an IntelliSense PCH Warning? -

a few of header files have no includes, receive message in visual studio 2010: intellisense: pch warning: cannot find suitable header stop location. intellisense pch file not generated. if add single header, instance: #include <iostream> it disappears. how can stop error showing without adding (potentially unused) include> add #pragma once @ start of file. it cause source file included once in single compilation, therefore compiler satisfied , won't require additional #include

c++ - Expected return of find STL algorithm -

list< int > a; list < int > ::iterator it; = a.begin(); it=a.insert(it,10); it=a.insert(it,210); it=a.insert(it,310); it=a.insert(it,410); it=a.insert(it,510); = find(a.begin(),a.end(),180); cout << *it << endl; in program value 180 not present in list. per find stl algorithm should return last value, when print value coming garbage. seems iterator pointing other location. please me spot error. std::find returns end() if element not found in stl container, dereference end() undefined behavior. you need test iterator it before dereference it: it = find(a.begin(), a.end(), 180); if (it != a.end()) { cout << *it << endl; } § 25.2.5 returns: first iterator in range [first,last) following corresponding conditions hold: *i == value, pred(*i) != false, pred(*i) == false. returns last if no such iterator found. range [first,last) half open range, last means end() not last element in container.

Java Generics Copy Constructor -

i'm wanting code copy constructor generically defined class. have inner class node, going use nodes binary tree. when pass in a new object public class treedb <t extends object> { //methods , such public t patient; patient = new t(patient2); //this line throwing error //where patient2 of type <t> } i don't know how generically define copy constructor. t can't guarantee class represents have required constructor can't use new t(..) form. i not sure if need if sure class of object want copy have copy constructor can use reflection like public class test<t> { public t createcopy(t item) throws exception {// here should // thrown more detailed exceptions decided reduce them // readability class<?> clazz = item.getclass(); constructor<?> copyconstructor = clazz.getconstructor(clazz); @suppresswarnings("unchecked") t copy = (t) copycons

Python: give start and end of week data from a given date -

day = "13/oct/2013" print("parsing :",day) day, mon, yr= day.split("/") sday = yr+" "+day+" "+mon myday = time.strptime(sday, '%y %d %b') sstart = yr+" "+time.strftime("%u",myday )+" 0" send = yr+" "+time.strftime("%u",myday )+" 6" startweek = time.strptime(sstart, '%y %u %w') endweek = time.strptime(send, '%y %u %w') print("start of week:",time.strftime("%a, %d %b %y",startweek)) print("end of week:",time.strftime("%a, %d %b %y",endweek)) print("data entered:",time.strftime("%a, %d %b %y",myday)) out: parsing : 13/oct/2013 start of week: sun, 13 oct 2013 end of week: sat, 19 oct 2013 sun, 13 oct 2013 learned python in past 2 days , wondering if there cleaner way this.this method works...it looks ugly , seems silly have create new time variable each date, , there should way offset given d

expression - Regex to get words within a Backslash -

following string: f:\shared\common\1a\gruwr050.pdf how strings preceding 3rd backslash using regex? for example: f:\shared\common use ^(?:[^\\]*\\){2}[^\\]* pattern. here's python example: >>> re.findall(r'^(?:[^\\]*\\){2}[^\\]*', r'f:\shared\common\1a\gruwr050.pdf') ['f:\\shared\\common'] javascript example: 'f:\\shared\\common\\1a\\gruwr050.pdf'.match(/^(?:[^\\]*\\){2}[^\\]*/) // => ["f:\shared\common"]

android - How to calculate X-axis reduction when view is rotated along Y-axis -

how find out x axis reduction when view rotated along y-axis? im trying create folding animation using combination of rotation , translation. i have 2 textviews sitting side-by-side each other shown xml below: <linearlayout android:id="@+id/colorbox" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginbottom="10dp"> <textview android:id="@+id/left" android:layout_width="150dp" android:layout_height="150dp" android:background="@android:color/holo_blue_dark" android:text="a" android:textsize="100sp"/> <textview android:id="@+id/right" android:layout_width="150dp" android:layout_height="150dp" android:background="@android:color/holo_green_d

scala - Abstract fields for dependency injection -

in scala, there there wrong using below method of dependency injection. // define interface trait filestorage { def readfile(filename:string):outputstream } // , implementation class s3filestorage extends filestorage { def readfile(filename:string):outputstream = ??? } // define our service trait abstract fields need // injected in order construct. implementation details go here. trait filehttpserver { val filestorage:filestorage def fetchfile( session:session, filename:string ) = ??? } now wire things up // wire concrete file service use in code // no implementation details should go here, we're wiring filehttpserverl // entire project wired way in central location if desired. object s3filehttpserver extends filehttpserver { val filestorage = new s3filestorage } // anonymously val myhttpserver = new filehttpserver { val filestorage = new s3filestorage } // or create mocked version testing val mockedhttpserver = new filehttpserver { val filesto

java - counting instances of int in a string -

trying count how many integers within string system.out.println("enter numbers, eg 1 2 3: "); = scan.nextline(); b = count(a).length; this not work. there simple method this? try this matcher m = pattern.compile("\\d++").matcher(input); int n = 0; while(m.find()) { n++; }

Simple Function C++ -

using namespace std; int main() { return 0; } double c2f() { f = value * 9 / 5 + 32; return f; } double k2f() { f = (value - 273.15) * 1.8 + 32.0; return f; } double n2f() { f = value * 60 / 11 + 32; return f; } im having trouble calling these functions calculate temperature conversion instead of calculation within cases. program not compile after adding these functions. "error: expected ";"" you cannot declare or define functions inside function. move definitions outside of int main(){ ... } .

javascript - How to detect if an object is at cordinates on canvas element? -

i'm working on creating tic-tac-toe game in canvas. i'm stuck @ point detect if there symbol(x or o) @ x/y cordinates on canvas. i tried using imagedata check if element present returns error if nothing there. thought perhaps assign id square or symbol. doesn't seem possible i've read. any appreciated. you can see game running here http://jsfiddle.net/weeklygame/dvj5x/30/ function ttt() { this.canvas = document.getelementbyid('ttt'); this.context = this.canvas.getcontext('2d'); this.width = this.width; this.height = this.height; this.square = 100; this.boxes = []; this.turn = math.floor(math.random() * 2) + 1; this.message = $('.message'); }; var ttt = new ttt(); ttt.prototype.currentplayer = function() { var symbol = (this.turn === 1) ? 'x' : 'o'; ttt.message.html('it ' + symbol + '\'s turn'); }; // draw board ttt.prototype.draw = function(callback) {

wpf - How to bind my own Style dependency property (DP) to Button's style DP? -

i've found usercontrol implementation of virtual keyboard. there many buttons. want usercontrol expose dp "keysstyleproperty", how bind inner button's style? if set 'layoutroot' datacontext of user control itself, can bind inner buttons style dependency property. more details, see article wrote: http://www.scottlogic.com/blog/2012/02/06/a-simple-pattern-for-creating-re-useable-usercontrols-in-wpf-silverlight.html for example, xaml: <usercontrol x:class="usercontrol.virtualkeyboard" ...> <stackpanel orientation="horizontal" x:name="layoutroot"> <button style="{binding keysstyleproperty}"/> </stackpanel> </usercontrol> and bind layoutroot follows: public virtualkeboard() { initializecomponent(); //this.datacontext = this; layoutroot.datacontext = this; }

java - Programming Algorithmic Thinking Improvement for Competitions -

i new community , have got lot of -1 votes trying best improve way can ask question. recently tried problem @ codechef. problem definition. this easiest task of problem set. understand task let define 2 key functions: f(n,k), (with k <= n) gives number of ways can draw sample of k objects set of n-distinct objects order of drawing not important , not allow repetition. g(x1, x2, x3, ... , xn) largest integer divides of {x1, x2, x3, ... , xn}. given integer n, task compute value of y y = g( f(2*n,1), f(2*n,3), f(2*n,5), ... , f(2*n,2*n-1)). input the first line of input contains integer t denoting number of test cases. description of t test cases follows. first , line of each test case contains single integer denoting given n described in problem statement. output for each test case, output single line containing value of y. constraints 1 ≤ t ≤ 10000 2 ≤ n ≤ 10 11 example input: 3 6 5 4 output: 4 2 8 now

sql - Rename a selected row in MYSQL -

how can rename value? it's giving me last selected value in in() clause. select cf_1573, sum(counter) lyncs ( select cf_1573, count(cf_1573) counter vtiger_purchaseordercf cf_1573 in('lync front end (std)','lync front end (ent)','lync backend', 'lync edge','lync sba','lync dns checks','lync certificate checks') group cf_1573 ) mslync i have output: cf_1573 |lyncs lync certificate checks | 8 the sub-query gave me this: cf_1573 | counter lync certificate checks | 1 lync dns check | 3 lync edge | 1 lync sba | 3 i want output display "data lync" instead of "lync certificate checks" last value in in() clause . help. try below query. select 'data lync' `cf_1573`, sum(counter) lyncs ( select cf_1573, count(cf_1573) counter vtiger_purchaseordercf cf_1573 in('lync front end (std)

android - Detect clicks outside of a View -

i have view declared such: layoutinflater layoutinflater = (layoutinflater) getsystemservice(context.layout_inflater_service); myview = layoutinflater.inflate(r.layout.background, null); i want detect clicks outside of myview, how can this? so background.xml small relativelayout pops when user clicks on button. has edit text gain focus , allow type on it: response.setfocusable(true); params.flags = params.flags & ~windowmanager.layoutparams.flag_not_focusable; mwindowmanager.updateviewlayout(myview, params); now if user clicks outside pop up(background.xml aka myview) want set param.flags flag.not_focusable you can create dummy view , make fill parent , add onclicklistener , want on onclick.

Using livecycle-designer, how can I add radio buttons dynamically? -

i need add radio buttons dynamically. having set of options coming form web service call , need convert options radio buttons , show user. how can it? your question quite vague doesn't explain trying do. going make few assumptions , try answer question based on these assumptions. assumptions: your web service call returning bunch of values need populate in set of radio buttons. lets assume trying set caption property of 2 radio buttons (rb1, rb2) in radio button list(radiobuttonlist) here need do. check total number of values getting web service call. for each value, create instance of radio button in radio button group. populate caption property of radio button display string value. radiobuttonlist.rb1.caption.value.text = "changed caption"; do let me know if have further questions this. thanks, armaghan.

Yii Php: Getting values having a specific key in an associative array -

i have model/database table looks this id | group_id| first_name | middle_name | last_name ------------------------------------------------------ | | | | ------------------------------------------------------ after retrieving model database: say: $people = personmodel::model()->findallbyattributes(array('group_id'=>$groupid)); and suppose i've retrieved 10 rows.. matching groupid given i want store first_name of 10 rows matched. i know can done by: $personarray = array(); foreach($people $person){ $personarray[] = $person->first_name; } but there way, e.g. php function same thing? thank you! $criteria = new cdbcriteria; $criteria->compare('group_id', $groupid); $criteria->limit = 10; $people = personmodel::model()->findall($criteria); $personarray = $list = chtml::listdata($people, 'id','first_name'); the chtml::listdata() returns associative array like:

c - Order of data while casting array to struct -

say have following struct: typedef struct mystruct { unsigned short a; /* 16 bit unsigned integer*/ unsigned short b; /* 16 bit unsigned integer*/ unsigned long c; /* 32 bit unsigned integer*/ }my_struct; and data array (the content demonstration): unsigned short data[] = {0x0011, 0x1100, 0x0001, 0x0fff }; then perform folliwing: my_struct *ms; ms = (my_struct *) data; printf("a is: %x\n",(*ms).a); printf("b is: %x\n",(*ms).b); printf("c is: %x\n",(*ms).c); i expect data read sequentially ms, "left right", in case output be: a is: 11 b is: 1100 c is: 10fff however happens is: a is: 11 b is: 1100 c is: fff0001 why happen? behavior should expect when casting arrays structs way? what behavior should expect when casting arrays structs way? the answer is, depends. welcome wonderful world of endian-ness: http://en.wikipedia.org/wiki/endianness the gist is, assuming data stored in manner in e

android - My Macbook Air doesn't recognize Samsung Galaxy S3 -

Image
i trying use eclipse on macbook air build android apps real devices, i've got samsung galaxy s3 (android 4.1) friend works in telco company. i've enabled usb debugging. when use adb devices i couldn't see android phone. in system report showed qualcomm cdma technologies msm. needless can't test apps on phone. i have tried echo 0x05c6 << ~/.android/adb_usb.ini , restart adb still can't see phone. please shed light on me. hmm, have working on mac book pro. did install appropriate sdk packages (window \ android sdk manager)?

filter - How to customize with css special characters like comma , vertical bar, point and so on? -

Image
for example want have commas ( or whatever other characters this: " /, |, &, $ and on " ) text in different colors. is possible?! you use spans separate commas or ampersand rest of text <p> text <span style="color:pink">/</span> text ....</p> i don't think yet possible using css in php theme text preg_replace add spans around comma, ampersand, slash, etc. http://php.net/manual/en/function.preg-replace.php or str_replace <?php str_replace(',', '<span class="pink">,</span>', $string); ?> for wordpress add suggested code template file, more info templating see: http://codex.wordpress.org/stepping_into_templates

javascript - Using different methods on a button based on its value -

i have series of buttons created database, set active or disabled based on value in database. i trying create script sees value button has , changes other state. my buttons <input type='button' name='activebutton' id='actbutton11' value='active' class='activebutton' /> my script looks this, unable differentiated between active , disabled buttons. i can change buttons value doesn't change value of c if method called again. i want user able call new appropriate method once button has changed state. $(document).ready(function(){ $(".activebutton").click(function(){ var c = $(this).val(); // alert(c) if(c = "active") { var answer = confirm("disable button?") if (answer) { var $inputelement = $(this), $("activebutton").val("disabled"); }

css - Centering jQuery Modal Dialog Popup -

im trying show modal dialog/popup when users visit homepage. i able show dialog, not appear in center of screen. i importing these files, in case issue: <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" /> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <script language="javascript" type="text/javascript"> $(function () { $("#dialog-modal").dialog({ width: 'auto', // position: 'center', center: true, modal: true, autooption: true, resizable: false }); }); </script> <div id="dialog-modal" title="offer" style="text-align:center"><img alt="" src="pack.jpg"/> </div> my fiddle: http://jsfiddle.net/szepb/ thanks

ruby on rails - How to present region in Google query -

i using rails geocoder. far been using directly not via activerecord/mongoid etc. i in google request specify region, e.g. 'au' what need in combination (or instead of) geocoder.search achieve this? try geocoder.search("paris", :region => 'au') , gem uses google default api , parameters google api accepts given here

Android: Show Listview when clicking on EditText -

i don't know if right method know if possible show listview when user clicks on edittext/textview , show afterwards selected item text in edittext. know how declare edittext in layout there example of when clicking on listener show listview? need add listview in xml layout or have add programatically? thank you if app wants have sort of text viewand when click on need show list view can use expandable list view check tutorial http://theopentutorials.com/tutorials/android/listview/android-expandable-list-view-example/

c++ - Parallelized quicksort in C++11 randomly crashes -

i writing quicksort in c++ , works fine, when try make use multiple threads (with c++11 threading) randomly crashes. says "terminate called without active exception" or "pure virtual method called" or crashes without error message. more threads use more crashes. could tell me did wrong? using mingw x64-4.8.1-release-posix-seh-rev5 -ofast optimization flag. template<class t> t partition(t begin, t end, t pivot){ t result_pivot; std::swap(*pivot, *(end - 1)); /* puts pivot end */ pivot = end - 1; t it_right = end - 1; /* starts searching item left bigger pivot */ for(t it_left = begin; it_left < it_right; ++it_left){ if(*pivot <= *it_left){ while(*(--it_right) > *pivot && it_right != it_left) /* empty - searches item smallar pivot right */ ; if(it_right != it_left){ /* if such item found , pointers not meet swap them */ std::swap(*it_right, *it_left

iphone - Adding UILabels Dynamically in a Loop -

i looking function or loop prototype add uilabels view on iphone. reason won't know in advance how many labels need add, need added dynamically. my pseudo code follows. idea each label given string , placed in next screen, hence +self.view.frame.size.width statement. paging etc work perfectly, problem labels appear ending on second screen i.e. label 3 appears on top of label 2. issue appear referencing altlabel, , such once move second position, referencing position , never moving once there. i can use 'count' variable multiple screen width, if that, every time update label text, overwrite previous. int count = 0; int maxnumber = 10; while(count < maxnumber) { //add label uilabel *altlabel; //declare label if (count > 0) { //move label altlabel = [[uilabel alloc] initwithframe:cgrectmake(cgrectgetminx(altlabel.frame)+self.view.frame.size.width,10,300,25)]; altlabel.text = [nsstring stringwithform