Posts

Showing posts from April, 2013

apache - Python 3.4 causes UnicodeEncodeError on Apache2 server (Mac) but works fine in command line -

i'm trying python 3.4 cgi script , apache output 'ü' character in browser (same problem occurs other unicode character, matter). python 3.4 cgi script causes unicodeencodeerror in apache while similar python 2.7 code works fine on same server. both scripts 3.4 , 2.7 work fine command line. this error while running python 3.4 script: unicodeencodeerror: 'ascii' codec can't encode character '\xfc' in position 23: ordinal not in range(128) here's code causes error: #!/usr/local/bin/python3 # -*- coding: utf-8 -*- print ("content-type: text/html; charset=utf-8\n\n") print ("""\ <html> <head> <meta charset="utf-8"> </head> <body> """) print ("u umlaut (python 3.4): ü<br>") print ("""\ </body> </html> """) the python 2.7 script below on same server displays ü , other unicode characters correctly: (so it&

Ansible get the username from the command line -

in playbooks reference username (exclusively "ubuntu") lot. is there built in way "get value passed in command line"? i know can do ansible-playbook <task> -u <user> -k --extra-vars "user=<user>" and can use {{user}} in playbook, feels odd defining user twice. as woodham stated, ansible variable represents connecting user is {{ ansible_user }} (ansible < 2.0 {{ ansible_ssh_user }} ) but don't have define in inventory file per se. you can define in: 1. play, if use ansible-playbook: see manual on playbooks - name: play hosts: remote_user: ubuntu 2. in inventory file: see manual on inventory [all] other1.example.com ansible_user=ubuntu (ansible < 2.0 ansible_ssh_user) 3. stated, on commandline: ansible-playbook -i inventory -u ubuntu playbook.yml 4. ansible config file remote_user directive. see manual on config file the ansible config file can placed in current folder ansi

Php download on the same page without redirecting -

i have question how can make sure when android apk file download trigger, index.php page remain without being redirected blank. index.php page <head> //the javascript loading progress bar fake simulation how kb left. <script> $(document).ready(function() { $('body').on('click', '.btn', function(event) { $('#init').hide(); $('#progress').show(); progress_bar(3210, 'kb'); }); }); </script> </head> <body> <a href="download.php?appid=100&sid=12345" class="btn">download & install</a> </body> download.php $appid= $_request['appid']; $sid= $_request['sid']; if($appid==100)//offer download url { $url= "http://yeahmobi.go2cloud.org/aff_c?offer_id=20374&aff_id=18009&aff_sub=".$sid; header(

ios - UIView viewwithtag method in swift -

i'm trying learn swift. programmatically add labels. want change properties later. the viewwithtag method returns uiview, how access uilabel this? cheers you need use typecast. code it: if let thelabel = self.view.viewwithtag(123) as? uilabel { thelabel.text = "some text" }

Saving bitmap to SdCard Android -

i writng code convert png file bmp , save on sdcard. current code. fileinputstream in; bufferedinputstream buf; try { in = new fileinputstream("file_path_to_read.png"); buf = new bufferedinputstream(in); byte[] bmaparray= new byte[buf.available()]; buf.read(bmaparray); bitmap bmap = bitmapfactory.decodebytearray(bmaparray, 0, bmaparray.length); //code segment save on file int numbytesbyrow = bmap.getrowbytes() * bmap.getheight(); bytebuffer bytebuffer = bytebuffer.allocate(numbytesbyrow); bmap.copypixelstobuffer(bytebuffer); byte[] bytes = bytebuffer.array(); fileoutputstream fileouputstream = new fileoutputstream("file_path_to_save.bmp"); fileouputstream.write(bytes); fileouputstream.close(); if (in != null) { in.close(); } if (buf != null) { buf.close(); } } catch (exception e) { }

c# - Entity Framework doesn't recognise methods like Add, Remove -

i working entity framework on asp.net mvc3 visual studio 2010 , have problem: after changed database , moved project 1 computer another, no longer recognize methods of dbcontext such add , remove , , not know how reproduce them. mention code worked on computer. did not nothing relevant changes on database model. on following example, db dbcontext , tmsentities name of instance. public class categorycontroller : controller { // // get: /category/ private tmsentities db = new tmsentities(); [httppost] public actionresult addcategory(category model) { bool success = true; string status = string.empty; category item = new category(); item.name = model.name.trim(); item.description = model.description; if (string.isnullorempty(item.name)) { success = false; status += "category name can not empty! <br />

python - Why are Pickle files in Pickle protocol 4 twice as large as those in protocol 3 without having any gains in speed? -

i testing python 3.4, , noticed pickle module has new protocol. therefore, benchmark 2 protocols. def test1(): pickle3=open("pickle3","wb") in range(1000000): pickle.dump(i,pickle3,3) pickle3.close() pickle3=open("pickle3","rb") in range(1000000): pickle.load(pickle3) def test2(): pickle4=open("pickle4","wb") in range(1000000): pickle.dump(i, pickle4,4) pickle3.close() pickle4=open("pickle4","rb") in range(1000000): pickle.load(pickle4) test1 mark: 2000007 function calls in 6.473 seconds test2 mark: 2000007 function calls in 6.740 seconds protocol 4 slower protocol 3. kind of difference can ignored. however, hard disk usage different. pickle3 uses 7,868,672 bytes. pickle4 uses 16,868,672 bytes. that's no reason. continue dig out. after read pep3154 , understand protocol. for tuple(1,2,3,4,5,6,7) of protocol 3

spring - Initial data on JPA repositories -

i'm looking convenient way provide initial data application. i've implemented spring data jpa based project foundation of database related operation. example: i've got entity role can assigned entity user . on clean application start provide directly default roles (e.g. admin, manager, etc). best i built random data factory : public class randomdatafactory { private static final string ungenerated_value_marker = "ungenerated_value_marker"; private static void randomlypopulatefields(object object) { new randomvaluefieldpopulator().populate(object); } /** * instantiates single object random data */ public static <t> t getsingle(class<t> clazz) throws illegalaccessexception, instantiationexception { t object = clazz.newinstance(); randomlypopulatefields(object); return object; } /** * returns unmodifiable list of specified type objects random data *

cocos2d x - cocos2dx onKeyReleased gets called at keydown instead of keyup in android -

i working cocos2dx 3.0rc2 , want respond key event in android platform. learned override onkeyreleased method of layer , setkeypadenabled(true) capture key. however got problem, can capture event, not accurately. is, expect method gets called when released finger key. gets triggered put finger on key. being said, responds @ key-down phase while wish @ key-up phase. can me this? way, tested code , seemed on win32, backspace key not responded (but not matter me care android) here code blocks: init: ... this->setkeypadenabled(true); ... onkeyreleased: ... if(keycode == eventkeyboard::keycode::key_backspace) { onback(nullptr); } ... i tried other way capture event, setting listener instead of putting setkeypadenabled(true). result same. i appreciate help! you have written correct code have used wrong key code. it shoud eventkeyboard::keycode::key_escape .

parsing - Unreachable rules in the Java 8 CFG? -

maybe rather in-depth question has idea why in the java languagespecification - java se 8 edition (2014-03-03) which defines formal context-free grammar of java 8 in terms of production rules , terminals not defined rules reachable? the specification describes dozens of rules such as ifthenstatement: if ( expression ) statement or assertstatement: assert expression ; assert expression : expression ; which make perfect sense. but strangely of defined rules not reachable others such important rule type: primitivetype referencetype in total counted following 2 rules not reachable others: packagename type how 1 define complete java 8 cfg having unreachable rules? often specification authors find convenient formulate rules of spec in terms of non-terminals; sometimes, however, of useful non-terminals not, technical reasons, used in main grammar. in such cases spec defines relevant non-terminals anyway, ground of rules o

objective c - iOS how to start the image picker -

i have uibutton , when user clicks it, want start image picker controller i configure think enough couldn't know message have pass image picker start working this code #import "imagepickerviewcontroller.h" @interface imagepickerviewcontroller () @property (weak, nonatomic) iboutlet uiimageview *image; @end @implementation imagepickerviewcontroller - (void)viewdidload { [super viewdidload]; // additional setup after loading view. } - (ibaction)selectimage:(id)sender { uiimagepickercontroller *imagepicker = [[uiimagepickercontroller alloc]init]; imagepicker.delegate = self; imagepicker.sourcetype = uiimagepickercontrollersourcetypephotolibrary; } @end i have set correct protocols: @interface imagepickerviewcontroller : uiviewcontroller < uinavigationcontrollerdelegate,uiimagepickercontrollerdelegate> @end you need present uiimagepicker - (ibaction)selectimage:(id)sender { uiimagepickercontroller *imagepicker =

Lightweight RSA Encryption PHP -

so need authenticate unique users, each user have own priv/pub keypair. i'm trying make lightweight class can generate key pair, , encrypt or decrypt data. here have far: class rsa { public $pubkey = ''; public $privkey = ''; public function genkeys() { /* create private , public key */ $res = openssl_pkey_new(); /* extract private key $res $privkey */ openssl_pkey_export($res, $privkey); $this->privkey = $privkey; /* extract public key $res $pubkey */ $pubkey = openssl_pkey_get_details($res); $pubkey = $pubkey["key"]; $this->pubkey = $pubkey; } public function encrypt($data) { $data = ''; if (openssl_private_encrypt($data, $encrypted, $this->privkey)) $data = base64_encode($encrypted); return $data; } public function decrypt($data) { $data = ''; if (openss

bash - ip proxy testing using wget not working -

i testing ip:port proxy downloading see if of these proxy valid or not. working script #!/bin/bash pro in $(cat testing.txt);do wget -e use_proxy=yes -e http_proxy=$pro --tries=1 --timeout=15 http://something.com/download.zip if grep --quiet "200 ok"; echo $pro >> ok.txt else echo $pro >>notok.txt fi done typical output on success wget --2014-06-08 10:45:31-- http://something.com/download.zip connecting 186.215.168.66:3128... connected. proxy request sent, awaiting response... 200 ok length: 30688 (30k) [application/zip] saving to: `download.zip' 100%[======================================>] 30,688 7.13k/s in 4.2s and output on failure --2014-06-08 10:45:44-- http://something.com/download.zip connecting 200.68.9.92:8080... connected. proxy request sent, awaiting response... read error (connection timed out) in headers. giving up. now problem , grep seems not working! output ip address in notok.txt file. weather wget su

c# - Why can I not find the XElements in my XML document? -

i know repeated question on so, answers haven't helped out. trying details of book using classify api c#. gives xml output like: <classify xmlns="http://classify.oclc.org"> <response code="2"/> <!-- classify product of oclc online computer library center: http://classify.oclc.org --> <work author="coelho, paulo | clarke, alan [author; translator] | sampere, daniel, 1985- [illustrator; draftsman] | lemmens, harrie, 1953- [translator] | smith, james noel | ruiz, derek, 1980- [adapter]" editions="176" format="book" holdings="7530" itemtype="itemtype-book" pswid="1151562357" title="the alchemist">123115868</work> <authors> <author lc="n94113544" viaf="65709090">clarke, alan [author; translator]</author> <author lc="no2005013941" viaf="12032914">lemmens, h

html - Show/Hide javascript query -

i made html test website test show/hide javascript. when load page, show first page in website hidden ' till click on button '. <html> <head><title>test</title> <script> function toggle(target){ var artz = document.getelementsbyclassname('article'); var targ = document.getelementbyid(target); var isvis = targ.style.display=='block'; for(var i=0;i<artz.length;i++){ artz[i].style.display = 'none'; } targ.style.display = isvis?'none':'block'; return false; } </script> </head> <body> <a href="#" onclick="toggle('about');">about us</a> <a href="#" onclick="toggle('contact');">contact</a> <

javascript - Node.js + Express: How to update page when something has been inserted into database? -

i have messaging set up, when sends message, want recipient see message without having refresh page. it cool when user receives message, there notification/badge appears indicate new message. i'm newbie delving web development, scenario use ajax? i've been reading it, , seems case. there better way node.js + express? i need push in right direction. thanks! having recipient see message without refreshing page can achieved ajax. situation want user receive notification message common one. there several ways of achieving that. can short-polling or long-polling, both of can achieved ajax scaling chat app - short polling vs. long polling (ajax, php) . if you're using node, why not websockets. node , sockets literally go hand-in-hand. luck!

java - What resource is the id parameter in ArrayAdapter constructor? -

i trying figure out resource id in arrayadapter constructor. have other questions, too: what used for? why should point text? isn't purpose of arrayadapter push kind of items it? why textview ? can't use arrayadapter<view> view can view ? what used for if supplied, points id of textview inside of row layout. if not supplied, , using default getview() implementation of arrayadapter , row layout must be textview . and why should point text because built-in implementation of getview() on arrayadapter wants take tostring() of model object , put text textview . why textview? because built-in implementation of getview() on arrayadapter expects. can't used arrayadapter view can view ? yes, can. however, if not have textview in row, cannot use built-in implementation of getview() , must comoletely override it.

c# - Listing matching items in a combo box while entering a text? -

i have combobox in form , while user typing text in box, if there matching items in database text typed, should listed in combobox . user can notified if item being entered in database. i'm trying achieve follows. when text entered in combo fire event. listening event, presenter matching user list database , list set datasource of combobox follows... but why not displayed in combo? please let me know issue in code! form public partial class frmuser : form { // 2 seperate , set properties used same combo box list set datasource. public string username { get{return cmbusername.text;} } public ienumerable<user> userlist { set { cmbusername.datasource = value; } } private void cmbusername_textchanged(object sender, eventargs e) { onchangetext(sender, e); } } presenter class userpresenter { private void wireupevents() { _view.onchangetext += new eventhandler(_view_onchan

gradle - gradlew assembleDebug requires my release key password -

i added signing settings the guide says. when run ./gradlew assembledebug , requires keystore , key passwords, , there 2 apk files @ end: ./main/build/outputs/apk/main-debug.apk ./main/build/outputs/apk/main-debug-unaligned.apk so gradle builds debug version of module requires release key. the build.gradle file of built module below. apply plugin: 'android' android { compilesdkversion 19 buildtoolsversion '19.1.0' signingconfigs { release { storefile file("my-release-key.keystore") storepassword system.console().readline("\nkeystore password: ") keypassword system.console().readline("key password: ") keyalias "my_key" } } defaultconfig { minsdkversion 9 targetsdkversion 19 versioncode 1 versionname "1.0" } buildtypes { release { runproguard true pr

SAS Is it possible not to use "TO" in a do loop in MACRO? -

i used use %do ... %to , worked fine , when tried list character values without %to got message error: expected %to not found in %do statement %macro printdb2 ; %let thisname = ; %do &thisname = 'test1' , 'test2' , 'test3' ; proc print data=&thisname ; run ; %end ; %mend printdb2 ; i know how complete task using %to or %while . curious possible list character values in %do ? how can %do ? if goal here loop through series of character values in macro logic, 1 approach take define corresponding sequentially named macro variables , loop through those, e.g. %let mvar1 = a; %let mvar2 = b; %let mvar3 = c; %macro example; %do = 1 %to 3; %put mvar&i = &&mvar&i; %end; %mend example; %example; alternatively, scan list of values repeatedly , redefine same macro var multiple times within loop: %let list_of_values = b c; %macro example2; %do = 1 %to 3; %let mvar = %scan(&list_of_val

r - Within C++ functions, how are Rcpp objects passed to other functions (by reference or by copy)? -

i've finished writing new version of abcoptim package using rcpp. around 30x speed ups, i'm happy new version's performance (vs old version), i'm still having concerns on if have space improve performance without modifying code. within main function of abcoptim (written in c++) i'm passing around rcpp::list object containing "bees positions" (numericmatrix) , numericvectors important information algorithm itself. question is, when i'm passing rcpp::list object around other functions, e.g. #include <rcpp.h> using namespace rcpp; list abcinit([some input]){[some code here]}; void abcfun2(list x){[some code here]}; void abcfun3(list x){[some code here]}; list abcmain([some input]) { list x = abcinit([some input]); while ([some statement]) { abcfun2(x); abcfun3(x); } ... return list::create(x["results"]); } what rcpp within while loop? x object passed reference or deep copy functions abcfun2 , abcfun3 ? i&

php - Data type isnt well received by the database -

so big idea want insert oracle database value through input tag number type. problem when input value > 0, works fine. when left if unfilled, error appears, warning: oci_execute(): ora-00936: missing expression in c:\xampp\htdocs\weltesinformationcenter\content\fabrication\update\fabricationqc\processexceededqcqty.php on line 76 so here input tag: echo "<td><input name='datamarkingqc' id='datamarkingqc' type='number' min='0' max='$availablemarkingqc' width='5' value='0'></td>"; and processing method this, $datamarkingqc = intval($_post['datamarkingqc']); if ($datamarkingqc == 0){ $markingqcuser = ""; $markingqcdate = ''; } else { $markingqcuser = $username; $markingqcdate = 'sysdate';} $updateqchistsql = "insert fabrication_qc_hist (marking_qc, marking_qc_date, marking_qc_sign) values ($datamarkingqc, $markingqcdate,

c# - Call Webmethod in Usercontrol.cs from Usercontrol.ascx javascript -

i have usercontrol , in have javascript function makes call webmethod. <%@ control language="c#" autoeventwireup="true" codefile="leftmenu.ascx.cs" inherits="usercontrols_leftmenu" %> <script type="text/javascript"> function getrealtimecount() { pagemethods.countofmenus('', '', getcountofmenus_success, getcountofmenus_fail); } my webmethod code is [system.web.services.webmethod] public static string countofmenus(string startdate, string enddate) { //code here } but when run code, gives me javascript error, countofmenus undefined . know error because cant find method in current page want access method in usercontrol.cs. cant write webmethod in every page have lots of pages usercontrol used. there way through can call method of usercontrol.cs in javascript? i solved below method javascript : function getrealtimecount(startdate, enddate) { var xmlhttp; if (window.xmlhtt

c# - Stop service without error "Service cannot be started. The handle is invalid" -

i have windows service app , want stop service when main code executed. trying execute servicebase.stop() in onstart event, works fine, service stopped annoying error message in event viewer "service cannot started. handle invalid" any ideas how stop windows service without errors? public partial class virtualserverinitservice : servicebase { public ilogger eventlogger = new eventlogger(); public virtualserverinitservice() { initializecomponent(); } protected override void onstart(string[] args) { eventlogger.write("starting service!"); new virtualserverinit(eventlogger).run(); eventlogger.write("virtualserverinit code executed"); stop();//this code works , gives error in event viewer } protected override void onstop() { eventlogger.write("stopping service!");

What does it mean if Android MediaCodec dequeueOutputBuffer returns -1? -

i followed official android documentation setup encoder audio input using mediacodec object. method dequeueoutputbuffer in code below returns -1. return value mean? my code: /*configuarion of mediacodec object*/ codec = mediacodec.createencoderbytype("audio/mp4a-latm"); mediaformat format = new mediaformat(); format.setstring(mediaformat.key_mime, "audio/mp4a-latm"); format.setinteger(mediaformat.key_channel_count, 1); format.setinteger(mediaformat.key_sample_rate, 44100); format.setinteger(mediaformat.key_bit_rate, 64 * 1024); format.setinteger(mediaformat.key_aac_profile,mediacodecinfo.codecprofilelevel.aacobjecthe); codec.configure(format, null, null, mediacodec.configure_flag_encode); codec.start(); bytebuffer[] inputbuffers = codec.getinputbuffers(); bytebuffer[] outputbuffers = codec.getoutputbuffers(); /*main loop encode audio data*/ (;;) { int inputbufferindex = codec.dequeueinputbuffer(-1); -->this never 0 data should written correctly!

c# - Select whole column by clicking ColumnHeader. WPF DATAGRID -

i have data grid has disabled sorting. want achieve - clicking column header want select cells in column(select whole column). i've added eventsetter datagridcolumnheader bind method click event, have no idea how method should written. ideas? my code: private void columnheaderclick(object sender, routedeventargs e) { var columnheader = sender datagridcolumnheader; if (columnheader != null) { if (dgdane.selectedcells != null) { dgdane.selectedcells.clear(); } foreach (var item in dgdane.items) { dgdane.selectedcells.add(new datagridcellinfo(item, columnheader.column)); } dgdane.focus(); } } i edited code, 1 above works fine(thanks @nit). i've added focus datagrid because necessary. this should trick private void columnheaderclick(object sender, routedeventargs e) { var column

Google Direction html instruction trouble -

i'm using maneuvers description responses of google server (html-instruction). there few problems , ask: 1) possible names of addresses in language specified in query, not in language of country, street is? example: request language: en_us country route is: germany server response: <html_instructions> take 1st <b>right</b> onto <b>halberstädter straße</b> </html_instructions> is possible this: <html_instructions> take 1st <b>right</b> onto <b>halberstadter street</b> </html_instructions> answers form geocoding api comes in transcription. perfect similar effect here well. 2) possible street names, avenue, bulevards , etc. — not abbreviated full? example: indianola ave: indianola aveneu union st: union street st. monica blvd: santa monica boulevard

gamekit - Whats the correct signature of receiveData:fromPeer:inSession:context: in swift? -

im trying rewrite gamekit multiplayer game (local) in swift , have problems missing documentation language. want receive data peer set datareceivehandler gksession this: session.setdatareceivehandler(self, withcontext: nil) in apples documentation says datareceivehandler hast implement method signature: sel = -receivedata:frompeer:insession:context: in objective-c documentation example of how signature should like: - (void) receivedata:(nsdata *)data frompeer:(nsstring *)peer insession: (gksession *)session context:(void *)context; if try rewrite method in swift looks this: func receivedata(data: nsdata, frompeer peer: string, insession session: gksession, withcontext context: cmutablevoidpointer) { println("received data: \(data)") } and gives me error when receive message: domain=com.apple.gamekit.gksessionerrordomain code=30500 "invalid parameter -setdatareceivehandler:withcontext:" userinfo=0x178462840 {nslocalizeddescription=invalid

python - Write output of for loop to multiple files -

i trying read each line of txt file , print out each line in different file. suppose, have file text this: how you? good. wow, that's great. text file. ...... now, want filename1.txt have following content: how you? good. filename2.txt have: wow, that's great. and on. my code is: #! /usr/bin/python in range(1,4): // range should increase number of lines open('testdata.txt', 'r') input: open('filename%i.txt' %i, 'w') output: line in input: output.write(line) what getting is, files having lines of file. want each file have 1 line, explained above. move 2nd with statement inside loop , instead of using outside loop count number of lines, use enumerate function returns value , index: with open('testdata.txt', 'r') input: index, line in enumerate(input): open('filename{}.txt'.format(index), 'w') output: output.write(line) also, u

c# - WPF DataGrid: setting style for an individual cell -

i trying change foreground color of datagrid cell. i trying use class extending imultivalueconverter , i'd bind item used generate row , name of column. i read other q&a , saw suggest use multibinding not sure how add bindings i managed solve issue. i needed change properties wanted highlight different color decorating them contain information whether value needed special formatting. then created binding each datagrid column described in this other q&a . bound decorated property , used ivalueconverter obtain brush color wanted use.

sass - Is it possible to make multiple css sheets from single layout-scss page, and multiple variable-scss sheets? -

i'm attempting integrate scss .net theming functionality. ideally scss in dedicated directory, each theme have own scss page containing exclusively variable values particular theme. the problem i'm encountering need pass placeholder variables _layout.scss sheet, , have values updated theme scss sheets. original null values outputted. scss files resources/scss/_variables.scss $theme_color: null; resources/scss/_layout.scss @import "variables"; div { color: $theme_color; } themes/blue/blue.scss $theme_color: #0000ff !default; @import '../../resources/scss/layout'; themes/red/red.scss $theme_color: #ff0000 !default; @import '../../resources/scss/layout'; desired css output files blue.css div { color: #0000ff; } red.css div { color: #ff0000; } you have backwards. !default flag tells sass value use if doesn't previous declaration doesn't exist. $foo: red; $foo: blue !default; @debug $foo; /

Send message every year to a list Sharepoint 2010 -

i'm trying accomplish in sharepoint 2010, have list containing information , each items related person (with email adress in column). want send them message @ least each year ask them review information , update it, if needed. workflow needed. i'm quite new sharepoint, i've tried looking didn't seem find i'm looking for. think try "pause until" , 2 workflows loop endlessly, i'm not sure. in advance! you've got couple of options, though none built without code (unless have 3rd party product). recommend against "pause until..." approach inside sharepoint designer workflow; it's both unreliable , unnecessarily taxing. you build & deploy workflow via visual studio able include such timer-based logic. option create sharepoint designer workflow configured start manually; create sharepoint timer job runs once year manually start wf on every item in list - or write small powershell script , have sp admin run once yea

python - Sum up previous values of a column -

i dealing rather simple problem, cannot find solution. let's consider following table: a 1 4 5 2 i create new column (b) sum of row until respective index: a b 1 1 4 5 5 10 2 12 i thinking , searching solution not find one. have idea how proceed? my approach: create default column 0. df['b']=0 df['b']=df.b.shift()+df.a is there way solve problem in python? i'm making pretty big assumptions here because unfortunately have forced answering question that. la = [1,4,5,2] lb = [sum(l[0:i+1]) in range(len(l))] and if don't list comprehension here more verbose version of code: lb = [] in range(len(l)): lstuffabove = l[0:i+1] lb.append(sum(lstuffabove)) also, check out, may of use: https://stackoverflow.com/help/how-to-ask

asp.net - Load a dynamic custom user control added during page execution (button click event) -

i'm trying add custom control panel (containing "form" input data) during button click event , want access it's methods .validate() after data has been inputted. when try ctrl comes null value. here's part of code : protected void btnnext2_click(object sender, eventargs e) { ... ctrlcompliance = (compliance)loadcontrol("../../ascx/srm/compliance.ascx"); ctrlcompliance.readonly = false; pnlcompliance.controls.add(ctrlcompliance); ... } protected void btnnext3_click(object sender, eventargs e) { ... ctrlcompliance = pnlcompliance.controls[0] compliance; ctrlcompliance.validate() <- allways null ... } i cannot use page_init of solutions propose , need load during button click. did had same problem me? you should load anyway using page_init, set visible property false. using javascript or code-behind can change visible property true when need show print button. so move: ctrlcompliance = (compliance)loadcontrol("../../ascx/sr

floating point - Float vs Decimal in C -

this question has answer here: is floating point math broken? 20 answers the following piece of code : int main() { float a=0.7; printf("%.10f %.10f\n",0.7, a); return 0; } gives 0.7000000000 0.6999999881 answer while following piece of code : int main() { float a=1.7; printf("%.10f %.10f\n",1.7, a); return 0; } gives 1.7000000000 1.7000000477 output. why in first case upon printing got value less 0.7 , in second case more 1.7? when pass floating-point constant printf , passed double . so not same passing float variable "the same" value printf . change constant value 0.7f (or 1.7f ), , you'll same results. alternatively, change float a double a , , you'll same results. option #1: double = 0.7; printf("%.10f %.10f\n",0.7,a); // passing 2 double values printf option #2: float = 0.7; p

c# - How can I configure entity framework to use a different connection string depending on its environment? -

this question has answer here: differentiating web.config between dev, staging , production environments 8 answers my company uses different databases depending on stage of development project in. i'm trying push adoption of entity framework + linq have hit stumbling block when asked how work across our multiple environments. they under impression have manually changed each environment , take forever deploy. how configure ef database-first use different connection on dev, test, , production servers? can set sort of variable? there option missed? edit: possible duplicate of managing debug , release connection string you can specify connection string application uses using app.config or web.config file, depending on type of project you're using. read great documentation: http://msdn.microsoft.com/en-us/data/jj592674 for database-first ap

java - REST call returns png, how do i render this? -

i testing rest endpoint using restclient, , content-type of response "image/png". how render content type in html? using java , play! controller, have line: promise<ws.response> imagepromise = ws.url(endpoint).get(); i using plain html/css view. thanks. you can use data uri scheme ( http://en.wikipedia.org/wiki/data_uri_scheme ) display image. example, in jsp/servlet code: <% promise<ws.response> imagepromise = ws.url(endpoint).get(); inputstream imagestream = // image stream string base64image = // read stream, , base 64 encode (you can use apache commons codec library this) %> <img src="data:image/png;base64,<%= base64image %>" />

unit testing - How to flush coverage data when my test cause app crash - For ios app -

i want code coverage of tests. set settings, build app .gcno files , run on simulator. it can coverage data if there no crash issue. but if app crashed, nothing. so how can code coverage data when app crash? in thought, because not call __gcov_flush() method when app crash. add app not run in background plist file, __gcov_flush() called @ time press home button. is there way call __gcov_flush() before app crash? i found way myself. apple provide nssetuncaughtexceptionhandler() method app. can add our own handler before app crash. so can call __gcov_flush() in function. #import <objc/runtime.h> extern void __gcov_flush(); // in exception handler function, call flush this: if(__gcov_flush){ __gcov_flush(); } done!

matlab - Autoscale DICOM images in "implay" -

i have series of dicom files i'm displaying through implay i'm not sure how use autoscaling syntax video doesn't whitewashed. imshow or imtool "imtool(i,'displayrange',[])" how can same implay? d = dir('*.dcm'); basefilenames = {d.name}; numberoffiles = length(basefilenames); k = 1:numberoffiles fullfilename = basefilenames{k}; imarray(:,:,k) = dicomread(fullfilename); end implay(imarray) i don't think there autoscaler implay . if data type double, should scale manually images between [0 1] - expected image processing toolbox functions. there various functions imadjust used purpose chances can apply same factor entire image stack. if don't want modify imarray because need original dicom values later, can in implay line: implay(imarray./sf) (will more complex if have negative values in dicom, of course).

java - How to add parameters to the SOAP Request -

i want call rfc function in sap , make request java , wsdl response. want send parameter soap request ? how ? the class below, used create request , response : public class soapclientsaaj { public static void main(string args[]) throws exception { // create soap connection soapconnectionfactory soapconnectionfactory = soapconnectionfactory.newinstance(); soapconnection soapconnection = soapconnectionfactory.createconnection(); // send soap message soap server string url = "http://10.130.105.8:8000/sap/bc/.....client=520"; soapmessage soapresponse = soapconnection.call(createsoaprequest(), url); // print soap response system.out.print("response soap message:"); soapresponse.writeto(system.out); soapconnection.close(); } private static soapmessage createsoaprequest() throws exception { messagefactory messagefactory = messagefactory.newinstance();

api - How to show the internal server errors to the user? -

i working in api . want throw detailed error messages user. in situation decide kind of error code should sent or how explain user if error occurs in application internally. example if database connection fails , kind of http status code want send user ? can ? an http status code refers status of http request itself, not status of application handling request. therefore, server-side errors covered 500 internal server error . additional info error should described in response body. apis, response body json or xml, can use formats errors. this: http/1.1 500 internal server error [headers] {"status":"error", "message":"the request failed due database connectivity."} there are, however, 2 cases can think of when might want status code. if user has requested api method not implemented, might want 501 not implemented , , when there temporary service outage, can use 503 service unavailable . more info server-side status codes here

ios - websql in android webview not created -

i using nparashuram's indexeddb polyfill websql in android webview. when first start app, create database, 4 stores each own indexes. tested polyfill in chrome , safari ios , works expected, in android 4.3's webview , below, seems init process not work. i need manually delete database , recreate again, in order able work websql database. did else had problem? is there sustainable solution this? it seems if delay init process of database, don't problems in android webview. far tested in android 4.1.2 , android 4.3. did this: settimeout(function(){ app.initdb(); },500); instead of app.initdb();

Angularjs directive conditional rendering without ng-if -

i have directive render if authentication service tells me so: <div my-loggedin-directive ng-if="security.isauthenticated()"></div> the directive quite empty : .directive('myloggedindirective', [ function() { return { templateurl: 'modules/myloggedindirective.tpl.html', restrict: 'a', replace: true, link: function($scope) { $scope.$on('$destroy', function() { console.log('$destroy'); }); } }; } ]); since directive should rendered when i'm logged in, ngif logic should inside directive declaration, , not in ng-if (the directive without ngif totally broken). how can change directive code (injecting test on security service inside directive declaration) knowing want same behavior ngif ? : directive present in dom when nfif resolves true automatic calling of $destroy wh

java - FB SDK not working on OS 7 -

i implementing fb in 1 of app.i using jar 0.8.25. working fine on simulators 5 7.1.and devices works os 5 , 6 not working on device 7 , 7.1.for os 7 after log in success remains on fb page doesn't redirect back. , when press button, error encountered unable refresh access token try again button. when analyzing on console never finds access token single time os 7.while 5 , 6 working perfectly. please tell may cause issue. thanks, this isn't solution specific problem. mentioned in comments i'm using interface. i'm posting here comment section. not complete solution, need handle flow , expired tokens, show logic of how did this. for interface open browserfield oauth url: https://www.facebook.com/dialog/oauth?client_id=<app_id>&response_type=token&redirect_uri=http://www.facebook.com/connect/login_success.html&scope=publish_actions and add listener browser listen redirects after login. once have access token, should persist , close b

wordpress - woocommerce how to get current category -

i accessing archive-products.php on woocommerce display products (like normal process in woocommerce). on page of archive-products.php have added sidebar product categories shop has (with or without products). have used following code so: $taxonomy = 'product_cat'; $orderby = 'id'; $show_count = 0; // 1 yes, 0 no $pad_counts = 0; // 1 yes, 0 no $hierarchical = 1; // 1 yes, 0 no $title = '<h2>' . _x('our products', 'mfarma') . '</h2>'; $hide_empty = 0; $args = array( 'taxonomy' => $taxonomy, 'orderby' => $orderby, 'order' => 'asc', 'show_count' => $show_count, 'pad_counts' => $pad_counts, 'hierarchical' => $hierarchical, 'title_li' => $title, 'hide_empty' => $hide_empty ); ?> <ul> <?php wp_list_categories($args); ?> </ul> now left side of page has ab

python - How do I patch or modify a list inside of a function when running a unit test? -

i think should have easy answer , i'm relatively new python, gentle. if have function: def random_fruit(): fruits = ['apple','banana','coconut'] return "i " + random.choice(fruits) i want create test modifies fruits list. i'm can't figure out how that. want this, not work. class testfruit(unittest.testcase): @mock.patch('fruits') def test_random_fruit(self, fruits_list): fruits_list = ['kiwi'] self.assertequal(random_fruit(), u"i kiwi") any appreciated. thanks one way test function seed random module , rather try modify list, same "random" result every time: >>> _ in range(5): random.seed(0) random_fruit() 'i coconut' 'i coconut' 'i coconut' 'i coconut' 'i coconut' alternatively, make list argument (note use of none mutable default argument - see this question ): def random_fruit(fruit

html5 - html 5 validation is not working in jquery ui dialog box -

i have dialog box form fields.when click on submit button inside dialog box form not validating using html5 attributes.but can validate form using jquery validate plugin.but need html5 native validation on button click, not working. my code below. $("#popup").dialog({ autoopen: false, title: "view/edit screen", dialogclass: "pop-content pop-header-colr pop-button pop-float", width: 800, height: 650, modal: true, resizable: false, show: 'clip', buttons: { 'submit': function () { var accs_lvl = $('#accs_lvl').val(); alert("accs_lvl " + accs_lvl); var curr_page = $('#curr_page').val(); alert("curr_page " + curr_page); if (accs_lvl == 1 || (curr_page == 'cis' && accs_lvl == 6)) { var url_path = 'url_path'; var args = { "

django - Receiving duplicate signals. How to search for the cause? -

i have wrote django signal in __init__.py of project. looks this: from django.db.models.signals import post_save paypal.standard.ipn.models import paypalipn def confirm_paypal_payment(sender, **kwargs): obj = kwargs['instance'] ... ... post_save.connect(confirm_paypal_payment, sender=paypalipn, dispatch_uid="confirm_paypal_payment") this signal waits saves in model, https://github.com/spookylukey/django-paypal/blob/master/paypal/standard/ipn/models.py i'm stuck , cannot understand why continue receive duplicate signals, i've read documentation , said should use dispatch_uid prevent this. using dispatch_uid continue receive duplicate signals. any ideas on how find root cause this? i'm using django 1.6.2. move out of __init__.py , save either signals.py (a new file in app directory, same place views.py ) or in models.py , recommended in documentation : you can put signal handling , registration code anywhere like