Posts

Showing posts from March, 2010

c# - ForEach extension method -

i'm bit confused on line of code: enumerable.range(1,10).tolist().foreach(console.writeline); this line says does, prints out each number 1 10 line break inbetween each of them, 1 neat little line of code.. now i'm c# novice @ best, looks foreign me, how can call console.writeline() without providing arguments? how know it's going print? syntax it's not clear me we're calling on method (considering lack of paranthesis around writeline ). i'm assuming there's lot of stuff going on "behind scenes" here i'm not @ reading il code, i've gathered reading msil seems foreach calls generic delegate( system.action ) on each element in collection, guessing passes element argument system.action delegate that's guess.. there implicit conversion method group ( console.writeline in case) , compatible delegate type. code same as action<int> f = console.writeline; enumerable.range(1,10).tolist().foreach(f); the delegat

jquery - Anyway to start animate smoothly? -

so, instead of using plugin wanted make basic marquee. fair enough. easy enough. works decent. thing bugs me way animate starts little slow , speeds up. there anyway solid speed out of animate function? slow down @ beginning it's no fluid. var marquee = $('#marquee'), marqueetext = marquee.find('span:first'), marqpos = marquee.position(), marqtextpos = marqueetext.position(), runmarquee = settimeout(startmarquee, 1000); function startmarquee() { marqueetext.css('left', (marqpos.left - marqueetext.width() - 8)).animate({ 'left': (marqpos.left + marquee.width() + marqueetext.width() + 8) }, { duration: 5000, complete: function () { startmarquee(); } }); } update as adeneo pointed out below, adding easing animate setting linear linear movement remedy problem. not need timeout loop. see updated fiddle. jsfiddle demo add linear easing (the default swing ) e

java - Is there any Comparable not comparable to itself? -

in contract of comparable , there's nothing forcing object comparable itself. it's just strongly recommended, not strictly required (x.compareto(y)==0) == (x.equals(y)) which implies it's recommended x.compareto(x) not throw. it's possible write a class x implements comparable<y> { ... } where x , y 2 unrelated classes. can't see for, in java 8 version of hashmap there's corresponding check. is allowed implement x implements comparable<y> 2 unrelated classes? does make sense? i guess answers yes , no, it's guess comparable promotes contract comparisons should consistent equals, i.e. (a.compareto(b) == 0) == a.equals(b) . not force , weird contract can enforced. so create a: class dumbinteger implements comparable<dumbinteger> { private final int i; public dumbinteger(int i) { this.i = i; } public int compareto(dumbinteger di) { return 0; } public boolean equals(object other) { /

No results with PHP search in MongoDB? -

i have database store dns logs. data stored in collection dnslog . document structure: { "_id" : objectid("53539df1e4b076aa8975840a"), "dateandtime" : isodate("2014-04-09t03:42:48z"), "client" : "222.29.72.224", "query" : "www.google.com", "other" : "aaaa" } i stored week's log database , total count 821943936; have following php script search results: $m = new mongoclient(); echo "connection database successfully"."<br />"; $db = $m->dns; echo "datebase dns selected"."<br />"; $collection = $db->dnslog; echo "collection selected succsessfully"."<br />"; $startdate = new mongodate("2014-04-09 11:42:00"); $enddate = new mongodate("2014-04-09 11:43:00"); $result = $collection->find(array("dateandtime"=>array('$gte'=>$startd

c - Unable to understand the spacefree function in scullpipe driver -

i reading "linux device drivers 3" , having trouble understanding following code: /* how space free */ static int spacefree(struct scull_pipe *dev){ if(dev->rp == dev->wp) return dev->buffersize - 1; return ((dev->rp + dev->buffersize - dev->wp) % dev->buffersize) - 1; } based on understanding: 1. *buffer beginning of buffer. 2. *end ending of buffer. 3. end = buffer + buffersize 4. so, buffersize total size of buffer. if(dev->rp == dev->wp) return dev->buffersize - 1; the above code correct, if both read pointer (rp) , write pointer (wp) @ beginning of buffer. because if no data written buffer, write pointer (wp) @ beginning of buffer (unless write pointer (wp) has wrapped), hence, total amount of free space equal buffersize . but not sure whether above code correct, if both read pointer (rp) , write pointer (wp) point end of buffer (or point memory location in middle of buffer). if write pointer (wp) points end of

ssh - Find (by name) and delete a directory and its contents -

i have been able create following command, works extent: find . -type d -name "thumbs" -delete however, deleted empty folders. if found folder called 'thumbs' wasn't empty, didn't delete it. how can find folders called 'thumbs' , delete them, including contents? found answer! use following (with caution): find . -type d -name "thumbs" -exec rm -rf {} \;

c++ - Can boost::lockfree::stack accept string pointers safely? -

i've discovered passing string pointer boost::lockfree::queue cause memory leak because string pointer cannot released. is situation same boost::lockfree::stack ? the requirement boost::lockfree::stack is: t must have copy constructor if regular string pointer cannot used, there other way string can put boost::lockfree::stack ? regular string when try this boost::lockfree::stack<string> my_stack(128); i these errors boost_static_assert(boost::has_trivial_assign<t>::value); boost_static_assert(boost::has_trivial_destructor<t>::value); which seems strange me, because of inexperience, because requirements boost::lockfree::queue strangely has no documentation t must have copy constructor t must have trivial assignment operator t must have trivial destructor the missing documentation doxygen bug, documentation page gets name macro :(, , here: http://www.boost.org/doc/libs/1_55_0/doc/html/boost/lockf

java - ReadFile cannot be resolved to a type -

i consider rookie , have searched hours on internet solve problem still no luck. i want understand java , if explain detail highly grateful. the problem in line readfile file = readfile(file_name); error message : "readfile cannot resolved type." here code: filedata.java package textfiles; import java.io.ioexception; public class filedata { public static void main (string[] args) throws ioexception { string file_name = "d:/java/readfile/test.txt"; try { readfile file = readfile(file_name); string[] arylines = file.openfile(); int i; (i =0; < arylines.length ; i++) { system.out.println( arylines[i] ); } } catch (ioexception e) { system.out.println( e.getmessage() ); } } } and other code: readfile.java package textfiles; import java.io.ioexception; import java.io.filereader; import java.io.buf

Store value in SharedPreference and get From it in android -

i new android , have been using code save value of checkboxes when app closes works fine (in settings.class) public void putbooleaninpreferences(boolean ischecked,string key){ sharedpreferences sharedpreferences = this.getpreferences(activity.mode_private); sharedpreferences.editor editor = sharedpreferences.edit(); editor.putboolean(key, ischecked); editor.commit(); } public boolean getbooleanfrompreferences(string key){ sharedpreferences sharedpreferences = this.getpreferences(activity.mode_private); boolean ischecked = sharedpreferences.getboolean(key, false); return ischecked; } but want use same saved value in activity (progress.class) here activities settings.class checkbox_one = (checkbox) findviewbyid(r.id.checkbox1); boolean ischecked = getbooleanfrompreferences("ischecked"); log.i("start",""+isc

mysql - #1005 - Can't create table 'xxx.item' (errno: 150) -

i creating database hotel , not able create "item" table. the error shown #1005 - can't create table 'xxx.item' (errno: 150) below sql queries: create table menu ( menu_id int , menu_name varchar(100) , primary key (menu_id) ); create table categories ( categories_id int , category_name varchar(100) , primary key (categories_id) ); create table menu_category_item ( mci_id int , menu_id int , categories_id int , item_id int , item_type int , restaurant_id int , primary key (mci_id) , foreign key (menu_id) references menu(menu_id) , foreign key (categories_id) references categories(categories_id) , foreign key (restaurant_id) references restaurants(restaurant_id) ); create table item ( item_id int , item_name varchar(100) , item_price decimal , foreign key (item_id) references menu_category_item (item_id) ); please me out of this!! i think problem in

javascript - How to get window id of the popup window that is created by chrome.windows.create() -

how window-id of popup window created chrome.windows.create() background.html window_options={ "url":"another_popup.html" "type":"popup" }; chrome.windows.create(window_options,call_back_function) call_back_function(window window) { console.log(window.id) //prints window's id } another_popup.html(the page popup window holds) $(document).ready(function() { console.log(window.id) //says ,cannot find property , gives null }); there no such property window.id in javascript. however, have such property in callback function when using chrome api (chrome.windows.create) not associated javascript (javascript not recognize internal browser's identification system). inside extension scope can use example chrome.tabs.getcurrent method retrieve information current tab. in callback function you'll have id. note id optional , may not set.

How do I return a longitude and latitude from Google Maps JavaScript geocoder? -

this question has answer here: how return variable google maps javascript geocoder callback? 5 answers when use code below alerting blank value? why that? html <body onload="initialize()"> <div id="map_canvas" style="width: 320px; height: 480px;"></div> <div> <input id="address" type="textbox" value="sydney, nsw"> <input type="button" value="encode" onclick="display()"> </div> </body> javascript var geocoder; var map; function initialize() { geocoder = new google.maps.geocoder(); var latlng = new google.maps.latlng(-34.397, 150.644); var myoptions = { zoom: 8, center: latlng, maptypeid: google.maps.maptypeid.roadmap } map = new google.maps.map(document.getelementbyid(&q

html css un-expected gap around left side and top need to fix -

okay have started out desingning website scratch html , css here link have far https://c9.io/ashg1990/secure/workspace/client/index.html and here code below html file <!doctype html> <html lang="en"> <head> <link rel="stylesheet" type="text/css" href="css/style.css"> <meta charset="utf-8" /> <title>arg modular</title> </head> <body> <div class="head"> <img class="header" src="img/headlogo.png" alt="logo" /> </div> </body> </html> and css file body { background-color:#a8a1a3; width:110%; } div.head { background-image: -webkit-gradient( linear, left top, left bottom, color-stop(0, #ffffff), color-stop(1, #a8a1a3) ); background-image: -o-linear-gradient(bottom, #ffffff 0%, #a8a1a3 100%); background-image: -moz-linear-gradient(bottom, #ffffff 0%, #a8a1a3 10

java - I'm unsure on how to save my float value on pause/destroy of the app -

i have app clicking image makes value (goldcount) increase 1. when run, app runs splash, before starting app. however, should minimize or close game, goldcount value reverts 0.0, , tutorials on sharedpreferences giving me no clues how may go saving float value. my main java code: package com.bipbapapps.leagueclickerapp; import android.app.activity; import android.graphics.typeface; import android.os.bundle; import android.view.gravity; import android.view.view; import android.view.view.onclicklistener; import android.view.window; import android.view.windowmanager; import android.widget.button; import android.widget.textview; public class mainclass extends activity implements onclicklistener { public float goldcount = 0.0f; button minionclick; textview textgoldcount; string texttotal; @override public void oncreate (bundle savedinstancestate) { super.oncreate(savedinstancestate); //set fullscreen requestwindowfeature(window.feature_no_title); getwindow()

Custom folder under vendor not loaded on Rails 4 -

i bought theme , want apply whole theme site. i put line in scss file *= require_tree ../../../vendor/assets/lenord-single-page-theme/css but didn't include folder want rails.application.config.assets.paths => ["pixnet_hackathon/website/dqa_streesful_server/app/assets/ace-admin-theme", "pixnet_hackathon/website/dqa_streesful_server/app/assets/images", "pixnet_hackathon/website/dqa_streesful_server/app/assets/javascripts", "pixnet_hackathon/website/dqa_streesful_server/app/assets/lenord-single-page-theme", "pixnet_hackathon/website/dqa_streesful_server/app/assets/stylesheets", "pixnet_hackathon/website/dqa_streesful_server/vendor/assets/javascripts", "pixnet_hackathon/website/dqa_streesful_server/vendor/assets/stylesheets", ".rvm/gems/ruby-2.1.0/gems/simple-navigation-bootstrap-1.0.0/vendor/assets/stylesheets", ".rvm/gems/ruby-2.1.0/gems/bourbon-3.1.8/app/assets/stylesheets&qu

android - Library import error -

Image
i need import tow external library project; 1-android-support-version 7(that added correctly) 2-a list-view animation library. that project not add last library(list-view animation). at first adding , worked right , after deleted , added again not work. i try several time adding library several location,then restart eclipse have problem yet , can't find library : go drive,where workspace located.delete list view animation library workspace in hard disk (i.e. manually drive) , try again.that should work.if not,then create new workspace , import again.

regex - validate a 10 digit USA style phone number using a Regular Expression in Javascript -

i want validate 10 digit usa style phone number using regular expression in javascript it should allow (validate correct) following formats: xxx-xxx-xxxx 215-121-1247 it should reject invalid: 8059311142 805 931 42ab 105 931 4288 i found regex implement below, can't work. /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/ please me on this you can as: ^\d{3}-\d{3}-\d{4}$ demo: http://regex101.com/r/jv1hp3 to understand regex doing, check this link

regex - I need regular expression to replace everything than certain text -

i want write regular expression can extract time data in format in following examples: 2 hours 2 hours 2 hours 30 minutes 2.5 hour i'm trying done , written following regular expression - [^0-9\s(h|h)our(m|m)in\.]? but when test - matches characters 'our' , 'in' separately. want match words 'hour' , 'hour' , not subset of characters. perhaps try this? (\d+(?:\.\d+)?)\s(?:h|h)ours?(?:\s(\d+)\s(?:m|m)inutes?)? the first group number of hours, second group number of minutes

php - Yii - reacting to attribute model assignation -

i want following in yii: when attribute `a` in model class `m` set, something. and tried using setter like: seta($value) it's not called since yii cactiverecord first detects if attribute exists in database (and assigns it) , if not exist in database (i.e. it's not table attribute) normal instance variable looked up. final fallback calling property accesor. ( edit - wrong resolution order: lookup seems first instance variable, attribute, , accessor - anyway, problem still same since accesor resolved if no database field exists name) here it's shown internal mechanics of __set (and bit upper, __get). question : how can invert order, @ least attribute? means: want capture database field edition setter seta($value) , performing field assignation (i.e. actual $this->a, should done without falling in stack overflow error) inside seta method a reasonable approach override cactiverecord::setattribute in model class behave way need to: class m ext

javascript - Topaz Signature Sigplus web. Is it possible to set windowless in firefox -

i have been trying find way set sigplus web firefox windowless mode. i have in vendors website no luck. couldnt find related it. have experiment different properties found in sigplus object within dom, negative results. there's not documentation out there on it. know if possible??? or if there workaround signature container wont show on top of fixed positioned divs?? this firefox, so, more npapi version of it, not activex. this website of npapi version: http://www.topazsystems.com/software/download/sigplusweb.htm thank much.

OTRS Email attachments not visible -

i've got otrs server running, functional. problem ticket attachments can viewed in web interface, , not in emails. have open ticket in browser first, before can view attached images , on. in web interface, displays fine. does have /opt/otrs/bin/otrs.articlestorageswitch.pl fs db? or there else i'm missing? thanks in advance, ben there sysconfig function this ticket -> frontend::agent::ticket::articleattachmentmodule there should 2 modules. in the framework -> core::web::attachmentdownloadtype you can select module use. this default set attachment, when set inline doesn't download attachment shows them inline.

Javascript / jQuery page change event on mobile browsers -

i designing mobile website keeping in mind leading browsers - safari, chrome, dolphin, opera. i want show "loading" element , when page navigates / changes / new page requested . i cannot use click event on anchor tags there many ones present preventdefault(); . i tried following: $(window).on('beforeunload', function() { ... }); but not work in dolphin or opera . can suggest cross-browser solution ? -- edit : realize wasn't clear in asking question, apologies. created fiddle here- http://jsfiddle.net/hiteshpachpor/7dada/5/ based on response. example makes use of event bubbling. now here's problem facing. showing loader ( $('.jacket').show(); ) each time page changes / navigates. don't want show if link clicked; want other operations on page instead. now, adding $('.jacket').hide(); line in such actions totally suffice not ideal scaling reasons. this why evaluating 'beforeunload' method, no luck there not

javascript - Uncaught ReferenceError: QRCode is not defined -

i tried implement qrcode in html-template: <div id="qrcode"> <script type="text/javascript"> new qrcode(document.getelementbyid('qrcode'), 'http://jindo.dev.naver.com/collie'); </script> </div> in qrcode.min.js have this: var qrcode = new qrcode(document.getelementbyid("qrcode"), { text: "http://jindo.dev.naver.com/collie", width: 128, height: 128, colordark : "#000000", colorlight : "#ffffff", correctlevel : qrcode.correctlevel.h }); but still error , qrcode don't show off.. here path: <script "type=text/javascript" src="qrcode.min.js"></script> solved i solved issue. the problem integrated : var qrcode = new qrcode(document.getelementbyid("qrcode"), { text: "http://jindo.dev.naver.com/collie", width: 128, height: 128, colordark : "#000000", colorlight : "#ff

c# - "/" character has been replaced with the string "%2F" in error page -

i have error page in web config i.e; <customerrors mode="off" defaultredirect="/contents/error.aspx"> </customerrors> whenever error happens re-direct error.aspx;but in error aspx if click button try redirect %2fcontents%2ferror.aspx. can me resolve.

c# - How do you pass object data into textboxes in a second form to edit? -

i relatively new c# , use getting on hurdle. have windows form along classes create call objects values entered user , add them list. take existing call , display values in different text boxes in seperate form opened when click button. have 'findcall' method finds desired call in list 'callername' , 'phonenumber' values. if call found display edit form. works fine , form opens, know code find call functioning properly. cannot wrap head around how can display values of call object in text boxes on edit form. appreciated. thanks a simple way create property on second form. allow set values on form before displaying , new values afterwards. on edit form have like... string somevalue { { return somevaluefield.text; } set { somevaluefield.text = value; } } ...where somevaluefield textbox on edit form. then in calling form can access textbox via property... var editform = new editform(); editform.somevalue = "..."; editf

c# - here my code if to navigate the files and copy if exist the files -

i'm having error please me. the error: 1 expected catch or finally the code: class program { static void main() { string sourcedir = @"c:\source";//folder directory path// try { var txtfiles = directory.enumeratefiles(sourcedir, "*.*", searchoption.alldirectories).where(s => s.endswith(".jpg") || s.endswith(".bmp") || s.endswith(".png") || s.endswith(".gif") || s.endswith("jpeg"));//identify extension name// foreach (string currentfile in txtfiles) { string filename = currentfile.substring(sourcedir.length + 1); directory.getfiles(currentfile, path.getextension(filename)); directory.getfiles(currentfile, path.getfilename(filename)); directory.getfiles(currentfile, path.getfilenamewithoutextension(filename));

Grand Total in Summary Band using Delphi Report Builder -

i have 2 variables in detail tab using delphi report builder , running totals correct. getting data 2 sets of client data sets within delphi code. now need grand total of total comes variables in details band calculate in summary band. how go doing this? declare global variable , set that? , if yes how use global variable 2 different totals? in advance. (i assume mean digital metaphor's report builder - not sure if that's bundled delphi or not...) to create grand totals: just create summary band in designer: report->summary , , put 2 dbcalc components in there. assign data fields fields want summarize grand totals. works because dbcalc component context aware - knows sort of band lives in: if it's in group footer, aggregates group, if it's in report summary section, aggregates whole report. important: consider if need summarize subtotals, or directly aggregate data in report. depending on data types , how handle rounding, truncating, etc,

javascript - Html style hidden for tables, td-s doesn't work well, just for div-s -

i hide , unhide part of html file. code use: function changevisible(colorclass, mode){ var items = document.getelementsbyclassname(colorclass); for(var i=0; < items.length; i++) { if(mode == "0") { items[i].setattribute("style",""); items[i].style.visibility = 'hidden'; } else if(mode == "1") { items[i].setattribute("style",""); items[i].style.visibility = 'visible'; <!--items[i].style.display = 'none';--> } } } the part select hideable parts: function geturlparameters(variable, element){ var query = window.location.search.substring(1); var vars = query.split("&"); (va

grails - How do I get the controller and action from which a button was clicked? -

i working on project in there "add person" button appears on multiple pages redirects controller/view lets user fill out required fields , add new person database. however, stumped on how make redirect view called once new person has been added. if possible, retain user input existed on calling view when add person button clicked. here code adds person. i need @ end of code. redirect(controller: 'callingcontroller', action: 'callingaction') any help? you need form <g:form url="[resource:person, action:'addperson']" method="get" > <label for="personname"> <span class="required-indicator">*</span> </label> <g:field name="personname" value="" required=""/> <!-- put here fields details above--> <fieldset class="buttons"> <g:actionsubmit class="save" action="addperson" value

c# - Exception while setting DataContext -

i have created custom usercontrol exposes dependencyproperties headertitle , headertitleforeground public partial class pageheadercontrol : usercontrol { public string headertitle { { return (string)getvalue(headertitleproperty); } set { setvalue(headertitleproperty, value); } } public static readonly dependencyproperty headertitleproperty = dependencyproperty.register("headertitle", typeof(string), typeof(pageheadercontrol), new propertymetadata("")); public string headertitleforeground { { return (string)getvalue(headertitleforegroundproperty); } set { setvalue(headertitleforegroundproperty, value); } } public static readonly dependencyproperty headertitleforegroundproperty = dependencyproperty.register("headertitleforeground", typeof(string), typeof(pageheadercontrol), new propertymetadata("")); public pageheadercontrol() { initializecomponent();

python - How do I append tuples together? -

i'm trying put multiple tuples not know how. know how create tuple, i'm not quite sure how put them together. want keep on appending (not appending because don't want list). i'm pulling string out of each line , putting of tuples x = (132, 534, 4) y = (345, 531, 1) z = (212, 421, 5) what want returned (132, 534, 4), (345, 531, 1), (212, 421, 5) the tuple in example can created this: >>> # following line equivalent to: new_tuple = (x, y, z) >>> new_tuple = x, y, z >>> new_tuple ((132, 534, 4), (345, 531, 1), (212, 421, 5)) >>> however, because tuples immutable (cannot changed after creation) sequences, need create new 1 each time want "append" it: >>> new_tuple = x, y, z >>> new_tuple ((132, 534, 4), (345, 531, 1), (212, 421, 5)) >>> w = 1, 2, 3 # tuple needs go inside new_tuple >>> new_tuple = x, y, z, w # so, have rebuild new_tuple include >>> new_

php - Uncaught SyntaxError Unexpected Number JSON.parse -

trying json data through ajax request, error : uncaught syntaxerror unexpected number here js code : var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>'; $.ajax({ url: ajaxurl, type: 'post', datatype: 'json', data: { action : 'getpills' }, success: function(data){ product = json.parse(data); console.log(product); }, error: function(jqxhr, textstatus, errorthrown) { console.log(textstatus, errorthrown); } }); here php code : add_action('wp_ajax_getpills', 'getpills'); add_action('wp_ajax_nopriv_getpills', 'getpills'); function getpills(){ $data = array( "test" => 'test' ); error_log(json_encode($data), 0); echo json_encode($data); } called error_log see json data trying receive: {"test":"test&quo

php - Image upload/receive API -

i'd offer simple api on website allows people upload images (and receive url access it). but have several questions: would better if user have send image in binary code or better if user have send in idk ascii or so? conventional way? (i'm asking because can imagine languages have functions read files textfiles.) where store images on server , how? can put them in mysql database , perform well? or should put them in 1 folder? how should user able specify file type? in header or in body? how receive , data save file? i found code somewhere else: <?php /* put data comes in on stdin stream */ $putdata = fopen("php://input", "r"); /* open file writing */ $fp = fopen("myputfile.ext", "w"); /* read data 1 kb @ time , write file */ while ($data = fread($putdata, 1024)) fwrite($fp, $data); /* close streams */ fclose($fp); fclose($putdata); ?> does work binary files images? idea "read data 1 kb @ time&

javascript - Bgcolor not working in while loop -

although know bgcolor not best thing use change web page's color dynamically, css route not appear allow numbers bgcolor (unless mistaken). code follows: <!doctype html> <html> <head> <title>title</title> <script> while(1===1){ confirm("you click this";) document.write("<h1>hello</h1>"); document.bgcolor = bgcolor; } </script> </head> <body></body> </html> i know code in infinite loop. can try document.body.style.background instead of document.bgcolor? also, have ask, why need infinite loop there?

php - Is there an alternative for file_get_contents? -

i tried getting 1 character file comments.txt i want random lines 1 one .. file_get_contents disabled urlencode $f_contents = file_get_contents("comments.txt"); $line = $f_contents[array_rand($f_contents)]; $messages = $line; $messages = urlencode($messages); you can simplify .. <?php $arr = file('comments.txt',file_ignore_new_lines); shuffle($arr); foreach($arr $v) { echo $v."<br>"; } the above code prints random lines text file 1 one.

r - Using dplyr to make sample from data frame -

i have large data frame (150.000.000 rows) format this: df = data.frame(pnr = rep(500+2*(1:15),each=3), x = runif(3*15)) pnr person id , x data. sample 10% of persons. there fast way in dplyr? the following solution, slow because of merge-statement prns = as.data.frame(unique(df$prn)) names(prns)[1] = "prn" prns$s = rbinom(nrow(prns),1,0.1) df = merge(df,prns) df2 = df[df$s==1,] i suggest "data.table" package on "dplyr" this. here's example big-ish sample data (not smaller own 15 million rows). i'll show right , wrong ways things :-) here's sample data. library(data.table) library(dplyr) library(microbenchmark) set.seed(1) mydf <- dt <- data.frame(person = sample(10000, 1e7, true), value = runif(1e7)) we'll create "data.table" , set key "person". creating "data.table" takes no significant time, setting key can. system.time(setdt(dt)) # user system ela

parsing - Java SimpleDateFormat parse Timezone like America/Los_Angeles -

i want parse following string in java , convert date: dtstart;tzid=america/los_angeles:20140423t120000 i tried this: simpledateformat sdf = new simpledateformat("'dtstart;tzid='z':'yyyymmdd't'hhmmss"); date start = sdf.parse("dtstart;tzid=america/los_angeles:20140423t120000"); and this: simpledateformat sdf = new simpledateformat("'dtstart;tzid='z':'yyyymmdd't'hhmmss"); date start = sdf.parse("dtstart;tzid=america/los_angeles:20140423t120000"); but still doesn't work. think problem in america/los_angeles. can me please? thank you try 1 using timezone . note: have split date string before doing operation. simpledateformat sdf = new simpledateformat("yyyymmdd't'hhmmss"); timezone tz = timezone.gettimezone("america/los_angeles"); sdf.settimezone(tz); date start = sdf.parse("20140423t120000"); in simpledatefor

wix - How can I use bind.FileVersion when harvesting using Heat? -

i've used... <?define productversion="!(bind.fileversion.mylibrary.dll)" ?> ... define version variable use in installers. first time i'm using heat.exe harvest files/folders need in installer (which includes mylibrary.dll) file called source.wxs. if try build installer following error: unresolved bind-time variable !(bind.fileversion.mylibrary.dll) it's product.wxs file productversion declared can't see source.wxs file has details of mylibrary.dll, know isn't true since if set productversion="1.0.0.0" installer builds , files installed correctly. how can bind.fileversion 'see' mylibrary.dll? edit i can work if use non-human friendly file id source.wxs (see below), best solution? <?define productversion="!(bind.fileversion.fil023e197261ed7268770dde64994c4a55)" ?> you can edit output generated heat using xsl. way can transform id fil023e197261ed7268770dde64994c4a55 more readable ca

java - Maven Test Scope -

if have 1 project of mine myproject1 has following depenedencies: <!-- logging --> <dependency> <groupid>org.slf4j</groupid> <artifactid>slf4j-api</artifactid> <version>1.7.6</version> </dependency> <dependency> <groupid>ch.qos.logback</groupid> <artifactid>logback-core</artifactid> <version>1.1.1</version> <scope>test</scope> </dependency> <dependency> <groupid>ch.qos.logback</groupid> <artifactid>logback-classic</artifactid> <version>1.1.1</version> <scope>test</scope> </dependency> and include myproject1 in myproject2 so: <dependency> <groupid>com.mydomain</groupid> <artifactid

vba - logical error/for loop not functioning within conditional statement -

Image
edit i realize code run every time button either checked or un-checked. need way may array values equal values column f when box first checked, , stay put, then, if box unchecked, need array values first instance of code being run printed (now empty) column f. possible? perhaps sort of global array variable? i have bit of vba code wrote, myself, of , lot of research. code attached check box button in excel sheet. when excel check-box button checked, 3 columns deleted. when button un-checked, columns put back. 2 of columns simple columns contain functions. these , g. have 2 for loops in code print these functions , set numberformat of columns general run automatically. these both work great. the problem is, need save values in column f array before column deleted. if check box unselected (after being selected once- can't undo something has never been done @ least once) want print values array1 (the variable names work in progress) column f. that part isn't worki

cocoa - core data object insert in loop causes problems with NSNumber* property on object novel in inner-loop -

i have loop has degrading performance proceeds (the first loop might 3 seconds, last might 400 on 500 iterations). i've narrowed down 1 line of code . . . attaching unique nsnumber value core data object. catalog size typically 20k-150k. here excerpt runs in outer loop. outer loop gets slower , slower each time due 1 line of code: for(int = 0 ; < 500 ; i++){ nsstring *key = @"somerandomstring" ; nsnumber* sampleidnumber = [nsnumber numberwithint:13] ; (it = catalog.begin(); != catalog.end(); it++) { // it->second->id changes each time in inner-loop nsnumber* tagnumber = [nsnumber numberwithint:it->second->id]; datummo *newdatummo = [nsentitydescription insertnewobjectforentityforname:@"datum" inmanagedobjectcontext:moc]; // **tagnumber changes each inner loop** // **each time outer loop calculated gets slower** // **this not happen if tagnumber constant** newdatummo.tagid = tagnumber ; newdatum

javascript - Google Maps for AngularJS does not work with any Angular directives related to "HIDE" and "SHOW" -

Image
the angularjs google maps library not work once ng-hide or ng-show used, once 1 of 2 display functions called, happens map: this can fixed when resize browser window, there hack that'll similar window resizing fix graphical issue javascript? without hack angularjs google maps library defeats purpose of single page applications. in stackoverflow issue this, solution add ng-cloak directive map tag: <map ng-cloak zoom="10" style="visibility:hidden; z-index:1000; width:900px; height:300px; display:inline-block;" width="1600" height="1600"/> but i've tried , absolutely nothing. maybe $rootscope.map.width = z; ??? how replicate window resizing fix instantly using javascript? or guess better question how can library work despite fact it's broken. this angular library not work unless issue patched , temporary hack used in place counter graphical bug. try using data-ng-if instead of ng-hide or ng-show.

android - Google Tag Manager hits not visible in Google Analytics -

i'm implementing google analytics v4 in android app through gtm. container , code configured according instructions found here https://developers.google.com/tag-manager/android/v4/ . i'm getting logs indicate events being matched rule , fired, don't data in google analytics. logs this: 04-23 22:01:35.966 v/googletagmanager(22149): puthit called 04-23 22:01:35.966 v/googletagmanager(22149): sending hit store path: https: params: ul=en-gb, ev=value, el=label, t=event, cd=mainactivity, .... 04-23 22:01:36.026 v/googletagmanager(22149): puthit called please give advice... can give 1 example of log looks /googletagmanager(22149): sending hit store path: https: params: ul=en-gb, ev=value, el=label, t=event, cd=mainactivity, ? the hits may appear in reports after delay. can make sure realtime reports not show activity?

python - User interface optimization when using pack -

Image
i have code, creates ui this. i want page up/down buttons next page 1 label couldn't managed that. way know pack side option , not working well. second thing is, scrollbar should in listbox. know, need create canvas frame in it. embed both listbox , scrollbar them couldn't either. this code. class interface(tk.frame): def __init__(self,den): self.pa_nu = 0 ##page number. both used in labeling , result slicing self.lbl1 = tk.label(den, text="keyword") self.lbl2 = tk.label(den, text="page %d" %(self.pa_nu+1)) self.ent1 = tk.entry(den, takefocus=true) self.btn1 = tk.button(den, text="search", command=self.button1) self.btn2 = tk.button(den, text="page up", command=self.page_up) self.btn3 = tk.button(den, text="page down", command=self.page_down) scrollbar = tk.scrollbar(den) scrollbar.pack(side=right, fill=y) self.lst1 = tk.listbox(

c - libssh2: What to do with unsolicited data from the ssh server? -

i have program uses libssh2 administrate linux boxes. it's straightforward: connects linux boxes, downloads config file, keeps libssh2 connection open (and idle) if user presses buttons on gui can send appropriate shell commands linux boxes necessary. it uses non-blocking i/o (via libssh2_session_set_blocking(session, 0)) network i/o can handled single thread without session a's activity being held off session b blocking on read or write, etc. this works fine. because there strange problem occurs when program connected many (i.e. several dozen) boxes @ once. happens sessions connect usual, , config files downloaded successfully, , connections idle, expected. on few of sessions, few milliseconds after download completes (i.e. after i've libssh2_channel_read()'d config file bytes, , after libssh2_channel_close() has succeeded), additional bytes of data (usually 104 or 140) appear on session's tcp socket, ready read me , passed libssh2. at point have pro