Posts

Showing posts from September, 2010

concurrency - Example of execution which is sequentially consistent but not quiescently consistent -

in context of correctness of concurrent programs, sequential consistency stronger condition quiescent consistency according art of multiprocessor programming maurice herlihy , nir shavit(chapter 3) authors mention in 3.4.1 there sequentially consistent executions not quiescently consistent. don't understand how. throw light or provide sample execution ? consider queue (fifo) enqueue , dequeue elements. from this dissertation concurrency, read (p.20): an example of scenario allowed in sequential consistency model , disallowed in quiescent consistency model shown in figure 2.1. 2 processes share concurrent queue data structure. first process enqueues x. @ non-overlapping subsequent interval, second process enqueues y. second process performs dequeue , receives y. example sequentially consistent not quiescently consistent, assuming time between enqueue operations falls outside quiescence interval. figure 2.1: t1: --- enq(x) ----------------

java - Get information outside a loop -

i've problem. want fill array objects containing different informations. here loop public filerecord [] calcpos() throws ioexception{ (int = 0; < getefsfatmaxrecords(); i++){ int blocknumber = i/5; int recordoffset = i%5; pos = (recordoffset*100+(getfsatpos() + 512 + 512*blocknumber)); filerecord rec = new filerecord(pos,getheader()); array = new filerecord[header.getmaxfilerecords()]; array[i] = rec; system.out.println("filename: " + array[i].getfilename()); } return array; } it should make different objects of filerecord. position depends on running variable i. t loop stores in array , returns array. ive declared array global variable in calss thought changes inside loop directly affect global array. doesnt work. i'm doing wrong? you re initializing array in every iteration. below correct version of code want: public filerecord [] calcpos() throws ioexce

php - send mail using if else -

i have form takes state drop down menu , opens pdf based on state value. want send different email based on value using php. want give them choice of 50+ states since have concerned 3 out of 50 states can hard code email ie. myaaemail@mydomain.com, mybbemail@mydomain.com, , mycc@mydomain.com. want put state name or value on email not priority. here if else statements how add email? sure don’t have mention new php. } if ($_post['recipient'] == 'aa') { header("location: aa.pdf"); } else if ($_post['recipient'] == 'bb') { header("location: bb.pdf"); }else if ($_post['recipient'] == 'cc') { header("location: cc.pdf"); }else { echo "error processing form"; } ?> you may define associative array e-mails: $emails = array( 'aa' => 'email1@mydomain.com', 'bb' => 'email2@mydomain.com', 'cc' =&g

r - Creating a multiple data frames in FOR-LOOP -

this question has answer here: how name variables on fly? 5 answers i create data frames for-loop in r. basically, this: for (i in 1:3) { x"i"= 1+i} in case, 3 dataframes: x1 contain 2 x2 contain 3 x3 contain 4 is there way in r ? for (i in 1:3) { assign(paste0("x", i), + 1) } this create objects x1 , x2 , , x3 values of i + 1 , i.e., 2-4.

Stop Android AVD showing location change toast -

Image
whenever change location on avd, whether it's via telnet or in ddms system toast message saying 'my current location .....' it's annoying it's covering app showing these details. i can't find way of removing , searching didn't show up. ideas? checked on avds android 4.4 , can safely toast not part of android system, , can assume toast being shown tool or application installed on avd. my suggestion track logcat whenever send mock location , see events being recorded log when toast being displayed. if such event recorded, track source package , remove package running adb uninstall <package_name> . if fails, try creating new avd , send mock location before making changes machine, incrementally install whatever tools , applications need identify culprit.

css - A button is bottom and a another button is top, why? -

i have problem 2 buttons css. want align 2 buttons next each other. css not wanted it. because button bottom , button top. see image: http://home.arcor.de/freedownload/buttonwrong.jpg maybe have solution me? appreciated. here html code: <head> <link href="formular.css" type="text/css" rel="stylesheet"> </head> <span id="form1"><input type="text" id="form_username" name="username"></span><span id="form2"><input type="image" src="loginbutton.png"></span> and here css code: #form_username { background: white url(username.png) left no-repeat; background-position: 8px; color: #adadad; padding: 8px; padding-left: 32px; font-family: verdana; font-size: 12px; width: 200px; border: 1px solid #e4e4e4; outline: 3px solid #efefef; } try adding style #form_username float: left; de

passwords - Change PASSWORD_BCRYPT_DEFAULT_COST PHP constant -

i've upgraded php running on our box php5.5 , looking leveraging new password hashing framework. through benchmarking i've decided use cost of 11 instead of default 10. there anyway change constant without recompiling? want take away chance of programming error if forget define cost when call functions. to clear, still want constant, different value. many thanks!

r - How to use the output of of paste function in rbind.fill? -

i have list of dataframe trying rbind.fill don't have same number of columns. dataframes names x1,x2,...x10. my code : x.list<-list(c(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10)) library(plyr) rbind.fill(x.list) this code works, trying avoid writing dataframe using paste0 , i.e. x.list1<-as.list(paste0(x,1:10)) x.list1 interprets x1, x2,... characters rather dataframe: str(x.list1) list of 10 $ : chr "x1" $ : chr "x2" $ : chr "x3" $ : chr "x4" $ : chr "x5" $ : chr "x6" $ : chr "x7" $ : chr "x8" $ : chr "x9" $ : chr "x10" so, can't use rbind.fill since expects list of dataframes. have tried using mget suggested here rbind.fill(mget(x.list1)) but, got error, error in mget(x.list1) : argument "envir" missing, no default setting environment (as mentioned in comment of answer earlier question) doesn't either: rbind.fill(mget(x.lis

php - Map value to color scale -

i have list of values should plotted map color. plotting map done, need figure out way map value n color represents value. an example , solution far normalize values based on min , max , assign them hex color 0 lowest , 255 highest. of course limits self grey scale. here code: $color = ($value / $max) * 255 // (min zero) but how if values should go blue red instance? there common libraries or tools can solve this? far haven't been able locate any. there might libs that. let's short warm general principles. in general have following options: a predefined color index, e.g. $coloridx=array(0=>'#ffffff',1=>'#ffee00',...); any algorithm, e.g. linear gradient, iterations based adaption of 3 rgb channels (r = red, g = green, b = blue). a combination of both, puts result of complex algorithm color index , goes there. if include algorithms in considerations must understand there no true or false . depends on implement. there mig

virtualbox - Oracle Virtual Box import VMWare Windows 2008 Crash on boot -

i given vmware image running windows server 2008 imported on pc fine , works. i want run on macbook pro , have use oracle virtual box seems there no vmware player osx. according internet, strategy opening vmware machine in oracle virtual box create new machine , attach existing hard drive. on mac tried , situation "windows error recovery" unable recover from. on pc same problems oracle virtual box same image on mac. on pc (as stated) can run vm in vmware if have attempted open vm in oracle virtual box, image corrupted , can't opened on pc vmware. my question if has knowledge of settings need changed in oracle virtual box before opening vm , destroying image it. many thanks kevin i worked around issue attaching windows server 2008 disk image additional storage vm working (e.g. ie8 win7 vm downloaded microsoft ). can set hard disk master or slave, or switch when booting main vm.

scala - How to run play2 web application from Eclipse ( ScalaIDE plugin ) -

i using eclipse juno scala plugin. of work play2 web application have first fire terminal , execute play debug ~run ( or play run if don't want debug ), , can work in eclipse , after each save play job of deploying code again jetty. can somehow skip terminal step? want run web app eclipse. j2ee web application, eclipse have nice server integration. can deploy , run application eclipse tomcat ( or other server ) easily. there similar play2? to knowledge, there no way skip step. have spent time looking on last few weeks no luck. co-worker, has been working play several months, isn't aware of tools either.

mysql - Deleting a row in a database using php -

i want delete row in database have added when try click delete button in index.php says record deleted when click ok, not delete record, here codes: index.php : $con = mysql_connect("localhost","pma"); if (!$con) { die('could not connect: ' . mysql_error()); } mysql_select_db("class_schedule", $con); $result = mysql_query("select * schedule"); ?> <center> <table border="1" width="800"> <tr> <td colspan='8'><input type="text" width='300'/> <input type="button" value="search" onclick="location='search.php'" /> <input type="button" value="view all" onclick="window.location.href=''"/> <input type="button" value="add" onclick="location='add.php'"/></td> </tr></table> <?php echo "<center>

sql - Finding duplicate values in a table with a twist -

Image
i have data file has many duplicate values. want both original , duplicate values identified , original , duplicate values ordered side side. my data files headings along data: i want data this: i have found duplicate values using following query: select a.[wallet] kycnew2 [dbo].[kycnew1] group a.[wallet] having count(*) > 1 it has shown duplicate values. not have idea how make original , duplicate values , both of associated data side side. 1 me please? a combination of row_number() , pivot this. you'll need know maximum number of duplicates before hand see everything. select account, [1] path1, [2] path2 ( select account, path, row_number() on (partition account order path) r dups ) x pivot ( min(path) r in ([1], [2]) ) piv example fiddle

ruby on rails - paperclip imagemagick convert to grayscale and crop to fit 144x144# -

Image
client.rb has_attached_file :avatar, :path => ":rails_root/public/system/:attachment/:id/:style/:filename", :url => "/system/:attachment/:id/:style/:filename", :styles => {:thumb => "144x144#", :grayscale => { :processors => [:grayscale] }} the thumb version version works great, image cropped required size, grayscale converts image grayscale, image not being cropped, here grayscale generator found on stackoverflow: lib/grayscale.rb module paperclip # handles grayscale conversion of images uploaded. class grayscale < processor def initialize file, options = {}, attachment = nil super @format = file.extname(@file.path) @basename = file.basename(@file.path, @format) end def make src = @file dst = tempfile.new([@basename, @format]) dst.binmode begin parameters = [] parameters << ":source" parameters << &quo

swing - Java 2D NullPointerException -

recently i've started coding java 2d. i made this: public void paintcomponent(graphics comp) { graphics2d comp2d = (graphics2d) comp; font fontx = new font("verdana", font.bold, 5); comp2d.setfont(fontx); comp2d.drawstring("hello world!", 5, 50); } i did import jframe , java.awt.*, there's still problem. when run it, this: exception in thread "main" java.lang.nullpointerexception @ game.game.paintcomponent(game.java:41) - comp2d.setfont(fontx); - sets font @ game.game.next(game.java:36) - paintcomponent(null); - calls paintcomponent public void next() public void @ game.game.main(game.java:26) - next.next(); - calls public void called "next" using object called "next" (this public void throws interruptedexception) java result: 1 how can solve it? you state: exception in thread "main" java.lang.nullpointerexception @ game.game.paintcomp

Ebay API: List the items bought -

i need list items bought using ebay api, can't seem find method purpose. the language doesn't matter. thanks. look here , getorders call. info: getorders recommended call use order (sales) management. use call retrieve orders in authenticated caller either buyer or seller. order types can retrieved call discussed below:

Are there known issues with PNG and JPEG images generated on iOS? -

i got brilliant idea generate app store screen shots app from... , app! works great, except fact of png or jpeg images not recognized valid screen shots when try upload them. checked image viewer, , have required size, colorspace , pixel density. is there perhaps strange issues png and/or jpeg images generated on ios?

PHP Upload multiple images and check their file extensions prior -

i have following code upload file folder, depending on file input upload file renamed e.g. first input - picture renamed picture01.jpg, 5th input - picture renamed picture picture01.jpg, etc... <form action="upload_file.php" enctype="multipart/form-data" method="post"> <p><input name="image01" type="file"> </p> <p><input name="image02" type="file"> </p> <p><input name="image03" type="file"> </p> <p><input name="image04" type="file"> </p> <p><input name="image05" type="file"> </p> <input type="submit" value="upload file"> </form> this upload_file.php - <?php $pic_names = array ( '01' => 'picture01', '02' => 'picture02', '03' => 'pi

c# - code indentation in Doxygen using Xml comment -

Image
i trying way indent example code in doxygen not find c# , xml comments. since every attempt little long on setting , , have not found proper documentation on issue, though of asking here. the idea create indentation c# xml comment. far have: /// <code>public void method()<br> /// {<br> /// <blockquote>float x = 10, y = 10 , z = 0;<br> /// vector3 vector = new vector3 (x, y, z);<br> /// if(something)<br> /// <blockquote>other code</blockquote></br></blockquote> /// }</code> but draws blue line on left side: does have simple , looking way? thanks how this? /// \code /// public void method() /// { /// float x = 10, y = 10 , z = 0; /// vector3 vector = new vector3 (x, y, z); /// if(something) /// other code /// } /// \endcode much easier read source comments :)

python - "Invalid Index to Scalar Variable" - When Using Scikit Learn "accuracy_score" -

not sure wrong exactly. however, goal establish cross-validtion python code. know there various metrics, think using correct one. instead of getting desired cv10 result receiving error: "invalid index scalar variable" i found on stackoverflow: indexerror: invalid index scalar variable happens when try index numpy scalar such numpy.int64 or numpy.float64. similar typeerror: 'int' object has no attribute '_ getitem _' when try index int. any appreciated... i trying follow :: http://scikit-learn.org/stable/modules/model_evaluation.html from sklearn.ensemble import randomforestclassifier sklearn import cross_validation numpy import genfromtxt import numpy np sklearn.metrics import accuracy_score def main(): #read in data, parse training , target sets dataset = genfromtxt(open('d:\\ca_dataprediction_traindata\\ca_dataprediction_traindatagenetic.csv','r'), delimiter=',', dtype='f8')[1:] target = np.array

Background image doesn't display on some Androids but does in others -

i still new coding , having issue footer background image on site: http://www.midlandspolechampionships.co.uk i have found works fine on iphones , androids.. example it's ok on samsung s3 mini. have samsung s3 , doesn't show on except when click link , background shows around link ( http://www.midlandspolechampionships.co.uk/img/screenshot.png ). this same galaxy note. don't know other phones don't know fix it. if consistent problem across devices more figure out seems bit strange... header background image , css same in footer don't it! i coded while ago had make live 2 days ago started working on again not familiar code when wrote it. any appreciated. thank :) your page doesn't validate http://validator.w3.org/ on chromebook i think line may main issue. <meta http-equiv="x-ua-compatible" content="ie=edge,chrome=1"> x-ua-compatible ie-specific header can used tell modern ie versions use specific ie engine

c# - How to remove special character while fetching data -

below query fetch data ,my problem ,i storing address field address1%address2%address3 now while fetching want fetch adress1 (newline) adress2 (newline)adress3 how can ? for e.g. dange%abc%pune as dange abc pune oledbdataadapter da = new oledbdataadapter(@"select firstname,lastname,address doctor_master type_of_dr='" + typeofdr + "'", con)) it's pity microsoft.jet.oledb.4.0 provider doesn't support replace() function microsoft.ace.oledb.12.0 provider does, otherwise easier you. i think have fetch address field , use helper function convert string format want, this: public string getbrokenlines(string address){ return address.replace("%","\r\n"); } //instead of using address directly, need pass getbrokenlines //method , expected result. for filling datatable using adapter, try this: public static datatable getrefdrlist(string typeofdr, bool display){ datatable refdrlisttable = new data

javascript - Difference in calling method on object or passing object as function argument -

what difference in calling method on object or passing object function argument, , accordingly how pass argument in method call? putting placeholder argument didn't produced desired effect. have iterate trough property names(not values) , compare given argument (as property name) real property name in object? here heavily commented piece of code, because i'm curious happening. // create object constructor function foo(prop1, prop2) { this.prop1 = prop1; this.prop2 = prop2; // create object method printobjectpropertym // , retreive property value // * there m @ end of property distinguish // method/function name // how can add placeholder/argument in method , // call method on object provided argument (here prop1 or prop2) this.printobjectpropertym = function() { console.log(this.prop1); }; } // instantiate new object bar of foo type var bar = new foo("prop1val", "prop2val"); // create function pri

android - AudioRecorder can't be initialized after trying every variation -

i've read many posts problems of initialization of audiorecorder used function test every possibility. unfortunately, there no working one. should check? @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); log.w("debug", "audio record"); // capture mono data @ 16khz int frequency = 44100; int channelconfiguration = audioformat.channel_in_mono; int audioencoding = audioformat.encoding_pcm_16bit; audiorecord audiorecord=null; // minimal buffer size cannot merely 20ms of data, must // @ least 1024 bytes in case, due mmio // hardware limit. final int buffersize = audiorecord.getminbuffersize(frequency, channelconfiguration, audioencoding); log.w("debug", "buffer size: "+buffersize); try { // audiorecord = new audiorecord(mediarecorder.audiosource.mic, // frequency, channelconfigurati

respond with - Rails: respond_with not working properly during create action -

here create method in controller (old way): def create @athlete = athlete.find(params[:video][:athlete_id]) @video = video.new(params[:video]) if @athlete.can_add_another_video? && @video.save flash[:notice] = "successfully created" pandaworker.perform_async(@video.id) log_activity(@video.logging_information) else flash[:notice] = @video.errors.full_messages.to_sentence end respond_with @video, location: athlete_profile_showcase_path end new way: def create @athlete = athlete.find(params[:video][:athlete_id]) @video = video.new(params[:video]) if @athlete.can_add_another_video? && @video.save flash[:notice] = "successfully created" pandaworker.perform_async(@video.id) log_activity(@video.logging_information) respond_with @video, location: athlete_profile_showcase_path else flash[:notice] = @video.errors.full_messages.to_sentence redi

ggplot2 - Plotting many natural cubic splines in ggplot (R) -

forgive me if i'm asking basic question here (i'm not experienced in r), i'm trying plot natural cubic splines in r , i'm running against wall. i have data set has ~3500 rows , 30 columns. data set of single-season baseball statistics 270 different baseball players on entire careers. basically, have 270 time series (one each player). i'm interested in player performance measured thing called woba on time, want fit natural cubic spline each , overlay splines on 1 graph. , yes, must natural cubic spline. , far know, way in ggplot. my current code doing is: #initialize plot plot <- ggplot(data, aes(x=age, y=woba, color=playerid, group=playerid)) + theme(legend.position="none") #loop through players add splines (i in unique(data$playerid)) { plot <- plot + stat_smooth(method = lm, formula = y~ns(x,3), data=data[which(data$playerid=="i"),list(playerid,age,woba)], se=false) } i have checked can run code snippet inside

database - Inserting now() from vb6 into mysql -

sorry english. when insert now() vb6 mysql(it's datetime type), zeros shown(0000-00-00 00:00:00 this). how can make them show normally? when change datetime type text shows normally, can't work it. here's how insert osql = "insert rendeles(id_vevo,datum,vcime,id_alkalmazott) values (" & _ cmbvasarlo.itemdata(cmbvasarlo.listindex) & ", '" & now() & "', '" & _ ors1!cim & "', " & logged_user_id & ")" set ors = oconn.execute(osql) you need (i real rusty on vb6) dim sqldate string sqldate = format$(now, "yyyy-mm-dd hh:mm:ss") ... cmbvasarlo.itemdata(cmbvasarlo.listindex) & ", '" & sqldate & "', '" & _ ors1!cim & "', " & logged_user_id & ")"

canvas - Android: how to SurfaceView multiple drawings on cavas with no drawing sync -

i'm trying simple app changes cavas background colour every 500ms, on cavas create n circles each vary radius every x millisecond. how can if sleep time in "run()" method dictated cavas colour change. should create new thread every circle , sync of them? cleary need take in consideration circles have drawn after canvas background color change, since risk circles not visible due background layer drawn obove circles? for kind of job should consider working opengl? this run(): public void run() { int i=0; paint paint= new paint(); paint.setcolor(color.red); log.d("zr", "in running"); while(running){ try { thread.sleep(500); } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } if(!holder.getsurface().isvalid())

objective c - EXC_BAD_ACCESS from outlineView:child:ofItem -

please explain why having problems line below have commented out. it causing exc_bad_access in outlineview:objectvaluefortablecolumn:byitem:. a gist full class at: https://gist.github.com/onato/9d12bbbf5c4135673f24 - (id)outlineview:(nsoutlineview *)outlineview child:(nsinteger)index ofitem:(id)item { if (!item) { item = self.data; } id returnvalue = @""; if ([item iskindofclass:[nsarray class]]) { returnvalue = @"value";//[item objectatindex:index]; } // return @{@"index":@(index), @"value":returnvalue}; // produces exc_bad_access in outlineview:objectvaluefortablecolumn:byitem: return returnvalue; } i have tried creating basic project datasource , nothing else , still see problem. you can't make items on fly in outlineview:child:ofitem: . of items must exist, or @ least continue exist afterward until deleted (i.e., removed on user's behalf both view and model) or until wh

php - How to pass value of variable from one page to another using header? -

how can pass value of $_post['login'] variable $login , use value in page home.php ? using code: header('location:home.php'); by using session-variables, this: <?php session_start(); $_session['login'] = $_post['login']; header('location:home.php'); ?> and <?php // home.php session_start(); $login = $_session['login']; ?>

symfony - How to automatically handle all unhandled php errors in symfony2? -

disclaimer: seems guys need real world example that. here is: file_get_contents($filename); keep in mind thread safety , race conditions. or other php notice/warning or kind of recoverable exception. where either not defined. , run in default app.php default symfony v2.3.5 configs - see notice: undefined variable: in /var/www/.../uibundle/controller/deploycontroller.php on line 57 call stack: 0.0000 629696 1. {main}() /var/www/.../web/app.php:0 which not expect since in production mode framework should handle everything, log , show nice 404/500 user. what missing , config parameter should change behaviour expect? upd : this question how handle unhandled php errors user didn't see stacktrace proper error page on production. treat $i++ , \bla() unexpected case, bug. upd 2 : yes, i'm aware of debug parameter of kernel class, , don't see switching to $kernel = new appkernel('prod', true); ^--

ruby - app is not stopping at "gets" - is my online interpreter forcing a timeout? -

while starting assignment (towers of hanoi), leave code in basic state while ponder logic of how continue. while arr3.count < 6 puts "move ring tower?" = gets.chomp puts "move ring tower?" = gets.chomp end before can start building rest of app, however, gets seems fall through without input me, , second puts displays on screen. continues looping every, say, 30 seconds or so. should assume feature of online interpreters (like codeacademy labs)? now i'm distracted continuing assignment , have find better place code. i'm installing aptana (based on advice on forum) see if can better environment assignments. or people use text editor run .rb file through windows console window? thx

javascript - How do I get JSON and push it into HTML with jQuery? -

i have html pages , have decided populate them using json generated api (api.example.com). the thing have never used jquery. basics pull information using jquery , fill html json data, name, surname, messages? should put javascript codes athe end of html pages (right before )? or, there easy way? really depends on json looks likes comming back. first data using ajax. var incomingdata; //incoming data variable $.ajax("http://yoururl.goes.here", { type: "get", datatype: "json", success: function(data) { incomingdata = data; }, error: function(req, status, err) { //console.error("something went wrong! status: %s (%s)", status, err); } }); now have data in incomingdata variable. i'd console.log data, can view it, accessing parts done through dot notation: incomingdata.name; incomingdata.phone; usually you'll array of objects when return json, may need loop through. for(var = 0; < incom

java - Cannot resolve symbol in Git repo files with IntelliJ -

Image
i've been working on getting set using github java project using intellij. i've figured out basics of using github reason after i've got repository set up, clone project , open in intellij has errors recognizing every single class type. the src files open fine, run fine, compile fine yet intellij highlights every single statement type declaration in it, "cannot resolve symbol", , says not recognize type. yet src files in same folder. intellij not recognising files proper source code because wasn't told to. need mark folder source root . right-click on folder select mark directory as → source root

java - Android AsycTask ellapsed time calculation -

i'm trying calculate time ellapsed in execution of asynctask, nothing logged in onpostexecute method, i'm doing wrong? here part of code: @override protected void onpreexecute() { this.dialog.setmessage(mensagem); this.dialog.show(); date date = new date(); starttime = date.gettime(); } @override protected void onpostexecute(string result) { if(this.dialog.isshowing() && this.dialog != null) this.dialog.dismiss(); date date = new date(); endtime = date.gettime(); long difftime = endtime - starttime; //here nothing logged in logcat log.d("tempo de requisiÇÃo", string.valueof(difftime) + " milisegundos"); check logcat level, @ debug . make sure not cancelling asynctask while running otherwise onpostexecute won't run. also if being run in service there maybe issues looper not being set if asynctask not running. try

c# - Export Listview to Excel (troubleshoot) -

i working on web application , need able export listview excel. listview bound (i can see data), export function below isn't working. function seems tripping on <asp:linkbutton> , <asp:imagebutton> . aware of way around this? public void exportintoexcel(listview lvexport, string header, string filename) { try { system.web.httpcontext.current.response.clear(); system.web.httpcontext.current.response.contenttype = "application/vnd.ms-excel"; system.web.httpcontext.current.response.addheader("content-disposition", "attachment;filename=" + filename + ".xls"); system.web.httpcontext.current.response.charset = ""; system.web.httpcontext.current.response.cache.setcacheability(httpcacheability.nocache); stringwriter stringwrite = new stringwriter(); stringwrite.write(header); stringwrite.writeline(); htmltextwriter htmlwrite = new htmltext

angularjs - How to watch an object property? -

i want have attribute directive can used this: <div my-dir="{items:m.items, type:'0'}"></div> in directive can turn object like: function (scope, element, attributes, modelcontroller) { var ops = $.extend({}, scope.$eval(attributes.mydir)); } now m.items array. , somewhere down line ajax call replaces array new one. i'd watch this. how can watch m.items or whatever typed in items property in attribute? should watch expression be? you should able use scope.$watch watch attribute. angular invoke callback entire object when of values change. function(scope, elem, attrs) { scope.$watch(attrs.mydir, function(val) { // new value, val. }, true); } http://plnkr.co/edit/jbgqw8ufzh1ej1ppq3ft anytime model changes (by typing in input) directive updates elements html in $watch. edited answer: want include true last argument compare object values, not references. otherwise run digest more 10 times , exception.

android - Widevine Video Playback -

the chromecast sdk states widevine content supported. through testing determined widevine browser plugin not installed on browser running on chromecast device. knowing that, how 1 play widevine video content using chromecast sdk? i'm running down path of working subclassing mediaprotocolmessagestream , trying figure out contentmetadata needs passed loadmedia(). guidance great! currently, have write own (javascript) player scratch support drm content, including widevine. chrome browser (in chromecast devices) supports eme can take advantage of that. to further clarify, here high level process needs happen: need register listener video element "needkey" event fired when protected content detected browser. have call video.generatekeyrequest(..) , pass appropriate "key system" , "initialization data" (initdata). needkey event contains initdata applications can modify before calling generatekeyrequest(). after going through content decryption

rubygems - Rails new create issue with multi_json -

i not sure initial problem when create new rails apps, seems every time create application, run json issue. when try gem install multi_json -v '1.8.1' , error well. seems gem can't updated because of server issue rubygems.org. missing something? create create readme.rdoc create rakefile create config.ru create .gitignore create gemfile create app create app/assets/javascripts/application.js create app/assets/stylesheets/application.css create app/controllers/application_controller.rb create app/helpers/application_helper.rb create app/views/layouts/application.html.erb create app/assets/images/.keep create app/mailers/.keep create app/models/.keep create app/controllers/concerns/.keep create app/models/concerns/.keep create bin create bin/bundle create bin/rails create bin/rake create config create config/route

python - Finding the intersection of a curve from polyfit -

Image
this seems simple can't quite figure out. have curve calculated x,y data. have line. want find x, y values 2 intersect. here i've got far. it's super confusing , doesn't give correct result. can @ graph , find intersection x value , calculate correct y value. i'd remove human step. import numpy np import matplotlib.pyplot plt pylab import * scipy import linalg import sys import scipy.interpolate interpolate import scipy.optimize optimize w = np.array([0.0, 11.11111111111111, 22.22222222222222, 33.333333333333336, 44.44444444444444, 55.55555555555556, 66.66666666666667, 77.77777777777777, 88.88888888888889, 100.0]) v = np.array([0.0, 8.333333333333332, 16.666666666666664, 25.0, 36.11111111111111, 47.22222222222222, 58.333333333333336, 72.22222222222221, 86.11111111111111, 100.0]) z = np.polyfit(w, v, 2) print (z) p=np.poly1d(z) g = np.polyval(z,w) print (g) n=100 a=arange(n) b=(w,v) b=np.array(b) c=(w,g) c=np.array(c) print(c) d=-a+99 e=(a,d) print (e) p1=

javascript - Node.js MySQL query execution flow -

if have mysql query returns value used again in where clause, work node.js' asynchronous execution flow? generally might case: select customerid customers customername=nikolas then result stored so: var customerid = customerid and reused in query: select orderid orders customerid=customerid will fetch me orderid of customer nikolas returned in first query? will written queries run sequentially? it depends on module you're using. 1 of commonly used drivers, node-mysql , asynchronous, code won't run sequentially. instead, you'd have use callbacks: var query1 = 'select customerid customers customername = nikolas'; var query2 = 'select orderid orders customerid = '; connection.connect(); connection.query(query1, function(err, rows, fields) { var customerid = rows[0].customerid; connection.query(query2 + customerid, function(err, rows, fields) { connection.end(); // results here }); }); in node.js, want write

Golang, Go : convert string to float number -

http://play.golang.org/p/7kr2uzlv5- this playground link. have array of numbers in string. tried convert them float number not give me anything. wrong it? var numbers []float64 _, elem := range str_numbers { i, err := strconv.parsefloat(elem, 64) if err != nil { numbers = append(numbers, i) } } fmt.println(numbers) // gives me nothing [] change if err != nil { to if err == nil { (you may doing already, unit testing great way catch bugs this.)

ubuntu - remove default nginx welcome page when access directly from ip address -

at ubuntu server, install nginx , setup virtual host using article. https://www.digitalocean.com/community/articles/how-to-set-up-nginx-virtual-hosts-server-blocks-on-ubuntu-12-04-lts--3 the virtual host's domain name www.example.com. when go www.example.com, can see application's index page. however, when go real ip address, still see nginx welcome page. can remove welcome page or point www.example.com if uses ip address access site? i setup a record point ip xxx.xxx.xxx.xxx www.example.com. i think when first set nginx comes "default" virtual host. did tried removing that? did tried deleting symlink? third option add "deny all;" on location / of default virtual host. i not sure if work , cannot test right now. if above not work, try out: http://nginx.org/en/docs/http/request_processing.html#how_to_prevent_undefined_server_names http://your-server-ip/ request undefined server name. should able block with: server { listen

android - getParcelableExtra always null on Pending Intent, but not Intent -

i'm new java let alone android development. have no coding background, thought i'd start 'simple' alarm clock. i'm writing alarm clock, , want update alarms inactive if aren't repeating after go off. when pass parcelable alarmclass (my alarm object) alarm set screen intent, passes fine. when pass same alarmclass intent, , put in pendingintent in alarm manager , try screen can dismiss alarm, alarmclass object i'm calling , populating exact same way null. here's alarm class: package com.example.wakeme; import java.util.calendar; import android.os.parcel; import android.os.parcelable; public class alarmclass implements parcelable{ calendar cal = calendar.getinstance(); private long id = 1; private int active = 1; private long time = cal.gettimeinmillis(); private int repeating = 0; private int skipweekends = 0; private int skipweekdays = 0; private int alarmnumber = -1; public long getid(){ return id;

ios - SQLite Database Hangs Upon Update -

i've been grinding on problem couple hours , grateful outside input. new ios, objective-c , sqlite , trying execute sqlite update statement. issue ui freezes , seems hang in process within sqlite. here's code: nsstring *docspath = [paths objectatindex:0]; nsstring *path = [docspath stringbyappendingpathcomponent:@"sqlite3database.sqlite"]; sqlite3_instance *db = [sqlite3_instance databasewithpath:path]; [db open]; nsstring *execupdate = [nsstring stringwithformat:@"update listitem set status=%i,message=\"%@\",gpslong=%@, gpslat=%@,lastupdated=datetime('now') userid = %@",[status_picker selectedrowincomponent:0],messagetextfield.text , longitude, latitude,loggedinuserid]; nslog(@"execupdate: %@", execupdate); if (![db executeupdate:execupdate]) nslog(@"data insert failed %@", db.lasterrormessage); this code executed in ibaction after clicking uibutton, mentioned, ui hung in process. output above code foll

wordpress index.php doesn't open locally -

i using mamp start creating wordpress themes. mamp, wp , db created fine. i have got index.php , style.css in theme folder , can see new theme created in there. when try preview code using localhost not getting result. when try open wordpress theme on local host (mamp) site doesn't open, opens list of what's in directory, clicking on index.php same. admin site works fine. not sure problem is. every other local site (not wordpress) works fine any clue? kind regards fábio have tried creating page called front-page.php, put text in there , see if shows

ios - Performing GET with JSON data using NSDictionary -

i trying data using nsdictionary. data looks this: { "id": 1, "items": [ { "id": 1, "correctanswer": "sample string 3", "difficulty": 4, "categoryid": 5, "categoryname": "sample string 6", "accountid": 7 }, { "id": 1, "picurl": "sample string 2", "correctanswer": "sample string 3", "difficulty": 4, "categoryid": 5, "categoryname": "sample string 6", "accountid": 7 } "starttime": "2013-10-07t00:24:22.0048045+00:00" } this tried: - (ibaction)play:(id)sender { [self performseguewithidentifier:@"playsegue" sender:self]; nsstring *gameid; nsnumber *id; nsurl *pictureurl; nsstring *ans1; nsstring *ans2; nsstring *ans3; nsstri