Posts

Showing posts from August, 2015

python - How should i feed this input into my regression network in tensorflow -

i working tensorflow, trying implement neural network regression purposes. regression consist of mapping input output. input in case samples , framed audio files, , output has mapped set of mfcc features each frame should correspond to. the input stored this. #one audio set [array([[frame],[frame],...,[frame]],dtype=float32)] and output stored this [array([[feature1, feature2, feature3, feature4, feature5, feature6, feature7, feature8, feature9, feature10, feature11, feature12, feature13],....,[...]])] the model trying input simple linear model. since input or output data isn't 1 dimensional dataset, have provide in way such capable of handling vector sizes. # set model weights w = tf.variable(rng.randn(), name="weight") b = tf.variable(rng.randn(), name="bias") # construct linear model pred = tf.add(tf.mul(x, w), b) evaluated solutions one solution flatten both input, , output , make use of...

SQL Server SELECT to timely return the most recent record -

i have below ‘pricedata’ database table contains 1,000,000 rows , growing 100,000 records/day: id | datecreated |tradedate |fk_currency | price -------------------------------------------------------------- 48982| yyyymmddhhmmss | yyyymmddhhmmss |1 | 1.09684 48953| yyyymmddhhmmss | yyyymmddhhmmss |1 | 1.22333 48954| yyyymmddhhmmss | yyyymmddhhmmss |2 | 1.22333 my requirements mandate must able retrieve recent price given currency input, below stored procedure achieves takes far long execute (3.4 seconds): procedure [dbo].[getrecentprice] @currency nvarchar(6) select price pricedata id = (select max(id) pricedata fk_currencypair = (select id currencypair name = @currency)); sql server execution times: cpu time = 78 ms, elapsed time = 3428 ms. i’ve tried including below clause examines past minute of data: and tradedate >= (select (dateadd(minute, -1, (select convert(datetime, sysdatetimeoffset() @ time zone 'cen...

java - Swing Timer issue - stop Timer -

i have been trying stop timer , solve days now, unfortunately no luck, hope able help. the idea use timer click button increases value in text field have timer in start button , wish stop in stop button. that's code have behind start button: private void btstarttimeractionperformed(java.awt.event.actionevent evt) { javax.swing.timer tm = new javax.swing.timer(100, new actionlistener(){ public void actionperformed(actionevent evt) { btaddoneactionperformed(evt); } }); tm.start(); } private void btstoptimeractionperformed(java.awt.event.actionevent evt) { } you've got problem of scope in posted code: timer variable, tm, declared within start button's actionperformed method , is visible within method . cannot viable reference when outside of method. solution declare variable on class level private instance (non-static) variable, , call start() on within start button's action listener. ...

uitabbar - ios 10 - UITabBarController UITabBarItem - items slow to render -

upon login initial display of ui worked fine in ios 9 uitabbarcontroller showing icons appropriately in ios 10 there noticeable delay of 5 - 10 seconds without error in log. i've posted bug apple id- 29127274 the fix below... -j here code cause problem: @implementation mytabbarcontroller //... - (void)viewdidload { [super viewdidload]; //the code below causing delay ... worked find in ios9 //tried legacy #define style //[self setselectedindex:int(selectedlandingtotab)]; //tried extern style .... both fail //[self setselectedindex:selectedlandingtab]; } //... @end if comment out setselectedindex uitabbar shows without delay. -j

vb.net - Predicate to use Find on a List of Tuple -

i have dictionary : public tbldic new dictionary(of string, list(of tuple(of date, date, decimal))) i need retrieve 3rd item (decimal) of tuple having highest date on 2nd item. i able retrieve 3rd item knowing date wasn't able retrieve highest date: dim lastdate date = date.parseexact("31/12/2016", "dd/mm/yyyy", new cultureinfo("it-it"), datetimestyles.none) dim lastrate2 decimal = tbldic("legali").find(function(d) d.item2 = lastdate).item3 another way put tuple datatable , use datatable.select retrieve decimal field way: dim lastrate decimal = dt_rates.select("enddate=max(enddate)")(0).field(of decimal)("rate") so, questions are: 1) possible use list.find without knowing last date? 2) best practice between list.find , datatable.select? you could use find... maybe? think simple enough without it. dim lastrate decimal = tbldic. selectmany(function(k)...

javascript - Bootstrap navbar wont collapse -

my bootstrap navbar got bootstrap jumbotron example won't collapse. if dont have right javascript, css or jquery links pls send me right ones. kinda new navbar thing need help. thank you! here code: <nav class="navbar navbar-inverse navbar-static-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".nav-collapse" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">project name</a> </div> <div id=...

if/else jQuery with JSON -

my json includes pictures. have gotten pictures work when should , when shouldnt. of if/else in jquery. want if image displayed, text. want foto dispalyed if image displayed. code below not work. the question is: want foto in json displayed when image is. var titel = post.titel; var content = post.content; var date = post.date; var author = post.author; var foto = post.foto var image = post.image; // if image going displayed if (image.length >= 1){ img = '<img src="/images/' + image+'" alt="image">'; if (foto.length >= 1){ renderfoto = foto; } else{ renderfoto = ""; } // else if image should not displayed }else{ img = ""; renderfoto = ""; } this how json displayed. works. var postcontent = '<div class="content-grid-info">'+img+'<div class="post-info"><h1>'+titel+' </h1><h3>datum: '+date+' author: '+...

java - JSch: Run command after Multi-Level ssh -

i using jsch run commands after multi-level ssh: public static void main(string[] args) { string user="user0"; string ip="ip0"; int port=22; string password="password0"; jsch jsch= new jsch(); session session=null; channelexec channel=null; try { session=(jsch.getsession(user, ip, port)); session.setconfig("stricthostkeychecking", "no"); session.setpassword(password); session.connect(); string dir=reomte_dir; string cmd1=somecomplexcommand; string cmd2=somemorecomplexcommand; channel = (channelexec) session.openchannel("exec"); channel.setinputstream(null); channel.setcommand("ssh user1@ip1_passwordlesslogin;ssh user2@ip2_passwordlesslogin; "+cmd1+" ; "+cmd2+" ;"); ...

php - Yii form textarea character limit -

i trying implement limit character showing user in textarea. code snippet seems not working. please me find error. <?php echo $form->textarea($model, 'tr_summary', array('rows' => 2, 'cols' => 50, 'class' => 'form-control fldrequired')); ?> <div class="errormessage tour_tr_summary"></div> <script type="text/javascript"> $(".fldrequired").keyup(function(e) { fldid = $(this).attr('id'); if(fldid == 'tour_tr_summary' && $(this).val().length > 20) { $('.'+fldid).html( 'maximum 20 characters allowed'); e.preventdefault(); } }); </script> this coding work textfield not textarea. no javascript needed if don't care old browsers. add textarea() 1 more parameter: array('maxlength'=>10) not sure version of yii using, assuming code it's yii 1.x more information can find here: http:/...

java - Design-by-contract finding pre-conditions -

i have create calculator in java, based on interface. public interface calculatorif { int add(int x, int y); int sub(int x, int y); int mult(int x, int y); //double div(int x, int y); //int sqrt(int x); } but every method, need pre-post conditions. need pre-conditions, because can't imagine single 1 makes sense , isn't handled java. edit: division , sqrt clear me, need ideas add, sub , mult. if add 2 integer.max_value values, result not fit int , truncated. on other hand, if input domain restricted, can guarantee result not truncated , has expected value instead. for example, if x <= integer.max_value / 2 , y <= integer.max_value / 2 , sum x + y less or equal integer.max_value , there no truncation positive integers. similar reasoning can used negative values , integer.min_value . preconditions subtraction can done same way. for multiplication, if either operand absolute value less sqrt (integer.max_value) , product inside r...

replace python parent function with child function -

i have problem in inheritance python. i need override python function , whenever class called should call child method not parent. here code : in file called test_inherit.py class test_me(object): def get_uid(self, node): return uid and did : in file called test_new.py from test_inherit import test_me class test_new(test_me) def get_uid(self,node): print "x here",node return uid i need when call test_me class or test_new class , should call get_uid of test_new class don't know how achieve ?! it's simple .. have project has class "test_me" contain function called get_uid ,, , fuction called in project many times,i want call function of child when ever parent function called because don't want change main project ,, want edits in separate file . subclassing changes behavior of child class has no effect on parent. class may have many inheritors , wouldn't clear subclass should called if co...

VB.NET How to reuse/ requery/ reset /clear an existing chart to display new data -

i'm trying reuse chart i'm getting error a chart element name 'series1' not found in 'seriescollection'. every time try requery. tried add 3 line of codes before calling function no avail, ideas? chart1.datasource = nothing chart1.series.clear() chart1.chartareas.clear() my code: private sub button1_click(byval sender system.object, byval e system.eventargs) handles button1.click 'still getting same error 'chart1.datasource = nothing 'chart1.series.clear() 'chart1.chartareas.clear() getdata() end sub private sub getdata() if not cnninventory.state = connectionstate.open cnninventory.open() end if dim d1 datetime = datetimepicker1.value dim d2 datetime = datetimepicker2.value dim searchsql1 new oledb.oledbdataadapter("select * saleshistbl histdate >= #" & string.format("{0:mm/dd/yyyy}", d1) & "# , histdate <= #" & string.format(...

How to transpose a 2D list array using loops in python? -

say = [[1, 1, 1, 6], [0, 2, -1, 3], [4, 0, 10, 42]] , want transpose = [[1,0,4], [1,2,0], [1,-1,10], [6,3,42]] using loops in python. current code have is: def transpose(a): s = [] row in range(len(a)): col in range(len(a)): s = s + [a[col][row]] return s but gives me output of: [1, 0, 4, 1, 2, 0, 1, -1, 10] instead of this: [[1,0,4], [1,2,0], [1,-1,10], [6,3,42]] can me? i'm still new @ stuff , don't understand why doesn't work. much! use zip() >>> = [[1, 1, 1, 6], [0, 2, -1, 3], [4, 0, 10, 42]] >>> [list(x) x in zip(*a)] [[1, 0, 4], [1, 2, 0], [1, -1, 10], [6, 3, 42]] zip(*a) unpacks 3 sub-lists in a , combines them element element. meaning, first elements of each of 3 sub-lists combined together, second elements combined , on. zip() returns tuples instead of lists want in output. this: >>> zip(*a) [(1, 0, 4), (1, 2, 0), (1, -1, 10), (6, 3, 42)] [list(x) x in zip(*a)] converts each...

php - Use wordpress shortcode in post title -

i trying use following shortcode in wordpress post title. shortcode looks following: //use [year] in posts. function year_shortcode() { $year = date('y'); return $year; } add_shortcode('year', 'year_shortcode'); any suggestions how execute shortcode in post title? i appreciate replies! you can absolutely use shortcode in title. need use wordpress hooks system run shortcode when title called. if want have shortcode [year] spits out current year, you'll create shortcode: add_shortcode( 'year', 'sc_year' ); function sc_year(){ return date( 'y' ); } then, hook filter the_title() run shortcode: add_filter( 'the_title', 'my_shortcode_title' ); function my_shortcode_title( $title ){ return do_shortcode( $title ); } that takes care of post/page title, you'll want run single_post_title hook used in wp_head on title tag on site. way, browser show proper title well: add_filter( ...

php - Emulating Node/Express Routes in .htaccess -

Image
i have been trying emulate how nodejs/express work routes. forwarding traffic index.php process routes (using altorouter ). my file struture this: -/ --public/ |- assets |- ... --routes/ |- route.php |- ... --index.php take these urls instance (all should return/redirect 404): http://testsite.com/routes http://testsite.com/routes/route.php http://testsite.com/somefile.php however assets should directly accessible (i dont want include /public/ : http://testsite.com/assets/image.png http://testsite.com/assets/styles/style.css this have far: # make sure mod_rewrite on <ifmodule mod_rewrite.c> rewriteengine on # should allow our assets , keep them public rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d rewriterule ^(.*)\.(gif|jpg|png|jpeg|css|js|swf)$ /public/$1.$2 [l,nc] # forward other traffic index.php rewriterule ^.+$ index.php [l] </ifmodule> one issue i've come accross going: htt...

How to save a list of classes using javascript to compare them against other classes later? -

i have series of polygons : <svg> <path class="_1600 _1500 _1400 leaflet"></path> <path class="_1300 _1700 _1900 leaflet"></path> <path class="_1600 _1400 _1800 leaflet"></path> </svg> and buttons: <button class="_1600 _1500"></button> <button class="_1600 _1300 _1200"></button> <button class="_1300 _1200 _1700 _1800"></button> <button class="_1300 _1200 _1100 _1900"></button> i need assign class on click , how , works fine: on click: this.getelement().classlist.add("active"); now polygons become: <svg> <path class="_1600 _1500 _1400 leaflet"></path> <path class="active _1300 _1700 _1900 leaflet"></path> <path class="_1600 _1400 _1800 leaflet"></path> </svg> how can save list of classes of...

python - Understanding dimension of input to pre-defined LSTM -

i trying design model in tensorflow predict next words using lstm. tensorflow tutorial rnn gives pseudocode how use lstm ptb dataset. reached step of generating batches , labels. def generate_batches(raw_data, batch_size): global data_index data_len = len(raw_data) num_batches = data_len // batch_size #batch = dict.fromkeys([i in range(num_batches)]) #labels = dict.fromkeys([i in range(num_batches)]) batch = np.ndarray(shape=(batch_size), dtype=np.float) labels = np.ndarray(shape=(batch_size, 1), dtype=np.float) in xrange(batch_size) : batch[i] = raw_data[i + data_index] labels[i, 0] = raw_data[i + data_index + 1] data_index = (data_index + 1) % len(raw_data) return batch, labels this code gives batch , labels size (batch_size x 1). these batch , labels can size of (batch_size x vocabulary_size) using tf.nn.embedding_lookup() . so, problem here how proceed next using function rnn_cell.basiclstmcell or using user defined lstm model? input dimensi...

android - Why does TextView.setText() warn you not to concatenate strings? -

if this sometextview.settext(somestring + " , more!"); it warns me "do not concatenate text displayed settext. use resource string placeholders." why warn when string concatenation seems work fine? it's better use resource strings thinking localization

transitive closure - (Prolog) How to find if a connection exists between 2 predicates -

this have far. need show if 2 stations connected via third station, connected each other station(hamburg). station(bremen). station(hannover). station(berlin). station(leipzig). station(osnabruck). station(stuttgart). station(fulda). station(munich). adjacent(hamburg, bremen). adjacent(hamburg, berlin). adjacent(berlin, hannover). adjacent(berlin, leipzig). adjacent(leipzig, fulda). adjacent(fulda, hannover). adjacent(hannover, osnabruck). adjacent(osnabruck, bremen). adjacent(stuttgart, munich). /* insert clauses here */ adjacent_(x,y) :-adjacent(y,x) . adjacent_(x,y) :-adjacent(x,y) . connected(x,y) :-adjacent(x,y) . connected(x,z) :-connected(x,y), adjacent_(y,z) . your first connected clause fail clause like: ?- connected(bremen, hamburg). presumably meant write connected(x,y) :- adjacent_(x,y) . instead. other above bug, code seems fine. thing i'd add you're not guarding against "cycles". e.g. if trying find if berlin connected fulda...

javascript - Cannot use letter x to start html attribute in Angular -

i noticed strange angular 1.5.6 components. have component called scale. call it: <scale x-scale="xscale"></scale> and in controller: $scope.xscale = 'lin'. and component definition: angular .module('myapp') .component('scale', { templateurl: 'analyse/components/scales/scale.tpl.html', controller: function(){ console.log('in controller , ', this); }, bindings: { xscale: '=' }, }); the console log outputs undefined. but if change x-scale r-scale in template , xscale in binding rscale , works. in fact seems if replace x other letter, works. why this? it's in documentation directives normalization angular normalizes element's tag , attribute name determine elements match directives. typically refer directives case-sensitive camelcase normalized name (e.g. ngm...

Will a C program compile in a C++ workspace? -

i'm new c/c++ , have downloaded codelite ide (any other suggestions free ones welcome). intend write c program, gives me option create c++ workspace. can write c in workspace same? it depends on ide, compiler (which invoked ides compile code, , [not always] not part of ide), , type of code write. practically, quite few c++ compilers have "c mode" - example, command line switches or other settings may configurable through ide - compile c. you'll need read compiler , ide documentation. bear in mind compilers, in c mode, support c++ features not valid in c (and reverse true). it depends on sort of c code intend write, , how know features of c not part of c++, , vice versa. but, yes, general rule can write c program in c++ workspace. aware of concerns above when doing so. also, don't surprised when proudly show of lovingly crafted code seasoned c or c++ developer, informed writing hybrid of c , c++. unfortunately, writing hybrid of c , c...

arrayList<File> to folder containing those files java -

i have arraylist<file> . and need write files output_directory computer this code for (file file : corpus) { try { filewriter fw = new filewriter (new file(outdirname, file.getname())); bufferedwriter bw = new bufferedwriter (fw); printwriter out = new printwriter (bw); out.close(); } catch (exception e){ system.out.println(e.tostring()); } } the corpus arraylist of files the error java.io.filenotfoundexception: diroutput/name of file (no files or directories of types) most output directory doesn't exist. create output directory first , error gone. also, can use files.copy() java.nio.file avoid create multiple filewriter instances try { files.copy( paths.get(file.getabsolutepath()), paths.get(new file("<correct path>", file.getname()).getabsolutepath())); } catch (ioexception e) { e.printstacktrace(); } ...

Swift iOS AVVideoCapturePreviewLayer resolves to nil -

in viewdidload() section of code have let previewlayer = avcapturevideopreviewlayer(session: capturesession) previewview.layer.addsublayer(previewlayer) however when called in here resolves nil in compiler: func captureoutput(captureoutput: avcaptureoutput!,didoutputsamplebuffer samplebuffer: cmsamplebuffer!,fromconnection connection: avcaptureconnection!) { autoreleasepool { let imagebuffer = cmsamplebuffergetimagebuffer(samplebuffer)! let formatdescription = cmsamplebuffergetformatdescription(samplebuffer)! self.currentvideodimensions = cmvideoformatdescriptiongetdimensions(formatdescription) self.currentsampletime = cmsamplebuffergetoutputpresentationtimestamp(samplebuffer) // cvpixelbufferlockbaseaddress(imagebuffer, 0) // let width = cvpixelbuffergetwidthofplane(imagebuffer, 0) // let height = cvpixelbuffergetheightofplane(imagebuffer, 0) // let bytesperrow = cvpixelbuffergetbytesperrowofplane...

Swift POST or GET request for user authentication iOS Swift -

i wondering if there advantages/disadvantages in using post/get method in swift 2 send password , username web server in order authenticate user. working on iphone application fetches data web. request passes parameters url , server sends data back. modeled current application enums defining different endpoints each request , easy me model login same way. however, not sure if right direction. so get used retrieve remote data, , post used add/update remote data. for security reasons, not make difference. sure connection secured https certificate, , not allow http connections.

sqlite3 - Update one value Python SQLite without effecting others -

i trying update sqlite table value without changing rest. tried this: cur.execute("insert test values(%s)") it didn't work , tried google , looked on stackoverflow, couldn't find definite answer. you want use update , not insert . like update test set value1 = 'foo' value1 = 'bar' , value2 = 'baz' http://www.w3schools.com/sql/sql_update.asp

Ruby Hash and Tumblr API -

controller page , json output api i'm trying display posts users tumblr account on view page using ruby. have never done api's before. i'm trying use hash tables. controller code such: @posts = client.posts"zombieprocess1.tumblr.com" on view page using html have <%=posts%> the response such {"blog"=>{"title"=>"untitled", "name"=>"zombieprocess1", "total_posts"=>1, "posts"=>1, "url"=>"url", "updated"=>1478191052, "description"=>"", "is_nsfw"=>false, "ask"=>false, "ask_page_title"=>"ask me anything", "ask_anon"=>false, "followed"=>false, "can_send_fan_mail"=>true, "is_blocked_from_primary"=>false, "share_likes"=>true, "likes"=>1, "twitter_enabled"=>false, "twitt...

function - Why the final result varies? -

when returning function, following coding style not seem work - return (int) minim(mid-l,r-mid) + (int) (mid+mid==n)?1:0; but following code working fine - int x = minim(mid-l,r-mid); int y = (mid+mid==n)?1:0; return x+y ; mid, l, r, n integers. can please me understand why? you need add parentheses '+' takes precedence on ternary operator '?:' return (int) minim(mid-l,r-mid) + ((int) (mid+mid==n)?1:0);

Launching a jQuery Event from a Plugin on Checkbox Change -

i have following code: <script> $('#switch-1:checkbox').change(function() { if (this.checked) { $('#generatepassword').pgenerator({'uppercase': true}); } else { $('#generatepassword').pgenerator({'uppercase': false}); } }; </script> when checkbox checked or unchecked, want change parameters of plugin, goal generate password. in case i'm trying set parameter uppercase false or true depending if checkbox checked or not. how write code sends parameters plugin upon event of checkbox click? try this: $('#switch-1').click(function() { if($(this).prop('checked') == true) { $('#generatepassword').pgenerator({'uppercase': true}); } else { $('#generatepassword').pgenerator({'uppercase': false}); } };

spreadsheetgear checking HPageBreaks -

i use spreadsheetgear. i want check how many hpagebreaks in worksheet. i want check row content pagebreak. how that. have tried following code went wrong spreadsheetgear.iworkbook wb = wbvmain.activeworkbook; iworksheet wspo4printing = wb.worksheets["testing"]; pagecount = wspo4printing.hpagebreaks.count; the pagecount return 0 have many data on worksheet. thanks, lvd i assume looking pagecount based on natural or automatic page breaks. iworksheet. hpagebreaks / vpagebreaks collections take account manual page breaks--not automatic--and return 0 if no manual page breaks present in worksheet. spreadsheetgear 2012 not support determining automatic page breaks occur. automatic breaks not determined until begin printing, discarded after print job completes, there's no way spreadsheetgear give information, unfortunately.

css3 - Gradient overlay on Image with single line of CSS -

i'm trying put gradient on background image using code background: url('../img/newspaper.jpeg'),linear-gradient(to bottom right,#002f4b, #dc4225); background-size: cover; i'm getting image gradient not being applied add gradient first , add image url, this: background: linear-gradient(rgba(244, 67, 54, 0.95), rgba(33, 150, 243, 0.75), rgba(139, 195, 74, 0.75), rgba(255, 87, 34, 0.95)), url("http://placehold.it/200x200"); or @ snippet below: .bg { background: linear-gradient( rgba(244, 67, 54, 0.45), rgba(33, 150, 243, 0.25), rgba(139, 195, 74, 0.25), rgba(255, 87, 34, 0.45)), url("http://placehold.it/200x200"); width: 200px; height: 200px; } <div class="bg"></div> hope helps!

How can I increment the input statement in python? -

my question how show "student 1 name," "student 2 name" etc goes through loop 12 names? students = 12 x in range(students): name = str(input('student name: ')) grade = int(input('enter average grade: ')) to add andrew li's comment, can append string directly in python using "+" operator: in case don't want use format method, can try this: name = input("student " + str(x + 1) + " name: ")

javascript - Qt: How are arrays or dictionaries passed from qscriptengine? -

i've created qscriptengine , exposed object's function can call js script. engine->globalobject().setproperty("obj", myobj); myobj qobject has function like... void myobject::dosomething(int w, int h) { ... } and in js code, can call like... obj.dosomething(5, 9); this works expect would, can't find docs on passing arrays or dictionaries these functions. example, if wanted pass array, how define c++ function this... obj.dosomething([1,2,3], "foo"); would like... void myobject::dosomething(qvector<qvariant> firstarg, qstring secondarg); it's hard work out when doesn't work, call seems silently fail. for arrays have 2 options registering c++ sequence container script engine, see qscriptregistersequencemetatype() . function's documentation has example int vector. use qscriptvalue function's argument. passed object can checked if array ( qscriptvalue::isarray() ) , accessed index using qscr...

exoPlayer not playing a radiostream on specific android device(s) as a service -

so have 3 real devices : (a) samsung galaxy s3, (b) nexus 1 (c) samsung galaxy note 3 i tried play radio stream in activity using below code of devices , worked : private static final int buffer_segment_size = 64 * 1024; private static final int buffer_segment_count = 256; private static final int renderer_count = 1; exoplayer exoplayer = exoplayer.factory.newinstance(renderer_count); exoplayer.addlistener(this); uri radiouri = uri.parse(streaminglink); allocator allocator = new defaultallocator(buffer_segment_size); string useragent = util.getuseragent(this, "randomthing"); datasource datasource = new defaulturidatasource(this, null, useragent); extractorsamplesource samplesource = new extractorsamplesource(radiouri, datasource, allocator, buffer_segment_size * buffer_segment_count); mediacodecaudiotrackrenderer audiorenderer = new mediacodecaudiotrackrend...

java - Using recursion, getting max int out of a string of numbers and letters? -

my class on chapter 18 of intro java book, chapter recursion. says: "for assignment, write 2 recursive functions, both of parse length string consists of digits , numbers. both functions should in same class , have following signatures." now first 1 int sumit(string s) sum ints in given string. completed part, , have @ each char , see if number , add total if so. in return, recall function char removed. the second function int findmax(string s, int max). way think work start max 0 , call function again in return, , each time check if next int bigger max, , replace if so. wrote similar first function(check code), realized, in one, cannot go character character. if string "xg12zz128-p/9" max should 128. there doesn't seem simple way next integer in string. i'm not sure do. here code: public class finder { public int sumit(string s) { int total = 0; if(s.length() > 0) { // checks string still has characters ...

How to write to Firebase table only if its greater than current value in table -

i need update table level value in firebase score table if table value less value being posted update. keyoflevel value never decreases. since client side involved calls fetch , check. need in rules tab of firebase. , don't know how write rules. eg: score: { "1234567890": { coinskey: 1000, keyoflevel: 5 } } where 123456789 user id. you might want write security rules this. { "rules": { "score": { "$userid": { "keyoflevel": { ".validate": "!data.exists() || data.val() < newdata.val()" } } } } } in place of .validate can use .write

django - Update form not work after using custom clean method -

my model form: class memberform(modelform): birth_date = forms.datefield(widget=forms.widgets.dateinput(format="%m/%d/%y")) class meta: model = person exclude =('user',) def clean(self): user = get_user(self.request) name = self.cleaned_data.get('name') birth_date = self.cleaned_data.get('birth_date') if person.objects.filter(user=user).exists(): self.add_error('name', "you submitted data") elif person.objects.filter(name=name, birth_date=birth_date).exists(): self.add_error('name', "person name , birth date exists.") return self.cleaned_data def save(self, commit=true): person = super().save(commit=false) if not person.pk: person.user = get_user(self.request) if commit: person.save() self.save_m2m() return person my views: class person...

Time complexity of javascript Array.prototype.filter()? -

what big o of array.protoype.filter ? i have looked @ documentation ( https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/array/filter ) haven't been able work out.

Stata failing to call global variable? -

the following simple thing doesn't work. global inputfolder "c:\users\focus\google drive\1. hani and\raw data\2004" cd $inputfolder it says invalid syntax but if global inputfolder "c:\users" cd $inputfolder then works. tried, among others, adding "=" global inputfolder="c:\users\focus\google drive\1. hani and\raw data\2004" but didn't help. what should make first thing work? when write global inputfolder "c:\users\focus\google drive\1. hani and\raw data\2004" cd $inputfolder stata substitutes global reference contents of global, cd sees cd c:\users\focus\google drive\1. hani and\raw data\2004 but spaces problematic. advice prominent in cd (see e.g. http://www.stata.com/help.cgi?cd ): if directory_name contains embedded spaces, remember enclose in double quotes. hence need cd "$inputfolder" note difference between copying string global , assigning str...

Economic simulation in R -

i'm trying create program simulates economic model. have parameters, have able change. should this. question how create program can decide time period, , parameters. let's capital period 1 given capital_1=(1-s)*output_0+capital_0. labour given labour_1=(1+n)*labour_0. output_1=capital_1*labour_1*k s,n , k parameters time | output | capital | labour | ------ | ------ | ------- | ------ | 0 | 10 | 2.5 | 2 | 1 | ... | ... | ... | 2 | ... | ... | ... | 3 | ... | ... | ... | the following should more enough give hint on how tackle this. not clear, whether homework or not, there might 1 or 2 problems code force you, @ in close detail , maybe make 1 or 2 corrections. principle of how works should obvious, though output <- 10 capital <- 2.5 labour <- 2 generator <- function(steps,s, n, k){ for(i in 2:(steps)){ capital[i] <- (1-s)*output[i-1]+capital[i-1] labour[i] <-...

r - how to import a dataframe with character lines between values -

i have dataframe brief description of software , lines between values this model: li-1500 light sensor logger config: salida session remark: software version: 1.0.0 v1 v2 v3 30 55 55 10 20 50 model: li-1500 light sensor logger config: salida session remark: software version: 1.0.0 i can remove first description using arg skip in read.table function haven't find way of remove text between values of dataframe thanks lot!!

c# - Where does Dispatcher get control from? -

in user-control, have thread besides main thread process data, show result in text box this private delegate void settextcallback(string text); private void settext(string text) { if (!dispatcher.checkaccess()) { dispatcher.invoke(new settextcallback(settext), text); return; } txtresult.text = text; } private void processthread() { string result = ""; // process ... settext(result); } on first application run, user-control worked perfectly. if close , open again, it's not working. debug settext function, txtresult.text show value has been assigned it's empty on ui. tried other controls enabling button result same: in debug, controls had held new value not on ui. got feeling thread got controls closed user-control. can tell me what's wrong ? in advance , sorry bad english. update my thread initilization: private timer _timer; public myusercontrol() { initializecomponent(); _timer = new timer(proce...

angular - How to know if component is currently the loaded component in router-outlet -

i have application lazy loaded modules. in 1 specific lazy loaded module, have parent component, has router-outlet . in parent component have button emit event using shared service (provided on lazy loaded module). each child component (which loaded in router-outlet ) subscribing event using same shared service! i tried recreate use case in following plunkr using heroes demo . open dev tools see console messages. click on heroes link (it should selected default). click on hero item list. click on admin link. click on emit test button (upper right nav) you'll see -in console- event received both components, both components should not ' active ' !!! 1) design? 2) how know if current component active one? summary/update from understanding, eventemitter/subject can subscribed many times, when unsubscribed cannot use it/subscribe afaik. my solution was: 1) in service ended doing folowing: get(){ if (!this.testevent.closed) { th...

python - How can I change recursive traversal of binary tree code to non-recursive traversal? -

class binarytree: def __init__(self, element, parent=none, left=none, right=none): __slots__ = '_element', '_parent', '_left', '_right' self._element = element self._parent = parent self._left = left self._right = right def getparent(self): return self._parent def getleft(self): return self._left def getright(self): return self._right def getsibling(self): if self.isroot(): return none elif self.getparent().getleft() == self: return self.getparent().getright() elif self.getparent().getright() == self: return self.getparent.getleft() else: raise valueerror("strange node") def _setparent(self, container): self._parent = container def _setleft(self, lchild): self._left = lchild def _setright(self, rchild): self._right = rchild def add...

Try successive methods until OK in PHP -

i create object using different methods in given order. goal try these methods until find 1 returns different null. $a = method_1(); if(!$a) $a = method_2(); if(!$a) $a = method_3(); ... if(!$a) print "error"; until then, doing using imbricated if-else structures. there more "elegant" way program ?

Sharing python globals() cross files -

this questions related global-scope of python. there have 2 files below. filea.py import pprint pprint.pprint(globals()) fileb.py import filea def global_funcb(): return "global_funcb" when run python fileb.py . globals() of filea.py contains filea's content. is possible address of global_funcb in fileb.py filea.py? far, can fileb.py. note: purpose, there no way import fileb filea.py [edit] let me describe purpose clearly. loader.py class loader(object): def __init__(self, module): print(dir(module)) builder.py + class function import loader class someobj(object): def somefunc(self): pass loader.loader(someobj) if passing module/class fileb build filea, it's possible fetch function of fileb. however, if function in builder.py globally. builder.py + global function import loader def someglobalfunc(self): pass loader.loader(???) i have no idea how pass globals() module/class file. ...

decision tree - Machine Learning - AdaBoost the best standalone algorithm -

on given problem, i've checked using k-fold (k=10) few standalone algorithms among them cart , knn. knn came upper hand on cart , furthermore tuned using best k found (3). when went on check ensemble methods tried adaboost tuned knn , default cart , surprisingly cart performed better. i'm not deep math behind scenes don't understand how makes sense. so 2 questions: how come adaboost cart performed better tuned knn? if standalone performance not predict ensemble base estimator, how wisely choose base estimators ensemble methods?

How to hide a div with it's id in angularJS? -

here want hide div id,is possible in angularjs.i know possible hide ng-hide or ng-show .but dont know how hide div it's id. you can use old jquery that, it's preferable avoid modifying dom directly that. using scope variable give far more flexibility modifying style attributes directly. use ng-if if don't want markup in dom.

java - Integer to char - cast and print: -

i want know logic behind programm , (char ) cast. how work , how printing letters, symbols , numbers package ascii1 public class ascii1 { public static void main(string[] args) { int i=1; while(i<122) { system.out.println((char)i+"\t"); if (i%10==0) system.out.println(""); i++; } } } its output is: //blanks in beginning... ! " $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = ? @ b c d e f g h j k l m n o p q r s t u v w x y z [ \ ] ^ _ ` b c d e f g h j k l m n o p q r s t u v w x y build successful (total time: 0 seconds) using ascii representation , every char has numerical value. when...

Jupyter notebook: How to \usepackage{} in for LaTeX -

i know how can \usepackage{} latex in jupyter notebook. not sure even best way of doing seems work. write template file ("mytemplate.tplx") in same directory ipynb notebook file ("mynotebook.ipynb"). mytemplate.tplx looks like: ((*- extends 'article.tplx' -*)) ((* block packages *)) ((( super() ))) \usepackage{amsmath} \usepackage{newtxtext,newtxmath} ((* endblock packages *)) build pdf latex file executing following: jupyter nbconvert mynotebook.ipynb --to latex --template mytemplate.tplx pdflatex mynotebook.tex

wordpress - Woocommerce Filter to update tax_class -

this filter work well. <pre><code> function wc_diff_taxes_for_ajax( $tax_class, $product ) { $tax_class = 'zero product'; return $tax_class; } add_filter( 'woocommerce_product_tax_class', 'wc_diff_taxes_for_ajax', 1, 2 ); </code></pre> i try fire filter inside other function have error... ajax part call , response. don't put here. <pre><code> function manage_taxes_aliquota() { if(isset($_post['tax_class'])) { <--what put here fire filter , pass new $tax_class--> } echo 'ok'; exit; } add_action('wp_ajax_nopriv_manage-taxes-aliquota', 'manage_taxes_aliquota'); add_action('wp_ajax_manage-taxes-aliquota', 'manage_taxes_aliquota'); </code></pre> regards.

listview - Custom adapter Filtering -

i using custom adapter listview, , searchmenu, before using filter gives me correct information example: name1 - email1 name2 - email2 name3 - email3 but after using filter searching names correct email column gives 1 row info. example: name3 - email1 how can solve problem, im new in java, 5 days work on problem. customrow adapter public class custom_row extends arrayadapter<string> { arraylist<string> list; public custom_row(context context, arraylist<string> names, arraylist<string> email) { super(context, r.layout.custom_cell, names); list = email; log.e("database operations", string.valueof(list)); } @override public view getview(int position, view convertview, viewgroup parent) { layoutinflater peoinf = layoutinflater.from(getcontext()); view customview = peoinf.inflate(r.layout.custom_cell, parent, false); string names = getitem(position); string email = list.get(position); textview name_text ...

Leaks in Swift 3 / iOS 10 -

when i'm running instruments , check leaks, it's showing leaks consisting of: _contiguousarraystorage<string> _nativedictionarystorageowner<int, cgfloat> _nativedictionarystorageowner<string, anyobject> this when i'm using swift 3 , testing on devices using ios 10. the leaks show in ios 10 while on ios 9.x seems normal. on top of that, in ios 10 uiswitch doesn't seem deallocate either. currently i've been creating kinds of workarounds trying avoid using dictionaries , in cases arrays, making annoying code. question: should concerned , try fix these leaks or wait , hope fixed in future updates? if so, there anywhere check bugs known etc? i had same problem , spent lot of time digging. found if create swift object objective-c code , swift object has native swift dictionary property, see leak. won't happen if code swift, , more usefully, won't leak if change native swift dictionary nsdictionary. applies swift set'...

email - Procmail mail to file -

i want configure procmail. right i've got code redirect mails selected topic server mail mail. it's code: :0 c *subject.*exampletopic example@mail.com i want copy mail content selected .txt file on server. how can it? your current code saves copy folder named example@mail.com . save file different name, change string. (to forward each matching message email address, syntax ! email@example.com exclamation mark action "verb".) the default saving action appends flat text file in berkeley mbox format. includes both headers , body. b flag can save email body, still raw mime transport format, want. :0b * condition, perhaps bodyfile.txt procmail regrettably knows nothing mime, if getting particular body part need, you'll want pipe message script understands mime , can implement extraction policy. :0 * condition, maybe | extracttool >>bodyfile.txt the vague wording of question implies not familiar details of email formatting in general ,...

symfony - How To get list of cities of selected country if country is not an entity using Dynamic Generation for Submitted Forms -

i have entity travel , dispaly list of cities of selected country in add form. i have applied example in documentation : [ http://symfony.com/doc/current/form/dynamic_form_modification.html#dynamic-generation-for-submitted-forms][1] in example , sport entity , has method called getavailablepositions() in example country not entity , countrytype::class . if have in example in documentation must instantiate un entity country don't have one $formmodifier = function (forminterface $form, country $country = null) { // country doesn't exist , wrong $cities = null === $country ? array() : $country->getcities(); $form->add('city', entitytype::class, array( 'class' => 'appbundle\entity\city', 'choices' => $cities, 'choice_label' => 'name', 'label' => 'city', 'multiple' => false, 'exp...