Posts

Showing posts from September, 2013

if statement - Python Counter doesn't count -

import urllib2 f=urllib2.urlopen("http://www.mbnet.com.pl/dl.txt") list = range(1,50) counter={} lines in f: tab_lines=lines.split(" ") formated_tab=tab_lines[-1].strip().split(',') #print formated_tab in formated_tab: if in list: counter[i]+=1 print counter.items() my counter doesn't work , don't know why :( this list of lottery numbers. count how many times drawn each number. instead of using: counter[i] = counter.get(i, 0) + 1 you can try collections.defaultdict : counter = defaultdict(int) so final version should this: import urllib2 collections import defaultdict f=urllib2.urlopen("http://www.mbnet.com.pl/dl.txt") list = range(1,50) counter=defaultdict(int) # use defaultdict here lines in f: tab_lines=lines.split(" ") formated_tab=tab_lines[-1].strip().split(',') in formated_tab: if int(i) in list: counter[i] += 1 # do...

html - Is it possible to apply CSS to an element whose name contains a particular string? -

i know can apply css styles element based on name: input[name=description] { width: 200px; } but possible apply css styles elements contain particular string in name? imagine several inputs: <input type="text" name="projectdescription"/> <input type="text" name="themedescription"/> <input type="text" name="methodologydescription"/> <input type="text" name="somethingelse"/> etc... so, want apply styles inputs name contains word "description". can done without scripting? yes, can: input[name*="description"] { width: 200px; } demo more info [attr] represents element attribute name of attr. [attr=value] represents element attribute name of attr , value "value". [attr~=value] represents element attribute name of attr value whitespace-separated list of words, 1 of "value". [attr|=...

android - IndexOutOfBoundsException while gradle sync with realm-java -

i install realm in android application, change bbdd model , extends realmobject , change lists realmlist , error while gradle sync: --info or --debug option more log output. exception stack-trace is: org.gradle.api.tasks.taskexecutionexception: execution failed task ':storage:compilereleasejava'. @ org.gradle.api.internal.tasks.execution.executeactionstaskexecuter.executeactions(executeactionstaskexecuter.java:69) @ org.gradle.api.internal.tasks.execution.executeactionstaskexecuter.execute(executeactionstaskexecuter.java:46) @ org.gradle.api.internal.tasks.execution.postexecutionanalysistaskexecuter.execute(postexecutionanalysistaskexecuter.java:35) @ org.gradle.api.internal.tasks.execution.skipuptodatetaskexecuter.execute(skipuptodatetaskexecuter.java:64) @ org.gradle.api.internal.tasks.execution.validatingtaskexecuter.execute(validatingtaskexecuter.java:58) @ org.gradle.api.internal.tasks.execution.skipemptysourcefilestaskexecuter.execute(skipemptysourcefile...

c# - How can i use mouse down click event and paint event of windows forms Chart control to draw points on the chart? -

i added start point end point , mouse x , mouse y variables want use them draw points on chart control when clicking mouse on left button. but want points draw on chart area , when mouse inside square area in chart not draw point on squares borders lines or outside chart control area. and display when moving mouse in squares in chart show me axis x , axis y values on labels. the left axis 1 120 present time , bottom axis 1 30 present days. if move mouse in first square area should show me day 1 time 112 or day 2 time 33. that's why i'm not sure spaces in axis x , axis y right. should 1 120 , 1 30 think every square should present inside 3 days , 120 time in jumps of 1 steps of 1 when move mouse can see in first squares day 1 time 3 or day 3 time 66 next row of squares present days 4 6. using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.linq; using system.text; using system.threading.ta...

jsf - How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar" -

the following code inspired primefaces datagrid + datatable tutorials , put <p:tab> of <p:tabview> residing in <p:layoutunit> of <p:layout> . here inner part of code (starting p:tab component); outer part trivial. <p:tabview id="tabs"> <p:tab id="search" title="search"> <h:form id="instable"> <p:datatable id="table" var="lndinstrument" value="#{instrumentbean.instruments}"> <p:column> <p:commandlink id="select" update="instable:display" oncomplete="dlg.show()"> <f:setpropertyactionlistener value="#{lndinstrument}" target="#{instrumentbean.selectedinstrument}" /> <h:outputtext value="#{lndinstrument.name}" />...

android - Fragment does not get displayed in viewpager -

pfb code , requirement , research requirement : i have 4 tabs (tabs a,b,c,d) having 4 different fragments (fragments a,b,c,d on each corresponding tabs) , attached viewpager i can swipe through tabs using of fragmentstatepageradapter saves state of fragments swiped now have list in fragment fragment , has button on click need call new fragment a1 . i have reffered stack site link : replace fragment inside viewpager but fragmenta on taba gets disappears , not display fragmenta1 on tab issue . kindly my pageadapter .java class import java.util.list; import android.support.v4.app.fragmentmanager; import android.support.v4.app.fragmentpageradapter; import android.support.v4.app.fragmentstatepageradapter; /** * <code>pageradapter</code> serves fragments when paging. * @author mwho */ public class pageradapter extends fragmentstatepageradapter { private list<fragment> fragments; private final fragmentmanager mfragmentmanager = null; private f...

mysql - Call a stored procedure with an integer array as argument? -

i want pass integer array argument stored procedure, how can done? create procedure rd22(unitlist int) begin select * abet inner join on a.id = abet.alarm_source , a.unit in (unitlist) abet.begin_timestamp = 1395874800000; end this how stored proc looks like, , want achive this: set @val = [1,2,3]; call rd22(@val); one way can think pass string , somehow convert integers. there other subtle way achive this. thanks time. cheers. you cant way, when pass param comma separated string in query take first value while executing in clause , need use dynamic query prepared statement create procedure rd22(unitlist varchar(100)) begin set @ul = unitlist; set @qry = concat("select * abet inner join on a.id = abet.alarm_source , a.unit in(",@ul,") abet.begin_timestamp = 1395874800000"); prepare stmt @qry; execute stmt; end the call as set @val = '1,2,3'; call rd22(@val); here test case in mysql my...

c# - New thread signature (static vs non static method) -

i guess have simple question used have code: thread mythread = new thread(mainprocessingthread); mythread.isbackground = true; isthreadrunning = true; mythread.start(); and method: public void mainprocessingthread() { } you can see method above isn't static. , code used work. have passed name of method (not forminstance.mainprocessingthread ) thread above. did wrong? how did work? ps mainprocessingthread member of main form. can access form member(instance) variables directly method? given mainprocessingthread instance method, following line thread mythread = new thread(mainprocessingthread); is shorthand of thread mythread = new thread(new threadstart(this.mainprocessingthread)); so, you're using object indeed. pointer taken implicit reference. able this, should calling in instance method/property, otherwise you'll not have access this reference. example if in static method, you'll compilation error because don't have access thi...

java - Android.com's basic app won't show DisplayMessageActivity in app -

so i'm building basic app tutorial, can't displayactivitymessage class work in app itself. no errors, nothing, nothing happens when input text , press button "send". heres classes , xmls. mainactivity.java package com.example.nan.joro2; import android.support.v7.app.actionbaractivity; import android.os.bundle; import android.view.menu; import android.view.menuitem; import android.content.intent; import android.view.view; import android.widget.edittext; import android.widget.textview; public class mainactivity extends actionbaractivity { public final static string extra_message = "com.example.nan.joro2.message"; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); } @override public boolean oncreateoptionsmenu(menu menu) { // inflate menu; adds items action bar if present. getmenuinflater().inflate(r.m...

asp.net mvc - Submit a form with a file upload -

i have simple form 4 input on it. 2 text input 2 check boxes my current view model posted server following: public class myviewmodel { public string firsttext { get; set; } public string secondtext { get; set; } public bool firstbool { get; set; } public bool secondbool { get; set; } } this works good. have requirement when secondbool value true ui should upload file server. have modified view model add public httppostedfilebase uploadedfile { get; set; } and modified form having attribute enctype="multipart/form-data" i use, using bootstrap base ui framework jquery file upload plugin did not through on how post , upload file @ same time. know should easy it. any hint? you need add httppostedfilebase uploadedfile post action in controller. cannot pass via model. e.g. [httppost] public actionresult myaction(mymodel model, httppostedfilebase uploadedfile) { //..... stuff here }

Spring Integration : How to retrieve header values in Aggregator class -

how retrieve header values when combine 2 different messages using aggregator. have 2 messages different header same uuid. when combine these 2 messages using aggregator uuid, not find way retrieve header in custom aggregator class. mean header values lost? pls help. the aggregated message gets union of headers. if there conflict, aggregator doesn't know value use header dropped, debug message... logger.debug("excluding header '" + keytoremove + "' upon aggregation due conflict(s) " + "in messagegroup correlation key: " + group.getgroupid()); if need retain values, need in different headers.

c# - Do functions slow down performance -

i using c# go through loop , (this loop massive, big 1,000,000 records long). wanted replace inline code code exact same thing, except in function. i guessing there slight decrease in performance, noticeable? if have loop: public void main() { int x = 0; (int = 0; < 1000; i++) { x += 1; } } would loop slow down if did same thing except time making use of function? public void main() { int x = 0; (int = 0; < 1000; i++) { x = incrementint(x); } } public int incrementint(int x) { return x + 1; } edit: fixed logic bug, sorry that. a method call slow down. jit compiler can inline method if set of conditions fullfilled results in assembly code equivalent first example (if fix logic bug in example). the question indirectly asking under circumstances method inlined? there many different rules easiest way sure inlining work measure it. can use perfview find out each method why not inlined. can give ...

c++ - How to integrate chromium browser project in Qt Creator in Ubuntu -

Image
i have managed understand structure of chromium browser , use ide in order make changes personal project on ubuntu trusty machine ( 14.04 ) . it compiled , want use ide make life easier. i have tried add chromium qt creator using option open project without luck. could please guide me have achieved ? steps helpful. more, possible compile / build chromium qt creator ? ( avoid typting in console ninja -c out/debug chrome chrome_sandbox , out/debug/chrome every time) if guys can suggest me ide you're used to, please, guide me , change title of post. //update 1 i tried make configurations build / run follows: build: run i following error: :-1: error: no rule make target all'. stop.` // update 2: the error compile output section you can edit code project in qt creator, can't use open project , when isn't qt project. instead use import project -> import existing project in new project dialog. when have existing proje...

javascript - Marionettejs Routes -

i'm new marionette , can't routes work. i'm using marionette's 2.4.1 version, , trying simplest way possible it'll work. this code works old version of marionette, v1.0.2, included in 1 of yeoman's generator. know there's huge gap between 2 versoins every post, blog, official documentation , books written framework code stays same. there no errors in console, 'home' method won't start. am missing here? application.js (application body): define(['backbone', 'marionette'], function (backbone, marionette) { 'use strict'; var app = new marionette.application(); app.router = marionette.approuter.extend({ approutes: { "home": "home" } }); var mycontroller = { "home": function() { console.log("this thing won't work."); } }; /* add initializers here */ app.addinitializer(fu...

jquery - Bootstrap drop down stops working after appending child elements to it -

i using bootstrap 3.2.0 , jquery 1.7.1 , using 2 bootstrap drop downs on web page. the user selects value in first drop down , jquery runs , fills respective values , prices in second drop down. the onchange event works fine on first drop down onchange event stops working on second drop down after populated via jquery (based on selection of first drop down). i @ loss why happening. i have coded example here http://www.offshoreprojectupdates.com/testb/test_page.php can 1 pinpoint may doing wrong in above code? update i have removed code solution have found requires there no adding/deleting of elements on drop down. have tried solutions available on internet no avail. if 1 have solution please share it. bootstrap adds click/change handlers various elements. if notice element's onchange events no longer firing, it's because modifying dom (adding, inserting, removing elements) inadvertently breaking bootstrap's event handlers. you must either fi...

excel vba - Checking cells contain data before printing - Run-Time error -

i've been doing work on spreadsheet work i've, until point, been able solve issues hunting around online. i'm relatively new vba , have built of researching online may pretty rubbish way it. unfortunately i've run problem following code giving me type mismatch error (run-time 13). suspect code pretty self explanatory, i'm trying disable printing in event cells aren't completed. run-time error highlighting bolded section. private sub workbook_beforeprint(cancel boolean) dim response integer sheets("settlement instruction") **if .range("m1").value = "" or .range("p1").value = "" _ or .range("e2").value = "" or .range("e3").value = "" or .range("e4").value = "" or .range("m4").value = "" or .range("u3").value = "" _ or (.range("m1").value = "wa" , .range("p1").va...

How many nodes max can be used when setup a etcd cluster -

i try setup coreos etcd cluster datacenter. how many nodes max can setup in cluster it? i , add more nodes can increase performance or not? i didn't find figure offical website. mentions 9 ok. to knowledge, i've got running small (3-5 nodes) coreos cluster , hearing coreos team themselves, 9 won't have latency issues, maybe 10 if you're lucky, after cluster has latency issues keeping etcd consistent on each node of cluster, therefore 9 should max if want play safe.

javascript - SyntaxError: unterminated string literal <script>...</script> tag not working within a string variable -

Image
please code. var id = 1; var htmltext = '<div id="horizontaluserpopup"><ul id="tabs1" class="rtabs"></ul><div class="panel-container"><div id="view1"><script>viewminiprofile("'+id+'",this);</script></div><div id="view2"></div><div id="view3" style="display:none;">blah blah blah</div><div id="view4" style="display:none;">444444</div></div></div>'; $('#contents').html(htmltext); above code getting following error - if remove </script> working fine. please check , let me know. edit: complete code - function modelinfo(id, username) { var pageurl = $('#pageurl').val(); $('#model-popup-box1 h3').addclass('newsfeed'); var content_area = $('#model-popup-content1');...

how to typecast the objects created by newInstance() method of reflection API in java dynamically -

how can create , clone , typecast object? public int createobjec(object object, string classname) { //object may user, role or userrole // classname name of class sessionfactory.getcurrentsession().save(dynamicobject); //dynamicobject may user, role or userrole } a better solution have factory handling object creation. depending on classname, create correct type in factory.

python - Unable to access Tastekid’s API. It says Error: 403 (Request forbidden) -

i unable run code read tastekid's api (python), says error: 403 (request forbidden) can access same url in browser. have tried same key aswell. please find below query from urllib2 import request, urlopen, urlerror req = request('http://www.tastekid.com/api/similar?q=red+hot+chili+peppers%2c+pulp+fiction') try: response = urlopen(req) except urlerror e: if hasattr(e, 'reason'): print 'we failed reach server.' print 'reason: ', e.reason elif hasattr(e, 'code'): print 'the server couldn\'t fulfill request.' print 'error code: ', e.code else: 'everything fine' you need add proper headers before making request url headers = { 'user-agent' : "mozilla/4.0 (compatible; msie 5.5; windows nt)" } req = request('http://www.tastekid.com/api/similar?q=red+hot+chili+peppers%2c+pulp+fiction', headers = headers) here user-agent k...

rstudio - Underline in RTF reporting in R -

hi want create following rtf data frame in r- df <- country n1 mean1 sd1 n2 mean2 sd1 ---------------------------------------------------- bangladesh 52 25.03 0.02 43 22.31 0.08 germany 42 95.01 1.02 53 9.31 0.09 italy 2 20.22 0.00 11 8.09 1.11 --- i want report as: treatment treatment b country n mean sd n mean sd ------------------------------------------------------ bangladesh 52 25.03 0.02 43 22.31 0.08 germany 42 95.01 1.02 53 9.31 0.09 italy 2 20.22 0.00 11 8.09 1.11 --- with 2 underlines under texts "treatment a" , "treatment b". like- treatment ------------------------ n mean sd can 1 please me.

java - No audio in MP4 file - Android -

i using mp4parsermergeaudiovideo add new audio mp4 file. library had said use .wav file, if keep .wav file in directory , give name of audiofile example.m4a , file not found exception. changed file .m4a audio file. code given below. findviewbyid(r.id.append).setonclicklistener(new onclicklistener() { @override public void onclick(view v) { string root = environment.getexternalstoragedirectory().tostring(); log.e("",""+root); string audio = root + "/download/"+"mymovieaudio.m4a"; string video = root + "/download/"+"my_movie.mp4"; string output = root + "/download/ouput.mp4"; mux(video, audio, output); } }); the mux function this public boolean mux(string videofile, string audiofile, string outputfile) { movie video; try { video = new moviecreator().build(videofile); } catch (runtimeexception e) { ...

regex - URL Rewrite: how to remove email parameters from an URL in Apache? -

how can remove email parameters url on apache server using rewrite rule? basically need strip out whatever email parameter present in url, example: www.example.com/?param_name=nobody@example.com will rewritten as www.example.com/ or www.example.com/?param_name_1=not_an_email&param_name_2=nobody@example.com to www.example.com/?param_name_1=not_an_email try these rules: rewriteengine on rewritecond %{query_string} ^(.+|)?&[^=]*=[a-za-z0-9._%+-]+@[a-za-z0-9.-]+\.[a-za-z]{2,4}((?:&(.*))|)$ rewriterule (.*) $1?%1%2 [nc,l] rewritecond %{query_string} ^[^=]*=[a-za-z0-9._%+-]+@[a-za-z0-9.-]+\.[a-za-z]{2,4}$ rewriterule (.*) ? [nc,l] rewritecond %{query_string} ^[^=]*=[a-za-z0-9._%+-]+@[a-za-z0-9.-]+\.[a-za-z]{2,4}(&|)((?:&(.*))|)$ rewriterule (.*) $1?%1%3 [nc,l] tested here the first rule matches query strings there other parameters both before , optionally after email address, e.g: www.example.com/?param_name_1=not_an_email&par...

Javafx how to add content to an existing tab in fxml file dynamically -

i have seen lot of answers on how add new tab existing tab pane of fxml file. need add content existing tab of tab pane. possible? if yes how do that? ofcourse possible. follow steps : assign fx:id tab in fxml use fx:id bind tab instance in controller. now, have instance, can add contents whenever want, using setcontent() . in fxml ... <tab fx:id="mytab"> ... in controller : class mycontroller { ... @fxml private tab mytab ... //somewhere in controller tab.setcontent(somenode); ... }

pandas - Handling duplicate rows in python -

i have date frame df, let's 5 columns : a, b, c, d, e. b c d e 1 6 x 8 3 2 3 y 2 3 3 5 d 1 1 3 4 g 3 4 5 3 z 3 1 this want do, rows same value of column a, want drop duplicates, value of column b should summed across rows, , rest of columns, want keep first value. final data frame : b c d e 1 6 x 8 3 2 3 y 2 3 3 9 d 1 1 5 3 z 3 1 how this? i'd assign column 'b' result of grouping on 'a' , summing, can drop duplicates: in [171]: df['b'] = df.groupby('a')['b'].transform('sum') df out[171]: b c d e 0 1 6 x 8 3 1 2 3 y 2 3 2 3 9 d 1 1 3 3 9 g 3 4 4 5 3 z 3 1 in [172]: df.drop_duplicates('a') out[172]: b c d e 0 1 6 x 8 3 1 2 3 y 2 3 2 3 9 d 1 1 4 5 3 z 3 1

linux - How to fix ../libcrypto.so: undefined reference to `rc4_md5_enc'? -

i trying cross compile openssl arm on 64bit ubuntu. getting following errors : undefined reference `bio_f_zlib' ../libcrypto.so: undefined reference `rc4_md5_enc' ../libcrypto.so: undefined reference `mod_exp_512' please tell me how rectify this. not sure if helps did tried running ./configure linux-x86_64

matlab - I want to add more noise to noisy audio, why is my calculation test for signal to noise not correct -

i have nothing audio recording want lower signal noise of. simplicity, extracted specific part of audio want measure signal noise, called audio . have extracted background noise area has no signal in it, called backgroundnoise data here: http://expirebox.com/download/bb9997de2dc5bae12fc7184dd2a0eb0f.html due lot of here: proper way add noise signal i have : originalsnr=snr(audio-backgroundnoise,backgroundnoise) %initial calculation 6.4762 desiredsnrindb = 5:-1:1; %what want lower snr down desired_snr_db=desiredsnrindb est_signal= audio- backgroundnoise; %the original matlab equation snr is: %signalpow = rssq(x(:)).^2; %noisepow = rssq(y(:)).^2; %r = 10 * log10(signalpow / noisepow); %solving noisepow rms_new = rssq(est_signal(:)).^2 / 10^(desired_snr_db / 10); %assuming rssq(new_noise).^2 = scale_factor * rssq(old).^2 scale_factor = rms_new / rssq(backgroundnoise(:)).^2; new_noise = scale_factor * backgroundnoise; %add nois...

excel - xlsx file corrupted while writing file in java -

i write code writing xlsx file try { fileinputstream fis = new fileinputstream(filepath); workbook workbook = new xssfworkbook(fis); workbook workbook_ = new xssfworkbook(); string value = cmbsheets.getselecteditem().tostring(); sheet sheet = workbook.getsheet(value); sheet sheet1 = workbook_.createsheet("sheet1"); int q = 1; row headrow = sheet1.createrow((short) 0); iterator<row> rowiterator = sheet.iterator(); while (rowiterator.hasnext()) { row = rowiterator.next(); iterator<cell> celliterator = row.celliterator(); while (celliterator.hasnext()) { cell = celliterator.next(); switch (cell.getcelltype()) { case cell.cell_type_boolean: system.o...