Posts

Showing posts from September, 2011

javascript - slowly animate a simple line -

my problem line draw instantaneous . what want draw line slowly , 3-5 seconds before finishes @ dy . reason cannot settimeout() work. have tried large , small values. i have basic line example expand on concept include x , bezier lines once can figure how timeout works. var canvas = document.getelementbyid('mycanvas'); var context = canvas.getcontext('2d'); function myline(x, y, dx, dy) { //line constructor this.x = x; //start x this.y = y; //start y this.dx = dx; //end x this.dy = dy; //end y } var line = new myline(100, 5, 100, 100); //line object function drawline(myline, context) { //draw function context.moveto(myline.x, myline.y); animate(line, context); } function animate(myline, context) { //animation function if (myline.y < myline.dy) { myline.y = myline.y + 1; context.lineto(myline.dx, myline.y); context.stroke(); window.settimeout(animate(line, context), 1000/60); } } drawline(line, contex...

c++ - What does (&) -- ampersand in parentheses -- mean in this code? -

in this answer , following code given (c++11): template <typename t, size_t n> constexpr size_t size_of(t (&)[n]) { return n; } what (&) mean in context? sort of thing exceptionally difficult search for. it's shorthand this: template <typename t, size_t n> constexpr size_t size_of(t (&anonymous_variable)[n]) { return n; } in function, don't need name of variable, template deduction on n - can choose omit it. parentheses syntactically necessary in order pass array in reference - can't pass in array value.

python - Getting UnicodeDecodeError when transposing DataFrame in iPython -

i importing excel table http://www.gapminder.org/data/ want switch columns , rows of table. , error getting: "unicodedecodeerror: 'ascii' codec can't decode byte 0xc3 in position 23389: ordinal not in range(128)" i trying encode/decode dataframe dataframe.decode('utf-8') says dataframe not have such attribute. the error occurs because transpose cannot convert data ascii. right? why need when table pure numbers? thank much. there more information on error: --------------------------------------------------------------------------- unicodedecodeerror traceback (most recent call last) <ipython-input-190-a252f2a45657> in <module>() 1 #your code here 2 countries = countries.transpose() ----> 3 income.transpose() 4 #income = income.decode('utf-8') 5 #content = content.decode('utf-8') /users/sergey/anaconda/lib/python2.7/site-packages/ipython/core/displayhook.pyc in __ca...

ios - how to reset/restart an animation and have it appear continuous? -

so, new ios programming, , have inherited project former coworker. building app contains gauge ui. when data comes in, want smoothly rotate our "layer" (which needle image) current angle new target angle. here have, worked slow data: -(void) moveneedletoangle:(float) target { static float old_value = 0.0; cabasicanimation *rotatecurrentpressuretick = [cabasicanimation animationwithkeypath:@"transform.rotation"); [rotatecurrentpressuretick setdelegate:self]; rotatecurrentpressuretick.fromvalue = [nssnumber numberwithfloat:old_value/57.2958]; rotatecurrentpressuretick.removedoncompletion=no; rotatecurrentpressuretick.fillmode=kcafillmodeforwards; rotatecurrentpressuretick.tovalue=[nssnumber numberwithfloat:target/57.2958]; rotatecurrentpressuretick.duration=3; // constant 3 second sweep [imageview_needle.layer addanimation:rotatecurrentpressuretick forkey:@"rotatetick"]; old_value = target; } the problem have new data s...

linux - 'find' (command) finds nothing with -wholename -

why command work: /home/user1/tmp $ find ./../.. -wholename '.*/tmp/file.c' -exec echo '{}' \; ./../../user2/tmp/file.c /home/user1/tmp $ and command not work? (finds nothing) /home/user1/tmp $ find /home -wholename '.*/tmp/file.c' -exec echo '{}' \; /home/user1/tmp $ the first command generates file names starting ./../.. . wholename pattern match because start . . the second command generates filenames starting /home . however, wholename pattern still looking paths starting . not match file in case. note patterns not regular expressions. if expecting them, @ -regex option instead.

javascript - How to save a textarea as a text file -

im trying make own software similar microsoft word html. have textarea , enter text , save it. problem is, when saved computer test out everytime reset textarea. had button did javascript alert box telling press "ctrl+s" save file, said resets textarea. there differnt tag other textarea tag, or need differnt method of savind file. if have code suggestions please share me, thanks! here code: textarea { background-color: #e6e6e6; } </style> </head> <body> <div class="container"> <div class="jumbotron"> </h1> </div> </div> </div> <button onclick="myfunction()"> <noscript> <b> press ctrl+s , name (---------).html </b> </noscript>save </button> <script> function myfunction() { alert("to save press c...

javascript - Canvas fallback to flash is loading images -

in site show ads flash i still use flash because visitors have older browsers not support html5 if user has no flash support, show canvas ad if user has no flash support or has no canvas support, show them image this code: <p> <object width="728" height="90" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" id="alter-content" align="middle"> <param value="http://www.bellezaculichi.com/banners/47.swf" name="movie"> <param name="quality" value="high"> <param name="bgcolor" value="#ffffff"> <param name="play" value="true"> <param name="loop" value="true"> <param name="wmode" value="window"> <param name="scale" value="showall"> <param name="menu" value="false"> <param ...

java - How to find all the input data from the internet onto your device -

so i'm trying create program in java on computer. needs take data sent internet computer, such data sent weather app or news app (as in use data sent computer). i'm self taught, wondering if knew ways go doing this? thinking using command line , seeing if there way view information sent computer? appreciated! if you're looking data that's been sent computer download utility called wireshark, or use tcpdump analyze it. i'm not sure explanation trying though. trying view data coming in , out of computer? trying experiment , see how write application communicates on tcp/ip, udp, web based protocol?

c# - When should I use ViewBag/model? -

i think using viewbag faster model. my example is: in action: public actionresult myaction() { viewbag.data = (from m in mydatabase.mytable select m).tolist(); } in view: @foreach(var item in viewbag.data) { <tr> <td>@item.mycolumn</td> </tr> } by using model: [table("tbl_mytable")] public class mytable() { public int id { get; set; } public int column2 { get; set; } public int column3 { get; set; } // ... public ienumerable<mytable> data { get; set; } } in model: public class mainclass { public list<mytable> mymethod() { list<mytable> list = new list<mytable>(); // code logic find data in database , add list list.add(new mytable { column2 = ... column3 = ... }); return list; } } in action: public actionresult myaction() { mainclass mc = new mainclass(); mytable model = new mytable(); model.data = mc.my...

android - The total of downloads shown in the PlayStore is counted by "Current Installations" or "Total of Installations"? -

i noticed when publish app playstore, make average count example: "+1000 downloads" or "+5000 downloads" , etcetera. when enter in publish app area , in apps shows 2 different numbers current installations , total of installations . so know 1 should take consideration when output in download area of app in playstore. "5000+ downloads" referred current installations or total of installations? thank you.

Vim with Pyflakes "Caught deadly signal SEGV." -

more frequent vim crashes terminal prompting vim: caught deadly signal segv. i use vim pyflakes plugin edit python scripts. does know problem caused by? i run mac osx 10.10.

linear algebra - Can somebody explain to me what 'void postConcat' in Android does? -

so have 2 matrices. colormatrix , threshold. colormatrix initially, c = [ 0.213 0.715 0.072 0 0; 0.213 0.715 0.072 0 0; 0.213 0.715 0.072 0 0; 0 0 0 1 0;] and threshold is: t = [ 255 0 0 1 -306; 0 255 0 1 -306; 0 0 255 1 -306; 0 0 0 1 -306;] now line of code in android colormatrix.postconcat(threshold); returns this: c = [ 54.315 182.325 18.36 1 -306; 54.315 182.325 18.36 1 -306; 54.315 182.325 18.36 1 -306; 0 0 0 1 0; ] why? steps follows come result? if same thing in matlab, c*t' this: c = [ 54.315 182.325 18.36 0; 54.315 182.325 18.36 0; 54.315 182.325 18.36 0; 0 0 0 0; ] a different dimension array different values. can explain me postconcat does? can't find online function, in android documentation, , says this: concat colormatrix specified postmatrix. . android thing? why? steps fol...

python - ForAll in Z3.py -

i have question using of forall in z3.py. want create local variable in forall declaration follows: a = declaresort('a') a0,a1,a2,a3 = consts('a0 a1 a2 a3', a) s = solver() f = function('f', a, a, boolsort()) s.add(forall ([a0],(f(a0, a0)))) print (s.check()) print (s.model()) the result should applied consts except a0 local variable in forall model shows solution apply consts including a0. creating local variable possible in smt not in python. can help? here model provides: sat [elem!0 = a!val!0, f = [else -> true]] it introduces single element called "elem!0" having unique value "a!val!0" (this z3's way generate fresh values"). interpretation of f given such f true. if want quantify on variables not listed in list, should walk formula being quantified on , collect variables not included in set. there 3 cases consider when walking expression: can satisfy 1 of following properties: is_quantifier(e...

neural network - Pybrain Reinforcement Learning Example -

as question states looking explanation/example reinforcement learning in pybrain documentation on confuses me no end, can work don't understand how apply other things. thanks tom unfortunately, pybrain's documentation rl classes disappointing. have found this blog quite useful. in summary, need identify following components (for implementation details follow tutorial on link): an environment: env = environment(...) a task --> task = task(env) a controller, module (like table) keep action-value information --> controller = module(...) a learner --> learner = sarsa() --> may add explorer learner. default epsilon-greedy epsilon = 0.3, decay = 0.9999. an agent integrate controller , learner --> agent = agent(controller, learner) an experiment integrate task , agent , actual iterations --> experiment = experiment(task, agent) each of capitalized classes should replaced corresponding class pybrain.then run do-while cycle perform iter...

vba - Concatenate data from multiple Excel sheets into one Excel sheet -

within excel workbook have 5 specific worksheets (different names) want concatenate data different worksheet (master) within same workbook. taking data each sheet , appending bottom of data in "master" sheet. removing blank rows if possible. there macro can this? there several choices. if need once, don't bother using macro. go each sheet, copy rows, move master sheet, scroll down first empty row, , paste. assuming need macro this, might work: sub combinesheets() dim wksht worksheet, mastersht worksheet, r integer set mastersht = worksheets.add r = 0 each wksht in thisworkbook.worksheets if not wksht mastersht wksht.usedrange.copy destination:=mastersht.cells(r + 1, 1) r = mastersht.usedrange.rows.count end if next wksht end sub

Image oversize in HTML -

Image
how can solve image oversize problem in simple html photogallery finding images in directory php? can't solve , it's not visually good. can please me? screenshot thanks. set of pictures same class, add image height class , set images same height. here example made - http://jsfiddle.net/3gd5oolf/ im not sure how getting image in php can't tell how set class without seeing code. here's css example: .height { height: 100px; }

c# - Generic Object Cache -

i working on project plan on using redis persistent data storage, task @ hand, working on generic object cache. , huge fan of linq have started designing cache support this. public concurrentbag<object> cache = new concurrentbag<object>(); public list<t> findby<t>(func<t, bool> predicate) t : class { var tmp = new list<t>(); foreach (var in cache) { try { t obj = t; if (obj != null) tmp.add(obj); } catch { } } return tmp.where(predicate).tolist(); } i afraid when object cache grows large become inefficient. (i estimate 500k-1m objects) i hoping possible use this public concurrentbag<object> cache = new concurrentbag<object>(); public list<t> findby<t>(func<t, bool> predicate) t : class { return cache.where<t>(predicate).tolis...

c - EQUATION SOLVER absurd result despite correct algorithm -

#include<stdio.h> #include<math.h> #include<stdlib.h> void bisect(float *p,int n,int a); float value(float *p,int n,int a); int main() { int a,i; float *p; printf("enter degree of polynomial\n"); scanf("%d",&a); p=(float *) malloc(a*sizeof(float)); for(i=0;i<=a;i++) { printf("enter coefficient of x^%d\n",i); scanf("%f",p+i); } printf("%f\n",value(p,-2,a)); printf("%f\n",value(p,1,a)); printf("%f\n",value(p,0,a)); for(i=-100;i<100;i++) { if(value(p,i,a)*value(p,i+1,a)==0.000) { printf("%d\n",value(p,i+1,a)); if(value(p,i,a)==0&&value(p,i+1,a)==0.00) { printf("the roots %d,%d\n",i,i+1); } if(value(p,i+1,a)==0.0) { printf("the real root %d\n",i+1); i+...

php - how to set date and time based on users location -

this question has answer here: convert utc date time local date time 18 answers i want set date , time based on users location. i used following php code set date , time in indian standard time. how find users timezone. <?php $timezone = "asia/kolkata"; date_default_timezone_set($timezone); $time=date("h:i a"); $date = date("m d,y"); ?> thanks in advance. you need timezone javascript code, , transmit server. examples can found here: get user timezone

javascript - Email sending with AngularJS and PHP -

i have created application in angularjs , has email contact form , sends emails using php file in server. here's controller.js part in angularjs: $scope.feedbacksubmit= function (){ var name1 = document.getelementbyid("name").value; var email1 = document.getelementbyid("email").value; var message1 = document.getelementbyid("message").value; $http({ url: "http://boost.meximas.com/mobile/email.php", method: "post", data: { name: name1, email: email1, message:message1 } }).success(function(data, status, headers, config) { // callback called asynchronously // when response available if(status == 200) { var return_data = data; if(return_data != 0){ $scope.hide(); //$scope.closefeedback(); }else{ $scope.showemailerror(); } } }). error(function(data, status, headers, config) { // called asynchronously if error...

c# - SdkUtility.LaunchSignInPage not redirecting to ebay sign in page -

.net 4.5 , mvc 5 , iis 8 sdkutility.launchsigninpage(apicontext, _sessionid); from application (in vs 2013) can access sign in page. problem occurs when published in iis. firstly shows error access denied. i have searched , in iis, applicationidentity pool, gave network_service , gave network service full authentication read or read & execute... error not show more. sign in page not appear. **edit 1: ** using asp .net mvc 5, iis 8.0.0.9, ebaysdk while try token via sdk call, error occurs. of course after hosting. in visual studio, works fine. think is, have set level of permission allow users use sdk or that. here full error trace. access denied description : an unhandled exception occurred during execution of current web request. please review stack trace more information error , originated in code. exception details: system.componentmodel.win32exception: access denied source error: an unhandled exception generated during execution...

c# - Kinectv2 normalizing depth values -

i using kinect v2 capture depth frames. saw kinect sdk 1.x codes in c++, used byte depth = 255 - (byte)(256*realdepth/0x0fff); i want know, purpose of command , need use kinect v2? if have use this, code in c#. getting error in multiplying 256*realdepth error: operator '*' cannot applied operands of type int , unshort . for give downmark, please explain reason that that line of code used normalize depth values, coded in 11 bits in c++ api. command, 11-bit representation converted in 8-bit one, allows display depth map grayscale image. anyway, don't need use line of code if developing application in c#, because api can you.

How do you plot a graph consisting of extracted entries from a nested list? -

i have nested list such that; nested_list = [[4, 3, 0], [6, 8, 7], [3, 1, 8], [2, 1, 3], [9, 9, 3], ...] which has 100 entries. i need plot graph of first elements of each sub-list where sub_list_1 = [4, 6, 3, 2, 9, ...] against third elements of each sub-list where sub_list_2 = [0, 7, 8, 3, 3, ...] over sub-lists, have no idea how this. this have tried: k=0 while k<=100: x=nested_list[0][0][k] y=nested_list[k][0][0] k=+1 plt.plot(x,y) plt.axis('image') plt.show() this not work however. you need build 2 new lists. can list comprehensions: x = [sub[0] sub in nested_list] y = [sub[2] sub in nested_list] plt.plot(x,y) your code tried access 1 level of nesting many (you can address nested_list[k][0] , not nested_list[k][0][0] ) or tried index first value of first nested list index k . did not build new lists; rebound x , y k times.

javascript - What is clojure.core equivalent of lodash _.pluck -

lodash _.pluck this var users = [ { 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 } ]; _.pluck(users, 'user'); // → ['barney', 'fred'] good thing can go deep this: var users = [ { 'user': {name: 'barney'}, 'age': 36 }, { 'user': {name: 'fred'}, 'age': 40 } ]; _.pluck(users, 'user.name'); // ["barney", "fred"] is there equivalent in clojure core of this? mean, can create 1 line this (defn pluck [collection path] (map #(get-in % path) collection)) and use this: (def my-coll [{:a {:z 1}} {:a {:z 2}}]) (pluck my-coll [:a :z]) => (1 2) i wondering if there's such thing included in clojure , overlooked it. there no built-in function this. can refer clojure.core api reference , the cheatsheet what's available. i clojure's syntax light enough feels sufficient use combin...

c# - Giving objects unique ids onStart -

i have bunch of gameobjects assigning unique ids in start function. void start() { uniqueid = string.format("{0:x}", datetime.now.ticks); } i thought work every , duplicate ids. how can make sure unique? unity provide unique id every object instance, have @ getinstanceid .

How can i run php file automatically in windows7 -

i using php , mysql running in windows7. need run php script @ scheduled time daily send sms birthday wishes. you can put command in task scheduler , , setup datetime interval need. to execute php script, need mention php path , file executed, example: d:/xampp/php/php.exe d:/xampp/htdocs/execute.php

ios - CLLocationManager: Unexpectedly Found Nil While Unwrapping an Optional Value -

here's code in viewcontroller.swift: import uikit import alamofire import swiftyjson import mapkit import corelocation import twitterkit class viewcontroller: uiviewcontroller, mkmapviewdelegate, cllocationmanagerdelegate { @iboutlet weak var mymap: mkmapview! @iboutlet weak var counterlabel: uilabel! var manager = cllocationmanager() override func viewdidload() { super.viewdidload() // additional setup after loading view, typically nib. //calling cllocation manager.delegate = self manager.desiredaccuracy = kcllocationaccuracybest manager.requestwheninuseauthorization() manager.startupdatinglocation() //map region let locationzoom = self.manager.location var latitude: double = locationzoom.coordinate.latitude var longitude: double = locationzoom.coordinate.longitude var centerlatitude: cllocationdegrees = locationzoom.coordinate.latitude var centerlon...

How to trace system calls in FreeBSD from source code? -

how log system calls (the syscall number , return value, both int 0x80 , sysenter/syscall ) on freebsd 10.1 x86_64 source code? i know truss can work, need log other information buffer of copyout during each system call. i tried locate source code of truss , failed. tried trace them in amd64_syscall() , result seems incomplete compared result of truss . idea functions should care in implementation? you have not specified why need of this. in particular, if need security purposes, doing wrong. what mean failed? sources here: http://bxr.su/freebsd/usr.bin/truss/ general mechanism used tools known ptrace ( https://www.freebsd.org/cgi/man.cgi?query=ptrace ), , amongst other things allows stopping traced threads execute syscalls. however, 1 has note while such mechanisms allow copy arguments, other threads can change memory pointed aforementioned args after copy them, before syscall same. want use mac hooks if of concern you.

php - Ajax load dynamic page -

html index.php <a class="cart-icon" href="cart"></a> <div class="content"></div> ajax load content load-content/cart.php $(document).ready(function(){ $(document).on('click', '.cart-icon', function(e){ e.preventdefault(); var page = $(this).attr("href"); $('.content').load('load-content/'+page+'.php'); }); }); this code load content cart.php not update url when refresh page content in div dissapear. want when refresh page not dissapear , update url. for example: default url: index.php , when press tag load content cart.php , update url index.php/load-content/cart.php you need persistent storage of some kind. load dom of page temporary. might same thing you're doing here on document load: $(document).ready(function(){ $('.content').load('load-content/'+page+'.php'); $(document).on('click', ...

How do I enter the git config command for Git Bash? -

i tried enter git config -- global user name , keep getting error messages when trying configure git bash account. using windows 7 , have downloaded git version 1.9.5 it seems if trying globally set username. correct command: git config --global user.name "john doe" have @ pro git book: 1.6 getting started - first-time git setup nice summary.

windows server 2012 r2 - Can create Scripting.FileSystemObject 64-bit but not 32-bit -

my client has windows 2012 r2 64-bit running in virtual machine. gave client 32-bit program compiled vb6, failing on line: set run.filesys = createobject("scripting.filesystemobject") where run.filesys has type variant. program has run on many, many systems on years, in case fails run-time error '429': activex component can't create object when client runs regsvr32 scrrun.dll in syswow64 folder, says registered successfully. instructed run following: reg query "hkey_classes_root\scripting.filesystemobject\clsid" reg query "hkey_current_user\software\microsoft\windows script host\settings\enabled" reg query "hkey_local_machine\software\microsoft\windows script host\settings\enabled" it says clsid value {0d43fe01-f093-11cf-8940-00a0c9054228}, , "enabled" keys (which used disable script host) not present. examining file scrrun.dll in syswow64 folder, version number 5.8.9600.17415. i have access instan...

c# - Adding GUI controls dynamically -

Image
i facing problem adding panel, 2 buttons in scrollable (through panel) group box. not in adding ui elements without designer, naturally, i've got cluttered interface doesn't work way intended. here code: private void client_downloadfilecompleted(object sender, system.componentmodel.asynccompletedeventargs e) { linksparser<track>.results.foreach<uri, track[]>( new action<uri, track[]>( // extension method delegate(uri key, track[] value) { groupbox gb = new groupbox() { text = key.absoluteuri, size = new size(550, value.length * 30), tabindex = 0, tabstop = false }; flwlayout.controls.add(gb); // flwlayout created designer panel gb_panel = new panel() { size = gb.size, tabindex = 0, tabstop = false, locat...

Amazon SQS - JMS vs custom implementation -

currently reading sqs queue following code public class sqsreceiver implements runnable { @autowired protected amazonsqs sqs; protected receivemessagerequest receivemessagerequest; public void run() { list<message> messages = sqs.receivemessage(receivemessagerequest) .getmessages(); (message msg : messages) { logger.info("processing message: {}", msg.getbody()); try { processmessage(msg); } catch (exception e) { logger.error("error processing message", e); } { sqs.deletemessage(new deletemessagerequest().withqueueurl( receivemessagerequest.getqueueurl()).withreceipthandle( msg.getreceipthandle())); } } } } and having scheduler read every second: threadpooltaskscheduler scheduler = new threadpooltaskscheduler(); scheduler.setpoolsize(1...

javascript - How to unit test an angularjs promise -

i unit test promise this: function getsongs() { var d = $q.defer(); var url = 'http://localhost:3002/songs'; $http({ method: 'get', url: url }) .success(function(data) { d.resolve(data); }) .error(function(data) { d.reject(data); }); return d.promise; } this returns , arrays of objects. used in controller calling getsongs function: var vm = this; vm.songlist = []; vm.init = function () { playerscreenservice.getsongs() .then(getsongssuccess); }; vm.init(); thank much. take @ $httpbackend . test this: describe('playerscreenservice', function () { it('should send http request', inject(function (playerscreenservice, $httpbackend) { $httpbackend.whenget('http://localhost:3002/songs').respond(200, {...}); var getsongssuccess = jasmine.createspy('getsongssuccess'); var getsongserror = jasmine.createspy('getsongserror...

javascript - AngularJS call function from click -

i can't life of me figure out why can't call function in controller. on clicking accordion-group attribute error: uncaught referenceerror: getconversationsforuser not defined here html: <ui-view id="smtconvocard" layout="column" layout-fill layout-padding> <div layout="row" flex layout-align="center center"> <md-card flex-gt-sm="90" onresize="resize()" flex-gt-md="80"> <md-card-content> <md-list> <h2>conversations</h2> <accordion close-others="oneatatime"> <accordion-group heading="{{contact.firstname}} {{contact.lastname}}" ng-repeat="contact in contacts" onclick="getconversationsforuser(contact.useruid)"> <div>test</div> </accordion-gr...

c# - calling a restful WCF from Xamarin.Android application -

i building android application vs 2012. when make webrequest wcf web service url: http://localhost:15763/service1.svc/getdata i following exception: system.net.webexception: error: connectfailure (connection refused) ---> system.net.sockets.socketexception: connection refused

linux - Synchronizing processes with semaphores and signals in C -

i have write program in c on linux. has have 3 processes - first reads stdin, sends message through fifo second process, counts lenght of recevied message , sends result third process (also through fifo), displays on stdout. have synchronize using semaphores. have add signal handling (which doing using shared memory) - 1 signal end program, second stop it, third resume. signal can send of processes. have code already, it's not working should. first problem synchronization - can see running it, first message received second process, stuck. first , second processes showing messages, not third one. there similar, it's confusing. have send message, p3 showing length of previous one. second problem signals - after sending one, have press enter (for sigusr) or send message (for sigint) served. any ideas what's wrong? there improvements posted before, it's still not working , don't have time finish (till monday). know it's lot of code, if analyze communicatio...