Posts

Showing posts from May, 2012

Java InputStream -

i reading tutorial using i/o streams in java , stumbled upon following code inputstream: inputstream input = new fileinputstream("c:\\data\\input-file.txt"); int data = input.read(); while(data != -1){ data = input.read(); } the tutorial mentions inputstream returns 1 byte @ time. if want receive more bytes @ time, possible using different method call? use read(byte[]) overload of read() method. try following: byte[] buffer = new byte[1024]; int bytes_read = 0; while((bytes_read=input.read(buffer))!= -1) { // read bytes here } further can channel inputstream datainputstream more specific tasks reading integers, doubles, strings etc. datainputstream dis=new datainputstream(input); dis.readint(); dis.readutf();

ios - Setting an image as a collection Cell -

i'm trying put image collection view cell, pretty much. no fancy stuff, image itself, and, well, @ least resized cell size. what doing doesn't compile, though feel pretty confident. context : collection view list of sports, required image. cell holds image , string (the title of sport), , segue page. don't need specific page dynamic, i'll type sports , put images myself, don't need many , no edited, ever. the collection view called typecollection , in .h (hence _ in code) myevent.typepictures 'event' object holding array of images 'typepictures'. this array of pictures in event class : _typepictures = [[nsmutablearray alloc]initwithobjects: [uiimage imagenamed:@"climbing.jpg"], [uiimage imagenamed:@"skydiving.jpg"], [uiimage imagenamed:@"running.jpg"],

python - How can I draw Chinese labels with scipy.cluster.hierarchy.dendrogram? I have already encoded the labels with 'utf-8' -

my sample input files containing chinese files, , found cannot label dendrogram chinese character. i've done dendrogram using scipy.cluster.hierarchy.dendrogram, , i've tried label dendrogram using different languages. result english, french, arabic, greek labels appear well, however, chinese, japanese, korean, thai , punjabi don't appear on screen @ all.

java - Getting around field shadowing -

for particular program, have abstract superclass several different subclasses. however, i'm having trouble field shadowing illustrated below. abstract class super { string name; string getname() { return name; } } now create subclasses each have own "name". class sub extends super { name = "subclass"; } however, creating instances of subclass, , calling inherited method getname() yield null due field shadowing. is there easy way avoid problem, , allow subclasses each have unique field can accessed inherited method? make field visible in child class , initialize in subclass constructor or in subclass instance initializer.

Verilog: Why the "maxcount" cannot keep its max value but changes with the "count"? -

any appreciated! i wrote module in order keep track of score (<= 99) game written in verilog , runs on led array. want able maintain max score. when current count greater maxcount , maxcount equal current count , else keeps value. the problem is, not know why maxcount changes value whenever count changes (it cannot keep value when count less, instead become less along count ) is there logical error? or there verilog error missed? thank much! module score_keep(clock, reset, pt_0, pt_1, pt_2, pt_3, hex1, hex0, hex3, hex2); input clock, reset; input signed [3:0] pt_0, pt_1, pt_2, pt_3; output [6:0] hex1, hex0, hex3, hex2; wire signed [6:0] count; wire signed [6:0] maxcount; score_counter sc (clock, reset, pt_0, pt_1, pt_2, pt_3, count, maxcount); display(count, maxcount, hex1, hex0, hex3, hex2); endmodule module display (count, maxcount, hex1, hex0, hex3, hex2); input [6:0] count, maxcount; output [6:0] hex1, hex0, hex3, hex2;

c++ - C++11: Type of string literal is "array of the appropriate number of const characters" -

c++11: type of string literal "array of appropriate number of const characters"; "bohr" therefore of type const char[5] void f() { char* p = "plato"; // error, accepted in pre-c++11-standard code p[4] = 'e'; // error: assignment const } (which short excerpt of "the c++ programming language bjarne stroustrup (4th ed.)" on p. 176 in 7.3.2 "string literals") yet compiler (dev-c++11 5.6.2) either settings of iso-c++11 or gnu-c++11 doesn't warn or break compilation at const char a[5] = "bohr"; const char *b = "bohr"; furthermore, question #2 @ cppquiz.org doesn't mention compiler breakage or other problems this: http://cppquiz.org/quiz/question/2 what output of below program in c+++11? #include <iostream> #include <string> void f(const std::string &) { std::cout << 1; } void f(const void *) { std::cout << 2; } int main() { f("foo");

virtualization - Interfaces using the same internal virtual switch in Hyper-V don't ping -

i have windows server 2008 , windows 7 on virtual machines (hyperv). win7 has 2 internal interfaces (local area connection 4 , 5), same situation on server 2008. interfaces using one, same internal virtual switch. i thought in same subnet , should ping each other, machines can communicate interface 5 (win7) interface 4 server. how can connect them all? understand interfaces , virtual switches properly? when ping command get: reply ...server ip adress.. destination host unreachable. virtual switch has static ip adress 192.168.1.1, when set default gateway on interfaces error: warning- multiple default gateways intended provide redundancy single networ. not function when gateways on 2 seperate, disjoint networks. your internal interfaces suppose have 1 configured current network on , other interface can bridged have virtual network established. 1 interface have same local area network machine using run virtual machines allows virtual machines use network. make sure

Clearing TextView in Android -

i'm facing problem textview. not erasing previous instances of data. when i'm running application in emulator displays output data in textview. that's fine. when i'm clicking button in emulator , re opening application not clear previous data. instead appends data existing data. any appreciated. my code below: public class mainactivity extends actionbaractivity { private textview mtextview; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); mtextview = (textview) findviewbyid(r.id.text_test); new thread(new testlocalhost()).start(); } private class testlocalhost implements runnable { @override public void run() { final string s = jsonparser.doget("http://192.168.0.107:15071/getresult.ashx?op=getinfo",null); runonuithread(new runnable() { @over

api - How to create event in google calender using php -

i have try create event in google calnder using php.but not reflected in google. i follow code http://docs.dhtmlx.com/scheduler/how_to_start.html in data.php file have code include('../src/google_proxy.php'); $calendar = new googlecalendarproxy( "878294925469@developer.gserviceaccount.com", // email google api console "878294925469.apps.googleusercontent.com", // user id google api console file_get_contents("./aizasybvnvhdrzj33lckigsurwmeed1liasgj7a"), // private key "35hnoajpn21hmjtk27s7rnc77g@group.calendar.google.com" // calendar id ); i have api console account ,in account have client id , client secret . i dont know how these2 values "878294925469@developer.gserviceaccount.com" "878294925469.apps.googleusercontent.com. how post , event. can 1 suggest better code google calender you can download google calender code link http://www.

Timestamp difference in PHP mysql -

i want exact time difference between 2 php timestamps. & m using code code 1: $d1=strtotime(date('h:i:s')); //current time consider e.g 15:00:00 $d2=strtotime('18:00:00'); $all = round(($d2 - $d1) / 60); $d = floor ($all / 1440); $h = floor (($all - $d * 1440) / 60); $m = $all - ($d * 1440) - ($h * 60); & if print $h & $m - m looking , difference between 2 timestamps. now want $d2 table .. i have stored timestamp in mysql table datatype time . as below code 2 $d1=strtotime(date('h:i:s')); //current time consider e.g 15:00:00 $d2=strtotime($rows['showtime']); //where $rows['showtime'] timestamp stored in mysql table. consider 18:00:00 $all = round(($d2 - $d1) / 60); $d = floor ($all / 1440); $h = floor (($all - $d * 1440) / 60); $m = $all - ($d * 1440) - ($h * 60); but when print $h & $m m not getting values properly... please 1 me so... code 1 works when try execute

ios - UILocalNotification wrong fire date -

i have alarm run mon, sat & sun. pretty simple stuff. use code create uilocalnotification. since today sat testing see if alarm goes off today. //user picks time date picker shows hours , mins nsdate *selecteddate = [datepicker date]; nscalendar *calendar = [nscalendar currentcalendar]; nsdatecomponents *selecdatecomp = [calendar components:(nshourcalendarunit | nsminutecalendarunit) fromdate:selecteddate]; nsinteger hour = [selecdatecomp hour]; nsinteger minute = [selecdatecomp minute]; //nslog(@"hour: %d ... minute: %d ...", hour, minute); // set components fire time nsdate *now = [nsdate date]; nsdatecomponents *componentsforfiredate = [calendar components:nsyearcalendarunit|nsmonthcalendarunit|nsweekcalendarunit|nsweekdaycalendarunit|nshourcalendarunit|nsminutecalendarunit fromdate:now]; [componentsforfiredate sethour:hour]; [componentsforfiredate setminute:minute] ; //testing [componentsforfiredate setweekday:2]; //mon [componentsforfiredate setweekday:

php - Sticky posts managment in Wordpress -

i have problem sticky post. code use works, sticky posts showed on every query, , need modification in order show them when categories in queried. example: i filter category cars , shows me 10 posts cars, see aston martin first post. if filter category motorcycles, should not show me aston martin first one, ducati example. the second problem is, if aston martin vanish showed sticky, should not come again normal post in query. after doing lot of research , thing found how solve sticky post on category didn't work. http://wordpress.org/support/topic/sticky-post-from-only-current-category <?php /*template displaying archives*/ ?> <?php get_header(); ?> <div id="middle-full"> <div id="middle"> <div id="slider"> <h1 class="rezultatipretrage"><?php $tit = wp_title('', false); $newtit = array("kursevi stranih jezika", ";"); $newtit2 = array("", "

how vagrantfile stores the changes in vagrant machine? -

i developing application php , client asked me set vagrant machine , install every needed extensions , modules, 1 vagrant command client have same environment have, i firstly installed vagrant machine 1 of boxes lsit vagrant box add ubuntu1 http://goo.gl/kwqsa2 then run these commands: vagrant init ubuntu1 vagrant in directory made file there vagranrfile question: need know if make changes server example, installing php or mysql how going saved in setting if give file client able have identical machine mine installed? i mean there changes vagrantfile or made mistake , had install machine puppet? thanks in advance no, vagrant file not going change install things in vm. if want client have same machine you, you'll have avoid installing softwares through vm's shell. should use provisioner, for everything , mysql tables, apache virtual hosts etc.. and don't use vagrant box add ubuntu1 http://goo.gl/kwqsa2 , add box's url vagrantf

Php QR Code library not working? -

i got display text when pass function getqrcode($qr){ include 'application/views/inc/qrcode.php'; $this->view->qrcode = qrcode::png($qr); $this->view->render('user/qrcode'); } it works fine when symbol '%' shows in $qr variable wont work why ?? php qr code library: http://phpqrcode.sourceforge.net/ the code you're showing isn't particularly relevant doesn't show how process variable before use it, nor significant part(s) of library. at guess you're passing in value using get/post , aren't url-encoding string. % used special sequences eg %20 represents space. a list of characters need encoded available here . try replacing % %25 . for future reference, online encoder/decoder can found @ http://meyerweb.com/eric/tools/dencoder/

MySQL insert error in PHP -

i've been trying code below execute, although no error appears, row not inserted when check result in database. there seems problem in passing $query $sql, because when echo same value of $query , add text $sql works fine. any idea error ? $i=3; $query = '"'."insert data (id,qn,qi,cb,bk,qk)".""."values("."'".$i."','".$price[17]."','".$price[47]."','".$price[77]."','".$price[107]."','".$price[137]."')".'"'; echo $query; $connect= mysql_connect("localhost", "urs" , "password") or die(mysql_error()); mysql_select_db("data", $connect); $sql= $query; mysql_query($sql,$connect) the problem query has no space right before values make query syntactically incorrect far mysql goes. render when script runs: insert data (id,qn,qi,cb,bk,qk)values(…); mysql

node.js - What is this \u001b[9... syntax of choosing what color text appears on console, and how can I add more colors? -

i messing around debug , colors.js more colors limited 4-6 colors i'm stuck @ figuring out coloring syntax args[0] = ' \u001b[9' + c + 'm' + name + ' ' + '\u001b[3' + c + 'm\u001b[90m' + args[0] + '\u001b[3' + c + 'm' + ' +' + exports.humanize(ms) + '\u001b[0m'; 'blue' : ['\x1b[34m', '\x1b[39m'], 'cyan' : ['\x1b[36m', '\x1b[39m'], 'green' : ['\x1b[32m', '\x1b[39m'], 'magenta' : ['\x1b[35m', '\x1b[39m'], 'red' : ['\x1b[31m', '\x1b[39m'], 'yellow' : ['\x1b[33m', '\x1b[39m'], i know windows console allows more colors six, color /? shows 0 = black 8 = gray 1 = blue 9 = light blue 2 = green = light green 3 = aqua b = light aqua 4 = red c = light red 5 = purple d = light purple 6 = yellow e = light yellow 7 =

r - NVD3 Bullet Chart with rCharts -

wondering if possible produce nvd3 bullet chart ( http://nvd3.org/examples/bullet.html ) directly via rcharts ? poking around seems nvd3.r might lack ability pass required (ranges, measures, , markers) arguments down d3 - i'm not sure. thanks ! here 18 examples ramnath rcharts package related java script nvd3 package, no sign of bullet chart, guess not there. ## {title: scatter chart} p1 <- nplot(mpg ~ wt, group = 'cyl', data = mtcars, type = 'scatterchart') p1$xaxis(axislabel = 'weight') p1 ## {title: multibar chart} hair_eye = as.data.frame(haireyecolor) p2 <- nplot(freq ~ hair, group = 'eye', data = subset(hair_eye, sex == "female"), type = 'multibarchart') p2$chart(color = c('brown', 'blue', '#594c26', 'green')) p2 ## {title: multibar horizontal chart} p3 <- nplot(~ cyl, group = 'gear', data = mtcars, type = 'multibarhorizontalchart') p3$char

php - Having trouble inserting inputted data into database -

this question has answer here: php: “notice: undefined variable”, “notice: undefined index”, , “notice: undefined offset” 23 answers i have written question similar before hand , have seemed fix minor errors in code of time, when fix 1 thing, arises. before clarify problem, want explain background. have 2 registration forms, both used 1 after other own input devices , validations. when input data in first registration form, press next , takes me second form must fill out other information before "register" completely. in second registration form, used list of hidden inputs, <input type="hidden" name="name" value="<?php echo $_post['name'];?>"/> can hold information first registration file , still possess same data without loosing when taken next registration page. below code: <?php if (isset($_pos

javascript - Uploading files using Skipper with Sails.js v0.10 - how to retrieve new file name -

i upgrading sails.js version 0.10 , need use skipper manage file uploads. when upload file generate new name using uuid, , save in public/files/ folder (this change when i've got working it's testing right now) i save original name, , uploaded name + path mongo database. this quite straightforward under sails v0.9.x using skipper can't figure out how read new file name , path. (obviously if read name construct path though it's name need) my controller looks this var uuid = require('node-uuid'), path = require('path'), blobadapter = require('skipper-disk'); module.exports = { upload: function(req, res) { var receiver = blobadapter().receive({ dirname: sails.config.apppath + "/public/files/", saveas: function(file) { var filename = file.filename, newname = uuid.v4() + path.extname(filename); return newname; } }), result

servlets - Java HttpOnly Flag -

i used servlet 3.0 , want secure cookies httponly flag. web.xml <?xml version="1.0" encoding="utf-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="webapp_id" version="3.0"> <session-config> <cookie-config> <http-only>true</http-only> <secure>true</secure> </cookie-config> </session-config> </web-app> and servlet response.setcontenttype("application/json"); printwriter pw = response.getwriter(); cookie cookie = new cookie("url", "google.com"); cookie.setmaxage(60 * 60); //1 hour respo

java - Unexpected result when writing a Unicode(UTF-8) text to file -

Image
i have problem when writing unicode(utf-8) text file java. want writ text in other language (persian) file in java, receive unexpected result after run app. file file = new file(outputfilename); fileoutputstream f = new fileoutputstream(outputfilename); string encoding = "utf-8"; outputstreamwriter osw = new outputstreamwriter(f,encoding); bufferedwriter bw = new bufferedwriter(osw); stringbuilder row = new stringbuilder(); row.append("some text in english language"); // in below code should 4 space before علی row.append(" علی"); // in below code should 6 space before علی یاری row.append(" علی یاری"); bw.write(row.tostring()); bw.flush(); bw.close(); how can solve problem? the output expected according unicode bidirectional algorithm . entire persian text rendered right-to-left. if want individual words laid out left-to-right, need insert left-to-right character between 2 persian words. there's spe

c# - How to Pass value from @Url.Action to contoller in mvc? -

i trying pass value @url.action controller taking contoller/action/id , returns "no view found". below code view <a href="@url.action("index", "directputawaydetails", new { id = @home[j].test.tostring()})" class="ui-li-has-count" data-role="button" data-ajax="false" data-mini="true" style="background-color:#52616d;color:white"> @home[j].test.tostring() <span class="ui-li-count ui-btn-up-c ui-btn-corner-all" style="background-color: white; color: #52616d">@home[j].think.tostring() </span></a> controller public actionresult index(string id) { directsearch.home.test = id; return view() } i unable assign id value home.test model property. displays object reference not set instance of object.

html - capitalize each letter of word without javascript -

this question has answer here: display letters in capitals in block 2 answers i've written code capitalize first letter of every word in sentence without using javascript. html , css. doesnt seem working. plz solve problem. first code demo works. second code want submit in assignment, plz me solve problem. code 1: <html> <head> <input type="text" size="60%" style="text-transform:capitalize"> </head> </html> code 2: <!doctype html> <html> <head> <meta charset="utf-8"> <title>untitled document</title> <style> h2{ color:#0f0; font-size:large; font-weight:bold; font-family:"comic sans ms", cursive } p{ color:#0f0; font-size:large;

c# - i want my second combobox not show the selecteditem from the first one -

hallo have 1 combo box , fill database, combo box showing me ofc values db. have 1 more combo box after 1 , want not showing me selected item first one. how can archive one? view: <combobox verticalalignment="center" grid.column="1" grid.row="0" iseditable="false" issynchronizedwithcurrentitem="false" itemssource="{binding combo}" selecteditem="{binding selectedteam}" itemtemplate="{staticresource datatemp}" /> i tried second 1 bind in same observer able collection , use converter returns value.visibility.hidden; , did not worked. ////////////// update 1 /////////////////////// hallo , lot answer, have tried method cannot see on 2 comboboxes not selecteditem... <combobox itemssource="{binding}" datacontext="{binding combofiltercollection}" itemtemplate="{staticresource datatemp}" />

jquery - How to retrive value from array of arrays? -

[["sports","any"],["sports","cricket"],["sports","football"],["sports","other"]] if want retrieve cricket that? how achieve it? depends on language, expect [1][1] should it. assuming array called arr arr[1] refers ["sports","cricket"] (0 based index) array, can indentify elements same way usual... using [1] access "cricket" ... together: arr[1][1] .

twitter - IOS can't reply status with status_id -

i want reply twitter status status id. http response 403. here code. can sent first tweet. it's id. when want sent reply first tweet it's id http response 403. wrong. - (ibaction)btnsendtoucupinside:(id)sender { __block nsdecimalnumber *tid; __block int = 0; while (true) { if (i == 0 || _birlestirilsinmi) { urlparametres = [nsdictionary dictionarywithobjectsandkeys: [nsstring stringwithformat:@"%@", [self.twitarray objectatindex:0]], @"status", nil]; }else{ urlparametres = [nsdictionary dictionarywithobjectsandkeys: [nsstring stringwithformat:@"%@", [self.twitarray objectatindex:0]], @"status",[nsstring stringwithformat:@"%@",tid], @"in_reply_to_status_id",@"true", @"include_entities", nil]; } twrequest *postrequest = [[twrequest alloc] initwithurl:[nsurl urlwithstring:@"https://api.twitter.com/1/statuses/update.json&

xml - Find a new page in a word document -

how identify new page, or identifier denotes pages number using python-docx? i've looked through docs no avail far , have tried looking wd_break.page attribute feature not yet support. appreciated thanks. the short answer can't reliably determine soft page breaks .docx file. can identify hard page breaks , may able detect word broke pages last time "flowed" document. a word document "flowed" document, meaning word's layout engine "flows" text of document page until runs out of room, creates new page flows remaining text. these "soft" page breaks not specified in .docx file; determined word @ time of rendering, either display or printing. makes sense because whenever change, example, margins, pages may break @ different locations. an implication of .docx file not contain markup identifying following text should flow onto new page. a hard page break 1 explicitly inserted document author cause following content flow

android - Can anyone help me reset the zoom of the image in ImageView? -

i made app downloads image url (using universal image loader library) , display image in touchimageview . used touch image view implement pinch zoom functionality. followed this tutorial learn how use touchimageview. the problem whenever zoom in image downloaded universal image loader , loads image touchimageview new image stretched , distorted. problem solved when previous zoomed image restored original size zooming out, , loading new image. so problem can solved zooming out of loaded image , loading new image. don't know how reset zoom , library not provide function that. i tried using latest version of touchimageview (which includes reset image function) newer version not compatible uil seems tutorial using part of code original library (tough working fine). does know how reset zoom in touchimageview ? **strong text**code : package com.hpubts50.hpubustracker; import android.content.context; import android.graphics.matrix; import android.graphics.pointf; imp

ios - Can't set frame of a UIView while it's a child of UIScrollView -

Image
i have created 1 uiview inside uiscrollview storyboard. i want set frame uiview programatically. have tried set frame using setframe function programatically, its not working uiview inside uiscrollview. if create 1 uiview inside uiscrollview using [[uiview alloc] initwithframe:cgrectmake(0, 0, 320, 110)],and change size of view,it work! my code: but want create uiview ib , set frame using setframe function. most impornatant condition autolayout "true". most impornatant condition autolayout "true". if want mix constraints setting view's frame directly, need make sure set view.translatesautoresizingmaskintoconstraints = yes view. afaik, cannot done in ib ios, in code. also beware setting translatesautoresizingmaskintoconstraints = yes add new constraints define in ib (or programmatically) , have ensure remain consistent, otherwise exception. so, e.g., if set frame origin in code, pinned top distance between view , superview, ru

c - Ignore space or newline when reading a line -

i'm reading line till enter/return pressed(like terminal), have problems when comes ignoring space(s) , enter(s). this how read , check space/new line/comment: char line[256]; while(printf("%s>", shell_name) && scanf(" %50[^\n]", line) != eof){ if(isspace(*line) == 0 && line[0] != '#' && line[0] != '\n'){ input example: mysh>echo lol lol mysh> *spaces* mysh> mysh> *next line(enter)* mysh> the " " in scanf(" %50[^\n]", line) consumes leading whites-space (including '\n' ), not leading spaces. isspace(*line) == 0 , line[0] != '\n' true. suggest fgets()/sscanf() . user input far easier handle first getting line , then 2) parsing it. char buf[256]; if (fgets(buf, sizeof buf, stdin) == null) handleeof(); char line[256]; if (sscanf(buf, " %50[^\n]", line) < 1) handle_whitespaceonlyline(); goodtogo();

javascript - Elements With name Attributes Going to Server: PHP Convention Only? -

many places have said elements name attribute go server on page change, , element name , value attribute's value travel between client & server. php feature or present in other scripting languages? example, case node.js , or of popular server frameworks express or grunt ? also, there ways send other elements or attributes server? i know ajax can cause pretty go server, asynchronous, , when isn't info doesn't go server right when page sent. if have relevant info on ajax , though, please share it. when give element name attribute, browser send form data in body of request (if using post) or in query string (if using get). happens no matter language or framework use. name attribute - not work id - can ajax, passing querystring xmlhttprequest.send (if you're using jquery, read on jquery.post ). requests via ajax are, server, identical requests client. if send data in ajax post request, identical request via equivalent form server. same whether

c# - how Synchronize database with Context object -

i take new context object in main window context object die when close window public main_window() { initializecomponent(); } datacontext db = new datacontext(); my problem after created datacontextdb if change date in database management studio not changing in datacontextdb update datacontextdb must close window , open again example 1 -create object public partial class main_window: window { public main_window() { initializecomponent(); } datacontext db = new datacontext(); } 2- select using linq var q=from in db.employee select new {a.name}; result a.name "aaaa" 3-change employee name management studio "bbbb" 4- select using linq again var q=from in db.employee select new {a.name}; result a.name stile "aaaa" why when changed employee name management studio "bbbb" not changed in object datacontext until close window , open again , have other question when creat

python - What do (lambda) function closures capture? -

recently started playing around python , came around peculiar in way closures work. consider following code: adders=[0,1,2,3] in [0,1,2,3]: adders[i]=lambda a: i+a print adders[1](3) it builds simple array of functions take single input , return input added number. functions constructed in for loop iterator i runs 0 3 . each of these numbers lambda function created captures i , adds function's input. last line calls second lambda function 3 parameter. surprise output 6 . i expected 4 . reasoning was: in python object , every variable essential pointer it. when creating lambda closures i , expected store pointer integer object pointed i . means when i assigned new integer object shouldn't effect created closures. sadly, inspecting adders array within debugger shows does. lambda functions refer last value of i , 3 , results in adders[1](3) returning 6 . which make me wonder following: what closures capture exactly? what elegant way convince lambda

r - updating column values when table name is a variable -

first question here, , new r well. i have loop creating data frames according list of studytables. can read csvs fine, field "subject" , add variable "study" before in field. trouble 2nd "assign" line, can't r assign new value "subject". thanks help. study <- 'study10' studytables <- list('ae', 'subject') studypath <- 'c:/mypath/' for(table in studytables) { destinframe <- paste(table,study, sep='') file <- paste(studypath, table, '.csv', sep='' ) assign(destinframe, read.csv(file)) # create dataframes assign(destinframe['subject'], rep('testing', nrow(get(destinframe)))) } using assign isn't great idea. , can see doesn't work when try add columns data.frame. it's better add columns before assign. replace assign(destinframe, read.csv(file)) assign(destinframe['subject'], rep('testing', nrow(get(des

c# - Microsoft Azure Server Hosting? -

i've built base server engine(in c#) , test on microsoft azure. engine works on normal pcs including portforwarding. however, when tested on vm, can't seem tcp or udp process between pc client application , server hosted on vm. main guess need portforwarding on azure vm, thought point of creating endpoint public/private port, in turn portforwarding. i've gone through vm , opened specified endpoint same public/private port needed server , i've disabled temporarily windows firewall testing. however, after of this, connection not initialize , udp datagrams not received. once again, server work across windows pc set on, not azure vm , not sure why. as bit of info, using tcplistener, tcpclient , udpclient classes , asynchronous functions server's main network control, if holds relevancy.

java - How to get battery level -

i trying battery level of mobile using adf. mean example if battery charged fifty want value. how can achieve this? i don't know can achieve using android-intent. if yes, have do? here code sample explains how battery information: http://www.tutorialforandroid.com/2009/01/getting-battery-information-on-android.html to sum up, broadcast receiver action_battery_changed intent set dynamically, because can not received through components declared in manifests, explicitly registering context.registerreceiver(). public class main extends activity { private textview batterytxt; private broadcastreceiver mbatinforeceiver = new broadcastreceiver(){ @override public void onreceive(context ctxt, intent intent) { int level = intent.getintextra(batterymanager.extra_level, 0); batterytxt.settext(string.valueof(level) + "%"); } }; @override public void oncreate(bundle b) { super.oncreate(b); setcontentview(r.layout.ma

linux - Python try and except in launching password less ssh connection -

i want know whether scenario of taking ssh works or not try , except. if try part ask ssh password should move except part. here code, import os,sys,subprocess def process (input): print input = subprocess.popen (input,shell=true,stdout=subprocess.pipe,stderr=subprocess.pipe) output,error = a.communicate() return output,error try: process('ssh system1@123.123.123.123 \'ls\'') except: process('ssh system2@10.101.10.1 \'ssh system1@123.123.123.123 \'ls\' \'') in case not working @ ssh time out. as wrote it won't, because ssh sit there waiting password , not fail. however since not sending input command, can pass -n option ssh , fail if wanted ask anything. -n should work.

html - Bootstrap - good practice for multilingual 2 directions support? -

i'm building small website both in english (ltr) , hebrew (rtl). the website uses same code base, , changes captions according language being displayed. when english user enters site should see content left right. lets have image text next - image on left , text on right. when hebrew user enters should see image on right , text it's left. is there acceptable way doing in bootstrap without having write same html twice , without overriding bootstrap css classes? if attach js language checkbox, add/remove pull-right class elements want move: example: http://www.bootply.com/fzmcivlvbl# js $('input:checkbox').change(function(){ if($(this).is(":checked")) { $('div.ltr').addclass("pull-right"); } else { $('div.ltr').removeclass("pull-right"); } }); html <div class="col-xs-6 ltr"> <div class="thumbnail"> <img src="http://placeho

c - Converting a number to string with multiple arguments -

i want convert number x of base n string , store in str . str has max size of max . in program don't want use library functions. if reach maximum size of array, function should return false , array contents should undefined. the prototype of function looks this: bool num2str(int x, char *str, unsigned n, unsigned max); how go making work? i'm having trouble understanding algorithm behind it. i need check value of n , did that: bool num2str(int x, char *str, unsigned n, unsigned max) { assert(n >= 2 && n <= 36); return true; } but that's do. please help. let's take number in base 10: 123456. let's repeatedly apply module , integer division using number , base 10: 123456 mod 10 = 6 123456 div 10 = 12345 12345 mod 10 = 5 12345 div 10 = 1234 as can see, module base extracts last digit, while integer division base shifts number on digit right. can same base. hope hint enough.