Posts

Showing posts from May, 2014

jquery - Javascript Inheritance Best Strategy -

currently have built our own javascript framework building widgets, divs, panels , forms our complex web application. our widgets (aka. components) inherit super object called viewable defines view htmlelememnt . viewable = { getview: function() { if (!this.view) this.view = this.createview(); return this.view; } createview: function() { alert(‘you have not implemented createview. naughty boy!); } } then use object.create(viewable) create our own components, need implement createview defined in viewable. header = object.create(viewable); header.createview = function() { var div = document.createelement('div'); div.id = 'header'; } header.foobar = function() { } i move away type of inheritance, create-object-on-the-fly , add methods on depending on mood. i have looked @ other approach using $.extends jquery. can create object (or better ‘define function’? ‘defined class’?) function header() ...

java - File.createTempFile check if file exists? -

if use method, , chance there temporary file same name, file overwritten? i'm talking application generate many temporary files, long time. from javadoc on createtempfile ( here ) on line labeled 2 , neither method nor of variants return same abstract pathname again in current invocation of virtual machine. edit and returns section says an abstract pathname denoting newly-created empty file and, further states creates new empty file in specified directory, using given prefix , suffix strings generate name. if method returns guaranteed that: file denoted returned abstract pathname did not exist before method invoked

python - Concatenation of two columns into one rounds float -

i've got 2 dataframes want concat. both have same column , of different dtypes. 1 float, other string. want concat these columns while keeping granularity of float column. see below example: import pandas pd df1 = pd.dataframe.from_dict({'row1':124.028125},orient='index') df2 = pd.dataframe.from_dict({'row2':'hello'},orient='index') df_ = pd.concat([df1,df2]) the df_ variable displayed as df_ 0 row1 124.0281 row2 hello basically how can concat these while keeping 124.028125 value row1? thanks guys! data not lost, not displayed sake of clarity. if 1 access df_[0]['row1'] one gets 124.028125

sql server - Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException -

i'm trying connect java application sql server 2012, giving me error: exception in thread "awt-eventqueue-0" java.lang.classcastexception: com.microsoft.sqlserver.jdbc.sqlserverconnection cannot cast com.mysql.jdbc.connection can can me please? thank much. code of connection: import java.sql.connection; import java.sql.drivermanager; import java.sql.sqlexception; public class criaconexao { public static connection getconexao()throws sqlexception{ try{ class.forname("com.microsoft.sqlserver.jdbc.sqlserverdriver"); string dburl = "jdbc:sqlserver://brgdb:1433;database=db_sql;integratedsecurity=true"; connection conexao = drivermanager.getconnection(dburl); return conexao; }catch(exception e) { e.printstacktrace(); return null; } } } error: exception in thread "awt-eventqueue-0" java.lang.classcastexception: com.microsoft.sqlserver.jdbc.sqlserverco...

hbase custom filter not working -

i'm trying create custom filter on hbase 0.98.1 in standalone mode on ubuntu 14.04. i created class extending filterbase. put jar in hbase_home/lib. looking in logs, see jar in path. then have java client first makes columnprfixfilter, makes custom filter. columnprefixfilter works fine. filter, nothing happens. client freeze 10 minutes , close connexion. i don't see thing in log. could please give me hint on , check ? regards, edit: turns out protc vesrion conflict. generated java class form proto file protoc 2.4.0 , in filter using protobuf-java 2.5.0 aligned 2.5.0 , it's working fine.

Struggling with formatting an HTML newsletter -

Image
i've been trying compose newsletter institute out, don't have extensive experience in using html. told need use online template designing newsletter, based in everlytic (the mass-mail sending service), after formatting , sending preview myself, found table not display should. reason, after columns, few empty cells show not show in wysiwyg editor. know they're not reliable, still. i've poked around html, can't figure out seems wrong? suspect amount of columns table assigned use blame, uncertain. i've included html of newsletter until past point problem occurs. <html> <head> <title></title> </head> <body> <style type="text/css"><!-- .grey { color: #666; } --></style> <table border="0" cellpadding="0" cellspacing="0" class="grey" width="704"> <tbody> <tr> <td valign="top...

php - Replace in one step based on matched result -

i have string , want each yyyy-mm-dd hh:mm:ss date time string replaced unix timestamp. i have managed far identifying date time strings occur: $my_string = 'hello world 2014-12-25 10:00:00 , foo 2014-09-10 05:00:00, bar'; preg_match_all('((?:2|1)\\d{3}(?:-|\\/)(?:(?:0[1-9])|(?:1[0-2]))(?:-|\\/)(?:(?:0[1-9])|(?:[1-2][0-9])|(?:3[0-1]))(?:t|\\s)(?:(?:[0-1][0-9])|(?:2[0-3])):(?:[0-5][0-9]):(?:[0-5][0-9]))',$my_string,$my_matches, preg_offset_capture); print_r($my_matches); this outputs array of arrays containing value of date time string matched , location: array ( [0] => array ( [0] => array ( [0] => 2014-12-25 10:00:00 [1] => 12 ) [1] => array ( [0] => 2014-09-10 05:00:00 [1] => 40 ) ) ) from point going loop through arrays , replace based on str...

Returning non-unique rows without group by in SQL Server -

i have dig though data in few columns tables find non-distinct rows based off name column , because each table has lots of columns (all on 50) i don't want use group because of requirement explicitly declare every single column. is there way of finding non-distinct rows allow using select * ? if single table fin typing out column names right have 4 different tables go through , see me having go though many more run same process. use window functions, in case, count(*) : select t.* (select t.*, count(*) on (partition name) namecnt table t ) t namecnt > 1;

c# - What is the convention for defining values for enum flags? -

let's have following code: [flags] enum myflags { none = 0, = 1, b = 2, c = 4, d = 8, e = 16, // ... } this not going optimal when amount of flags grow large. , optimal, mean readable, not fast or memory saving. for combined flags, such as ab = 3 we can use ab = | b instead, more readable. , combining flags all = | b | c | ... it more favorable use all = ~none instead, if don't make full use of 32/64 bits available. but regular values? between e = 16 e = 0b10000 e = 0x10 e = 1 << 4 or other ways haven't thought of, best suited large amount of flags? or in other words, (agreed upon) convention setting values flags in c#? let assume sake of argument, values not aligned, code might this none = 0, apple = 1, banana = 2, strangefruit = apple | banana, cherry = 4, date = 8, elderberry = 16, // ... for regular values, 1 << n : after you've taken (short) time understand it, it's easy ...

c# - index out of range exception when using tasks -

i getting "index out of range" exception when using async tasks on array list. checked on stackoverflow , try different ways none of them working. maybe missing something... can please suggest. task[] datatasks = (from eachrow in ppcrowscollection.rows select createdatarows(eachrow, subctablearray, rowsarraywithdefaultandcommonvalues)).toarray(); private async task<datarow[]> createdatarows(ppcrow givenppcrow, datatable[] subctablearray, datarow[] rowsarraywithdefaultandcommonvalues) { return await task.run(() => { datatable[] subctablearraylocal = subctablearray; datarow[] defaultrowsarray = getrowsarraywithdefaultandcommonvalues(ref subctablearraylocal, ref rowsarraywithdefaultandcommonvalues); setotherthancommoncolumnvalues(ref defaultrowsarray, givenppcrow); return defaultrowsarray; } ).configureawait(false); } private datarow[] getrowsarraywithdefaultandcommonvalues(ref d...

unity3d - RaycastHit Randomly Gets 2 Hits -

i've been following tutorial online while , far gone pretty well. problem have raycasthit. @ first glance seems working pretty well, every , seems if 2 hits. have set every time press mouse button, animation go off player swinging club , ray sent player(actually gameobject parented first person camera) enemy. instead of gameobject being destroyed in 2 hits, every , then, destroyed in one. #pragma strict var thedamage : int = 50; var distance : float; var maxdistance : float = 1.5; var thesystem : transform; function update () { if(input.getbuttondown("fire1")) { animation.play("attack"); } } function attackdamage () { var hit : raycasthit; if(physics.raycast (thesystem.transform.position, thesystem.transform.transformdirection(vector3.forward),hit)) { distance = hit.distance; } if (distance < maxdistance) { enemy...

java - Android - Google Play Service throw IllegalStateException complaining about size and ad unit id -

since replaced admob library google play service library, android app triggers following exception java.lang.runtimeexception: unable start activity componentinfo{com.xxx.xxx/com.xxx.xxx.ui.activity.feedactivity}: java.lang.illegalstateexception: ad size , ad unit id must set before loadad called. @ android.app.activitythread.performlaunchactivity(activitythread.java:2328) @ android.app.activitythread.handlelaunchactivity(activitythread.java:2386) @ android.app.activitythread.access$900(activitythread.java:169) @ android.app.activitythread$h.handlemessage(activitythread.java:1277) @ android.os.handler.dispatchmessage(handler.java:102) @ android.os.looper.loop(looper.java:136) @ android.app.activitythread.main(activitythread.java:5476) @ java.lang.reflect.method.invokenative(native method) @ java.lang.reflect.method.invoke(method.java:515) @ com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:1268) @ com.android.internal.os.zygoteinit.main(zygoteinit.java:10...

html - Render a 'static' container inside a form_for block -

i creating application form , wanting embed/render long text(static html)page "inside" form scrolling container. i've saved partial in /app/views/layouts directory _membershipagreementv_1.html.erb the partial renders fine outside of form_for block when inside page/form fails load. snippet partial _membershipagreementv_1.html.erb <div class="membershipagreement"> <div class="container"> <div style="height: 400px; overflow: auto; padding: 5px"> <h2>eligibility , membership.</h2> (lllloooonnnggggg long put in form imo) . . . snippet new_app view <div class="row"> <div class="span6 offset3"> <%= form_for (@member), :url => {:action => "approve"}, :html => {:method => "put"} |f| %> . . . <%= f.label :email, "email address" %> ...

excel - Reference a check box in another open workbook -

i trying refer value of activex checkbox control in worksheet. goal make value of check box in current workbook same 1 in open workbook. i can between 2 checkboxes in same workbook on different sheets: private sub commandbutton1_click() if sheets("sheet2").box2.value = true box1.value = true else: box1.value = false end if end sub but i'm receiving run-time error '9' "subscript out of range" error when run following code: private sub commandbutton2_click() if worksheets("book2").oleobjects("box3").value = true box1.value = true else: box1.value = false end if end sub the "if worksheets" line highlighted when try debug code. i'm sure i'm referring other checkbox incorrectly, i've searched high , low proper way refer without luck. thank in advance help! if worksheets("book2").oleobjects("box3").value = true "book2" not name of worksheet, presumably...

r - Maptools: Plotting different geographic groups with different colors -

i have dataset biological groups , geographic information: results2 id latitude longitude -3,5 -39,5833 -7,0167 -37,9667 -9,2258 -43,4631 b -16,6667 -49,5 b -15,4333 -55,75 b -19,0333 -57,2167 c -29,2 -58,1 c -30 -59,5167 c -34,5667 -59,1167 i used maptools plotting these points on map, here code: xlim<-c(min(results2$longitude),max(results2$longitude)) ylim<-c(min(results2$latitude),max(results2$latitude)) readshapelines("americas_adm0.shp") -> shape plot(shape, xlim=xlim, ylim=ylim) par(new=true) ## vamos aqui!! pontos<- data.frame(results2$longitude,results2$latitude) colnames(pontos)=c("longitude","latitude") points(pontos$longitude, pontos$latitude, pch=16, col=2, cex=1) but dont know how delimit polygons each group, , change color options of studied groups. i'm not sure understand mean "the polygons of each group" ? perhaps refering known " ...

node.js - Upload blobs with metadata, node -

how go uploading blob metadata azure in node? have: blobservice.createblockblobfromtext(containername, function(error) { //what go in here? }); i see there link set blob metadata, can't interpret means. does know if it's possible set blob metadata in node? try code. creates blob in blob container using createblockblobfromtext method , sets 2 metadata items blob: var azure = require('azure'); testblobupload('testcontainer'); function testblobupload(containername) { var blobservice = azure.createblobservice('usedevelopmentstorage=true'); // error occurred @ line blobservice.createcontainerifnotexists(containername, {publicaccesslevel : 'blob'}, function(error){ if(!error) { console.log("container created successfully."); blobservice.createblockblobfromtext(containername, 'simplefile.txt', 'sample content', { metadata: { ...

c# - Get a subsection from XML -

i have followign xml: <validationobject> <role name='pm front end'> <filesystem> <directory path='c:\deleteme\hashingtest\main' validateentirefolder='true'> <file path='c:\deleteme\hashingtest\main\1.txt' hashvalue='-1109720489'/> <file path='c:\deleteme\hashingtest\main\2.txt' hashvalue='824588598'/> <file path='c:\deleteme\hashingtest\main\3.txt' hashvalue='-1033034397'/> <directory path='c:\deleteme\hashingtest\main\sub1'> <file path='c:\deleteme\hashingtest\main\sub1\sub1-1.txt' hashvalue='-1443348279'/> <file path='c:\deleteme\hashingtest\main\sub1\sub1-2.txt' hashvalue='-666832362'/> </directory> </directory> <!--only 2 file selected validation purposes in following folder--> <directory path='c:\deleteme\hashingtest\s...

list - Having trouble with predicate in Prolog -

i trying right predicate in prolog accepts item, list, , number, , checks see if item in list number of times. example count(7,[3,7],x). would return x=1 . count(7,[3,7],1). would return true this have far count_occur(a,[0|b],d). count_occur(a,[a|c],d) :- count_occur(a,c,d1), d d1+1. count_occur(a,[b|c],d) :- count_occur(a,c,d). i new prolog , struggling understand programming paradigm. what trying see if first item in list matches passed-in value (a), if increment d , check again against remainder of list. how in lisp or language anyway. use help, been @ while , isn't clicking me. i don't have prolog right test it, try that: count_occur(a, [], 0). count_occur(a, [a|t], d):- count_occur(a, t, d1), d d1 + 1. count_occur(a, [b|t], d):- \= b, count_occur(a, t, d). the idea if list empty, there 0 occurrences of each element. rest same yours think correct. the difference have added a \= b , should mean a \neq b . think otherwise accept a == b , mig...

installing ruby with rbenv error: ld: warning: directory not found for option -

i'm trying install ruby 2.0.0-p247 rbenv build keeps failing. did work before: $ rbenv versions system 2.0.0-p195 2.0.0-p353 * 2.1.0 (set /users/nemo/.ruby-version) i looked @ using rbenv install throws error , tried suggestion didn't i tried following before trying install sudo rm -rf /var/folders/yt/5nww85g11gdgqcz4tcl1dndc0000gn/t/* sudo rm -rf /tmp/ruby* $ brew update up-to-date. $ brew doctor system ready brew. $ gcc --version configured with: --prefix=/library/developer/commandlinetools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 apple llvm version 5.1 (clang-503.0.40) (based on llvm 3.4svn) target: x86_64-apple-darwin13.1.0 thread model: posix $ sudo rbenv install 2.0.0-p451 last 10 log lines: installing default openssl libraries linking shared-object dl/callback.bundle ld: warning: directory not found option '-l/users/nemo/.rbenv/versions/2.0.0-p451/lib' linking shared-object openssl.bundle ld: warning: directory not found optio...

html - How to animate my element in my case? -

i want create animation using angular js i have html <ul ng-click="expandmenu =!expandmenu; mycss='expand'"> <li id='unit-btn' ng-class='mycss'> </li> <li id='lesson-btn' ng-class='mycss'> </li> <li id='day-btn' class='tree-nav-btn'> </li> </ul> css .expand{ -webkit-animation: openmenu 5s; } @-webkit-keyframes openmenu{ {width: 100px;} {width: 200px;} } i able expand li 200px need collapse menu 100px after user clicks again. how accomplish it? help try classes angular uses ng-show ng-hide directives when element closing: .my-element.ng-hide-add { ... } when elements opening: .my-element.ng-hide-remove { ... } so can turn that: .expand.ng-hide-remove { -webkit-animation: openmenu 5s; } .expand.ng-hide-add { -webkit-animation: closeme...

javascript - HTML tag in scope of angularjs -

i need put <br /> tag in $scope.mytext in controller, how ? something $sce.trustashtml("<br />") should work. $sce.trustashtml() returns string safe use ng-bind-html . can read more here $sce.trustashtml vs. ng-bind-html

Inheritance for controller and service classes in a spring project -

in current spring project, controller , service classes have similar structures. want create base class both of them, used base other controller , service classes. can tell me if possible? the basic structure classes (the term <> vary): controller @controller @requestmapping(value="<<name>>") public class <<name>>controler { @autowired private <<name>>service <<name>>; @requestmapping(value="cadastra.htm", method=requestmethod.post) @responsebody @preauthorize("haspermission(#user, 'cadastra_<<name>>')") public string cadastra(httpservletrequest request, httpservletresponse response) { if(<<name>>.cadastra(request, response)) return "yes"; else return "not"; } @requestmapping(value="altera.htm", method=requestmethod.post) @responsebody @preauthorize(...

Starting wrong activity on Android -

all, trying understand why simple code this: device.setphoto( bmp ); intent intent = new intent( context, sexselector.class ); intent.putextra( "device", device ); startactivity( intent ); does not start "sexselector" activity, goes first activity of application. i have minsdkversion = 8 , targetsdkversion = 19. i tried surround code try/catch no availability. not crashing. starts first activity of applicatiactivity()" line. and not go sexselector.java file. i'm testing on samsung device android 4.2.2. here start of sexselector class: @override protected void oncreate(bundle savedinstancestate) { super.oncreate( savedinstancestate ); intent intent = getintent(); bundle bundle = intent.getextras(); device = (device) bundle.get( "device" ); setcontentview( r.layout.sex_selector ); the sexselector activity in manifest. once again program not crash, restarts. thank hints.

c# - Convert Task<String> to String in Windows 8 apps -

i writing windows 8 app. have code : public async task<string> readweb() { var uri = new uri(@"http://stackoverflow.com/"); var httpclient = new httpclient(); var data = await httpclient.getstringasync(uri); string text = data; return text; } i want web-data string data = readweb(); error "cannot convert task string". me! thanks! do this, public async task<string> readweb() { var uri = new uri(@"http://stackoverflow.com/"); var httpclient = new httpclient(); var data = await httpclient.getstringasync(uri); string text = data; return text; } private async void something() { var data = await readweb(); }

javascript - How to put a if condition so that it matches these two conditions? -

i have 2 variables sellprice , buyprice , need check these 2 conditions before procedding further . difference between buyprice - sellprice should not less 1 . difference between sellprice - buyprice should not greater 6 . i able achive first 1 , not both @ same time <!doctype html> <html> <head> <script> function verify() { var sellprice = parsefloat(150); var buyprice = parsefloat(148); if(buyprice -sellprice>=-1.00) { alert('ok'); } else { alert('false'); } } </script> </head> <body> <button type="button" onclick="verify()">verify</button> </body> </html> require advice , if nything better can done achieve . you can add many conditions , ( && ) , or ( || ) function verify() { var sellprice = parsefloat(150); var buyprice = parsefloat(148); var total = buyprice - sellprice; if (total >= 1 && total ...

node.js - Does Go have callback concept? -

i found many talks saying node.js bad because of callback hell , go because of synchronous model. what feel go can callback same node.js in synchronous way. can pass anonymous function , closure things so, why comparing go , node.js in callback perspective if go cannot become callback hell. or misunderstand meaning of callback , anonymous function in go? a lot of things take time, e.g. waiting on network socket, file system read, system call, etc. therefore, lot of languages, or more precisely standard library, include asynchronous version of functions (often in addition synchronous version), program able else in mean-time. in node.js things more extreme. use single-threaded event loop , therefore need ensure program never blocks. have written standard library built around concept of being asynchronous , use callbacks in order notify when ready. code looks this: dosomething1(arg1, arg2, function() { dosomething2(arg1, arg2, function() { dosomething3(func...

php - Implementing invoice payment in ccavenue -

hi have gone through ccavenue payment gateway , provides nice form based solution payment. in php have used stripe invoice payment payment initiated server (programatically). possible generate invoice using php , ccavenue. have read document in link . doesn't specify generating invoices. my question can generate invoices in php using ccavenue gateway ? thanks.

codeigniter - locate file from outside a sub-directory in CI -

i have 2 codeigniter installs in ci project. in second codeigniter install having trouble calling path outside of install folder. project layout: application folder download folder image folder install folder "this contains own index.php , application folder" system folder index.php "main index.php" the area having trouble call path outside install folder. need able locate first application folder. example having problem. this code here finds in install application folder. view file located <tr> <td><?php echo fcpath . 'application/config/database.php'; ?></td> <td class="align_right"><?php echo is_writable(fcpath . 'application/config/database.php') ? '<span class="text-success">writable</span>' : '<span class="text-danger">unwritable</span>'; ?></td> </tr> </tbody> </table> and displays c:\xampp\htdocs\...

unity3d - How to make a 15 sliding puzzle game? -

i have created game has 16 spheres in , swapping on mouse click. want have 15 spheres , 1 empty gameobject, make them slide of empty gameobject.and want shuffle spheres when game starts each time. how possible? i follow this tutorial after tried make it, cubes overlapped on 1 while changing position on start. var xtemp ; var ytemp ; var slot : transform; var cubesposition : vector3[] = new vector3[16]; var cubegameobjects: gameobject[] = new gameobject[16]; function start () { changeposition(); assignpositions(); } function changeposition() { for(var i=0;i<cubegameobjects.length;i++) { cubegameobjects[i].transform.position; } slot.transform.position = new vector3(random.range (1,4),random.range (1,4),10); } function assignpositions() { (var = 0; < cubesposition.length; ++i) cubegameobjects[i]....

android - Why does my app show the content from the wrong tab? -

i have got problem tabs of app. have got 3 tabs , set second tab 1 shown whenever app started code: getactionbar().setselectednavigationitem(1); after used command app started tab wanted, showed me content of first tab (so content was: tab 2 + overlay content tab1) after manually switched problematic tab tab whoms content shown , content normal again. has idea how fix this? public class tablistener <t extends fragment> implements actionbar.tablistener{ private final activity myactivity; private final string mytag; private final class myclass; public tablistener(activity activity, string tag, class<t> cls) { myactivity = activity; mytag = tag; myclass = cls; } @override public void ontabselected(actionbar.tab tab, fragmenttransaction ft) { fragment myfragment = myactivity.getfragmentmanager().findfragmentbytag(mytag); if (myfragment == null) { myfragment = fragment.instantiate(...

extjs - Ext JS Forms at multiple depth -

so in ext js view have form can potentially contain fields , multiple forms inside , forms contain main form can contain forms , fields. there no limitation of how deep last form be. when submit want thing this main-form { key1: value1, key2: value2, form-l2 { key-l2:value-l2, form-l3 { key-l3:value-l3, ... } } } as object. in html, form cannot contain form , in extjs, if somehow trick it, wouldn't play , doubt is worth effort. better have 1 bounding form in you'd implement tree-like ui plus custom methods (or overrides of existing methods) return nested json made of field values.

Single Application ROM for Android -

i'm going develop android application , need custom android rom prevent user of android device exiting our application. other functionality in device should disabled/blocked. custom rom requires on start run 1 application , 1 service. i know custom rom , how modify it, wanna ask possible add script doing this? , how find way develope script? there number of applications can use lock down device, without having build own rom. some examples: https://play.google.com/store/apps/details?id=com.gears42.surelock https://play.google.com/store/apps/details?id=com.adsi.kioware.client.mobile.app or follow process this: https://thebitplague.wordpress.com/2013/04/05/kiosk-mode-on-the-nexus-7/

Booth's algorithm Verilog synthesizable -

i trying implement booth's algorithm (a finite state machine implementation) xilinx fpga. basically, @ start signal initialize auxiliary regs, go in state 0, start compare 2 bits , shifting. repeat until state 4 reached. assign result = p[8:1]; always@(posedge clk or negedge start) if(start == 1) begin // initialize start values state <= 3'd0; end else if(state == 3'd0 || state == 3'd1 || state == 3'd2 || state == 3'd3) begin // compare bits , shift data end endmodule test module clk = 0; = 4'b0011; b = 4'b0011; b = ~b+1; start = 1; #10; start = 0; clk becomes ~clk after #5 time units. i not own fpga, cannot test program (i'll have test later @ class). i testing icarus. problem auxiliary regs not initialized before first posedge of clock. what can in order initialize auxiliary variables , maintain code synthesizable? i've tried using loop , initial begin, , simulation w...

python - How can I add more to a file when printing stdout to a file, instead of overwriting the file? -

is there way can print stdout file without overwriting file? if file reaches size, starts overwrite file? there way can achieve in python? know how print stdout file this: sys.stdout = open('file.txt', 'w') # print stuff unfortunately, limited knowledge of python, can't want achieve, there way can this, or not possible? appreciated! you can use open('file.txt', 'a') append end of file rather overwrite. starting overwrite once reach size more complicated: need write new text @ right location in file, may complicated if file's lines have variable length.

C (linux) - Emulate / Skip scanf input -

i have program running 2 threads. first waiting user input (using scanf), second listening data on udp socket. emulate user input handle specific notification first thread everytime recive specific udp packet. know can share variables between threads, question is: can force scanf take input different thread? can skip scanf in first thread? i believe scanf() definition reads stdin. said, though, different threads share memory it's easy pass information between them. maybe have shared variable , sort of boolean value indicating whether or not information has been updated thread reading network. depends on you're trying do, may want have other mechanism simulation bypasses scanf().

c++ - Trouble with template and stringstream -

i want create function convert string number using stringstream . if suppose number int : int stringtonumber(string str) { stringstream ss; ss << str; int num; ss >> num; return num; } cout << stringtonumber("182") + 100 << endl; //282 this code works correctly. when try use template error. below code: template <typename number> number stringtonumber(string str) { stringstream ss; ss << str; number num; ss >> num; return num; } the errors: main.cpp: in function ‘int main()’: main.cpp:17:33: error: no matching function call ‘stringtonumber(const char [4])’ cout << stringtonumber("125") + 280 << endl; ^ main.cpp:17:33: note: candidate is: main.cpp:6:8: note: template<class number> number stringtonumber(std::string) number stringtonumber(string str) ^ main.cpp:6:8: note: template argument deduction/substituti...

plugins - Install gtk in cygwin -

how can install gtk + 2.4 or greater in cygwin. trying write plugin in wireshark. prior run ./configure , following error checking gtk+ - version >= 2.4.0... no *** not run gtk+ test program, checking why... *** test program failed compile or link. see file config.log *** exact error occured. means gtk+ incorrectly installed. configure: error: gtk+ 2.4 or later isn't available, wireshark can't compiled i running cygwin on windows operating system. you can't build wireshark under cygwin far know. build wireshark on windows, follow instructions @ https://www.wireshark.org/docs/wsdg_html_chunked/chsetupwin32.html

wordpress - jQuery TypeError .offset is undefined -

have been trying resolve issue many hours , cant figure out. the environment wordpress using smooth scroll function smooth scroll when select link on 1 page location on page. the error getting is... typeerror: $(...).offset(...) undefined the offending line of code is... scrolltop: $(elem).offset().top - headerheight my entire function is jquery(document).ready(function($) { var headerheight = $('#header-wrap').height(); //when header position fixed $('a').click(function(){ var hashele = $(this).attr('href').split('#'); if (hashele.length > 1) { if (hashele[1] == 'top') { $('body, html').animate({ scrolltop: 0 },800); } else { jquery('body, html').animate({ scrolltop: $('#'+ hashele[1]).offset().top - headerheight },800); } }; }) // find element url hashname = window.location.hash.replace('#...

Nginx rewrite for folder -

i'm having problem rewrite rule in nginx here have: location / { rewrite ^/([a-za-z0-9\-\_]+)$ /index.php?p=$1; } i have folder named example in html folder nginx. want take variables , put them behind url folders. basically need www.example.com/example/index.php?p=something&var=something2 to like www.example.com/something/something2 any great. i'm switching apache nginx , it's bit confusing. try this: rewrite ^/([a-za-z0-9\-\_]+)/([a-za-z0-9\-\_]+)$ /example/index.php?p=$1&var=$2;

queryover - NHibernate filter collection by subcollection items -

health record may have symptom, consists of words. ( er diagram .) what need: given set of words return health records corresponding symptoms. i have code: public ienumerable<healthrecord> getbywords(ienumerable<word> words) { var wordsids = words.select(w => w.id).tolist(); word word = null; healthrecord hr = null; isession session = nhibernatehelper.getsession(); { return session.queryover<healthrecord>(() => hr) .whererestrictionon(() => hr.symptom).isnotnull() .inner.joinalias(() => hr.symptom.words, () => word) .whererestrictionon(() => word.id).isin(wordsids) .list(); } } what should use here is: inner select, i.e. subquery . can many-to-many maping, performance suffer. the (easier, prefered) way not use many-to-many mapping. because explicitly mapped pairing object symptomword , querying more easier. word word = null; symptom symptom = nu...

javascript - How to pass a header once when sending a list of JSON objects? -

i'm passing list of json objects client server. there way or standard send headers once instead of passing in each json object (more csv style pass header , list of objects containing content only)? for example: { "employees": [ { "firstname":"john" , "lastname":"doe" }, { "firstname":"anna" , "lastname":"smith" }, { "firstname":"peter" , "lastname":"jones" } ] } if have 10,000 employees pass, repeating each time headers ("fisrtname" , "lastname") wasteful. you can create array of firstname , lastname , pass data this, { "employees": { "firstname" : ["john", "anna", "peter"], "lastname" : ["doe", "smith", "jones"] } }

java - drawImage() on JPanel OR add Image on top of GridLayout -

i have 100 100 grid of labels. i've got method creates , populates array of strings. next method creates array of labels , adds string (created previous method) labels using settext() method. of labels contain images too. method after takes jlabels , adds them jpanel of grid layout(lets call x1). i've added jpanel jscrollpane(x2), jscrollpane gets added jpanel(x3) empty border , final jpanel(x3) gets added jframe. that's how i've created grid , i'm happy that, don't want change it. i add image x1 - jpanel grid layout. have add paintcomponent method , use drawimage() method. question how eclipse know panel add image to? i's prefer not create separate class x1, did before , didn't work out right , rather not go down incredibly frustrating road again, i'm sorry! i have considered using glass pane no longer able see images of jlabels - important. i think adding image background of jpanel best because want have button shows/hides grid lines ...

javascript - Create effect similar to Twitter's retweet? -

i'm sorry didn't provide specifics - i'm writing twitter application our school project, , i'm kinda stuck - how create pop on twitter's retweet function? here's initial thoughts far: 1.the retweet div , blackout separate html page 2.the retweet content directly copied tweet retweet clicked (but how? should fetched php? or directly "copied" tweet jquery? if so, pointers please?) 3.and have no idea how page appears on top of page. i'm thinking of like $("#retweet").on('click', function() { // loads page on top of page? }); 1.how "load" page on top without reloading page? 2.is ajax involved? (sorry, i'm not familiar.) 3.how pass variables between page , popup page? (this referring in question 2 - if retweeted box reconstruction based on tweet, how fetched?) i'd appreciate if can point me in right direction. thanks! why not use http://bootboxjs.com library? try out, seems simila...

android - JavaScript: Sound not looping on Firefox (Phone/Tablet) -

i cannot life of me sound loop on firefox @ all. i've searched google hours , still feel i'm asking stupid question, there answer out there. @ highly appreciated. thank much! here have tried: var newjobaudio = new audio('/audio/newjobalert.mp3'); newjobaudio.loop = true; newjobaudio.play(); edit: updated code (doesn't work still, but, can see have) var newjobaudio = new audio('/audio/newjobalert.mp3'); audioloop(true); function audioloop(play) { if ( play ) { newjobaudio.addeventlistener('ended', playaudio, false); newjobaudio.play(); } else { newjobaudio.removeeventlistener('ended', playaudio, false); newjobaudio.pause(); } } function playaudio() { newjobaudio.currenttime = 0; newjobaudio.play(); } edit: even though tablet/phone firefox works fine mp3 sound breaks after first play. able determine using workaround sound looping using setinterval. when setinterv...

ember.js - Unit test a controller action that makes calls to async relationships -

i have 2 models, program , project . program has many project s. app.program = ds.model.extend projects: ds.hasmany 'project', async: true app.project = ds.model.extend program: ds.belongsto 'program' i have arraycontroller responsible displaying projects in program. each project rendered has destroy link (a simple action on arraycontroller ). app.projectsindexcontroller = ember.arraycontroller.extend needs: 'program' program: ember.computed.alias 'controllers.program.model' actions: destroy: (project) -> @get('program.projects').then (projects) -> projects.removeobject(project) # how can test line? @get('program').save() project.destroyrecord() since relationships async, calling program.get('projects') returns promise. i'm using firebase (and emberfire ) backend, stores relationships like programs: { programid: { projects: { projectid: true }...

ios - MFMailComposeViewController never deallocates -

i'm presenting mfmailcomposeviewcontroller this: mc = [[mfmailcomposeviewcontroller alloc] init]; mc.mailcomposedelegate = self; [self presentviewcontroller:mc animated:yes completion:null]; mc = nil; and removing delegate method: - (void) mailcomposecontroller:(mfmailcomposeviewcontroller *)controller didfinishwithresult:(mfmailcomposeresult)result error:(nserror *)error { [self dismissviewcontrolleranimated:yes completion:nil]; } the problem vc never deallocated, , opening , closing "send email" function in app eats memory doesn't release it. what missing? don't see how can other way, , other vcs deallocate fine on own after calling dismissviewcontroller on themselves. why set mc = nil ; after presentviewcontroller:mc ? you should like:- mc = [[mfmailcomposeviewcontroller alloc] init]; mc.mailcomposedelegate = self; [self presentviewcontroller:mc animated:yes completion:null]; then - (void) mailcomposecontroller:(mfmailcomposev...

How to show the pipe "|" symbol in Markdown table? -

i want show markdown table 1 of cells has pipe "|" column1 | column2 ------- | ------- | | hello just doesn't work. how escape | in table? tried *|* didn't work this depends on markdown interpreter. in general markdown escapes backslash (like markdown additional pipe ) column1 | column2 ------- | ------- \| | hello this works in markdown extra.

How to script the profiling of multiple executable on an Android device? -

i have executables compiled native toolchain, ndk, android. i script execution of programs , since i'm interested in performance of application, run them basic information execution cpu usage, time, memory, , usual stuff basic profiler. it's possible starting executables on pc, pushing them device, run them , information i'm looking ? you try these executables on linux using pss vss monitoring commands or memusage command, own't effective unless tried on android device. use ddms profiling android apps, can method profiling or trace profiling. have at: http://developer.android.com/tools/debugging/ddms.html http://developer.android.com/tools/debugging/debugging-tracing.html

python - sort() and reverse() functions do not work -

i trying test how lists in python works according tutorial reading. when tried use list.sort() or list.reverse() , interpreter gives me none . please let me know how can result these 2 methods: a = [66.25, 333, 333, 1, 1234.5] print(a.sort()) print(a.reverse()) .sort() , .reverse() change list in place , return none see mutable sequence documentation : the sort() , reverse() methods modify list in place economy of space when sorting or reversing large list. remind operate side effect, don’t return sorted or reversed list. do instead: a.sort() print(a) a.reverse() print(a) or use sorted() , reversed() functions. print(sorted(a)) # sorted print(list(reversed(a))) # reversed print(a[::-1]) # reversing using negative slice step print(sorted(a, reverse=true)) # sorted *and* reversed these methods return new list , leave original input list untouched. demo, in-place sorting , reversing: >>> = [66.25, ...

html - Ajax .Post - Sending own defined variable through to mail.php -

i getting info rest of variables last 1 want send in own predefined. reason aint going through mail.php var it1 = "it service" ; //send ajax request $.post('mail.php',{name:$('#name').val(), companyname:$('#companyname').val(), designation:$('#designation').val(), onumber:$('#onumber').val(), mnumber:$('#mnumber').val(), email:$('#e-mail').val(), message:$('#message').val(), manage:$('#manage1').val(), tech:$('#tech1').val(), it:$it1}, mail.php looks like: <?php // declare our variables $name = $_post['name']; $email = $_post['email']; $message = nl2br($_post['message']); $companyname = $_post['companyname']; $designation = $_post['designation']; $onumber = $_post['onumber']; $mnumber = $_post['mnumber']; $it = $_post['it']; $tech = $_post['tech']; $manage = $_post['manage']; // set title message $subject...

Does HTML tags within PHP code work? -

i using php echo bunch of text table in database. problem is, text printing php poems , need have line breaks separate different lines. (one poem stored in cell of table) my question code below work? i.e. can <br> tag work? if doesn't, can produce intended results? (i haven't set php cant test myself...) in advance! <?php echo "to drift every passion till soul <br> stringed lute on winds can play, <br> have given away <br> mine ancient wisdom, , austere control? <br> "; ?> yes can use html code inside php using echo function. here's example link manual might understand better. <?php echo "<html>"; echo "<title>html php</title>"; echo "<b>my example</b>"; //your php code here print "<i>print works too!</i>"; ?>

perl - Hiding GET variables with sockets -

i have script send request page. im trying figureout how surpress output, here code itself: use io::socket; $domain = 'yahoo.com'; $socket=io::socket::inet->new( proto => 'tcp', peeraddr => $domain, peerport => '80', ) or return $!; print $socket "get /index.php http/1.0\r\n"; print $socket "host: ", $domain, "\r\n"; print $socket "connection: close", "\r\n"; print $socket "user-agent: mozilla/5.0 (compatible; msie 9.0; windows nt 6.1; trident/5.0)", "\r\n"; print $socket "accept: text/html, application/xhtml+xml, */*", "\r\n\r\n"; print while <$socket>; here output. http/1.0 200 ok server: nginx/1.4.7 content-type: text/html x-powered-by: php/5.4.27-1~dotdeb.0 set-cookie: phpsessid=k2bviiurukqdju1l26j4fat0q0; path=/ ...

jquery - Remove follow button from embedded tweet -

i'm embedding tweet on website , remove follow button , reply , favorite , retweet buttons in footer. minimal html example following <blockquote class="twitter-tweet"> <a href="https://twitter.com/stackcareers/statuses/468107750333894656"></a> </blockquote> <script src="http://platform.twitter.com/widgets.js" charset="utf-8"></script> by inspecting code, once tweet diplayed, figured button wrapped following <a class="follow-button profile" href="https://twitter.com/stackcareers" role="button" data-scribe="component:followbutton" title="follow stackoverflowcareers on twitter"><i class="ic-button-bird"></i>follow</a> so far tried remove class using jquery $('.follow-button.profile').remove() i tried overwrite css adding following line stylesheet : .follow-button {visibility:hidden;} and follow...