Posts

Showing posts from April, 2013

node.js - Where i should keep my libs for testing with mocha in nodejs? -

i need test nodejs module, writes data output. wrote debugstream stream collect output data assert later: function debugstream () { stream.writable.call(this); this.data = ''; }; util.inherits(debugstream, stream.writable); debugstream.prototype._write = function (chunk, encoding, done) { this.data += chunk; done(); } debugstream.prototype.getdata = function () { return this.data; } i not want write code in every test file. nice move away somewhere, can't how organize it. can't place in test/ folder, because mocha think it's test. how that? under tests can create folders , node modules, treat tests subproject in folder required modules , tools, check example: https://github.com/edsadr/change-api/tree/master/test

android - Unable to apply plugin: 'dexguard' at build.gradle file -

i've below error when add apply plugin: 'dexguard' main module's build.gradle file. error:unable load class 'com.android.build.gradle.baseplugin$postcompilationdata'. possible causes unexpected error include: you using jdk version 'java version "1.7.0_67"'. versions of jdk 1.7 (e.g. 1.7.0_10) may cause class loading errors in gradle. please update newer version (e.g. 1.7.0_67). open jdk settings gradle's dependency cache may corrupt (this occurs after network connection timeout.) re-download dependencies , sync project (requires network) the state of gradle build process (daemon) may corrupt. stopping gradle daemons may solve problem. stop gradle build processes (requires restart) your project may using third-party plugin not compatible other plugins in project or version of gradle requested project. in case of corrupt gradle processes, can try closing ide , killing java processes. my project's bu

mysql - play 2.4 connect to remote database -

i'm new play , scala, using latest play 2.4.x. want connect mysql through remote ip following configuration in application.conf db.default.driver="com.mysql.jdbc.driver" db.default.url="jdbc:mysql://10.0.1.32:3306/scala_test_db" db.default.username="scalauser" db.default.password="test" in build.sbt "mysql" % "mysql-connector-java" % "5.1.36" but jdbc trying connect local ip. following error got java.sql.sqlexception: access denied user 'scalauser'@'10.0.0.224' can me how connect remote ip? your configuration looks fine. error message told mysql user 'scalauser'@'10.0.0.224' has no access. means app connecting database 10.0.0.224. i guess need add new database user. grant usage on scala_test_db.* 'scalauser'@'10.0.0.224'; flush privileges; check mysql docs: http://dev.mysql.com/doc/refman/5.6/en/grant.html

c++ - Sending QStringList between classes using signals and slots -

i have gui built using qt creator. @ point dialog window opened need send variable of type qstringlist. using signals , slots method. however, variable empty once sent. here code samples: widget.h class widget : public qwidget { q_object public: explicit widget(qwidget *parent = 0); ~widget(); signals: void mysignal(qstringlist); }; widget.cpp widget::widget(qwidget *parent) : qwidget(parent), ui(new ui::widget) { // blah blah } widget::~widget() { delete ui; } void widget::on_pushbutton_4_clicked() { qstringlist dlist; int damount = ui->listwidget->count(); for(int i=0; < damount; i++){ dlist << ui->listwidget->item(i)->text(); qdebug() << dlist; } emit mysignal(dlist); mysaver mdialog; mdialog.setmodal(true); mdialog.exec(); } mysaver.h (the dialog box) class mysaver : public qdialog { q

c# - Get system path from rewritten URL -

given rewritten url string: /contact-us i convert it's actual path, example: /pages/contact/contact-us-page.aspx is possible? please note, i'm not asking how re-write url's, how convert re-written path it's actual file in code.

Character array in c with function -

i have problem character array in c program. the program shutdown when run it. think problem somewhere passing character array in function. here's code: #include<stdio.h> #include<string.h> #define dagen 7 void inlezen(int[][dagen], char[][12]); int main(void) { int i; int temp[1][dagen]; char dagen[7][12]; strcpy(dagen[0], "ma"); strcpy(dagen[1], "di"); strcpy(dagen[2], "woe"); strcpy(dagen[3], "do"); strcpy(dagen[4], "vr"); strcpy(dagen[5], "za"); strcpy(dagen[6], "zo"); inlezen(temp, 1, dagen, dagen, 7, 12); } void inlezen(int t[][dagen], char d[][12]) { int i; (i = 0; < dagen; i++) { printf("geef de temperatuur overdag van %s", d[i]); scanf("%d%*c", &t[0][i]); } (i = 0; < dagen; i++) { printf("geef de temperatuur 's avonds van %s", d[i]);

symbol table not found debugging python + C -

i have c module, compiled -g option, using of functions of module using python script. when run command - gdb -ex r -args python test.py it shows- reading symbols /usr/bin/python2.7...reading symbols /usr/bin/python2.7...(no debugging symbols found)...done. (no debugging symbols found)...done. and while using gdb command list throws - no symbol table loaded. use "file" command. what potential reason..? what potential reason.. the reason /usr/bin/python2.7 compiled without debug symbols, , c module has not yet been dynamically loaded. one way deal set deferred breakpoint on module initialization code. once hit breakpoint, list start working.

javascript - show options in select tag when a specific option is selected in other select tag from json -

i have 3 select tags in html document , , when select 1st option 1st select tag, want show other options in second select tag hidden, need load options external file json. how can ? for e.x have object var object = { usa: { californina: ['san fransisco', 'san diego' ],nevada: ['las vegas', 'reno'] } } when select usa option in 1st select tag, want show states (california,nevada) in second select box, , when choose nevada option want show city(las vegas, reno) in 3d select tag! i want options kept in external json file! how can load json file? having json this: {"resource":"a","literals":["b","c","d"]} , taking account want read external json file, can follow different answers post: how read external local json file in javascript . after read information need, can or append options your(s) select(s) ( wh

Disable all requests in Google Chrome developer tools -

is there way disable forms of request whilst in developer tools in chrome? reason being whilst prototyping changes, can particularly frustrating if accidentally click button or whatever reason cause page request erases changes made point. if toggle device mode can set network offline. same disconnecting device internet.

Copy/Paste line in Visual Studio 2015 seems broken -

Image
i use "copy/paste line" functionality of ctrl + c in visual studio (when nothing selected, copies entire line). in past versions, when pasted line, inserted above line cursor on, regardless of cursor on line. in visual studio 2015, seems broken or @ least non-deterministic. see screen capture below (note visual studio in "safe mode", started devenv.exe /safemode ): i'm ever pressing ctrl + c , ctrl + v , can see inserts copied line at cursor , inserts copied line above cursor . i've tried toggling option looks applies, text editor , all languages , apply cut or copy commands blank lines when there no selection , makes no difference. does else see behavior? i found possible solution/reason issue today. behavior more prevalent when have tightvnc connection window open, , after few hours of testing, have yet see problem when no vnc session open. this application monitors clipboard mouse , keyboard, it's possible doing interfer

coding style - return a conditional statement in javascript -

i have kind of method: function() { if (condition) { return true; } return false; } i thought of returning condition , make more clean, , maybe more readable. this: function() { return (condition); } is considered practice? if there no other code returning true/false yes, return condition. function() { return (condition); } just said, more readable, less code. wouldn't call practice, it's more first code bad practice.

version control - Git revert back to previous commit and keep committing new changes to master -

i'm on branch master, head pointing last commit on master , i'm wondering if following possible: revert previous commit b. move commits b (b excluded) new branch "experimental". after master's last commit should b , "experimental"'s last commit should a. make new commit c after b under branch master. after master's last commit should c all commits pushed origin, , working directory clean (no staged or unstaged changes). any guidance appreciated. git checkout -b experimental // create , switch branch "experimental" existing changes master. git push origin experimental // push "experimental" remote origin. git checkout master // switch branch "master" git reset --hard <commit> // bring head <commit> mentioned. also, remove uncommitted changes "master" git add <files> // add files committed "master" git commit -m "n

jquery - Why wont my div vertical-align? -

Image
i've literally metaphorically looked everywhere , still can't seem make work.. i programming on microsoft edge looked fine, , worked fine.. when uploaded , people started using chrome, firefox etc... this: here's code i'm using align it: position: relative; top: 50%; -webkit-transform: translatey(-50%); -ms-transform: translatey(-50%); transform: translatey(-50%); and here jsfiddle better overview of i'm doing: http://jsfiddle.net/wc1f8ewd/ (edit) click on cod logo or league logo see problem for vertical-align trick work, need specify height of container. add: .cod-main, .league-main { height: 100%; }

Create a spring boot application with multiple child contexts -

i'm trying create application using spring boot hierarchical application context. current main method looks like: public static void main(string[] args) { new springapplicationbuilder(testapplication.class) .child(auditserviceconfiguration.class).web(true) .child(taskserviceconfiguration.class).web(true) .run(args); } and 2 children configurations annotated with: @enableautoconfiguration @configuration the idea have parent context containing common beans , each child context run own mvc while being isolated siblings. unfortunately when run above, last child context initialised , started. any pointers in right direction appreciated. regards, alessandro the child(...) method creates , returns springapplicationbuilder , when call second child(...) method, not instantiating brother child, making child on first child, makes parent become grandpa . jokes aside, have @ sibling(...) method allows create context same

javascript - Execute a src script inserted with .innerHTML -

i'm working on blogger. have function (showmusic, takes json code parameter) show posts , i'm calling this: <script src='/feeds/posts/default/-/album/pop?max-results=20&orderby=published&alt=json-in-script&callback=showmusic'></script> i'm looking way change labels ("album" , "pop") <select> tags , need insert script innerhtml, script doesn't execute: function myfunction(label1,label2) { var label1 += "/"; var label2 += "/"; var script = "\x3cscript src='/feeds/posts/default/-/"+label1+label2+"?max-results=20&amp;orderby=published&amp;alt=json-in-script&amp;callback=showmusic'>\x3c/script>" document.getelementbyid("my-container").innerhtml = script; } try out: function myfunction( label1, label2 ) { var s = document.createelement( "script" ); s.type = "text/javascript"; s.asyn

python - Kivy, how to use datas in canvas -

Image
i've list of products , wanna display labels. know how fetch datas textinput wanna display list in canvas. how can ? edit: i have datas in 'global': products = [{'name' : 'coca' , 'price' : 1.8000},{'name' : 'fanta' , 'price' : 1.8000}] and want display in gridlayout 2 cols, x rows, 2 labels, 1 name , other price of fanta, coca , others ... <commandescreen>: gridlayout: rows: 4 cols: 2 button: text: 'coca' label: text: '1.80 euros' button: text: 'orangina' label: text: '1.80 euros' button: text: 'ajouter' button: text: 'quitter' on_press: root.manager.current = 'menu' a way go add in python code in class definition: from kivy.uix.label import label class commandescreen(screen): def _

iBeacon Trilateration and showing user's position on a map iOS -

i want build simple ios application ibeacons. i have 4 ibeacons , goal calculate room position doing trilateration. want show room on display, set fixed positions of ibeacons , calculate position , show on display. my problem is, don't know how start. even though ibeacons relatively simple use, trilateration done them far that. standard meant determining current location zone nearest beacon. zones are: immediate (0-0,5m), near (0,5-2m), far (2-20m). due instability of signal, difficult obtain more precise location data. that being said, there couple of companies know, have worked issue: estimote ( estimote indoor sdk ) , steerpath . maybe looking @ 2 solutions started project.

java - How do I return a JSON response message and an HTTP error code from javax.servlet.filter doFilter method? -

i have created servlet filter our application processes rest requests. have annotated web.xml , created filter. filter works well, returns json text message. need return 405 http status code. when perform tests, , 1 fails, have simple printwriter prints error message: public class myfilter implements filter { @override public void dofilter(servletrequest request, servletresponse response, filterchain chain) throws ioexception, servletexception { httpservletresponse apiresponse = (httpservletresponse) response; apiresponse.setcontenttype("application/json"); htmlout = apiresponse.getwriter(); mainerrorobject = new jsonobject(); if(true){ htmlout.println(mainerrorobject.tostring()); } htmlout.close(); } } so, said, how return both json text message , http error code? servletresponse implements httpservletresponse , has setstatus method, sets status code response. setstatus

bluetooth lowenergy - How to make my android app connectable to BLE headset? -

i'm working on android application acts ble peripheral (using nexus 9 able work ble peripheral) provides services , characteristics. i'm able interact , it's ok. how can make connectable ble headset now? can see headset ble profile enum value: http://developer.android.com/reference/android/bluetooth/bluetoothprofile.html#headset does mean need implement specific service, characteristics , specific logics support transferring sound ble headset? let's i'd record real-time audio , transfer in ble headset. how can stream sound real-time data ble headset?

Android: Why the layout changes when I delete the drawable-hdpi folder -

Image
i developing layout 320dp devices. have layout-sw320dp have following code displaying 6 imagebuttons. <android.support.v4.widget.drawerlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:elevation="4dp" > <!-- main content view --> <framelayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" > <gridlayout android:layout_width="match_parent" android:layout_height="match_parent" android:rowcount="3" android:columncount="2" android:paddingtop="10dp" android:paddingleft="@dimen/activity_horizontal_margin"> <i

javascript - chrome extension get source html not currentPage -

how can source https://google.com when i'm in http://example.com in chrome extension. read: getting source html of current page chrome extension html currentpage only. need html source url. thanks! use xmlhttprequest download whatever server responds when url accessed. on sites minipage script loader later render page in case loaded browser normally. to rendered source or dom tree of arbitrary url you'll have load in tab first. make process less distracting user load in pinned tab: chrome.tabs.create({url: "https://google.com", pinned: true}, function(tab) { .... wait tab load, source }); (the simplest form of waiting doesn't require additional permissions periodic checking of tab.status == "complete" invoked above callback, otherwise use webnavigation.oncompleted example or inject content script run-of-the-mill "domcontentloaded" or "load" event handlers). or load page in iframe sites forbid browser

how to ssh to a server without password when there is no .ssh on it -

i wanted setup passwordless login local machine linux server. when tried upload public key found there no .ssh on server. created 1 ssh-keygen on server. in newly generated .ssh directory, there no authorized_keys or known_hosts. made new authorized_keys , pasted public key local machine. not work, still need password ssh. can tell me if doing right? here output of ssh -vvv: debug1: authentications can continue: publickey,gssapi-with-mic,password,keyboard-interactive debug3: start over, passed different list publickey,gssapi-with-mic,password,keyboard-interactive debug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,password debug3: authmethod_lookup gssapi-with-mic debug3: remaining preferred: publickey,keyboard-interactive,password debug3: authmethod_is_enabled gssapi-with-mic debug1: next authentication method: gssapi-with-mic debug3: trying reverse map address . debug1: unspecified gss failure. minor code may provide more information credentials cac

soap - PHP SoapClient with BasicAuth -

i have php script trying connect wsdl. need allow self signed , give basic auth details. using soap ui, when connect wsdl prompted username / password. got working. i found out each request requires basic auth (so on request screen, have select auth, basic, enter same credentials used on prompt). how auth in php said, can connect, not problem, seem kill service or timeout if try make request <?php $context = stream_context_create(array( 'ssl' => array( 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true ) )); $data = array( 'columna' => 'dataa', 'columnb' => 'datab', 'columnc' => 'datac'); $url = 'https://111.111.111.111:1234/dir/file'; $login = 'username'; $pwd = 'password'; $client = new soapclient(null, array( 'location' => $url, 'uri' =>

javascript - how to stick my vertical scrollbar to bottom using onUpdate function in jQuery Scrollbar? -

$('.scrollbar-dynamic').scrollbar({ "onupdate": function (container) { container.animate({ scrolltop: $(container)[0].scrollheight }, "slow"); }, }); i using http://gromo.github.io/jquery.scrollbar/ plugin .. please me when use reinitialize size , scrolls top bottom .. want stick bottom on new items added

Installing Python on WIndows 10 64 bit -

i w trying install python on 64 bit windows 10 machine. downloaded latest python 2 release(following zed shaw's book, not installing python 3). after installation complete, entered python in power shell. following error. ps c:\> python python : python 2.7.10 (default, may 23 2015, 09:44:00) [msc v.1500 64 bit (amd64)] on win32 @ line:1 char:1 + python + ~~~~~~ + categoryinfo : notspecified: (python 2.7.10 (...md64)] on win32:string) [], remoteexception + fullyqualifiederrorid : nativecommanderror type "help", "copyright", "credits" or "license" more information. >>> the shell takes no more input. i'm forced use ctrl+c. know extremely basic cant seem figure out googling error. are environment variables set correctly? see following post user had similar issue: i'm trying use python in powershell try typing in powershell console well: [environment]::setenvironmentvariable("path"

python - How to populate a django database with users -

i want populate django database using manage.py loaddata initial_data.json json file contains specifications of several objects. problem these object have 'user' attribute referencing django user object, indicate user created them. model these objects looks this: from django.db import models django.contrib.auth.models import user class myspecialmodel(models.model): name = models.charfield(max_length=200) user = models.foreignkey(user) the objects in json this: [{"fields":{ "name": "some name", "user": xxx } ...] the problem don't know write in place of xxx indicate user. have tried user names django tells me expects number xxx are. using number not produce bug don't see database populated. there way place django object in initial_data.json file ? you should write user.pk there, integer value. [{"fields":{ "name": "some name"

How to add disqus to Ionic app? -

Image
i'm new ionic framework, , created simple side-menu app , want add disqus comments it. how code looks like: i add srcipt <head> in index.html : <script type="text/javascript"> /* * * configuration variables: edit before pasting webpage * * */ var disqus_shortname = '<hooligansapp>'; // required - replace '<example>' forum shortname /* * * don't edit below line * * */ (function() { var dsq = document.createelement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getelementsbytagname('head')[0] || document.getelementsbytagname('body')[0]).appendchild(dsq); })(); and template: <ion-view view-title="comments"> <ion-content> <div id="disqus_thread"></div> </ion-content> </ion-view> and nothing happend :( so, how

c++ - Can I get all instances of some class in Qt? -

i have implemented qabstractitemmodel , qsortfilterproxymodel source model. have 1 itemmodel instance , several filtermodel instances. in each filtermodel have variable value of calculated based on filtered data itemmodel . when itemmodel recreated (all items removed , new ones inserted back) value of variable should set default (or recalculated after filtering done). the problem don't have list of pointers filtermodel instances iterate them. sure can create such static list in constructor. moc did instead of me , saved such list inside of qmetaobject of class? your filter proxy implementation broken. proxies informed of each , every change model - that's why models qobject s , emit change signals! there's nothing preventing changing "some variable" appropriate, when source model indicates has changed. you need think of "some variable" depending on data (and structure!) source model. every time source model indicates changes depe

mysql - Issue with sql query in GO -

i have simple mysql table, 3 columns, a, b , c. a , b keys. i have go app , i'm trying retrieve data db. other queries works charm, 1 doesn't: aparam := "avalue" bparam := "3,4,6,9" stmt, err := o.database.prepare("select * tablex `a`= ? , `b` in ( ? )") defer stmt.close() rows, err := stmt.query(aparam, bparam) rows.next() { ... } if replace second ? values, works perfect: stmt, err := o.database.prepare("select * tablex `a`= ? , `b` in ( 3,4,6,9 )") i tried (it doesn't work): stmt, err := o.database.prepare("select * tablex `a`= ? , `b` in ( " + bparam +" )") any idea? the issue single ? not expanded select statement (like string replace), single string value 3,4,5,6 you need expand each value of in clause such: params := []interface{} { "avalue", 3, 4, 6, 9 } stmt, err := o.database.prepare("select * tablex `a`= ? , `b` in ( ?, ?, ?, ? )") defer stmt.close(

javascript - Change MongoDB find results dynamically -

i'm using mongoose node.js. let's have 'posts' db each document in post. each post has 'readby' array holds names of users had read post. when i'm searching documents in db, want "change" 'readby' value show boolean value if user searching in array or not. for example, let's these 2 documents in db: { "postname": "post number 1", "readby": ["tom", "john", "adam"] } { "postname": "post number 2", "readby": ["john", "adam"] } if i'm user 'tom', want results this: [ { "postname": "post number 1", "readby": true, }, { "postname": "post number 2", "readby": false, } ] now, know can documents , go on each 1 of them foreach function, , use foreach again on "readby" array , change field. i

android - picked image as background in image button and convert to byte -

i need upload image in parse picked gallery. use imagebutton call de intent , show image picked , working. public class datos extends activity implements onitemselectedlistener { private final int select_photo = 1; private imagebutton imageview; byte [] data; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); requestwindowfeature(window.feature_no_title); setcontentview(r.layout.activity_datos); btnclick(); imagebutton pickimage = (imagebutton) findviewbyid(r.id.imagebutton); pickimage.setonclicklistener(new onclicklistener() { @override public void onclick(view view) { intent photopickerintent = new intent(intent.action_pick); photopickerintent.settype("image/*"); startactivityforresult(photopickerintent, select_photo); } }); } @override protected void onactivityresult(int requestcode, int resultcode, intent imagereturnedintent) {

vba - Sorting of a calculated field fails when using report within a form in Access -

i have report code sort on calculated column, when user clicks label report sorted, here's code: private sub label44_click() if me.orderby = "iif([sumofcurrentpricevol]<>0,([sumofofferedpricevolume]-[sumofcurrentpricevol])/[sumofcurrentpricevol],0) desc" me.orderby = "iif([sumofcurrentpricevol]<>0,([sumofofferedpricevolume]-[sumofcurrentpricevol])/[sumofcurrentpricevol],0) asc" else me.orderby = "iif([sumofcurrentpricevol]<>0,([sumofofferedpricevolume]-[sumofcurrentpricevol])/[sumofcurrentpricevol],0) desc" end if me.orderbyon = true end sub when use report works fine. if put report inside of form following error message: "run-time error '5': invalid procedure call or argument" at me.orderbyon = true i tried changing me report , same results. idea of may failing? i able re-create issue. it's not complicated calculation may want add recordsource. re-created simple sort of sing

objective c - How to dynamically update an NSTreeController and NSOutlineView? -

when outlineviewitem expanded - (void) outlineviewitemdidexpand:(nsnotification *)notification -, i'm able add object treecontroller (log statements show newly added object in correct place of hierarchy), outlineview/ui isn't updating reflect insertion. to no avail, i've used [self.outlineview reloaditem:nil reloadchildren:yes] , [self.outlineview reloaddata] , , [self.outlineview sethidden:yes] then [self.outlineview sethidden:no] to try force reload structure. this done programmatically in objective-c. 6 hours later, got it. i needed update nstreecontroller cache, achieved via rearrangeobjects method. so answer question is: [self.clouddirectorytreecontroller rearrangeobjects];

javascript - $q.all() in angular does not resolve well -

i doing 3 $http calls in factory , in troubles. i declare 4 promises: var promise = $q.defer(), pbdeferred = $q.defer(), rdeferred = $q.defer(), pdeferred = $q.defer(); after first call api $http.get('/pendingbills').then(function(response) { var pendingbills = ['id', 'path', 'reservas', 'importe', 'fecha']; pbdeferred.resolve(pendingbills); }); and resolve last 2 promises empty array (i have not endopoint yet) rdeferred.resolve([]); pdeferred.resolve([]); there use $q.all $q.all([pbdeferred, rdeferred, pdeferred]).then(function (results){ console.log('results', results); promise.resolve({ pendingbills: results[0], remittances: results[1], payed: results[2] }); }); and return higth level promise return promise.promise; the console log shows promises thougth in there point promises resolved. some idea fix this? you not using promises correctly, use d

javascript - Prev and Next buttons switch images (links to images) in array??? -

these instructions: "have image , 2 buttons, prev , next. have 10 images in array. when click on next, next picture should display , when click on prev, previous image should display." this wrote far: <html> <head> <title>image loop</title> </head> <body> <img src="http://placekitten.com/500/200" id="image" style="height:150px; width:150px" /> <input type="button" value="prev" name="previous_picture" onclick= nextimage();> <input type="button" value="next" name="next_picture"/> <script> function nextimage () { var = images.indexof(); var imagesrc = document.getelementbyid("image").src=images[i]; (i = weekdays.indexof(day); i<weekdays.length; i++) } function previmage () { } var images = new array(

c - What ensures reads/writes of operands occurs at desired timed with extended ASM? -

according gcc's extended asm , assembler template , keep instructions consecutive, must in same asm block. i'm having trouble understanding provides scheduling or timings of reads , writes operands in block multiple statements. as example, ebx or rbx needs preserved when using cpuid because, according abi, caller owns it. there open questions respect use of ebx , rbx , want preserve unconditionally (its requirement). 3 instructions need encoded single asm block ensure consecutive-ness of instructions (re: assembler template discussed in first paragraph): unsigned int __func = 1, __subfunc = 0; unsigned int __eax, __ebx, __ecx, __edx; __asm__ __volatile__ ( "push %ebx;" "cpuid;" "pop %ebx" : "=a"(__eax), "=b"(__ebx), "=c"(__ecx), "=d"(__edx) : "a"(__func), "c"(__subfunc) ); if expression representing operands interpreted @ wrong point in time, __ebx saved ebx (a

c++ - Debugging with Resharper 9 and Visual Studio 2013 -

i use newest build of resharper (9.3) , resharper c++ visual studio 2013. code editing, refactoring, ... works great. if try debug code, weird error: an empty window "source not available. current thread not running code or call stack not obtained". which makes debugging quite difficult. i think problem related resharper, because problem did not occur before installed resharper nor problem occur if resharper disabled. is there solution problem or tool similar capabilities can used instead? latest version 9.2 , bug should reported jetbrains

arrays - Removing letters from a string and only retaining numbers -

i have array arr in haml, inside loop. - item.each |grp, arr = []| - grp.section.each {|abc| arr.push(abc.values_with_units) } for each iteration, values , units of them change. might ["23 mm", "34 mm", "56 mm"] , in next iteration might ["25 km/s m", "32 km/s m", "12 km/s m"] . want rid of units , retain values: in case 1 [23,34,56] , , in case 2 [25, 32, 12] . how can achieve in ruby? to_i ignores after numbers can following. array = ['23 mm', '34 mm', '56 mm'] array.map(&:to_i) # [23, 34, 56] array = ['25 km/s m', '32 km/s m', '12 km/s m'] array.map(&:to_i) # [25, 32, 12]

string - C# Map all possible characters to the alphabet -

i'm trying map possible letters letters a-z, # numbers , maybe & other characters. i'm using normalize(normalizationform) method. gets rid of of unwanted characters characters accents , on. however doesn't deal duplicates. seems letter m located in more 1 position , therefore equal-check fails. here's code checks every possible letter: for (uint = char.minvalue; <= char.maxvalue; i++) { char normalizedchar = char.toupper($"{(char)i}".normalize(system.text.normalizationform.formkd).firstordefault()); if (char.isletter((char)i) && !allowedletters.contains(normalizedchar)) throw new exception(); } where allowedletters char array containing letters of alphabet , '#'. it fails @ = 181 normalized 924 = 'm' 77 = 'm'. i'm open better ways normalize character since method find works on strings. the normalizationform msdn page explicitly warns this: some unicode sequences consider

Rails 4 Update Active Record with JSON data from AJAX -

i've spent time looking around there not seem answer question. appreciated. i'm sending json data ajax call rails app (no cors). javascript: $.ajax({ type: "post", url: "/tasks/", data: json.stringify(res), datatype: "json", async: true }); the json data (res) copied browser console: [{"task_id":"9","grid_position":[0,2,2,2,false]},{"task_id":"8","grid_position":[0,0,2,2,false]}]: so far good. this gets sent via route: resources :tasks, only: [:index, :update, :create, :destroy] to tasks controller, trying reach update action: def update @task = task.find(params[:id]) respond_to :html, :json if @task.update_attributes(task_params) flash[:success] = "task updated" redirect_to @user else flash[:error] = "task not saved! please see guidance form labels"

Selenium WebDriver Java Maven input date with sendkeys isn't working -

i'm trying input date date field has calendar plugin every reservation site has. here's code: webelement checkin = driver.findelement(by.id("check-in")); checkin.sendkeys("08/31/15"); webelement checkout = driver.findelement(by.id("check-out")); checkout.sendkeys("09/06/15"); this isn't inputting date when run script. date format correct. doing wrong? how fix this? one thing might want try run javascript snippet through webdriver instance change input's value. this: ((javascriptexecutor) driver).executescript("$('#check-in').prop('value', '08/31/15');");

c# - Hiding ItemTemplate Controls within Formview -

currently code hiding panel (s) contained within itemtemplate of formview dependent on users role(s). the current solution: ((panel)formview1.findcontrol("pnlisadmin")).visible = isadmin; the problem code can't run until formview has been completed .databind(); now don't know formviews, surely there's way me hide controls such panel above in better place, , not dependent on .databind(); ( on page load )?? thanks information. i don't mixing code-behind & display pages, wrap control in server tags: <% if(isadmin){ %> <asp:panel id="pnlisadmin" runat="server"></asp:panel> <% } %>

how to create a join feature in php with a mySQL database -

hello im new php scenario this: i have created login/logout feature , event page, on event page, there join button next each event. i want decrease int value (expected number of people) in mysql database when user clicks join button. how go doing this? problem not know how associate each button corresponding event. the events dynamically created other users. the following javascript within tags $("button").click(function() { var id = $(this).attr('id'); var request = $.ajax({ url: "decrease.php", method: "post", data: { id : id }, }); request.done(function( msg ) { $( "#log" ).html( msg ); }); request.fail(function( jqxhr, textstatus ) { alert( "request failed: " + textstatus ); }); }); }); the following file decrease.php: define(&

java - Persisting Full Data Binding POJO to Database -

i have converted json response pojo , following concept of full data binding . pojo looks this public class user { public name _name; @jsoncreator public user(@jsonproperty("_name") name _name,){ this._name=_name; } public static final class name { public string _first; public gender _gender; @jsoncreator public name(@jsonproperty("_first") string _first,@jsonproperty("_gender") gender _gender){ this._first = _first; this._gender = _gender; } public static final class gender { public string age; public gender(@jsonproperty("age") string age){ this.age=age; } } } } now need persist pojo , not sure how should efficiently, have consider using hibernate unaware how proceed. how fields annotated in case use hibernate, since complex pojo . is there way use jdbc

Python - merging two 2D lists, overwriting values of one -

i have two, 2 dimensional lists list 1 = [[none, none], [none, none], [none, none]] list 2 = [[1, 2], [3, 4]] the desired output is list 3 = [[1, 2], [3, 4], [none, none]] in case there simpler solution, i'm doing because don't have data third element in list. need list have 3 first level items. i'm trying stop script throwing out of range error. some additional context address below questions. this comes in app when database query returns result put list, e.g. 'biggest 10 problems'. things aren't bad, , there 9 problems. when part of application looks 10th problem (a flask website), throws error. try/except indeed work, pretty heavy. so need solution can create list of placeholder values, , overwrite them data if available. the accepted solution works great 1 line of code. i think meant list_3 = [ list_2[i] if < len(list_2) else e i,e in enumerate(list_1) ] here equivalent without list comprehension list_3 = list() i,e i

Copy all files and folders except few in Ruby -

i wondering if can use fileutils.cp_r method copy files , directories source target except .tar files. can give me example better understanding? thanks sure you'd have implement kind of filter first this: [8] pry(main)> dir.glob("**/*") => ["bin", "code_of_conduct.md", "gemfile", "gemfile.lock", "hello.tar", "lib", "license.txt", "mygem.gemspec", "rakefile", "readme.md", "spec"] that gave files in directory , subsequent directories(thanks ndn tip), let's filter out hello.tar : files = dir.glob("**/*").reject { |file| file.end_with?(".tar") } now can pass array filteutils::cp_r fileutils.cp_r(files, destination)

git - How to list all releases of public repository with GitHub API V3 -

so per documentation https://developer.github.com/v3/repos/releases/#list-releases-for-a-repository get /repos/:owner/:repo/releases should list relases , https://api.github.com/repos/jquery/jquery/releases should list releases in jquery project , not , why ? because repository doesn't have releases. has tags github presenting in releases page. for more clear example, see: https://github.com/hashicorp/terraform/releases which has both releases , tags showing on page, api shows releases: https://api.github.com/repos/hashicorp/terraform/releases

regex - Regexp match all between parenthesis. -

i have following snippet of text: @article{carr2006, title={techniques qualitative , quantitative measurement of aspects of laser-induced damage important laser beam propagation}, author={carr, cw , feit, md , nostrand, mc , adams, jj}, journal={meas. sci. technol.}, volume={17}, number={7}, pages={1958}, year={2006}, publisher={iop publishing} } @article{nif1998, author = {schwartz, sheldon , feit, michael d. , kozlowski, mark r. , mouser, ron p.}, title = {current 3-ω large optic test procedures , data analysis quality assurance of national ignition facility optics}, journal = {proc. spie}, volume = {3578}, number = {}, pages = {314-321}, year = {1999}, } and i've been trying extract article it's tag, fail understand how greedy/non-greedy works, or rather how capture in brackets when contains more brackets :/ the following regexp returns result until first brackets, not i'm aiming for... /\{(carr2006[^}]+)\}?/s also trying capture full text

arduino - Using a distance sensor in Processing to control the attributes of shapes -

i'm trying make program use readings gets distance sensor control attributes of circles (size, xy , colour). i'm trying make record current value , apply value when press relevant key (eg. press 's' , changes size whatever distance @ point). - ideally i'd circle change whatever field next dynamically move hand on sensor, seems bit beyond me. i've tried as can, i'm not sure of i've commented out. tips or advice? i'm not sure i'm doing when comes classes , constructors. edit: when run code, nothing happens. import processing.serial.*; int xpos, ypos, s, r, g, b; circle circle; int shapesize, distance; string comportstring; serial myport; void setup(){ size(displaywidth,displayheight); //use entire screen size. //open serial port communication arduino myport = new serial(this, "/dev/cu.usbmodem1411", 9600); myport.bufferuntil('\n'); // trigger serialevent on new line } void draw(){ background(0); delay(50); //del

assembly - Using EMU8086, is there a direct way to print a variable's hex value? -

i'm using emu8086 on windows 7 hp x64, intel i3-2330m pc. i have spent 2 weeks researching , tinkering assembly language program in effort print hex value of integer entered user. have found nothing directly printing value memory location. can, if necessary, write code string conversion hex. however, attempting avoid lines of code this. (i think called optimizing.) my research has lead me comment on site corbin says: very unpleasantly. you'll have determine value of decimal string ("100"), make new string same value in hex ("0x64"). it's same algorithm use conversion in head; it's bit more complicated since have deal ascii encoding on top of things. none of has directed me manner in desire perform task. i have written , tested code incrementally, receiving desired results. watching variable , viewing cx register, can confirm values values want print. i including code here. ugly , over-commented. commenting benefit me lear

Python Django - form.is_valid() keeps throwing unicode object has no attribute get error -

i creating form custom user type. each time submit form test it, returns error says unicode object has no attribute error. forms.py: class registrationform(forms.modelform): """ form registering new account. """ password1 = forms.charfield(widget=forms.passwordinput, label="password") password2 = forms.charfield(widget=forms.passwordinput, label="password (again)") class meta: model = student fields = ('firstname', 'lastname', 'email', 'password1', 'password2', 'is_second_year') def clean(self): # check 2 password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 , password2 , password1 != password2: raise forms.validationerror("password

Python Gaussian Kernel density calculate score for new values -

Image
this code: import numpy np scipy.stats.kde import gaussian_kde scipy.stats import norm numpy import linspace,hstack pylab import plot,show,hist import re import json attribute_file="path" attribute_values = [line.rstrip('\n') line in open(attribute_file)] obs=[] #assume list obs loaded obs=np.asarray(osservazioni) obs=np.sort(obs,kind='mergesort') x_min=osservazioni[0] x_max=osservazioni[len(obs)-1] # obtaining pdf (my_pdf function!) my_pdf = gaussian_kde(obs) # plotting result x = linspace(0,x_max,1000) plot(x,my_pdf(x),'r') # distribution function hist(obs,normed=1,alpha=.3) # histogram show() new_values = np.asarray([-1, 0, 2, 3, 4, 5, 768])[:, np.newaxis] e in new_values: print (str(e)+" - "+str(my_pdf(e)*100*2)) problem: obs array contains list of obs. need calcolate score (between 0 , 1) new values [-1, 0, 2, 3, 4, 500, 768] so value -1 must have discrete score because doesn't appears in distributio