Posts

Showing posts from January, 2012

r - Collecting an unknown number of results in a loop -

what idiomatic way collect results in loop in r if number of final results not known beforehand? here's toy example: results = vector('integer') i=1l while (i < bigbigbignumber) { if (somecondition(i)) results = c(results, i) = i+1 } results the problem example (i assume) have quadratic complexity vector needs re-allocated @ every append. (is correct?) i'm looking solution avoids this. i found filter , requires pre-generating 1:bigbigbignumber want avoid conserve memory. (question: for (i in 1:n) pre-generate 1:n , keep in memory?) i make linked list this: results = list() i=1l while (i < bigbigbignumber) { if (somecondition(i)) results = list(results, i) = i+1 } unlist(results) (note not concatenation. it's building structure list(list(list(1),2),3) , flattening unlist .) is there better way this? idiomatic way that's typically used? (i new r.) i'm looking suggestion on how tackle type of problem. sugge

Javascript calculator not working. -

i created javascript calculator little while ago. worked me ages, after going have discovered simple doesn't work @ anymore. here js fiddle... http://jsfiddle.net/adammartin121/xxfxv/ this code used. it's long , unnecessary. know firstly why it's not working, , secondly more efficient way of doing this? javascript code... var display = document.getelementbyid("display"); document.addeventlistener("domcontentloaded", init, false); function init() { var name = prompt("enter name", ""); if (name == null) { document.getelementbyid("head").innerhtml="enter name!"; } else { document.getelementbyid("head").innerhtml= "<p>welcome, " +name+ ". </p> <p2> simple javascript calculator. open source , designed people learn javascript. <br> feel free copy , paste code, , use how wish. </p>"; } document.getelementbyid("cal

ios6 - When I change the background of my UIButton it resizes -

i looking change uibutton background image using click event when buttons resize, can prevent this? code i'm using below. uiimage *btnimage = [uiimage imagenamed:@"bttn_datesel_up.png"]; [startdtselbttn setimage:btnimage forstate:uicontrolstatenormal]; uiimage *btnimage2 = [uiimage imagenamed:@"bttn_datesel_down_clear.png"]; [enddtselbttn setimage:btnimage2 forstate:uicontrolstatenormal]; something you: -(ibaction)btnclicked:(id)sender { [startdtselbttn setimage:someotherbuttonimagenamehere forstate:uicontrolstatenormal] } this change image of button startdtselbttn . also, if want button have 2 images 1 normal state , 1 selected image, can write code this: uiimage *btnimagenormal = [uiimage imagenamed:@"bttn_datesel_up.png"]; uiimage *btnimageselected = [uiimage imagenamed:@"bttn_datesel_up_selected.png"]; [startdtselbttn setimage:btnimagenormal forstate:uicontrolstatenormal]; [startdtselbttn setimage:btnimageselect

css - Iconfont / webfont not showing in iPhone safari browser -

Image
the glyphs in iconfont, custom web font in navigation in footer, not showing when viewed on iphone. ios 6.1.4 any idea why happening , how fix it? here screenshot of icons in footer not appearing: here link page happening the problem ios provides partial support font-feature-settings css property can use ligatures in ios safari adding text-rendering: optimizelegibility . following link ( http://clagnut.com/sandbox/opentype/ligatures ) shows text using font magenta common & discretionary ligatures on , other text common & discretionary ligatures off. if access link ios device see both texts equal. means ios not support ligatures font-feature-settings , why gyphs in typography not work on ios. to make work in ios, you'll have add text-rendering: optimizelegibility css. reference may "tomorrow’s web type today: fine flourish of ligature" . but, should read "is safe use css rule “text-rendering: optimizelegibility;” on text?" .

Adding onto a file with java AWT FileDialog and FileWriter -

i having problem code. using awt filedialog, , creating files work fine. in program, have option add text existing file, not add text file. cannot figure out solution, because not returning errors. here code: if (optiondialog == 1) { filedialog fc = new filedialog(form, "choose file open", filedialog.load); fc.setdirectory("~/"); fc.setvisible(true); string filename = fc.getfile(); if (!filename.isempty()) { stuff = new file(fc.getdirectory() + fc.getfile()); form.studentnamebox.requestfocus(); form.setvisible(true); system.out.println(stuff); novalidinput = false; } else { joptionpane.showmessagedialog(null, "error! no name entered, please go , try again.");

How can I force `vagrant ssh` to do pseudo-tty allocation? -

the first thing after vagrant ssh attaching tmux session. i want automate this, try: vagrant ssh -c "tmux attach" , fails , says "not terminal". after googling find this article , know should force pseudo-tty allocation before executing screen-based program, , can done -t option of ssh . but don't know how use option vagrant ssh . according this documentation , should try adding -- command. have not used vagrant , unsure of formatting, assume similar to: vagrant ssh -- -t unless, need include username , host, in case add username , host.

assembly - Importance of Hexadecimal numbers in Computer Science -

when studying programming 8085, 8086 , microporcessors in general have hexadecimal representation. ok binary numbers important in computers. how these hexadecimal numbers important? historical importance? it nice if point historical papers also. edit: how computers handle hexadecimal numbers? example happens in 8085 when hexadecimal number given input? hexadecimal has closer visual mapping various bytes used store number decimal does. for example, can tell hexadecimal number 0x12345678 significant byte hold 0x12 , least significant byte hold 0x78 . decimal equivalent of that, 305419896 , tells nothing. from historical perspective, it's worth mentioning octal more commonly used when working older computers employed different number of bits per word modern 16/32-bit computers. wikipedia article on octal : octal became used in computing when systems such pdp-8, icl 1900 , ibm mainframes employed 12-bit, 24-bit or 36-bit words. octal ideal abbreviation of

PythonXY, IPython Qt Console, matplotlib, draw something not in inline mode -

Image
i'm new pythonxy , matplotlib. installed pythonxy (v2.7.3.1) in default full mode. i use "ipython qt console" application. i draw using matplotlib.pyplot (imported plt ). example. when plt.plot([1,3,2,4]) , figure display in same ipython console immediately. if this, cannot add other properties, plt.title , plt.xlabel , plt.ylabel , or more. why? , how can draw figures in window, adding more properties, , making figure not display until plt.show() ? if select interactive consoles dropdown on python(x,y) home launcher, "ipython (qt)" , click either console 2 or cmd.exe button, should run ipython (qt) qt4agg backend allow plot in separate window , apply titles , on. more info see what backend . what python(x,y) in example above doing launching ipython pylab inline backend different standard backends commands aren't having affect, similar behaviour noted in issue on github . doesn't seem possible change backend once ipython has

performance - Android : how to implement PullToRefreshListView in proper way -

i new android , start learning how implement pulltorefreshlistview using library of chrisbanes. can guys please explain me, should put code call api getting data, , part should set the(imagebitmap) after data (image url) api. know, should in background avoid ui freeze when loading image ui, not sure. please help. the following sample code library: please explain me should in getdatatask , onpostexecute. in case loading image. @override public void onrefresh(pulltorefreshbase<listview> refreshview) { // work refresh list here. new getdatatask().execute(); } private class getdatatask extends asynctask<void, void, string[]> { @override protected string[] doinbackground(void... params) { // simulates background job. try { thread.sleep(4000); } catch (interruptedexception e) { } return mstrings; } @override protected void onpostexecute(string[] result) { mlistitems.addfirst("a

configuration - RequireJS Text Plugin installed with Bower -

how should using requirejs-text installed via bower? supposed put in baseurl wonder if use components/requirejs-text/ ? whats best practice? define path plugin in config: requirejs.config({ paths: { "text" : "components/requirejs-text/text" } }, and use in module documented on https://github.com/requirejs/text : require(["some/module", "text!some/module.html", "text!some/module.css"], function(module, html, css) { //the html variable text //of some/module.html file //the css variable text //of some/module.css file. } ); you can use technically use plugin without path definition in requirejs.config, propbably not best practice: require(["your_path_to_the_plugin_from_baseurl/without_js_at_the_end!some/textfile"], function(yourtextfile) { } );

php - Mysql DB single field matching to multiple other fields -

ok, creating sort of dating service , have db requires field match against multiple other fields. need stored, can ignored , set maybes later viewing. know setting comma delimited field unwise, cannot figure out better way keep track of matches while being able categorize them separate columns later on. does have better way of doing without comma delimited field? how array? can store array of information in database. in php declare such: variable = array(); can deal variable array using loops, variable[index#], etc. hope helps!

android - 9-patch background does not align with button and is too big? -

i'm getting kinda frustated since i've been stuck on issue day. i've created different 9-patch background pngs each dpi folder , connected button image yet image big. heres button in activity_mail.xml <button android:id="@+id/button5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignleft="@+id/button11" android:layout_below="@+id/textview4" android:layout_margintop="16dp" android:text="@string/fifty_lp" android:background="@drawable/custom" /> my buttom.xml in drawable-hdpi folder: <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android" > <item android:state_pressed="true" android:drawable="@drawable/example"></item> <item android:state_focused="false"

optimization - Pecuiliar output with Liblinear -

i facing peculiar problem lib-linear package. have 2 levels (+1, -1). have 1 feature takes values $x_1$, $x_2$,..., $x_n$ n points. classifies giving positive weight $w*$ , cost c example. if stack $1$ previous feature make new feature vectors [1 x_i] i=1, 2, ...,n; new problem lib-linear gives following: weight vector [w_1 -w_2]; w_i>0 i.e. weights 1 w_1 , x w_2. cost c1 greater previous cost c. i understand new feature (1) has no variation throughout , hence weight should automatically go zero. it minimization problem should give w_1~0 cost c1 @ equal c. can help? since have constant input dimension, contribution in decision function constant. liblinear's decision function is f(x)=sign(w^t*x-rho) my guess new model corrects term (due non-zero w_1) through rho. can't have idea why w_1 not minimized zero, though. predictions of both models equal?

django - Django_extensions failing to work with iPython notebook -

i using django 1.4.5 , have installed django-extensions, in virtualenv. using python 2.7.1. when type: ./manage.py shell_plus --notebook i error: traceback (most recent call last): file "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) file "/users/.../lib/python2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line utility.execute() file "/users/.../lib/python2.7/site-packages/django/core/management/__init__.py", line 382, in execute self.fetch_command(subcommand).run_from_argv(self.argv) file "/users/.../lib/python2.7/site-packages/django/core/management/base.py", line 196, in run_from_argv self.execute(*args, **options.__dict__) file "/users/.../lib/python2.7/site-packages/django/core/management/base.py", line 232, in execute output = self.handle(*args, **options) file "/users/.../lib/python2.7/site-packages/django/core/m

R Basket Analysis using arules package with unique order number but duplicate order combinations -

r basket analysis using arules package unique order number duplicate order combinations just learning r. i'm trying basket analysis using arules package (but i'm totally open other package suggestions!) compare possible combinations of 6 different item types being purchased. my original data set looked this: orderno, itemtype, itemcount 111, health, 1 111, leisure, 2 111, sports, 1 222, health, 3 333, food, 7 333, clothing, 1 444, clothing, 2 444, health, 1 444, accessories, 2 . . . the list goes on , has 3,000 observations. i collapsed data matrix contains 1 row each unique order containing counts of specific itemtype: orderno, accessories, clothing, food, health, leisure, sports 111, 0, 0, 0, 1, 2, 1 222, 0, 0, 0, 3, 0, 0 333, 0, 1, 7, 0 , 0, 0 444, 2, 2, 0, 1, 0, 0 . . . every time try read in transactions using following command (and million attempted variations of it): tr <- read.transactions("dataset.c

java - Compute the unix timestamp for the previous midnight -

how can you, in java, compute unix timestamp truncated midnight? php examples show making strings , parsing them back. there has cleaner way in java that, surely? unix timestamp starts midnight utc can following calendar c = calendar.getinstance(timezone.gettimezone("gmt")); c.set(calendar.hour_of_day, 0); c.set(calendar.minute, 0); c.set(calendar.second, 0); c.set(calendar.millisecond, 0); long unixtimestamp = c.gettimeinmillis() / 1000;

ember.js - Ember-Data makes requests whenever it visits a route -

whenever navigate /users/1 /users ember-data makes new request. @ point isn't problem, when re-visit /comments route, dom elements duplicated - didn't happen on fixtures, when switched json appeared. shouldn't requests cached? think read should , are. ember-data last commit: 6140f7d (2013-04-11 15:48:46 -0700) in reply comment my routes set follows: index route app.indexroute = ember.route.extend redirect: -> this.transitionto 'users' users route app.usersroute = ember.route.extend setupcontroller: (controller, model) -> this.controllerfor('users').set 'content', app.user.find() this.controllerfor('currentuser').set 'content', app.currentuser.find 1 comments route app.commentsroute = ember.route.extend model: -> app.comment.find() setupcontroller: (controller, model) -> @controllerfor('currentuser').set 'content', app.currentuser.find 1 i think l

c# - A generic error occurred in GDI+, JPEG Image to MemoryStream -

this seems bit of infamous error on web. so have been unable find answer problem scenario doesn't fit. exception gets thrown when save image stream. weirdly works png gives above error jpg , gif rather confusing. most similar problem out there relate saving images files without permissions. ironically solution use memory stream doing.... public static byte[] convertimagetobytearray(image imagetoconvert) { using (var ms = new memorystream()) { imageformat format; switch (imagetoconvert.mimetype()) { case "image/png": format = imageformat.png; break; case "image/gif": format = imageformat.gif; break; default: format = imageformat.jpeg; break; } imagetoconvert.save(ms, format); return ms.toarray(); } } more detail exception. reason causes many issues lack of expla

matlab - Clustering: Error for "Lose" its Member During Initial. Possible? -

i'm working k-means in matlab gui. have done it. program (gui) works quite fine (in command window, works perfectly). don't know, gui working, error appears suddenly. here error message: ??? error while evaluating uicontrol callback ??? error using ==> kmeans>batchupdate @ 436 empty cluster created @ iteration 1. error in ==> kmeans @ 337 converged = batchupdate(); error in ==> calcrand @ 4 [g c] = kmeans(data,k,'dist','sqeuclidean'); error in ==> kmeansfin2>centroid_callback @ 203 [g,c,y,clr]=calcrand( data,k ); error in ==> gui_mainfcn @ 96 feval(varargin{:}); error in ==> kmeansfin2 @ 42 gui_mainfcn(gui_state, varargin{:}); error in ==> @(hobject,eventdata)kmeansfin2('centroid_callback',hobject,eventdata,guidata(hobject)) ??? error while evaluating uicontrol callback a little explanation: gui has 4 push buttons, cluster, show centroid, show graphic, evaluate graphic. give code here, l

Android : Notification Manager only notify when the application is closed -

i implemented broadcast receiver, @ onreceive() method notification manager code written. custom ringtone being played @ notification. on click of notification sound stops issues failed do, if application open notification won't showed @ notification bar. expect of notification update ui of view[i.e. show stop button stop ringtone.] notification code public void sendnotification(context context, string title, string message, string filename) { final string ns = context.notification_service; final notificationmanager notificationmanager = (notificationmanager)context.getsystemservice(ns); final notification notification = new notification(r.drawable.ic_launcher, context.getstring(r.string.salahclock), system.currenttimemillis()); intent intent = new intent( context, main.class); intent.putextra("isalarmplaying", true); //pending event open our application screen when notification

c - For "int demo[4][2]",why are all these same in magnitude: &demo[1],demo[1],demo+1,*(demo+1) ?What about type? -

just when had relaxed thinking have fair understanding of pointers in context of arrays,i have fallen face down again on following program.i had understood how array arr , arr , &arr both same in magnitude,but different in type,but fail solid grip on following program's output.i try visualize succeed partially.i appreciate if can give rigorous , detailed explanation thing guys me can done confusion good. in following program,i have used "2d" array demo[][2] .i know demo[] array of arrays of size 2.i know demo used alone of type (*)[2] .still @ loss following : 1) why &demo[1] same demo[1] ?isn't demo[1] supposed address of second array?what on earth &demo[1] , why same address of second array? 2) know second printf() , fourth same,as demo[1] nothing else *(demo+1) .but i've used illustrate point.how can equal third printf() ,ie,how can demo+1 equal *(demo+1) ? demo[1] being same *(demo+1) well-known,but how can demo+1 equal *

html - page-break-inside:avoid blank page issue in IE 10 -

i have lot of tables on page variable amounts of content in them. trying use page-break-inside: avoid ; each table section not broken on 2 pages. it working in browser not in ie 10. blank page gets added on print-preview/print how remove blank page. following link wiil show test page , on print preview see blank page on page no 2 http://ourclientwebsites.com/test.htm maybe time html show: http://msdn.microsoft.com/en-us/library/ie/ms530844(v=vs.85).aspx says re page-break-before: "this property applies when printing document. property not apply br or hr elements." so if applied page break <br> element in: <br style="page-break-before:always"> just apply <p> element instead , work: <p style="page-break-before:always"></p>

wcf - Binding datagrid in silverlight from database using ADO.Net -

i trying bind silverlight pivotgrid sql database using ado.net. purpose have added wcf service , interacting local database , passing data silverlight project, able receive datasource property of pivotgrid control , unable bind pivotgrid control. below method have written in wcf service public dataset getdata() { string connstr = "server=sys3248\\sqlexpress; database=employeedb; integrated security=true;"; sqlconnection conn = new sqlconnection(connstr); sqldataadapter da = new sqldataadapter("select * employee", conn); dataset ds = new dataset(); da.fill(ds); return ds; } here .xaml file <usercontrol x:class="optimityv5.mainpage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-

android - Onclick back button the application stops -

i have 1 problem regarding app,when click button application getting finish.i need prevent it.how make . @override public void onbackpressed() { log.d("cda", "onbackpressed called"); intent setintent = new intent(intent.action_main); startactivity(setintent); } i have tried this.but not working .actually need when click button ,the application should not finish should run in background.can me out.@thanks try doing this: @override public void onbackpressed() { log.d("cda", "onbackpressed called"); intent intent = new intent(); intent.setaction(intent.action_main); intent.addcategory(intent.category_home); startactivity(intent); } by doing this, activity not destroyed (i.e. ondestroy not raised). also, there's no guarantee android preserve activity long. in case, running process want keep on running in background, suggest go service or intentservice .

c# - How to show Microsoft Report Rdlc Rows in Group and Show Sub Total -

e.g. have class called "product.cs" product class has 3 properties:name, groupname , price. call function list of product object , want show below format in report(rdlc). name groupname price name1 g1 10 name2 g1 10 20 name3 g2 5 name4 g2 10 15 35 how format way in report? help/hint appreciated. in advance.

How to run a SQL command to update some opencart products to non taxable items? -

i have 4000 products in opencart 1.5.5.1 store, products set "taxable" items. have 500 of these products in fact "none taxable" products. i able run sql command update 500 products using phpmyadmin change 500 products. need have set none under tax class in products. does know how complete such task using sql commend? here part of products db file. 1 of 2 products manually changed in opencarts admin area on 2 products - made tax class none: insert `oc_product` (`product_id`, `model`, `sku`, `upc`, `ean`, `jan`, `isbn`, `mpn`, `location`, `quantity`, `stock_status_id`, `image`, `manufacturer_id`, `shipping`, `price`, `points`, `tax_class_id`, `date_available`, `weight`, `weight_class_id`, `length`, `width`, `height`, `length_class_id`, `subtract`, `minimum`, `sort_order`, `status`, `date_added`, `date_modified`, `viewed`, `call_for_price`, `custom_message`, `youtubevideo`) values (1, 'aaj - 101', 'aaj - 101', 'aaj - 101', ''

ios - Apple's Mobile Device Management without UDID -

after installing mdm profile, when device registers server mdm; server gets following response(s) device: authenticate : {'topic': 'com.apple.mgmt.external.dadd0670-xxx', 'udid' : 'xxxx', 'messagetype': 'authenticate'} tokenupdate : {'topic': 'com.apple.mgmt.external.dadd0670-xxx', 'udid' : 'xxx', 'token': xxxx, 'pushmagic': 'xxxx', 'messagetype': 'tokenupdate'} as can see in response, map mdm token(we in tokenupdate command) device can use device's udid . so, in ios app have send device's udid our server link token device. using "[[uidevice currentdevice] uniqueidentifier]" this. but, apple not accepting apps access uniqueidentifier. protocol reference starting in ios 6.0+, apple has provided new identifiers can use. options are: [[uidevice currentdevice] identifierforvendor]] this meant identifying device specific

Newly added elements using jQuery doesn't have it's CSS applied correctly -

i use jquery dynamically add new elements. newly added element doesn't have it's css applied properly. i have demonstrated problem jsfiddle . newly added input text box has different spacing between them. html code: <fieldset> <div class="control-group custom"> <label class="input-mini" for="first">start</label> <label class="input-mini" for="first">end</label> <label class="input-mini" for="first">share</label> </div> <div class="control-group custom"> <input type="text" class="input-mini"> <input type="text" class="input-mini"> <input type="text" class="input-mini"> </div> <div> <a id="plus_time_button" class="btn plus" href="#">

c# - Queued Method invocation in its own thread -

maybe functionality buried somewhere in .net-framework couldn't find it. need execute methods in given order, 1 after one. methods should return (e.g. object), there way react returned data (e.g. cancel execution of following methods because error occurred). execution of methods should run in own thread , should able add methods queue @ time. idea how implement in c#? thanks jon's comment tried implement such queue on me own. might completly wrong - comments welcome ;-) using system; using system.collections.concurrent; using system.threading.tasks; namespace functionqueue { public class errorresult { public string errormessage { get; set; } public bool cancelqueue { get; set; } } public class functionqueue { private readonly concurrentqueue<func<object>> queue; private bool isexecuting; private bool iscanceled; private readonly action<errorresult> onerror; private readonly

jsf - ajax javascript call not working due to a <h:form> -

problem: i have button action , ajax call js function javascript function not executed. when remove <h:form> work perfectly. has idea why happens, , how fix it? i use form. code: working: <h:commandbutton id="dice" alt="w&uuml;rfel" image="resources/img/wuerfel0.png" action="#{spiel.dice()}" tabindex="4" title="w&uuml;rfel"> <f:ajax render="gameinfo" onevent="animate" /> </h:commandbutton> not working: <h:form> <h:commandbutton id="dice" alt="w&uuml;rfel" image="resources/img/wuerfel0.png" action="#{spiel.dice()}" tabindex="4" title="w&uuml;rfel"> <f:ajax render=":gameinfo" onevent="animate" /> </h:commandbutton> </h:form>

Apache virtual host to tomcat server -

i set apache root tomcat server in same machine.apache listening port 80 , tomcat 9090. dns name of service example.com.gr machine ip "150.111.111.11" , in httpd file wrote this namevirtualhost *:80 <virtualhost *:80> <servername example.com.gr errorlog logs/example.com.gr.gr_error_log transferlog logs/example.com.gr.gr_access_log proxyrequests off proxypreservehost on <proxy *> order deny,allow allow </proxy> proxypass / http://150.111.111.11:9090/ proxypassreverse / http://150.111.111.11:9090/ <location /> order allow,deny allow </location> </virtualhost> but when hit example.com.gr (110) connection timed out,but if hit example.com.gr:9090 see portal.any ideas?

facebook - Android - FQL query to get album photo count -

i using facebook sdk integrate facebook android application. want count number of photos in album. having album id. need following one. select count album aid = '1232323_1212121'; but returns count not member of album table. how can number of photos in album? as can see the documentation , field in question photo_count .

java - Generate ID fast and with high probability of uniqueness -

i want generate id event occur in application. the event frequency user load, might occur hundreds-thousand of time per second. i can't afford using uuid.randomuuid() because might problematic in performance matters - take @ this . i thought of generating id follows: system.currenttimemillis() + ";" + long.tostring(_random.nextlong()) when _random static java.util.random class holding. my questions are: do think distribution of combination enough needs? does java's random implementation related current time , therefore fact i'm combining 2 dangerous? i use following. final atomiclong counter = new atomiclong(system.currenttimemillis() * 1000); and long l = counter.getandincrement(); // takes less 10 nano-seconds of time. this unique within system , across restarts provided average less 1 million per second. even @ rate, number not overflow time. class main { public static void main(string[] args) { system.ou

Is there another better way to get file ext from a given path in python -

i'm new in python, know, can file ext path use: os.path.splitext(path)[1][1:] this works well, seems not quite beautiful, want ask: there better way file ext the readable way be name, ext = os.path.splitext(path) ext = ext[1:] though that's no longer single expression. if want single expression, wrap in function: def extension(path): name, ext = os.path.splitext(path) return ext[1:] be aware on systems, files may have empty extension, e.g. >>> os.path.splitext('ham.') ('ham', '.') and you're treating same files no extension @ (just ham ). usually, difference doesn't matter, in cases might, why splitext works way does.

python - Avoid docstrings from parent, in Sphinx -

i use sphinx autodocs, find annoying how default appends parent class docstring docstring. the result each , every documented test class inheriting unittest.testcase , docstring "create instance of class use named test method when executed. raises valueerror if instance not have method specified name." appended. these 2 sentences litter test documentation, on , on again. how can stop sphinx pulling docstring parent?

Android app: How do change the battery percentage? -

i'd access battery details i'll able change it. example, display 80% battery instead of 50%. how access in code? thanks in advance! dvir private handler handler = new handler; private broadcastreceiver mbatinforeceiver = new broadcastreceiver() { @override public void onreceive(final context context, intent intent) { int level = intent.getintextra(batterymenter code hereanager.extra_level, 0); int scale = intent.getintextra(batterymanager.extra_scale, 100); log.i(tag, "level: " + level + "; scale: " + scale); int percent = (level*100)/scale; final string text = string.valueof(percent) + "%";enter code here handler.post( new runnable() { public void run() { toast.maketext(context, text, toast.length_short).show(); } }); } };

web applications - Google maps - get static map link -

i have web application generates dynamic map rout beetween n waypoins, origin , destination using gmap3 jquery plugin. need add function genereate pdf map server-side. need send server link static map rappresenting dynamic generated map in order of re-generate image rappresenting map , put file. there way obtain link static map maybe using gmap3? thank you

c++ - why # followed by a number seems do nothing in C plus plus -

repro steps: insert following line line of c++ source code. #1234 any line including first line, last line. can input between function header , body this. int foo() #1234 { return 0; } the number can long, tested more 170 characters. if add non-numeric character, compile error. my question is: why # followed number doesn't break compile, while # followed non-numeric character does. thanks time, everyone. that line directive. preprocessors output these tell compiler lines in original source file. as preprocessor can add many (sometimes hundreds or thousands) lines source provides compiler, compiler needs way keep track of line numbers of original source file. done through special directives such that.

iphone - How to hide show view titanium? -

hi new titanium. i have taken 3 view , want hide show view on button click iphone app. any idea how achieve this? thanks in advance. you can hide / show view easily, heres self contained example: var win = ti.ui.createwindow(); var view = ti.ui.createview({ width : 100, height : 100, backgroundcolor : 'red' }); var redview = ti.ui.createview({ title : 'hide / show red view', bottom : 0, width : 200, height : 35 }); var visible = true; button.addeventlistener('click', function(e) { if(visible) { redview.hide(); } else { redview.show(); } visible = !visible; }); win.add(redview); win.add(button); win.open();

c# - Int to string - Saving back to a database from a textbox -

i saving values textbox database. how save number entered in textbox database. have tried following error saying input string not in correct format newcarsrow.customerid = convert.toint32(textbox5.text); //i have tried newcarsrow.customerid = int.parse(textbox5.text); i saving text entered textbox so newcarsrow.surname = textbox1.text.tostring(); instead of using newcarsrow.customerid = int.parse(textbox5.text); you should try using int customerid = 0; if(int.tryparse(textbox5.text.trim(), out customerid)) { newcarsrow.customerid = customerid; } else { // customer id received text box not valid int. relevant error processing } now wont exception facing, , able perform relevant error handling.

how to encrypt text in python using tkinter -

i want encrypt piece of text, if type in password come stars or dots i'm using tkinter if matters. in entry part can users password encrypted? w2 = label(root, text="password") w2.pack() e1 = entry(root) e1.pack() e1 = entry( root, show= '*', textvariable = passport )

c++ - Unit-testing MPI Programs with gtest -

i'm parallelizing existent application uses gtest mpi. in mpi programs, first thing initialize environment call mpi_init( int *argc, char ***argv ) at end of mpi program root process should call mpi_finalize. how can write unit-tests such application using google test? in particular, how access argc, , argv tests before gtest modifies them. right i'm doing: int argc = 0; char** argv = null; boost::mpi::environment env(argc,argv); test(component_test, test_name) { // stuff using mpi } and feels wrong. are sure want access argc , argv values before googletest? modified remove googletest specific arguments such --gtest_filter application not see them. i think want using following snippet main : int main(int argc, char* argv[]) { int result = 0; ::testing::initgoogletest(&argc, argv); mpi_init(&argc, &argv); result = run_all_tests(); mpi_finalize(); return result; }

npm publish with private registry (git+ssh) -

i'm working private module created. stored private git server. i set dependencies modules using : "dependencies" : { "mymodule" : "git+ssh://git@git.myrepo.com/myproject#mybranch" } now interested in publishing new release of module without committing manually branch. possible use : npm --registry git+ssh://git@git.myrepo.com/myproject#mybranch publish in order push local update directly used branch ? by way previous cmd return error : in next foo username created npm adduser npm --registry "git+ssh://git@git.myrepo.com/myproject#mybranch" publish npm warn package.json foo@2.0.0 no readme.md file found! npm http put git+ssh://git@git.myrepo.com/foo npm err! error: invalid protocol npm err! @ request.init (/usr/local/lib/node_modules/npm/node_modules/requ/main.js:302:31) npm err! @ new request (/usr/local/lib/node_modules/npm/node_modules/request/main.js:103:8) npm err! @ request (/usr/local/lib/node_module

database - Memo fields and forms DBASE PLUS -

how can display information within memo field using editor form component. know using image go with: form.image.datasource = 'binary image_name' but editor not know how access memo field , display data. sugestions,methods? typically dbase or xbase, reference columns in table so: mytable->myfield or mytable.myfield so in example try: form.image.datasource = mytable->mymemofield or form.image.datasource = mytable.mymemofield

visual studio 2010 - OpenMP C++ (trouble with compliling) -

i decided calculate e sum of rows 2.718.... code without openmp works , measured time taking calculations. when used openmp parralelize calculation however, got error. running program on core i7(8 cores 4 logic , 4 physical). people must time twice fast without using openmp. below code: #include <iostream> #include <time.h> #include <math.h> #include "fact.h" #include <cstdlib>; #include <conio.h>; using namespace std; int main() { clock_t t1,t2; int n; long double exp=0; long double y; int p; cout<<"enter n:"; cin>>n; t1=clock(); #pragma omp parallel num_threads(2); for(int i=1; i<n; i++) { p=i+1; exp=exp+(1/((fact(p)))); } t2=clock(); double total_clock; total_clock=t2-t1; long double total_exp; total_exp=exp+2; cout<<total_clock<<"\n time used parralel calculations"<<endl; cout<<total_exp<<endl; cin.get(); getch(); return 0; } fact(

asp.net web api - Web API get route values -

is there way statically route values service method (outside of controller) running in web api context? example, can following in asp.net mvc: var mvchandler = httpcontext.current.handler mvchandler; var routevalues = mvchandler.requestcontext.routedata.values; i'd find equivalent version of code web api. when try debug sample web api request , @ httpcontext.current.handler of type httpcontrollerhandler , type doesn't have properties access route data. edit to try provide more information. code trying read value inside of factory class have builds custom object application. you can use getroutedata() extension on httprequestmessage. need include system.net.http namespace this. system.web.http.routing.ihttproutedata routedata = request.getroutedata();

perl - What is RMAGICAL? -

i'm trying understand xs code inherited. i've been trying add comments section invokes perl magic stuff, can't find documentation me understand line: svrmagical_off((sv *) myvar); what rmagical for? when should 1 turn in on or off when working perl magic variables? update perlguts illustrated interesting , has little bit of info on rmagical (the 'r' 'random'), doesn't when mess it: http://cpansearch.perl.org/src/rurban/illguts-0.42/index.html it's flag indicates whether variable has "clear" magic, magic should called when variable cleared (e.g. when it's destroyed). it's used mg_clear called when 1 attempts like undef %hash; delete $a[4]; etc it's derived information calculated mg_magical should never touched. mg_magical called update flag when magic added or removed variable. if of magic attached scalar has "clear" handler in magic virtual table, scalar gets rmagical set. otherwise, gets t

Why doesn't jQuery form .submit() call enclosed function? -

i trying call named function on form submit. here code: $(document).ready(function() { showpartnersettings = function(e) { e.preventdefault(); var $dialogform = $("<div />") .attr("id", "partner-settings-form") .append($loading.clone()) .load(envpath + "/partner/settings?partnerid="+e.data.partnerid, null, function(){ $("#partner-settings-form").css("display", "block"); }) .dialog({ title: "partner settings", modal: false, resizable: false, width: 580, //cpb 04.11.13 position:['middle',130], "close" : function(){ var dialogid=$(this).parent("div").attr("id"); $("#tabs ul li."+dialogid).remove(); $(this).remove(); $("#alertmod").remove(); //$link.removeclass('preventclick'); }, }) .dialog("open")

c# - Send email through SMTP -

i have contact page on website , want users enter name , email id (no password) , send email on button click. i did google , solutions getting requires user password, public static void sendmessage(string subject, string messagebody, string toaddress, string ccaddress, string fromaddress) { mailmessage message = new mailmessage(); smtpclient client = new smtpclient(); // set sender's address message.from = new mailaddress(fromaddress); // allow multiple "to" addresses separated semi-colon if (toaddress.trim().length > 0) { foreach (string addr in toaddress.split(';')) { message.to.add(new mailaddress(addr)); } } // allow multiple "cc" addresses separated semi-colon if (ccaddress.trim().length > 0) { foreach (string addr in ccaddress.split(';')) { message.cc.add(new mailaddress(addr)); } } // set subject , mes

c# - stored procedure returns many records but datareader sees only one -

i created sql server stored procedure in use cursor , created asp.net method execute procedure. i'm using sqldatareader , while(reader.read()) read values. problem cursor in stored procedure returns many rows, method reads first record only. can help? stored procedure: create procedure [dbo].[getmenususergroupcanview] ( @usergroupid int ,@languageid int ) begin declare @menuid int declare @title varchar(255) declare db_cursor cursor ( select menuid triogate.dbo.sys_usergroupmenus usergroupid=@usergroupid , viewflag='true' ) open db_cursor fetch next db_cursor @menuid while @@fetch_status = 0 begin select sys_menus.menuid ,sys_menus.parentmenuid ,sys_menus.descriptionlabelid ,sys_menus.titlelabelid ,sys_menus.tooltiplabelid ,sys_menus.[icon] ,sys_menus.[menuname] ,sys_menus.[menutypeid] menutype ,[dbo].[get_paren

printing - How to print rectangle with exact size in c#? -

i new dot net, want print rectangle 20mm width , 8mm height if measure scale. want print text in middle of rectangle.can suggest me how can achieve this? i sorry not being clear earlier. have tried using "pageunits" working fine. however, have problem margins. i able print correct margins(8.8mm left , 22mm top) if using printer "hp laserjet p2035n". if print using "canon ir2020 pcl5e" getting incorrect margins(8.1mm left , 8.0mm top) should 8.8mm left , 22mm top margins. can explain me doing wrong. using system; using system.collections.generic; using system.linq; using system.text; using system.drawing; using system.drawing.printing; namespace consoleapplication6 { class drawshape { public static void drawrec() { printdocument doc = new printdocument(); doc.printpage += doc_printpage; doc.print(); } static void doc_printpage(object sender, printpageeventargs e)

javascript - Wrap table rows without breaking HTML validation? -

i have table , want wrap table rows , problem don't know with what wrap those guys up... if use <div> , <span> , <tr> , <td> ...they break validation. so can wrap table-rows without breaking validation ? this how want problem html not valid. fiddle here i generating wrappers using following jquery $(document).ready(function(){ $('tr:first').nextuntil('.section2').andself().addclass('section1'); $('tr:nth-child(3)').removeclass('section1').addclass('section2'); $('.section2').nextuntil('.section3').removeclass('section1').addclass('section2'); //lets wrap 2 sections inside divs ... //this break validation:( $('tr.section1').wrapall('<div class="section_box1"></div>'); $('tr.section2').wrapall('<div class="section_box2"></div>'); }); as @kevinb writes in comment, tbody element wa