Posts

Showing posts from March, 2011

java - Right way to postprocess a file after upload with a JSP -

i have written jsp , class takes file upload , stores locally on server. after saving file, uploaded file processed. required method calls should not called statically file storage. not this: storefile (file); mypostprocessingmanager pm = new mypostprocessingmanager(file); pm.createthumbs(); pm.dofoobarwiththefile(); this coupling tight. the methods should started on kind of "event". after uploading file event fired , informed appropriate classes carry out further processing. the whole fails on fact not know , how need register appropriate listener. in instances done in main class. can not since not have central starting point. i wrong track? maybe 1 of has idea? thanks , greetings, ben

c# - Javascript client & asp.net server user authentification via session -

i have javascript client , asp.net server. using simplemembership provider style authentification, login/register , roles working fine. problem is, once user logs in, have able check future server controller hits , determine whether permit or deny user use controller functions. first thought using sessions, once user logs in have created session store username (or id or whatever), , use later check whether role has sufficient rights. problem occurs when log in function hit, session created , credentials stored, function ends session ends (which means can't check future controller hits). question is, there way makes work way (lets somehow forcing session stay open until logout or timeout), or going wrong? thank in advance, , hope isn't 1 of "stupid" questions!

nservicebus distributor model vs msft sql server -

we setting nservicebus in distributor/worker model , wondering if worth us. in our initial test lab, have 2 clustered distributors , 1 worker (more workers in prod). wondering if effective leverage our high availability sql server storage , rebuild servers handle work instead of having dedicated distributors , workers. of our messages onto bus via simple .net web api service. install service on each box along endpoint dlls , have them talk sql server has more enough horsepower handle load. have load balancer available distribute messages handlers. what of drawbacks in taking approach vs distributor model? what has me concerned line david boike's book on nservicebus (great book btw) read... "using sql server transport can great choice small projects on teams use sql server" the small projects part worried about. no means small project , have pretty high volume of messages flowing through layer refactor more systems message driven. has been down same r

indexing - mysql warning : primary key and index on the same field in MYSQL -

mysql warning : primary key , index on same field in mysql . as in theory books these 2 terms used explain indices, in practice, when try make index on particular field primary key, mysql generates warning, although index created. could explain? a primary key implies index on set of columns make key, therefore second (separate) index is redundant : the primary key table represents column or set of columns use in vital queries. has associated index, fast query performance. so creating explicit index don't gain on contrary saddle database responsibility of having maintain 2 separate indexes.

Spark to subscribe to ActiveMQ or Mosquitto MQTT broker -

i want subscribe spark activemq or mosquitto mqtt broker. how can that? a more recent pull request , code mqtt adapter spark streaming in apache incubator-spark repository here https://github.com/apache/incubator-spark/pull/64

android - Differences between Adoble Flash Builder 4.7 standard and premium -

does know differences between adobe flash builder 4.7 standard , premium features? in particular, need enough of flash builder able start existing flex project, build , package android , ios targets. is available in standard version or need premium 1 mobile packaging? edit: this similar question found, unfortunately doesn't address feature of mobile target packaging check out adobe's flash builder faq has more information editions of flash builder 4.7? adobe flash builder 4.7 standard edition: flash builder 4.7 professional-grade development tool rapidly creating games , applications web , mobile devices using actionscript , open source flex framework. includes support intelligent coding, interactive step-though debugging, , multiplatform publishing workflows. adobe flash builder 4.7 premium edition: edition has great features standard offers plus professional testing tools, including profilers, network monitoring, unit test

ubuntu - How to fix an error with libsn0wcore "Failed to link opensn0w_cli!"? -

i'm brunodm. keep getting error ( http://pastebin.com/naapfyju ) when try compile opensn0w ( https://github.com/winocm/opensn0w ) @winocm in ubuntu, i've reinstalled. think need libraries make works, don't know which. me fix error? in advance, brunodm. you need patch opensn0w source code. go root of source, , download this: http://devbug.me/attachment/4174303333.zip , unzip it. run: patch -p1 < opensn0w3.diff

android - Send Sms With Genymotion -

i'm new android developer , want test app works sms service . want test app genymotion emulator cant find way send message ! there way send , receive sms genymotion emulator ? no, moment, cannot send/receive sms genymotion. still in "todo list" of genymotion dev team (i'm part of it).

windows - Game Programming in C -

i have have basic knowledge of c, , want expand ot. want study 2d game programming in c. possibility? there engine may use? take @ sdl library : simple directmedia layer cross-platform development library designed provide low level access audio, keyboard, mouse, joystick, , graphics hardware via opengl , direct3d. sdl written in c, works natively c++. so can use both c++ , c. likewise, can take @ sfml library (which native c++, has bindings c well): sfml provides simple interface various components of pc, ease development of games , multimedia applications. composed of 5 modules: system, window, graphics, audio , network. personally suggest sfml more, since seems have better support opengl , easier program in.

java - How to consume mouseClick event if mouse clicked outside JWindow? -

right i'm looking solution how restrict/consume mouseclicked event if mouse clicked outside jwindow . example - jwindow has 2 buttons "yes" , "no" (like dialog). , it's parent has various buttons - must inactive during jwindow (dialog) visible. should restrict parents buttons actions each manually - or maybe there better solution? ..some better solution? a modal dialog. when modal dialog visible, access tot parent component blocked. see how use modality in dialogs more details.

php - DOMXPath query returns zero results -

i'm xpath newbie. have tested query xpath firefox plugin returns perfect result. when ran query in php , var_dump(), no results. output similar to: class domnodelist#4 (0) { } php accepts expression valid. far i've removed tbody that's part of browser-generated query. in addition i've tried query ("*") without result. else can try? query below $page = curl_exec($ch); # close php/curl session curl_close($ch); // create new php dom document $dom = new domdocument; // load html curl request document model @$dom->loadhtml($page); $xpath = new domxpath($dom); //$tablerows = $xpath->query("//id('divresults')/x:table/x:tbody/x:tr"); //$tablerows = $xpath->query("id('divresults')/table/tbody/tr"); //$tablerows = $xpath->query('/*'); $tablerows = $xpath->query('*'); var_dump($tablerows); for reason, var_dump() does'nt work. here's code gets job done. $dom = new domdocume

jquery cookie - How can I implement my default html into the json portion of gridster? -

i'm experimenting gridster.js , jquery-cookie store layout , have following implementation working. displays json , i'd have default/display html content. i'm sure solution simple/elegant i'm new json , gridster. believe need edit the, "if ($.cookie("grid-data") == null) { var json =..." i know can change values, sizes, want know how put html content in. hoping steer me in right direction. have far. <section class="demo"> <div id="main" class="gridster"> <ul> <li data-row="1" data-col="1" data-sizex="2" data-sizey="1">my content</li> <li data-row="3" data-col="1" data-sizex="1" data-sizey="1">some text</li> <li data-row="3" data-col="2" data-sizex="2" data-sizey="1">maybe image

Scheme car and cdr recursion -

can explain me how recursion works in following function? specifically, interested in happens when function reaches base case. also, why named let used in code? (i not familiar named lets) (define (unzip list-of-pairs) (if (null? list-of-pairs) (cons '() '()) (let ((unzipped (unzip (cdr list-of-pairs)))) (cons (cons (car (car list-of-pairs)) (car unzipped)) (cons (cdr (car list-of-pairs)) (cdr unzipped)))))) the procedure shown doesn't have special it, you're iterating on list of form: '((1 . 2) (3 . 4) (5 . 6)) the "weird" part output building two lists instead of usual single list. know, when we're building single list output base case this: (if (null? lst) '() ...) but here, given we're simultaneously building 2 lists, base case looks this: (if (null? lst) (cons '() '()) ...) the code in question not using named let , it's plain old garden-variety let , there's nothi

speech recognition - Are MFCC files generated from MATLAB and SPhinx4 different? -

i converted .wav file .mfc file using matlab. found 2 matlab codes same. http://www.ee.columbia.edu/~dpwe/resources/matlab/rastamat/ http://www.mathworks.in/matlabcentral/fileexchange/32849-htk-mfcc-matlab/content/mfcc/example.m both gave different mfccs. 1 of them giving mfc file 20 rows , other 13. guess 13 mfcc coefficients there,so 13 rows stand 13 coefficients? had use mfcc of 2 wave files find how 1 sound occured in other one. result not correct. please help.

ruby - rails server (4.0.0) cannot start - Error: LoadError:8 lib/mysql2.rb:8:in `require': libmysqlclient.so.18 -

i cannot start rails server. error shows: $ rails server /usr/local/lib/ruby/gems/1.9.1/gems/mysql2-0.3.13/lib/mysql2a.rb:8:in `require': libmysqlclient.so.18: cannot open shared object file: no such file or directory - /usr/local/lib/ruby/gems/1.9.1/gems/mysql2-0.3.13/lib/mysql2/mysql2.so (loaderror) /usr/local/lib/ruby/gems/1.9.1/gems/mysql2-0.3.13/lib/mysql2.rb:8:in `<top (required)>' /usr/local/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runtime.rb:72:in `require' /usr/local/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runtime.rb:72:in `block (2 levels) in require' /usr/local/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runtime.rb:70:in `each' /usr/local/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runtime.rb:70:in `block in require' /usr/local/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runtime.rb:59:in `each' /usr/local/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runtime.rb:

shell - Fish equivalent of bash $(command) notation -

i trying out fish shell instead of using bash. 1 type of notation i'm having trouble learning fish-equivalent notation $(command) , similar how described in this sof post . how write using fish? keep in mind use backslash characters around command want evaluate, linked post , other posts discourage because old style of evaluating commands. specifically, bash command want convert fish syntax (for initializing rbenv during startup of shell): eval "$(rbenv init -)" in fish, $ used variables. correct notation equivalent bash $(command) (command) in fish.

c# - GetResponseAsync does not accept cancellationToken -

it seems getresponseasync not accept cancellationtoken in async/await. question how can cancel bellow procedure, provided need collect cookies response: using (httpwebresponse response = (httpwebresponse) await request.getresponseasync()) { cookies.add(response.cookies); } an alternative code achieve above welcome. something should work (untested): public static class extensions { public static async task<httpwebresponse> getresponseasync(this httpwebrequest request, cancellationtoken ct) { using (ct.register(() => request.abort(), usesynchronizationcontext: false)) { var response = await request.getresponseasync(); ct.throwifcancellationrequested(); return (httpwebresponse)response; } } } in theory, if cancellation requested on ct , request.abort invoked, await request.getresponseasync() should throw webexception . imo though, it's idea check cancellation explicitly when

c++ - Accessing wiringPi (GPIO) from java through JNI -

i wanna access pi's gpio through java. yes know there pi4j, need use library called rcswitch-pi (on github), sends 433mhz signals (well believe can more thats need) the thing is, if use library plain c++, can control powerplugs , signals transferred. once use java via jni gpio pin never triggered. plugged in led check no current created. goes way point of script calls functions digitalwrite(this->ntransmitterpin, high); delaymicroseconds( this->npulselength); } but thats it. doesn't "digitalwrite" if not called java. yes performed sudo privileges that's not problem :-/ also, sort of out of curiousity: in code says "delaymicroseconds" , variable "npulselength" set 300. means each amplitude set 300ms before next 1 called. simple as: _ _ | |_| |_ for 1010 or something. anyways 433mhz pulse require each wave 60cm long or in other terms: 2.30947 nanoseconds * speed of light = 69.2361688 centimeters which mea

linux - Java feed cmd arguments from file -

i hava java program depends on argument list work. , want unit test on windows or linux. wanna feed arguments program text file. without changing in program. possible? something like: java myprogram **-arg "test.txt"** or java myprogram **< test.txt** or java myprogram **type text.txt** everything bolded ofcourse made me , doesn't work, think point quite clear. for linux: program="java myprogram "`cat test.txt` exec $program i think, must similar windows

camera - Image Processing - Beaglebone vs Raspberry Pi -

i've been researching while , found tons of helpful resources on subject, figured lay down specifications here can recommendations people experienced in area. seems beaglebone , raspberry pi logitech or microsoft camera best options @ point. my target speed 50 fps (20 ms per image) processing involved. i've looked at, doesn't seem feasible considering webcams don't go past 30 fps. more specifically, need take endpoints of object (like sheet of paper) , calculate midpoint is. nothing incredibly fancy. 1080p isn't requirement, can go lower. python preferable on c , c++ since i've done lot of image processing python. it looks lot of code i'll needing open-source already, need figure out controller/camera combo should using. it's still bit of toss between 2 here views. the bbb use usb web cam , take amount of processing power image. after can manipulate simplecv the rpi has camera board use < 3% of cpu , rest can used processing image

node.js - Database Exposure: Best Practices -

i'm relatively new web programmer , i'm working on first major project. i'm using angular, express (on top of node), , graph database neo4j. right i'm trying determine best (in terms of security , speed optimization) way set how web app interacts database. right feel i'm going blindly- i'm looking guide of best practices, security issues take account, , other relevant advice or pitfalls aware of in setting web app backend. to put bit more concrete terms i'll give idea of how i'm setting routes right now. following routes setup in app.js file. //match database query functions function dataquery(req, res) { var func = database[req.param('query')]; func(req, res); } //match database create functions function datacreate(req, res) { var func = database[req.param('create')]; func(req, res); } //handle data queries app.get('/query/:query', dataquery); //handle adding new content app.post('/create/:c

r - Show customised X-axis ticks in ggplot2 -

Image
i have large data frame (2 columns) in terms of records. have plotted graph in ggplot2. x axis time , y axis values. on specific interval time 50 60, want make ticks increments smaller , clear in graph such (50,51,51,53,...59,60). rest of axis, fine have ticks incremented 10. so,i expect have x-axis values : 10,20,30,40,50,51,52,53,54,55,56,57,58,58,60,70,80,90,..190,200. below code(with mwe) producing following graph. x<-seq(1:200) y<-seq(51,250,by=1) df<-data.frame(x=x,y=y) ggplot(data=df, aes(x,y))+geom_line(size=1.6)+ scale_x_continuous( breaks=c(10,20,30,40,seq(50,60,by=2),seq(70,200,10)) ,minor_breaks=seq(50,60,by=2) )+ theme(axis.text.x=element_text(size=16),axis.text.y=element_text(size=16))+ theme(axis.title.x=element_text(size=16),axis.title.y=element_text(size=16))+ theme(axis.ticks.x = element_line(size = 1))+xlab("time")+ylab("value")+ theme(axis.ticks.length=unit(0.8,"cm")) is there anyway make cle

php - Function returns "Array" instead of actual output -

i have code: function returnarray() { $intdata = array("1", "3"); return $intdata[array_rand($intdata)]; } i'm trying make function similar 1 above. instead of adding integers commas i'm trying implode commas integers. sort of dynamic version of above using json_decode , file_get_contents , foreach loop, array , array_rand & return this code: function something() { foreach (json_decode(file_get_contents('removed'), true) $jsonarr) { $arrdata = array(implode(",", $jsonarr)); $rounddata = $arrdata[array_rand($arrdata)]; return $rounddata; } } i wondering if i'm doing right , if array correct or not. also doesn't return array . when try implode, throws error implode invalid argument it seems you're trying print random room_id json response. the problem lies here: $intdata = array(implode(",", $arrroomsreverse['room_id'])); you can't i

coq error when trying to use Case. Example from Software Foundations book -

i trying learn coq working through online software foundations book: http://www.cis.upenn.edu/~bcpierce/sf/ i'm using interactive command line coq interpreter coqtop . in induction chapter ( http://www.cis.upenn.edu/~bcpierce/sf/induction.html ), following instructions exactly. compile basics.v using coqc basics.v . start coqtop , type exactly: require export basics. theorem andb_true_elim1 : forall b c : bool, andb b c = true -> b = true. proof. intros b c h. destruct b. case "b = true". everything works until last line, @ point following error: toplevel input, characters 5-15: > case "b = true". > ^^^^^^^^^^ error: no interpretation string "b = true". i'm new coq start unpack why isn't working. found online suggesting needed require string. first, however, didn't work either. has worked through book or encountered problem? how code work properly? this case keyword (tactic?) seems dependent on els

php - Problems with echoing array values -

i having trouble echoing values array. using mysql query create array, $online , containing names of online users. here code: <?php $goodbye = time() - 300; $qry="select username members seen >=$goodbye"; $result=mysql_query($qry); if($result) { $online = mysql_fetch_assoc($result); foreach($online $u) { echo $u; echo "<br>"; } } else { die("query failed"); } ?> when viewing on web page, first index of array shown (as in: if user1, user17, , user69 online, user1 appear on list). i'm sure happening because i'm using echo incorrectly, haven't been able figure out yet. tips? thanks. you should loop ( mysql_fetch_assoc ) if($result) { while ($row = mysql_fetch_assoc($result)) { echo $row["username"]; } } also, notice warning .

php - MYSQL Statement with Array Variable -

so have following mysql statement saving array: $sql = "select did did id = '$did_id'"; $result = mysqli_query($link, $sql, mysqli_store_result); while($row = $result->fetch_row()){ $did[] = $row; } that part works great. need take values in $did array , perform lookup using values in it. way works have users assigned did's. find did's user assigned (the $did array) , show them results table based on did values. have no idea how part works, next statement needs do: select * log did_id = "the values in $did array" hope can help. appreciate it. haven't been able find on it. you can use php's join mysql's in make comma separated strings can use implode , join() alias of implode() ; select * log did_id in( ".join(',',$did).") one thing mention here $did should contains ids in manner array("1","2","3"....) so in loop fetch first index ho

java - Algorithm count of independent sets, always down by 1 -

i'm having trouble writing algorithm count number of independent sets in tree. (an independent set 2 nodes have no edge between them.) here java class listnode: 1public class listnode 2{ 3 private object data; 4 private listnode next; 5 6 public listnode(object data, listnode next) 7 { 8 this.data = data; 9 this.next = next; 10 } 11 12 public object getdata() {return data;} 13 public listnode getnext(){return next;} 14 public void setnext(listnode n){next = n;} 15 public void setdata(object d){data = d;} 16 public boolean search(listnode l, object o) 17 { 18 while (l != null){ 19 if (l.getdata().equals(o)) 20 return true; 21 l = l.getnext(); 22 } 23 return false; 24 } 25 public static listnode rev(listnode curr) 26 { 27 listnode rev = null; 28 while (curr != null){ 29 rev = new listnode(curr.getdata(), rev); 30 curr

php - Is there a quick way to populate array from DB with record id? -

(simplification) have table [id][username] when fetch table not get [ 0=>[10,'unam1'], 1=>[20,'unam2'], ... ] but rather use record id array key. there way in php5.4? use pdo. [ 10=>[10,'unam1'], 20=>[20,'unam2'], ... ] or [ 10=>['unam1'], 20=>['unam2'], ... ]

email - Process an incoming mail -

i have email account provided web hosting service (1and1.fr). filter automatically filters incoming emails (24/7) : if (subject=="mysubject1") { send new email sender subject="bonjour", text="lorem ipsum...." } what service / language / tool use in order ? online service? (ps: features provided webmail don't provide such advanced "filters") thanks in advance

r - Backreferences evaluation time in gsub -

i trying generate functions combining n gaussians, , using values retrieved nls run. use gsub replace original coefficients nls ones using backreferences. however, seems [ on datafame evaluates before \\1 . here mwe : nls <- data.frame(estimate = seq(1,3)) row.names(nls) <- c("a","b","c") gsub("(a|b|c)",paste0(" ",nls["\\1","estimate"]," "),"a + b*x + c*x^2") as can see, replacements nas, while call nls dataframe appear valid : gsub("(a|b|c)",paste0(" ","\\1","estimate"," "),"a + b*x + c*x^2") any ideas delay evaluation of [ ? thanks ! edit : sake of clarity, here full function working great (it takes number of peaks, formula of 1 peak, parameters in formula, variable, constant boolean, , nls results arguments, , returns formula use in ggplot 's stat_function() : generate_func <- function(peaknb,peak

Complexity of inefficient divide and conquer algorithm -

an instance of size n divided p≥2 instances each of size n-a a small integer , p constant . computation cost of operation (i.e. dividing instances) unit, c(0)=1. i trying find complexity of design. having trouble putting words equation, here think recursion should like: c(n) = (n-a)*c(n/p) + 1 is correct? i think this: c(n) = (p)*c(n-a) + 1 my rationale said 'p≥2 instances each of size n-a' in question. size reduces c(n-a) , there p subproblems. think p*c(n-a) . got other term right. cost of dividing @ each step c(0) = 1 said.

php - How does get_headers work in the background -

i tryied searching , belive alredy know answer it's crusal i'm not wrong, here go.. when calling get_headers , retrieve whole file though function returns headers or retrieve, expected, headers , nothing else? i'm guessing last if i'm wrong cause serious problems.. noticed there global setting can change send head request instead of default request, witch why i'm asking self whats going on. edit maybe function better alternative? stream_get_meta_data or same thing? you take @ source code, if familiar c. the function defined here . looked on this, , seems header-only request, see line 715: stream_only_get_headers

mysql - Simple creation of table and inserting value to it -

i want create table in mysql has column time value time column must accept 9am 10pm +-----------------------------+ | date | +-----------------------------+ | 9am 10pm | +-----------------------------+ which datatype should use ? if don't want use varcar & if can use time data-type- how represent values there ? i looking create table , insert statement answer above specifications ? i newbie please go easy answers thanks ! as suggested above in comment table structure be: create table yourtable ( fromtime time, totime time ) now insert values below: insert yourtable values(time(str_to_date('09:00 am', '%h:%i %p')),time(str_to_date('10:00 pm', '%h:%i %p')))

javascript - AngularJS : Passing a function to an isolated scope of a directive to be called within its controller? -

i'm trying call function passed controller's scope directive via "&" operation directive's controller. method, however, claimed angular undefined. after reading code on , over, scouring internet, , repeating process, i've decided turn here. here's relevant part of controller. contains method pass directive. angular.module('myapp.controllers', []).controller('postctrl', ['$scope', 'postalservice', function($scope, postalservice) { $scope.posts = []; $scope.getposts = function() { postalservice.getposts(function(err, posts) { if(err); else $scope.posts = posts; }); }; }]); here's directive. unable invoke onpost. angular.module('myapp.directives', []).directive('compose', ['postalservice', function(postalservice) { return { restrict: 'e', transclude: false, replace: true, scope: {

read eval print loop - list of SML/NJ REPL commands -

i'm looking full list of commands ctrl-z work in sml/nj repl. i've searched here, google , sml/nj website can't find anything, not ones know. to clear, i'm not looking sml language reference, repl interface commands. ctrl-z (under windows assume) not sml command. rather colses console instance. means end-of-file. under win can see simple application of behavior using: copy con text.txt this copies characters keyboard (con) text file. many repls use same mechanism/understanding. largely same exists under unix/linux systems ctrl-d. coming here, there might no more repl commands sml/nj.

java - Known issue: "R cannot be resolved to a variable" -

when first started android app development following developer.android.com course, , first error stumbled upon famous "r cannot resolved variable". i've been looking around issue, cleaned projects multiple times, no avail. thinking maybe has version of java, android sdk seems more stable java 1.6. what haven't figured out how resolve issue completely, love use switch on string. edit: wrote answer well. hope unfortunate people out there. what haven't figured out how resolve issue completely, love use switch on string. if developing code android, cannot use "switch on string" or other java 7 language features. android's java language java 6. as generic "r cannot resolved ..." problem, there lots of possible causes. suggest start trawling through possibilities listed here: "r cannot resolved variable"?

javascript - I want to create a countdown from 50 down to 1, but I don't want to count down the same amount of time between each number -

i want create countdown 50 down 1, don't want count down same amount of time between each number.. if 50 seconds, don't want count down number every second. i'm trying create countdown bit of randomness maybe takes 2 secs next number or .5 seconds. i'm trying way down last 10 seconds slow down bit more before counter stops @ number 1. heres html have: <span id="count">50</span> the javascript: sec = 50; interval = setinterval(function () { sec--; document.getelementbyid('count').innerhtml = sec; if (sec == 1) { clearinterval(interval); } }, 1000); jsfiddle: http://jsfiddle.net/avrpg/ how slow down last 10 seconds , how add bit of randomness it? var sec = 50; function execute() { document.getelementbyid("count").innerhtml = sec; } (function loop() { if(sec-- == 0) { return // stop when reach 0 } settimeout(function() { execute(); loop() }, math.round(math.random()

sql - Select returns the same row multiple times -

i have following problem: in db, have 2 tables. value 1 column in first table can appear in 2 different columns in second one. so, configuration follows: table_a: column print_group table _b: columns print_digital , print_offset the value different rows , print_group column of table_a can appear in 1 row of table_b in different column. i have following query: select distinct * table_a inner join b on (table_a. print_digital = table_b.print_group or table_a.print_offset = table_b.print_group) the problem query returns same row table_a 2 times. what doing wrong? right query? thank help if i'm understanding question correctly, need clarify fields come table_a : select distinct a.* table_a inner join b on a.print_digital = b.print_group or a.print_offset = b.print_group edit: given comments, looks need select distinct b.* select distinct b.* table_a inner join b on a.print_digital = b.print_group or a.print_offset =

c++ - recursive tracing output sum of series -

why recursive method not giving me answer of 2.2833? double m(int i) { if (i == 1) return 1; else return (1/i) + m(i -1); } int main() { double value=m(5); cout << value << endl; return 0; } the answer 1? because 1/1 1 , 1/2 = 0 (1/3 = 0 ....) so need 1.0/(double) i then 1.0 / 2.0 = 0.5 #include <iostream> double m(int i) { if (i == 1) return 1; else return (1.0/(double) i) + m(i -1); } int main(int,char**) { double value=m(5); std::cout << value << "\n"; return 0; }

Use of references in c++ -

i trying wrap head around use of references. have understood references need constant , alias variable. while writing code stack, when passed value reference push function. had include "const" keyword. need know why necessary. in short why works class stack { public: void push(const int &x); }; void stack::push(const int &x) { // code push } int main() { stack y; y.push(12); return 0; } but not? class stack { public: void push(int &x); }; void stack::push(int &x) { // code push } int main() { stack y; y.push(12); return 0; } if use int main() { stack y; int x = 12; y.push(x); return 0; } you see works if remove "const". it's because 12 constant, x not constant! in other words: if use void push(const int &x); --- can use const or non-const values! if use void push(int &x); --- can use non-const values! the basic rule is: my function do

python - Simple mod_rewrite example -

i trying write simple mod_rewrite rule, , have no clue why it's not working. i want rewrite http://example.com/to/abc http://example.com/to/index.py?to=abc . currently, rewrite rule is: rewriteengine on rewriterule ^/?to/(.*)$ /to/index.py?to=$1 which, knowledge, should match url similar /to/whatever , or without leading / . can tell me i'm missing here? for starters, haven't mentioned in way, exactly, it's "not working". if had guess, it's looping, , need instead: rewriteengine on rewritecond %{request_uri} !index.py rewriterule ^/?to/(.*)$ /to/index.py?to=$1 [pt] that says "don't rewrite if it's been rewritten. the [pt] on there says "treat target uri, rather file path. however, in order certain, you'll need tell what's happening, , in way differs want happening. error log entries helpful. rewrite log entries more helpful.

bit manipulation - Shifting bits java -

to insert value, start using mask clear out 8-bits of pixel corresponding given color channel. example, in case of red, shift 8-bit mask of ones left 16 bits, invert (using ~ operator), , “and” (&) mask rgb value, clears out 8 bits of red , leaves other bits unchanged. next, shift parameter value (red, in case) left same number of bits (16, in case of red) , “or” (|) shifted value pixel value. int getred(){ red = (pixel>>16); red = ~pixel; red = pixel<<16 | pixel; return red; } what doing wrong according directions? the problem here seems fundamental problem in understanding how assignment works (in java ... , every imperative programming language!). example: red = (pixel>>16); red = ~pixel; that says: assign red value of pixel shifted 16 bits assign red value of pixel negated bitwise. clobbers value of red calculated in previous step. if want negate value calculated in step 1, need this: red = ~red;

Exclamation mark in Rails model method not found when object is passed in -

using rails 3.2. have following mailer action: # shop.rb class shop < activerecord::base def deliver_update_notification!(user) version = self.versions(user).last editormailer.updated_spot(self, version).deliver end end # shops_controller.rb class shopscontroller < applicationcontroller def update @shop = shop.find(params[:id]) if @shop.update_attributes(params[:shop]) @shop.deliver_update_notification!(current_user) redirect_to shop_path(@shop) else render 'edit' end end end somehow when pass in current_user object method deliver_update_notification! , throws error saying method cannot found. if changed method not accept object, method works. why behaving way? also, don't remember why have exclamation mark in method. saw somewhere. what's purpose of exclamation mark? thanks. exclamation marks supposed indicate method "dangerous" , edits value of object calls it. not sure how defin

Using txt file input in a different class in java -

i having issue getting file input 1 class , using in another. happens have file called readfile.java reads in line of txt file. have file using evaluate stack want use file input. in all, trying find way replace testinput string in evalstack.java file file input readfile.java. here readfile.java: import java.util.scanner; import java.io.*; public class readfile { string fname; public readfile() { system.out.println("constructor"); getfilename(); readfilecontents(); } public void readfilecontents() { boolean looping; datainputstream in; string line; int j, len; char ch; /* read input file , process. */ try { in = new datainputstream(new fileinputstream(fname)); looping = true; while(looping) { /* line of input file. */ if (null == (line = in.readline())) { looping = false;

Ember.js 1.0.0: Computed Property in Parent Controller Based on Child ItemController Property Not Updating -

i have alertscontroller has multiple alertcontroller children underneath it. when user clicks on alert set isselected flag true in alertcontroller alertview . have computed property in alertscontroller should return number of selected alerts. the alertscontroller , alertcontroller this: app.alertscontroller = ember.arraycontroller.extend({ itemcontroller: 'alert', //numselected doesn't update when isselected flag in alert changes numselected: function(){ return this.filterproperty('isselected', true).get('length'); }.property('@each.isselected') }); app.alertcontroller = ember.objectcontroller.extend({ isselected : false, }); i know isselected property in alertcontroller updating value numselected in alertscontroller computed once when page loads. i recreated issue in following fiddle: jsfiddle: http://jsfiddle.net/wlanf/8/ does know doing wrong here? thank assistance! you shou

Scan code of Keyboard in c# -

i'm doing project in c#. want catch data of scan code of keyboard. have used mapvirtualkey() function. function, keyboard have translated scan code ascii code, use function translate ascii scan code. want know how catch scan code of keyboard, before translate ascii code, mean when press key, make code. when release, break code. example, press key 'a' "1e" , release "9e" (makecode , breakcode of scan code set 1). all. here microsoft's information on raw input . here article on how using raw input c# handle multiple keyboards . (has code samples) this os level (winapi) function. seems need registering raw input , can perform standard/buffered read of raw input .

Python High Low Game Reversed Optimized -

def highlowr(): play_again = 1 while play_again==1: ct = 0 guess = 50 x = 0 ans = "" print "lets play game. \nthink of number between 1 , 100.\n" while ans!="c": temp0 = 0 temp1 = 0 print "i guess %d" %guess ans = raw_input("am (h)igh, (l)ow, or (c)orrect? \n") if ans=="h": temp0 = guess/2 temp1 = guess%2 guess = temp0 + temp1 elif ans=="l": temp0 = guess/2 temp1 = guess%2 guess = guess + temp0 + temp1 elif ans=="c": print "i got it! took me %d guesses." %ct else: print "i didn't quite understand meant there." ct = ct+1 play_again = input("would play again? yes = 1, no = 0: "

spring aop - java - @Aspect value attribute - Prototype scoped aspect bean -

i trying create aspect using spring aop , aspectj. @aspect(value = "perthis(execution(* x.y.z.command.command.execute()))") public class commandadvice { // advices.... } the javadoc 'value attibute says:- per clause expression, defaults singleton aspect. valid values "" (singleton), "perthis(...)", etc everything works file without specifying 'value' attribute in @aspect annotation. using above perthis setting resulted in following exception:- caused by: java.lang.illegalargumentexception: bean name 'commandaspect' singleton, aspect instantiation model not singleton. so tried changing scope of advice bean prototype:- <bean id="commandaspect" class="x.y.z.command.commandadvice" **scope="prototype"** factory-method="aspectof" /> this resulted in :- caused by: java.lang.illegalargumentexception: can not set x.y.z.command.command field x.y.z.test.commandtest.com

python - Flask Heroku Staging and Production builds -

i new python, , wondering if there way can manage profiles staging or production ? best way other changing code every time ? there no "best" way pretty in programming (since "best" subjective idea, , every programmer , project different), since you've thrown on heroku tag, assume need way works on heroku. therefore, give the advice heroku gives you : a given codebase may have numerous deployments: production site, staging site, , number of local environments maintained each developer. open source app may have hundreds or thousands of deployments. although running same code, each of these deploys have environment-specific configurations. 1 example credentials external service, such amazon s3. developers may share 1 s3 account, while staging site , production sites each have own keys. the traditional approach handling such config vars put them under source - in properties file of sort. error-prone process, , complica

php - MySql PDO beginning a transaction and passing it to objects -

will work? i'd test don't know how crash things half way though. $db = db::getdb(); try{ $db->begintransaction(); invoice::saveinvoice($info, $db); invoicedetails::savedetails($moreinfo, $db); $db->commit(); }catch(exception $e){ $db->rollback(); } and if work there bite me in butt besides doing causes implicit commit? the thing i'd fix exception handling. example catch (exception $e) { $db->rollback(); throw $e; } doing lets safely rollback transaction letting error bubble further in application. you wrap inner exception (which pdoexception ) 1 of choosing, eg $db->rollback(); throw new runtimeexception('error saving invoice details', 0, $e); to "crash things half way though" , throw exception within 1 of save* methods, eg throw new exception('ka-blam!');

asp.net - GridView in multiple pages -

how can show grid data in 2 or more pages? say, on page load have grid, below have range of numbers hyperlinks(1,2,...). when click 2 should open data of gridview in second page. how do this? reference link <a href ='<%#"updategridviewvalues.aspx?userid="+databinder.eval(container.dataitem,"userid") %>'> <%#eval("username") %> </a> hope helps you

java - JSP Compilation Issue -

Image
i working on java web application worked upon else earlier , person provided me source code of application. problem if try make changes application , deploy on tomcat (7.0.35) jsps not render , following error: additionally, notice class file welcome.jsp not created. the way can app working re-installing new version of tomcat , building, deploying , accessing original source code. when build , deploy code, , access jsps compile , .class , .java files created in tomcat work directory. after copy paste changes original source code , redeploy modified app , works fine because class , java files corresponding jsp pages created after deploying , accessing original application. also, if try modify jsps, same error starts appearing. i have no clue going wrong here.it great if 1 can please me this. jdk version using 1.6.0_38-b05. tomcat points same jdk version , not have other version of jdk or jre installed on computer. here code: <!doctype html> <%@page i