Posts

Showing posts from September, 2013

java - Correct way to execute periodic background tasks -

so need execute periodic tasks in background, if app closed. did creating service , restarting in period of time, using alarmmanager: public class myservice extends service { @override public int onstartcommand(intent intent, int flags, int startid) { log.i("myservice","on command!"); stopself(); return start_not_sticky; } as can see, service intended started not sticky, job , stop immediately. shedule (1 second fast testing only, causes wakelock): @override public void ondestroy() { alarmmanager alarm = (alarmmanager)getsystemservice(alarm_service); alarm.set( alarm.rtc_wakeup, system.currenttimemillis() + (1000), pendingintent.getservice(this, 0, new intent(this, myservice.class), 0) ); } my service start on boot or on alarm (each 1 second currently). however, i'm not sure if it's correct way want. noticed, 3rd party

python - Ipython : Installation error, unable to find _sqlite.so -

on trying install ipython python3.4 message installed. pip3 install ipython requirement satisfied (use --upgrade upgrade): ipython in /usr/local/lib/python3.4/site-packages but when try run ipython3 notebook this: traceback (most recent call last): file "/usr/local/bin/ipython3", line 11, in <module> sys.exit(start_ipython()) file "/usr/local/lib/python3.4/site-packages/ipython/__init__.py", line 120, in start_ipython return launch_new_instance(argv=argv, **kwargs) file "/usr/local/lib/python3.4/site-packages/ipython/config/application.py", line 573, in launch_instance app.initialize(argv) file "<string>", line 2, in initialize file "/usr/local/lib/python3.4/site-packages/ipython/config/application.py", line 75, in catch_config_error return method(app, *args, **kwargs) file "/usr/local/lib/python3.4/site-packages/ipython/terminal/ipapp.py", line 321, in initialize super(terminalipythonapp, se

google chrome - Getting 404 error sometimes in production environment in Rails application -

i have quiz module on website user take quizzes. have set cache buster in controller: def set_cache_buster response.headers["cache-control"] = "no-cache, no-store, max-age=0, must-revalidate" response.headers["pragma"] = "no-cache" response.headers["expires"] = "fri, 01 jan 1990 00:00:00 gmt" end few users getting random 404 error . users using chrome on windows 8.1 . daily around 300-400 users take quiz , few of them 404 error. getting difficult track 404 issue notified 500 errors in production , have not faced issue in local or test environment. , concern is, if code issue users should have got there more 30,000 users. idea why happening few of users? adding more info: not related link, happens randomly. have 3 attempts user clear quiz. few error ask them avail left on attempts , attempt quiz , able to. of time works fine only. other users have completed quiz few report 404 same quiz. example: in

c# - interface generic return type -

i have serveral classes similar method signatures wish capture in interface: namespace mylib public class clientlist public icollection<client> fetch() { { //do stuff return this.createcollection(); } private icollection<client> createcollection() { list<client> clientlist = new list<client>(); // populate list return clientlist; } public class productlist public icollection<product> fetch() { //do stuff return this.createcollection(); } private icollection<product> createcollection() { list<product> productlist = new list<product>(); // populate list return productlist ; } i interface method signature fetch returns icollection, type undefined (as different every list). ensure each *list object have fetch method , new ones won't have 'getlist' or other such named calls. after doing bit of resear

javascript - AngularJS and JSON -

i have simple html-file , json-file <!doctype html> <html lang="en" ng-app="myapp"> <head> <meta charset="utf-8"> <title>document</title> </head> <body> <div ng-controller="aboutcontroller"> <p ng-repeat="post in about"> {{name.about}} </p> </div> <script src="angular.js"></script> <script> var myapp = angular.module('myapp', []); myapp.controller('aboutcontroller', function($scope, $http) { $http.get('about.json').success(function(data, status, headers, config) { $scope.about = data; console.log('this data:',data); }); }); </script> </body> </html> { "name" : "peter", "surname

gradle - Adding bolts to an android studio project -

i'm running error: error: cannot access task class file bolts the problem is, once follow suggestion solution (adding bolts jar parse library), i'm getting this error: :app:dexdebug execexception finished non-zero exit value 2 looking @ solution here, seems seems problem 1 of jars (the 1 added, apparently), , solution removing it... any idea how out of deadlock?

php - Find post of author with meta_key - Wordpress -

this's query: $list = query_posts(array( 'post_type' => 'post', 'author' => $current_user->id, 'category__in' => array(11), )); it ok, when change to: $list = query_posts(array( 'post_type' => 'post', 'author' => $current_user->id, 'category__in' => array(11), 'meta_key' => 'author_alias_id', 'meta_value' => '1' )); the result empty. somebody can me? $args = array( 'post_type' => 'my_custom_post_type', 'meta_key' => 'age', 'orderby' => 'meta_value_num', 'order' => 'asc', 'meta_query' => array( array( 'key' => 'age', 'value' => array( 3, 4 ), 'compare' => 'in', ), ), ); refer ex

python - Getting matplotlib to work - plots not showing -

Image
i able install matplotlib; however, when run code, don't error, instead python icon bouncing on , on again. i don't know if has from rcparamssettings import * i don't have idea is, if try run line uncommented out, importerror: no module named rcparamssettings here's code i'm trying run: import pylab #from rcparamssettings import * import random def flipplot(minexp, maxexp): """assumes minexp , maxexp positive integers; minexp < maxexp plots results of 2**minexp 2**maxexp coin flips""" ratios = [] diffs = [] xaxis = [] exp in range(minexp, maxexp + 1): xaxis.append(2**exp) numflips in xaxis: numheads = 0 n in range(numflips): if random.random() < 0.5: numheads += 1 numtails = numflips - numheads ratios.append(numheads/float(numtails)) diffs.append(abs(numheads - numtails)) pylab.title('difference bet

Multiple Items: Dynamic Item Name and Number in PayPal Form with PHP -

This summary is not available. Please click here to view the post.

Random subsampling in column (r) -

is possible random subsample (i.e size 50) entire column? input example: pa 0 pb 0 pc 127 pd 0 pe 13 pf 39 pg 0 ph 113 pi 0 output example (size 50, random subsampled): pa 0 pb 0 pc 22 pd 0 pe 2 pf 8 pg 0 ph 18 pi 0 any ideas? try indx <- df1$v2!=0 df1$v2[indx] <- sample(50, sum(indx), replace=false) update for getting subsamples based on condition values should less original value f1 <- function(x, n){ indx <- x!=0 v1 <- sample(n, sum(indx), replace=true) while(any(v1 > x[indx])){ v1 <- sample(n, sum(indx), replace=true) } x[indx] <- v1 x} set.seed(24) f1(df1$v2, 50) #[1] 0 0 15 0 12 36 0 26 0 or use repeat f2 <- function(x, n){ indx <- x!=0 repeat{ v1 <- sample(n, sum(indx), replace=true) if(all(v1 <x[indx])) break } x[indx] <- v1 x} set.seed(24) f2(df1$v2, 50) #[1] 0 0 15 0 12 36 0 26 0 data df1 <- structure(list(v1 = c("pa", "pb&quo

ravendb - Some guidance request on 'custom defined' resultsets -

Image
i guidance/thoughts on route create functionality allows me let user customize datasets. have added image showing functionality has been called queues here. a view segmentation of resultset conditions defined either system (default views) or user. i can create predefined indexes/projections default views under control stuck on approach when user should able create custom views. i can create 1 big index properties, , query fields on index in conditions defined user. in scenario index 1 big blob of information. easiest way feels ugly. i can dynamically create new index, based on entered conditions. never explored options of runtime defined indexes before though. i can dynamically create query conditions, have deal stale results because let ravendb define index; avoid index creation ravendb if possible. some guidance highly appreciated; how , parts of ravendb can efficiently accomplish this? not in search of complete solution, since personal project experimenting ravendb.

php add dots to a variable received from load function -

i receive variable through jquery var x = 15; $("#block").load("file.php", {n:x}); when try use $i=$_post['n']; echo $i; i receive : .15. my question - how delete dots. , why appear. to delete dots: <?php $i = trim($_post['n']); // delete first dot (if exists) if(substr($i, 0, 1) == '.') $i = substr($i, 1); // delete last dot (if exists) if(substr($i, -1) == '.') $i = substr($i, 0, -1); echo $i; ?>

Should I choose Cardboard SDK or Oculus Sdk? -

i'm new vr development, bit confused what's differnce , relationship between cardboard sdk , oculus sdk, if want develop app can play 360 vr video or photos, 1 better should choose? by oculus sdk, assume mean mobile sdk gearvr since mention cardboard. if you're talking sdk pc, question oculus vs steamvr vs openvr vs morpheus :) the major choice develop think comes down timeline , audience is. gearvr best quality device out there right , more polished cardboard, , requires specific expensive hardware (note 4 or s6, note 5). has store people buying things off of (even if it's not yet). since gearvr apps in development need signed, have audience if can commit @ least demo accepted on samsung store. (the alternative have every user use developer-signing system, means you'll tens of people instead of thousands see probably) cardboard short-term experience. there no head-straps on cardboard reason - it's intended hold minute or 2 @ time. of a

twitter bootstrap - Setting different container type for Yii2 BS layout -

does know how change container layout in yii2 on pages. naturally, if change container div 'container-fluid' instead of default 'container' in site css, site wide change. want use on 1 or 2 specific views, how can target particular views container div ? create layout suitable in directory views\ layouts , call in action entering $ this-> layout = 'yourlayout'; return $ this-> render ('yourform', [ 'model' => $ yourmodel, ]); for example layout main use <div class='container'> ......> <?= $content ?> </div> the layout wide use no container window wide page <div > ......> <?= $content ?> </div>

Thinking sphinx string date attribute -

i have column 'value' of type text. can contain regular text, , dates in string format. index column indexes value . can add attribute converts column integer? tried both of following: has "str_to_date(model.value, '%y-%m-%d')", as: :value_as_date, type: :integer has "convert(model.value, datetime)", as: :value_as_date, type: :integer thanks there's 2 approaches here... sphinx has timestamp (datetime) data type attributes, use that: has "convert(model.value, datetime)", as: :value_as_date, type: :timestamp or, may better use integer representing date (because sounds don't ned time aspect) extracting date string, , converting %y%m%d value integer (note, no hyphens in date format). has "... more complex sql snippet ...", as: :value_as_date, type: :integer in situation, you'd need convert dates filters integers of same format well. all of aside: you'll want have in sql snippets handles situa

php - .htaccess not working properly on ubuntu server -

rewriterule ^profile?$ profile.php [nc,l] rewriterule ^profile/?$ profile.php [nc,l] rewriterule ^profile/([0-9]+)/?$ profile.php?profile_id=$1 [nc,l] # handle product requests rewriterule ^profile/([0-9]+)/([a-z0-9a-z]+)/?$ profile.php?profile_id=$1&p=$2 [nc,l] # handle product requests rewriterule ^profile/([0-9]+)/([a-z0-9a-z]+)/([a-z0-9a-z]+)/?$ profile.php?profile_id=$1&p=$2&id=$3 [nc,l] # handle product requests rewriterule ^([a-z]+)/?$ index.php?p=$1 [nc,l] # handle product requests when open {url}/profile/{profile_id} the request going profile.php profile_id not accessible via $_request['profile_id']. other requests working properly. can can possible reason? try disabling multiviews option per @valdimirdimitrov's comment .

java - Jasper report PDF not taking chinese characters -

i unable embed chinese characters pdf using jasper reports. getting english characters not text in chinese characters. appreciate of can provide me quick fix issue. add dynamicjasper-core-fonts-1.0.jar resource report trying use , check pdf embeded in field has chinese characters. you can find , download http://archiva.fdvs.com.ar/repository/public1/ar/com/fdvs/dynamicjasper-core-fonts/1.0/

qt - Preserving aspect ratio when using torch's image.display -

i have following simple script written in lua. running qlua. require "image" input_image = image.load(arg[1]) image.display{image = input_image} if image large qt window takes whole screen, stretches image fit screen. i can't figure out way keep happening. thanks! if image large, resize down can configure "max height/max width", while preserving aspect ratio. sample code: maxsize = 480 -- find smaller dimension, , resize maxsize (while keeping aspect ratio) local iw = input:size(3) local ih = input:size(2) if iw < ih input = image.scale(input, maxsize, maxsize * ih / iw) else input = image.scale(input, maxsize * iw / ih, maxsize) end

actionscript 3 - categorize arrays AS3 -

i've got array : var usersarray:array = new array("this array1 , it's array","this array2", "this array3", "this array4", "this array"); usersarray.push(usersarray.splice(usersarray.indexof("userid"), 1)); var companion:string = usersarray[math.floor(math.random() * (usersarray.length - 1))]; trace(companion); is possible class array letter or number array long ? like if (companion==a){ trace("this array 1") } instead of if (companion=="this array1 , it's array"){ trace("this array 1") } thanks ! if understand question well,you can set variable strings in array: var usersarray:array = new array("this array1 , it's array","this array2", "this array3", "this array4", "this array"); usersarray.push(usersarray.splice(usersarray.indexof("userid"), 1)); var a:string=userarray[0]; var b:string=use

.net - How to get whole list of processes in decreasing order of their thread count ( C# ) -

Image
this question has answer here: how count amount of concurrent threads in .net application? 2 answers how whole list of processes in decreasing order of thread count ( c# ) you try this, process[] processlist = process.getprocesses().orderbydescending(x => x.threads.count).toarray();

ruby - Rails + Devise: Undefined Local Variable in UserRegistration#Edit -

Image
update: i needed put controller code above super, , had access @company instance variable in view: user registration controller: class userregistrationcontroller < devise::registrationscontroller before_action :configure_permitted_parameters skip_before_filter :load_customer_access, only: [:new, :create] def configure_permitted_parameters devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:first_name, :last_name, :current_password, :password, :password_confirmation, :email) } devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:first_name, :last_name, :current_password, :password, :password_confirmation, :email) } end def edit @customer = current_user.customer @company = company.find_by_domain(user.get_domain(@customer.email)) super end end i want pass through company id of logged-in user can view users same company. this page accessed via button edit account page (automatically generated view d

javascript - Scroll to end to grid UI-Grid Angular js -

i want scroll end of grid when data loaded. code not working. please help $scope.adddata = function () { var n = $scope.gridoptions.data.length + 1; $scope.gridoptions.data.push({ "type":"student", "is_job_ready":"true", "is_night_shift":"true" }); $scope.scrollto($scope.gridoptions.data.length -1,0) }; $scope.scrollto = function( rowindex, colindex ) { $scope.gridapi.core.scrollto( $scope.gridoptions.data[rowindex],$scope.gridoptions.columndefs[colindex]); }; you need include module js code: ui.grid.cellnav then, scroll going work: $scope.gridapi.core.scrollto($scope.gridoptions.data[$scope.gridoptions.data.length - 1], $scope.gridoptions.columndefs[0]);

Sahi file and image upload error in playback -

while trying run script image upload or file upload, following play error in sahi open source. what done prevent error? script goes like: _click(_link("プロフィール")); _assertexists(_file("profile-fileupload")); _assert(_isvisible(_file("profile-fileupload"))); _assertequal("", _getvalue(_file("profile-fileupload"))); _setfile2(_file("profile-fileupload"), "c:\\fakepath\\img_69546123046766.jpeg"); you can't record file upload. sahi provided dummy path file upload. if @ this: _setfile2(_file("profile-fileupload"), "c:\\fakepath\\img_69546123046766.jpeg"); this using fakepath. enter actual filesystem path of file , uploaded.

javascript - canvas to svg converting in fabricjs has problems -

Image
after design on canvas in fabricjs convert svg.but there problem converting itext.itext misplaced.how solve problem.any idea or example apriciated.thank you. before convert after convert

system verilog - test case hanging at start_item -

i've been facing problem start_item. every time gets start_item , entire test hangs , there's no way can find out issue is. pointers appreciated. here's code looks like: task good_bad_seq_0_task (); rx_eth10g req; rx_eth10g rsp; rx_eth10g_knobs t; int good_bad_seq_count; //'vy_good_bad_long_seq' loop variable int vy_good_bad_long_seq; int tmp_rand_status; tmp_rand_status = std::randomize (good_bad_seq_count) { good_bad_seq_count inside {100}; }; if(!tmp_rand_status) begin `uvm_error(get_full_name(), "randomization failed!"); end `uvm_info(get_full_name(), $sformatf(": driving good_bad_long_seq %0d times ...",good_bad_seq_count), uvm_high) for(vy_good_bad_long_seq = 0; vy_good_bad_long_seq < good_bad_seq_count; vy_good_bad_long_seq++) begin req = new(); start_item (req); // nothing after executed t = good_bad_seq_knob; req.set_seqitem_type (t); if(!req.randomize ()) begin

fast way to return the key based on dictionary value in python -

i have 2 dictionaries: dict1 = agent_id:agent_email dict2 = user_id:agent_id i want create dictionary: agent_id: list of user_ids associated agent_id how search dict2 each agent_id dict1 , return associated key? i've been told creating list of keys , searching slow. there faster way? the question suggested dupe not tell me i'd know. i'm trying search values without creating separate list. also, once have value, how corresponding key? edit information need in dict2. question how @ it. each agent_id associated multiple user_id's. want create dict looks this: {agent_id_1:(user_id_1, user_id_2, user_id_45), agent_id_2:(user_id_987), agent_id_3:(user_id_10, user_id_67)...etc} based on 1 of answers, i'm looking created 'reverse dict'. i'm don't understand yet, values in dict2 (the agent_ids) not unique. way go? try this. key1, val1 in dict1.iteritems(): key2,val2 in dict2.iteritems(): if key1 ==

pointers - Go array for method -

can use array , pointer go methods? i have following code: var array = [3]string{"a", "b", "c"} type arraytypept *[3]string func (m *arraytypept) change() { m[1] = "w" } func main() { (arraytypept(&array)).changearray4() } but code: http://play.golang.org/p/mxdehma9wk give me error of: invalid receiver type *arraytypept (arraytypept pointer type) invalid operation: m[1] (type *arraytypept not support indexing) arraytypept(&array).changearray4 undefined (type arraytypept has no field or method changearray4) i same error when try slice. why cannot in method? the receiver type of method cannot pointer pointer, wrote: func (m *arraytypept) change() { m[1] = "w" } arraytypept pointer *[3]string . quoting language specification : [the receiver] type must of form t or *t (possibly using parentheses) t type name. type denoted t called receiver base type; it must not pointer or interface type

javascript - Apply Transition effect when adding and remove class -

trying add sliding transition effect when add , remove class. tried sticky nav js below: lastscroll = 0; $(window).on('scroll',function() { var scroll = $(window).scrolltop(); if(scroll === 0){ $(".nav").removeclass("darkheader"); } else if(lastscroll - scroll > 0) { $(".nav").addclass("darkheader"); } else { $(".nav").removeclass("darkheader"); } lastscroll = scroll; }); my try: lastscroll = 0; $(window).on('scroll',function() { var scroll = $(window).scrolltop(); if(scroll === 0){ $(".nav").removeclass("darkheader", 1000, "easeinoutquad"); } else if(lastscroll - scroll > 0) { $(".nav").addclass("darkheader", 1000, "easeinoutquad"); } else { $(".nav").removeclass("darkheader", 1000, "easeinoutquad"); } l

python - Checking Palindrome text, with ignored punctuation marks, spaces and case -

homework exercise: checking whether text palindrome should ignore punctuation, spaces , case. example, "rise vote, sir." palindrome our current program doesn't is. can improve above program recognize palindrome? origin code: def reverse(text): return text[::-1] def is_palindrome(text): return text == reverse(text) = input('enter text: ') if (is_palindrome(something)): print("yes, palindrome") else: print("no, not palindrome") my try: import re def reverse(text): global words words = text.split() return words[::-1] def is_palindrome(text): return words==reverse(text) = input('enter text: ') if (is_palindrome(something)): print("yes, palindrome") else: print("no, not palindrome") error: enter text: jfldj traceback (most recent call last): file "/users/apple/pycharmprojects/problem solving/user_input.py", line 13, in <module> print("ye

php - Missing the result printed from database -

my purpose search book type input keyboard , count it. have error: counting number of book right when print, miss result. example, put 'f' show 7 result( right) print 2 two result. here code: <form action="" method="post"> enter type of book here:<input type="text" size="20" name="sbt"> <br /> <input type="submit" name="sb" value="search"> </form> <table align="center" border="1" width="600"> <thead><tr align="center"> <tr align="center"> <td><b>book id</b></td> <td><b>book title</b></td> <td><b>book author</b></td> <td><b>pulished year</b></td> <td><b>book type</b></td>

php - Image cannot be display after uploading -

Image
previously, when tried uploading image database, image won't display. when check path in db , in folder, correct. correct path in db , folder. and when tried view image has been uploaded says don't have permission view it. i have tried uploaded different photo extension , different photo viewer application , still cannot view image. apart that, have tried w3school php5 file upload. again same thing happen, cannot view image. this code : if (!isset($_files['image']['tmp_name'])) { echo ""; } else { $file=$_files['image']['tmp_name']; $location= $_server['document_root'] . '/ehars/photo/' . $_files["image"]["name"]; move_uploaded_file($_files["image"]["tmp_name"], $_server['document_root'] . '/ehars/photo/' . $_files["image"]["name"]); mysql_query("insert photo (location,emp_id) values ('$location&

java - How to reference a shadowed variable in the superclass of a superclass? -

this simple example of inheritance there shadowed variable x. class a{ int x=1; } class b extends a{ int x=2; } class c extends b{ int x=3; int y; } how can reference shadowed variable x of class in class c?(i want y=super.super.x; works well.) not hard might think. (while encourage avoiding situation,) if have class c inherits class b , in turn inherits class a , of implement public field x , using super wrong way go it. instead, given class c , try this: ((a)this).x; //don't forget parentheses! that give value of x a . also, super.x == ((b)this).x; which why, single steps, use super . hopefully helps.

javascript - How do I clear a form and reset a drop down menu to the first option? -

i have form has text fields, drop down menu, radio buttons, , check boxes. able clear of input entered user need modify form when user clicks "clear entries" of above fields cleared , drop down menu return default state of "pa". function doclear() { document.pizzaform.customer.value = ""; document.pizzaform.address.value = ""; document.pizzaform.city.value = ""; document.pizzaform.state.value = ""; document.pizzaform.zip.value = ""; document.pizzaform.phone.value = ""; document.pizzaform.email.value = ""; document.pizzaform.sizes[0].checked = false; document.pizzaform.sizes[1].checked = false; document.pizzaform.sizes[2].checked = false; document.pizzaform.sizes[3].checked = false; document.pizzaform.toppings[0].checked = false; document.pizzaform.toppings[1].checked = false; document.pizzaform.toppings[2].checked = false; document.pizzaform.toppings[3].checked = false; document.pizzaform.

objective c - I don't know what's missing in my code. It says "Expected identifier or '('" -

i don't know what's missing in code. says "expected identifier or '('" please help. these lines have error. #import "viewcontroller.m" { - (bool)textfieldshouldreturn:(uitextfield *)textfield; nslog(self.mytextfield.text) [self.mytextfield resignfirstresponder]; return yes; } @end first, #import header (.h) files, not source (.m) files. so, first line should be: #import "viewcontroller.h" normally, such import near top of source file. method definition follows has inside of @implementation , appear between imports , method definitions. so, should add line like: @implementation viewcontroller the @end @ bottom of code snippet corresponds @implementation . then, seem have swapped method signature line , line opening brace method. have: { - (bool)textfieldshouldreturn:(uitextfield *)textfield; when should have: - (bool)textfieldshouldreturn:(uitextfield *)textfield; { you don'

jsp - Convert session.lastAccessedTime into javascript date object -

i need convert session.lastaccessedtime object jsp javascript date object . currently, displays long object. how can convert javascript date object? console.log('maxinactive interval == ' + ${pagecontext.session.lastaccessedtime}); you can use date.parse() method convert date string date object . mdn date.parse() the date.parse() method parses string representation of date, , returns number of milliseconds since january 1, 1970, 00:00:00 utc date.parse(lastaccessedtime)

Postgresql Table Partitioning Django Project -

i have django 1.7 project uses postgres 9.3. have table have rather high volume. table have anywhere 13million 40million new rows month. i know best way incorporate postgres table partitioning django? as long use inheritance , , connect parent table django model, partitions should entirely transparent django . is, select on parent table cascade down partitions, unless only keyword explicitly used (where applicable). note partitioning add complexity in terms of needing implement programmatic method of determining when new partitions need created, , creating them -- or doing manually @ intervals. depending on exact data , business logic, quite may need implement triggers , rules determine partition to, say, insert (since wouldn't want insert parent table). these, too, should abstracted django , however. i have found that, depending on exact circumstances, may need done main apps shutdown, lest new partition creation cause deadlock. also worth considering w

winforms - Resizing button size during run-time in C# with mouse -

i using following code make , move buttons @ runtime mouse. i want resize them mouse. code provided kekusemau. lot kekusemau this; helped me. private point origin_cursor; private point origin_control; private bool btndragging = false; private void button1_click(object sender, eventargs e) { var b = new button(); b.text = "my button"; b.name = "button"; //b.click += new eventhandler(b_click); b.mouseup += (s, e2) => { this.btndragging = false; }; b.mousedown += new mouseeventhandler(this.b_mousedown); b.mousemove += new mouseeventhandler(this.b_mousemove); this.panel1.controls.add(b); } private void b_mousedown(object sender, mouseeventargs e) { button ct = sender button; ct.capture = true; this.origin_cursor = system.windows.forms.cursor.position; this.origin_control = ct.location; this.btndragging = true; } private void b_mousemove(object sender, mouseeventargs e) { if(this.btndragging) {

regex - How to convert list to float in Python -

i'm trying write program lines of form new revision: 39772 extract numbers, , find average. here code: import re import statistics file_name = raw_input("enter file: ") file = open(file_name) revision_nums = [] line in file: line = line.rstrip() x = re.findall("new revision: (\d+)", line) if len(x) > 0: revision_nums.append(x) print statistics.mean(revision_nums) however, realized elements in revision_nums stored lists, , i'm getting error when try run it: typeerror: can't convert type 'list' numerator/denominator i tried: for in revision_nums: j in i: j = float(j) and returns same error. doing wrong , how can fix this? x list , if re.findall found 1 match. try revision_nums.append(x[0])

while loop - Small python program - Binary string to Decimal integer converter stuck -

just making code converts 4 bit binary value denary. have done far, keep getting syntax errors , highlighting >. answer = 0 column = 8 while column not < 1: bit = int(input("enter bit value: ")) answer = answer + (column * bit) column = column/2 elif column < 1: print("decimal value " + str(answer)) question similar binary string decimal integer converter wasnt helpful. thanks, there no not > operator in python. you're trying saying <= . anyway, looks you're doing wrong here. maybe helps: while column >= 1: try: bit = int(input("enter bit value: ")) answer = answer + (column * bit) column = column/2 except valueerror: print "wrong input" print("decimal value " + str(answer)) the elif doesn't make sense both logically , syntacticly.

java - How to share IDE layout in IntelliJ IDEA? -

i'm changing projects , creating new ones, have big project work on lot. ide layout (view positions, sizes , docking) evolves use more , more. i'm looking way automatically share ide layout between projects in idea? i avoid re-setting environment every time file/new/project. avoid exporting/importing configuration every file/new/project. handling of updates nice 1 too, is, when resize project/debug view in 1 project changes in of projects created new or reopened. essentially avoid repetitive clicking whenever switch context (project). i'm used eclipse storing settings tied workspace , when new project created have same settings. the closest functionality know of window/store current layout default . save current layout , used newly created projects. but when modify layout , want use version default, have first save default using action mentioned above , in other projects use window/restore default layout (ie. changes default layout won't saved/applie

php - Why mysqli_real_escape_string have a connection object as a first parameter -

i'm using mysqli functions in php long time. , ask me same thing: why funcion mysqli_real_escape_string needs connection in first parameter? doesn't make sense! it's funcion scape quotes. do know why? mysqli_real_escape_string must aware of character set of connection can escapes special characters properly. if use multi-byte set mysqli must know. otherwise sql injection possibile . see this answer more detail. however, don't use it! use prepared statements !

c++ - Driver's license magnetic strip data format -

from wikipedia article( http://en.wikipedia.org/wiki/magnetic_stripe_card#cite_note-14 ), understand basic data format driver's license. starts location data looks this: %codenver^ i wondering if city consists of 2 or more words new york city? what data output like, , white-space character separates words, or it's else? how write c++ statement return each word in city name in different strings? it depend on delimiter. states use different formats data. mag stripes have 1 delimiter split data different sections, delimiter split sections individual parts. for example, let's data want parse is: new^york^city use split out: int main() { std::string s = "new^york^city"; std::string delim = "^"; auto start = 0u; auto end = s.find(delim); while (end != std::string::npos) { std::cout << s.substr(start, end - start) << std::endl; start = end + delim.length(); end = s.fin

c# - How do I change the text in a RichTextBox size and removing the highlight on the text? -

this code. when open text file it's changing font size of text coloring text making highlight select text. private void opentoolstripmenuitem1_click(object sender, eventargs e) { openfiledialog thedialog = new openfiledialog(); thedialog.title = "open text file"; thedialog.filter = "txt files|*.txt"; thedialog.initialdirectory = @"c:\"; if (thedialog.showdialog() == dialogresult.ok) { string filename = thedialog.filename; richtextbox1.text = file.readalltext(filename); this.richtextbox1.selectionstart = 0; this.richtextbox1.selectionlength = this.richtextbox1.text.length; this.richtextbox1.selectionfont = new system.drawing.font("maiandra gd", 30); string s = richtextbox1.text; richtextbox1.clear(); richtextbox1.text = s;

C++ Xcode OpenCV - No member named in namespace -

today installed opencv framework first time, running in errors when call methods of opencv. i included following files: #include "opencv2/core/core.hpp" #include "opencv2/highgui/highgui.hpp" i've set search paths this: header search path: /usr/local/include library path: /usr/local/lib when try call cv::puttext(...) or cv::line(...) following error: no member named ... in namespace cv. i new opencv , don't know if method names wrong since project have work on may referencing older opencv version.

node.js - NodeJS run code in X minutes architecture -

i want schedule code run @ variable time. example, after 60 minutes want send http request endpoint , update database document, want able cancel code being ran if action occurs before 60 minutes. what best way architect this? want able survive server restarts , work if app scaled across multiple servers. thanks! you use settimeout() , save timer id returns because can use timer id cancel timer. schedule timer: var timer = settimeout(myfunc, 60 * 60 * 1000); then, sometime later before timer fires, can cancel timer with: cleartimeout(timer); if want survive server restarts, need save actual system time want timer fire persistent store (like config file on disk or database). then, when server starts, read value persistent store and, if set, set new settimeout() trigger @ time. likewise, when timer fires or when clear timer because no longer need it, update persistent store there no future time stored there. you make clean use creating persistenttimer o

cuda thrust: selective copying and resizing results -

i copying items selectively between 2 thrust device arrays using copy_if follows: thrust::device_vector<float4> collated = thrust::device_vector<float4> original_vec.size()); thrust::copy_if(original_vec.begin(), original_vec.end(), collated.begin(), is_valid_pt()); collated.shrink_to_fit(); the is_valid_pt implemented as: struct is_valid_kpt { __host__ __device__ bool operator()(const float4 x) { return x.w >= 0; } }; now after running code, expecting size of collated vector less original array still same size. thrust doesn't resize vectors part of algorithm call. size of vectors going thrust algorithm size of vectors coming out of algorithm. shrink_to_fit has no impact on vector's size , may impact capacity, has allocation. if want reduce size of collated actual number of elements copied it, need use the return value of copy_if function , compute size, , resize. somet