Friday 15 June 2012

PHP CURL image upload to remote System -



PHP CURL image upload to remote System -

i using next code

$ch = curl_init("http://198.155.239.118/~bulacs/ssapi-staging/images/upload_images"); curl_setopt($ch, curlopt_useragent, "mozilla/5.0 (x11; linux x86_64; rv:21.0)gecko/20100101 firefox/21.0"); curl_setopt($ch, curlopt_post, true); curl_setopt( $ch, curlopt_postfields, array( 'image' => '@' . $_files['image']['tmp_name'] . ';filename=' . $_files['image']['name'] . ';type=' . $_files['image']['type'] )); curl_setopt($ch, curlopt_returntransfer, true); var_dump(curl_exec($ch));

here there no error , showing success message file not moving destination.

curl_setopt($ch, curlopt_post, 1); curl_setopt($ch, curlopt_postfields, array( 'image' => '@' . $_files['image']['tmp_name'] ));

i did , set tmp_name, above. should work.

php curl

jquery - Combine 2 functions into 1 -



jquery - Combine 2 functions into 1 -

how can combine functions. basically, when if checkbox clicked, happens , if page loads , if checkbox clicked, same thing happens sec function.

$(document).on("click", ".dimensions", function() { var size = $('.td-hide'); if ($('input#dimensions').is(':checked')) { size.show(); $('.single-select-sm').css('width','148px') } else { size.hide(); $('.single-select-sm').css('width','230px') } }); $(function() { var size = $('.td-hide'); if ($('input#dimensions').is(':checked')) { size.show(); $('.single-select-sm').css('width','148px') } else { size.hide(); $('.single-select-sm').css('width','230px') } });

var myfunc = function() { var size = $('.td-hide'); if ($('input#dimensions').is(':checked')) { size.show(); $('.single-select-sm').css('width','148px') } else { size.hide(); $('.single-select-sm').css('width','230px') } } $(document).on("click", ".dimensions", function() { myfunc(); } $(function() { myfunc(); }

jquery function

android - Database to use for storing profile information -



android - Database to use for storing profile information -

i'm making application android used store profile info of user( firstname, lastname, email, username, password ). store profile image of person. can think of applications whatsapp, viber tango. there many more it.

in order store , access info , efficiently, how should these info stored? i'm thinking storing info in relational database mysql. have fn,ln,email,username, password , link profile image columns of table. 1 more issue had in mind if user has 100 friends, should create new table per user his/her friends can separate , accessed single table or should run complex sql query returns list of friends of user?

thanks lot

i believe on right track. mysql fine selection storing info long on server can accessed application.

you need 2 tables: 1 store of users , map users friends.

your users table pretty straight forwards have laid out. other table (could named user_friends) have column containing id of friend made request, column containing id of friend accepted request, , other x amount of columns may need contain info friendship. record without id accepted friend can displayed pending request.

i create sure there can 1 record containing mapping of friends prevent duplicates well.

android sql database database-design relational-database

java - Is there an easy way to populate a ListView with Cursor? -



java - Is there an easy way to populate a ListView with Cursor? -

i wondering if there easy way fill listview cursor, can edittext:

final edittext visnavn=(edittext)findviewbyid(r.id.visnavn); dbadapter db; cursor cur = db.findall(); if(cur.movetofirst()){ do{ visnavn.append(cur.getstring(0)); visnavn.append(" "); visnavn.append(cur.getstring(1)); visnavn.append("\n"); }while(cur.movetonext()); } cur.close();

i've tried this, no luck:

cursor c = db.findall(); listview list = (listview)findviewbyid(r.id.list); if(c.movetofirst()){ do{ list.add(c.getstring(0)); list.add(" "); list.add(c.getstring(1)); }while(c.movetonext()); } c.close();

oke, said in comments there easy way load cursor info listview, here code used. maybe it's useful you! :)

final cursor locations = <get info here> locations.movetofirst(); layoutinflater inflater = this.getlayoutinflater(); while ( locations.isafterlast() == false ) { view tablerow = inflater.inflate(r.layout.tablerow, null); textview txtname = (textview)tablerow.findviewbyid(r.id.txtname); txtname.settext(locations.getstring(1)); sview.addview(tablerow); locations.movetonext(); }

java android android-listview android-sqlite android-cursor

c++ - Intersection of two actors - Vtk -



c++ - Intersection of two actors - Vtk -

i seek indicate intersection part of 2 vtkactors. have 3 vtkactors in total- 2 cones , 1 intersection of cones.

i have used vtkintersectionpolydatafilter draw intersection. couldn't create dynamic. when move actors different positions using keyboard interaction defined, intersection actor's initial state remains same. not beingness updated. how can create , alter intersection actor dynamically?

from description seems modifying actors, representation of polydata. vtkintersectionpolydatafilter works on polydata (that is, independent representation). if original polydata untouched, intersection same.

on other hand, if updating polydata (e.g. changing height of cone), remember set flag modified() trigger update of vtkintersectionpolydatafilter

c++ vtk

Can't cast or instanceof to true from Object to IProject || Java Eclipse Plugin-Development -



Can't cast or instanceof to true from Object to IProject || Java Eclipse Plugin-Development -

why can not cast content array of type object, eclipse framework method getting selection of bundle explorer returns, iproject? instanceof returns false , casting without check causes exception. debugger shows content of object[]-array have instance-variables , of iproject-type:

private list<iproject> getvalidselectedprojects(iworkbenchwindow window) { final iselectionservice service = window.getselectionservice(); final istructuredselection structured = (istructuredselection) service.getselection("org.eclipse.jdt.ui.packageexplorer"); if (structured == null){ homecoming null; } else { final object[] selectedprojects = structured.toarray(); arraylist<iproject> validatedprojects = new arraylist<iproject>(); (final object projectobj : selectedprojects){ if (projectobj instanceof iproject){ iproject project = (iproject) projectobj; //do } //rest of method; returning list of validated projects

i tried how convert between object[] , interface (iproject[]) in java?

but there exception @ line:

system.arraycopy(objectarray, 0, projectarray, 0, objectarray.length);

user interface objects returned getselection() not straight instances of iproject, ifile or iresource.

to iproject ... utilize iadaptermanager:

iproject project = (iproject)platform.getadaptermanager().getadapter(projectobj, iproject.class);

sometimes object not provide adapter straight iproject, seek more general iresource:

iresource resource = (iresource)platform.getadaptermanager().adapt(projectobj, iresource.class); if (resource instanceof iproject) { iproject project = (iproject)resource; ... code }

java eclipse casting eclipse-plugin instanceof

How to change cursor Icon in C# like in autoit -



How to change cursor Icon in C# like in autoit -

this question has reply here:

using custom colored cursors in c# windows application 4 answers

i alter cursor in autoit syntax:

dllcall($user32, 'int', 'loadcursorfromfile', 'str', 'data\cursors\rotmg.cur')

does know how in c#?

you need utilize pinvoke/dllimport create windows api calls.

from pinvoke.net, declaration be:

[dllimport("user32.dll")] static extern intptr loadcursorfromfile(string lpfilename);

and sample use:

intptr colorcursorhandle = loadcursorfromfile("c:\\temp.cur"); cursor mycursor = new cursor(colorcursorhandle); this.cursor = mycursor;

pinvoke.net resource getting right function signatures of pinvoke calls , construction marshalling.

c# cursor autoit

javascript - How to remove axis, and other information from Bar Chart? -



javascript - How to remove axis, and other information from Bar Chart? -

i need draw line graph, line graph no axes, values​​, etc. graph , percentage @ end.

q: how remove items graph, indicate axes, axes, etc. need leave line graph , interest.

$('#audience').jqchart({ legend: { visible: false }, border: { visible: false }, title: { text: 'chart title', font: '12px sans-serif', linewidth: 1, // strokestyle: 'black', fillstyle: 'white' }, animation: { duration: 1 }, series: [ { pointwidth: 0.2, type: 'bar', fillstyle: '#7fbbe5', data: [['a', 33]], labels: { stringformat: ' %s %%', valuetype: 'datavalue', font: '11px sans-serif', fillstyle: 'white' }, tickoptions: { showgridline: false } }, { pointwidth: 0.2, type: 'bar', fillstyle: '#92b5c7', data: [['a', 67]], tickoptions: { showgridline: false }, labels: { stringformat: ' %s %%', valuetype: 'datavalue', font: '11px sans-serif', fillstyle: 'white' } } ] });

i have image, show, have, , need: http://i57.tinypic.com/2h3x3yx.jpg

you can splice jqchart axes -

var axes = $('#jqchartdiv').jqchart('option', 'axes'); //remove series axes.splice(0, axes.length );

javascript jquery bar-chart jqchart

How To Use Ads With Chrome Extension? -



How To Use Ads With Chrome Extension? -

i'm trying inject 1 advertisement in popup created extension. how so? because when seek add together direct code provided adsense, shows "refuse execute script because of cpp".

is there way? i'm inserting advertisement on page , looks allowed chrome.

google-chrome google-chrome-extension

iOS - 'MyProject-Swift.h' file not found when running Unit Tests for Swift -



iOS - 'MyProject-Swift.h' file not found when running Unit Tests for Swift -

i trying setup unit testing project. existing objective-c app, have added 1 swift class to. have setup 'myproject-swift.h' , swift bridging files (both 'myproject' , 'myprojecttest') , able build , run app fine using both objective-c , swift code.

however, want run unit tests on new swift class. setup test file , looks following:

myswiftclasstests.swift:

import uikit import xctest import myproject class myswiftclasstests: xctestcase { override func setup() { super.setup() // set setup code here. method called before invocation of each test method in class. } override func teardown() { // set teardown code here. method called after invocation of each test method in class. super.teardown() } func testexample() { // illustration of functional test case. xctassert(true, "pass") } func testperformanceexample() { // illustration of performance test case. self.measureblock() { // set code want measure time of here. } } }

i error when running app test:

'myproject-swift.h' file not found

i not sure why happens when trying run tests. suggestions?

"myproject-swift.h" file generated @ next path:

"$(target_temp_dir)/../$(project_name).build/derivedsources"

i end adding header search paths unit test target.

also @hyouuu pointed out beingness known issue, apple provide solution @ end. until believe need utilize above solution.

https://developer.apple.com/library/mac/releasenotes/developertools/rn-xcode/chapters/xc6_release_notes.html

ios unit-testing swift header

java - I am storing text file in a mongodb and i want to perform search operations on content of a file. Is mongodb support content search of file? -



java - I am storing text file in a mongodb and i want to perform search operations on content of a file. Is mongodb support content search of file? -

i have created java application , through able insert file in mongodb , want perform content search on it.

here file insertion code.

import java.io.file; import com.mongodb.db; import com.mongodb.mongoclient; import com.mongodb.gridfs.gridfs; import com.mongodb.gridfs.gridfsdbfile; import com.mongodb.gridfs.gridfsinputfile; public class testfileinsert { public static void main(string[] args){ try{ // create connection mongodb mongoclient mongoclient = new mongoclient("localhost",27017); db db = mongoclient.getdb( "temp" ); system.out.println("connect database successfully"); // insert file mongo db using grid fs string newfilename = "tssmessage"; file newfile = new file("/home/n.dat"); gridfs gfsphoto = new gridfs(db, "test"); gridfsinputfile gfsfile = gfsphoto.createfile(newfile); gfsfile.setfilename(newfilename); gfsfile.save(); system.out.println("text file inserted successfully"); // file in database string getfilename = "tssmessage"; gridfs gfsphoto1 = new gridfs(db, "test"); gridfsdbfile imageforoutput = gfsphoto1.findone(getfilename); system.out.println(imageforoutput); } catch(exception e){ system.err.println( e.getclass().getname() + ": " + e.getmessage() ); } } }

how can perform content search in database?

your files seem images. content analysis of images hard problem. , mean very, hard. there progress on corner applications (text recognition, biometric face recognition...) the universal image identification algorithm can recognize image human brain can still unsolved problem of computer science , remain foreseeable future. , mongodb isn't trying provide solution sector.

but much simpler case, let's text file search, mongodbs gridfs not best tool.

when files text-based, seek create text index on fs.chunks collection, in collection each file stored multiple separate documents, each 1 (by default) 255kbyte of data. when info searching happens across chunk boundary, won't help much.

however, have ability query files metadata store them. depending on want do, extract relevant search terms files before store them , store these search terms in metadata.

java mongodb full-text-search

Excel (VBA): data formatted as date not recognized -



Excel (VBA): data formatted as date not recognized -

so have excel file, vba code in it. problematic bit need sort lot of info barcode number first, date of visit (each barcode visits multiple times).

this works fine random test info generated. gets sorted barcode, date latest earliest.great!

but not, when seek utilize actual data, doesn't: barcode gets sorted right not date. actual info come android app (xscan) has csv files output.

unfortunately, info exports looks "21/10/2014". when seek have sorted, sorts according first number, not date (not useful)... no matter month is, if day 31 st, it'll place highest.

i have tried following: changing datatype & forth, , run code datatype set different things, still doesn't work.

****how can create excel understand 21/10/2014 read date, though comes csv file , looks string/weird division?****

ideally, solution coded vba somehow... i'm dealing low-tech skills users....

edit: see screenshot below: column need sort column h. doesn't matter if set info type number, date, general.... still same. code:

function sorting_all(mysheet worksheet, myrangerow range, myrangecol range, secondsort string) dim mycol range set mycol = getcol(mysheet, secondsort) mysheet.range("a1", mysheet.cells(myrangerow.row, myrangecol.column)).sort key1:=mysheet.range("a1"), order1:=xlascending, key2:=mysheet.range(columns(mycol.column).address()), order2:=xldescending, header:=xlyes, orientation:=xlsortcolumns end function

the barcode in column , be, hence hardcode (i know know). that's key1. key2 date of visit (though function called sort other things, hence secondsort variabel).

further edit: apparently output file application isn't saved .csv (even though that's app claims), saved excel 97-2003 file. if copy-past file, doesn't work. if saved file csv (properly), copy-past it.... works. not gonna lie, hate excel. not built-in function alter app. heart of matter might between excel 97-2003 file format & excel 2010 file use... in case seem importing info through vba best answer.

in similar cases, problem imported date not match settings in windows command panel regional settings. excel interprets dates not fit settings text, , converts other dates incorrectly.

several fixes can used.

alter output info source date formats match -- not feasible. change windows regional short date settings match csv format -- not thought "lo-tech users" import file rather opening it. whether manually or via vba, have chance utilize text import wizard, allow specify imported date format.

excel vba date data-type-conversion

loops - Function to find number of words in a file using C++? -



loops - Function to find number of words in a file using C++? -

while (ch != '\0') { if (iswhitespace(contents[i-1]) == 1) countwords++; i++; }

i'm trying print word count in text file. i've defined function iswhitespace, homecoming 1 if char white space, otherwise returns 0. i've tested iswhitespace function , works properly. added code word count function , i'm getting segmentation fault error. i've tried multiple methods within while loop of getting word count , they've compiled, didn't homecoming right number, it's not problem outside while loop. can explain i'm doing wrong? give thanks much!

since ch never changes, loop doesn't end until contents[i-1] shouldn't accessing, hence segmentation fault.

c++ loops count while-loop word

c# - Accessing JQuery Auto complete with Selenium Webdriver -



c# - Accessing JQuery Auto complete with Selenium Webdriver -

i trying html of jquery autocomplete after word typed in. decided seek selenium webdriver.

i had read of documentation , think got couple of issue.

1) i'ts not finding search suggestions although pretty sure selecting right

2) don't know how html string iwebelement.

here code doesn't work:

iwebdriver driver = new firefoxdriver(); driver.navigate().gotourl("https://site.xxx/"); iwebelement query = driver.findelement(by.name("stext")); query.sendkeys("iphone"); // point works, set wait in here incase takes few seconds load webdriverwait wait = new webdriverwait(driver, timespan.fromseconds(2)); // seems come empty in developer tools chrome can see iwebelement results = driver.findelement(by.classname("ac_results"));

can see going wrong?

on result phone call add together .text(); end text value of element. java syntax.

string val = driver.findelement(by.classname("ac_results")).text();

or

webelement driver.findelement(by.classname("ac_results")); string val = we.text();

c# selenium-webdriver

shell - how to merge two files in unix -



shell - how to merge two files in unix -

i want merge 2 files in unix. how can this?

eg file1 contains:

host1:90:/users:user1 host2:90:/users:user1 host3:90:/users:user1 host4:90:/users:user1 host5:90:/users:user1 host6:90:/users:user1 host7:90:/users:user1

file2 contains:

host1:owner_name host2:owner_name host3:owner_name host4:owner_name host5:owner_name host6:owner_name host7:owner_name

output result:

host1:90:/users:user1:owner_name host2:90:/users:user1:owner_name host3:90:/users:user1:owner_name host4:90:/users:user1:owner_name host5:90:/users:user1:owner_name host6:90:/users:user1:owner_name host7:90:/users:user1:owner_name

i have used command paste -d ':' file1 file2 >merged_file, getting:

host1:90:/users:user1:host1:owner_name host2:90:/users:user1:host2:owner_name host3:90:/users:user1:host3:owner_name host4:90:/users:user1:host4:owner_name host5:90:/users:user1:host5:owner_name host6:90:/users:user1:host6:owner_name host7:90:/users:user1:host7:owner_name

use join instead:

% bring together -t':' file1 file2 host1:90:/users:user1:owner_name host2:90:/users:user1:owner_name host3:90:/users:user1:owner_name host4:90:/users:user1:owner_name host5:90:/users:user1:owner_name host6:90:/users:user1:owner_name host7:90:/users:user1:owner_name

shell unix

join - ArangoDB link documents -



join - ArangoDB link documents -

is possible link documents different collections in arangodb in orientdb?

in orientdb can create field of type link , specify type linked. creates relation between both documents.

do have utilize border collections in arangodb?

i'm trying define main collection , secondary collection info supplement main one. don't want have info in main collection shared between other entities.

thanks in advance.

there 2 options:

using joins

you can define attribute on main document containing info identifies sub-document (e.g. _key) , utilize aql bring together 2 documents in query:

for x in maindocuments filter x.whatever < 42 y in secondarydocuments filter x.sub = y._key homecoming merge(x,y)

using edges

you can define border collection holding "relations" between documents. border documents can optionally additional info on edges themselves.

for x in maindocuments allow n = neighbors("maindocuments", "edgecollection", x._id, "any"); homecoming merge(x, n[0].vertex);

however there no such thing foreign key constraint in arangodb. can refer non-existing documents in edges or delete sub-document without main document beingness informed.

the benefit of sec approach can utilize arbitrary number of edges between these documents , decide on 0, 1 or more during runtime of application without modification. first approach have decide @ origin making attribute single value or list of values.

join hyperlink document-database arangodb

excel - vba check if value exists in column h and if month of date in column m is this month? -



excel - vba check if value exists in column h and if month of date in column m is this month? -

i trying utilize vba count rows on sheet 2 ('logs') column h matches value entered cell on sheet 1 ('home'). doing using next code:

dim ival integer ival = application.worksheetfunction.countif(sheets("logs").columns("h"), range("n10").value) ival2 = application.worksheetfunction.countif(sheets("logs").columns("j"), range("n20").value) if iserror(application.match(range("n10").value, sheets("logs").columns("h"), 0)) msgbox "no match" else msgbox "hi " & range("n10").value & "," & vbnewline & vbnewline & "your section has requested " & ival2 & " suppliers month. have " & 5 - ival & " requests remaining month." & vbnewline & vbnewline & "each section allowed 5 new supplier requests per month.", vbokonly + vbinformation, "important notice!" exit sub end if

now want add together if statement , count matching values against column h value entered in cell on sheet 1 if date in same row in column m on sheet 2 contains current month , year.

so instance lets todays month 'october 2014' , column h contains word 'apples' , in same row in column m '21/10/2014'.

if type 'apples' in cell on sheet 1 count 1 occurrence of word apples month.

but if in column h have 'apples' , in column m '21/09/2014' , todays month oct 2014 not counted month not current month.

does know way this? trying surround code if statement i'm new vba , don't think way go.

> if month(date) = month(sheets("logs").columns("m")) > msgbox "date now" > else > msgbox "date not now" > end if

you don't strictly require vba accomplish this. assuming info grid of 99 rows on both sheet1 , sheet2, next formula using native excel functions homecoming count sheet1!h1:99 matching n10 , sheet2!m1:99 matching year , month of n20. =sumproduct((sheet1!$h$1:$h$99=n10)*(text(sheet2!$m$1:$m$99,"yyyymm")=text(n20,"yyyymm")))

addendum: if qualify cell references, can utilize square brackets evaluate formula this:

sub test() activesheet .range("a1") = [=sumproduct((sheet1!$h$1:$h$99=sheet3!n10)*(text(sheet2!$m$1:$m$99,"yyyymm")=text(sheet3!n20,"yyyymm")))] end end sub

note i've added worksheet references n10 , n20.

excel vba

javascript - Angular filter list without ng-repeat -



javascript - Angular filter list without ng-repeat -

is there way of using angular filter list without ng-repeat? dont want utilize javascript draw list @ first, want utilize angular filter afterwards.

example:

class="snippet-code-html lang-html prettyprint-override"><input type="search" ng-model="search" placeholder="search fruits!" /> <ul> <li>banana</li> <li>apple</li> <li>orange</li> </ul>

i want utilize search box filter existing html.

(please dont give examples ng-repeat or jquery in general)

you can write simple directive handle show/hide:

app.directive('filterlist', function($timeout) { homecoming { link: function(scope, element, attrs) { var li = array.prototype.slice.call(element[0].children); function filterby(value) { li.foreach(function(el) { el.classname = el.textcontent.tolowercase().indexof(value.tolowercase()) !== -1 ? '' : 'ng-hide'; }); } scope.$watch(attrs.filterlist, function(newval, oldval) { if (newval !== oldval) { filterby(newval); } }); } }; });

and utilize way:

<input type="search" ng-model="search" placeholder="search fruits!" /> {{search}} <ul filter-list="search"> <li>banana</li> <li>apple</li> <li>orange</li> </ul>

there couple of benefits of using directive:

1). don't have set ngshow/ngif directives on every li.

2). work new appended li elements list.

demo: http://plnkr.co/edit/wpqlykkeutfr5tjveer4?p=preview

javascript html angularjs angularjs-ng-repeat

java - Deserializing XML file without converting xml file -



java - Deserializing XML file without converting xml file -

the below xml generated scheme needs converted java application object of type employee.

<?xml version="1.0" encoding="utf-8"?> <employee xmlns:i="http://www.w3.org/2001/xmlschema-instance"> <designation>executive</designation> <name>praveen kumar</name> <salary>90000</salary> <bankaccount>10111</bankaccount> </employee>

how deserialize above xml using xmldecoder's readobject method without converting xml file generated system?

here how can handle utilize case:

java model

the next class used answer:

package forum26609152; public class employee { private string designation; private string name; private int salary; private string bankaccount; public string getdesignation() { homecoming designation; } public void setdesignation(string designation) { this.designation = designation; } public string getname() { homecoming name; } public void setname(string name) { this.name = name; } public int getsalary() { homecoming salary; } public void setsalary(int salary) { this.salary = salary; } public string getbankaccount() { homecoming bankaccount; } public void setbankaccount(string bankaccount) { this.bankaccount = bankaccount; } } xmlencoder/xmldecoder

below xml xmlencoder/xmldecoder expecting work with. different xml in question. xmlencoder/xmldecoder not fit utilize case.

<?xml version="1.0" encoding="utf-8"?> <java version="1.7.0_60" class="java.beans.xmldecoder"> <object class="forum26609152.employee"> <void property="bankaccount"> <string>10111</string> </void> <void property="designation"> <string>executive</string> </void> <void property="name"> <string>praveen kumar</string> </void> <void property="salary"> <int>90000</int> </void> </object> </java> jaxb

jaxb standard api object-to-xml binding. implementation has been included in jdk/jre since java se 6, have it.

employee

the mappings between java , xml configured via annotations. below annotations necessary map java object xml question.

import javax.xml.bind.annotation.*; @xmlrootelement(name="employee") @xmltype(proporder = {"designation", "name", "salary", "bankaccount"}) public class employee { private string designation; private string name; private int salary; private string bankaccount; @xmlelement(name="designation") public string getdesignation() { homecoming designation; } public void setdesignation(string designation) { this.designation = designation; } @xmlelement(name="name") public string getname() { homecoming name; } public void setname(string name) { this.name = name; } @xmlelement(name="salary") public int getsalary() { homecoming salary; } public void setsalary(int salary) { this.salary = salary; } @xmlelement(name="bankaccount") public string getbankaccount() { homecoming bankaccount; } public void setbankaccount(string bankaccount) { this.bankaccount = bankaccount; } }

demo code

below code need write read xml object form, , output xml.

import javax.xml.bind.*; import java.io.file; public class jaxbdemo { public static void main(string[] args) throws exception { jaxbcontext jc = jaxbcontext.newinstance(employee.class); unmarshaller unmarshaller = jc.createunmarshaller(); file xml = new file("input.xml"); employee employee = (employee) unmarshaller.unmarshal(xml); marshaller marshaller = jc.createmarshaller(); marshaller.setproperty(marshaller.jaxb_formatted_output, true); marshaller.marshal(employee, system.out); } }

input.xml/output

as can see xml question:

<?xml version="1.0" encoding="utf-8" standalone="yes"?> <employee> <designation>executive</designation> <name>praveen kumar</name> <salary>90000</salary> <bankaccount>10111</bankaccount> </employee>

java xml serialization

Java ASM: Cant Instantiate ClassNode -



Java ASM: Cant Instantiate ClassNode -

i using asm v5.0.3. trying create classnode constructor appears hang forever. here code:

logger.warn("______ creating class node"); seek { logger.warn("______ creating class node 1"); classnode classnode = new classnode(); logger.warn("______ creating class node 2"); } grab (exception e) { logger.error("could not instantiate class node"); } logger.warn("______ created class node");

on console see

warn 2014-10-29 17:06:37,704 [line 39] ______ creating class node warn 2014-10-29 17:06:37,704 [line 42] ______ creating class node 1

and nil else. @ total loss whats happening here. how go diagnosing , fixing this? has seen before. other thing have been doing seek solve issue remove old versions of asm transitive dependencies, such as:

class="lang-xml prettyprint-override"><exclusions> <exclusion> <groupid>asm</groupid> <artifactid>asm</artifactid> </exclusion> </exclusions>

since using

class="lang-xml prettyprint-override"><dependency> <groupid>org.ow2.asm</groupid> <artifactid>asm-all</artifactid> <version>${ow2.asm.version}</version> </dependency>

does sound familiar anyone?

java java-bytecode-asm

winforms - Add datetimepicker to StatusStrip control in C# -



winforms - Add datetimepicker to StatusStrip control in C# -

i want add together datetimepicker statusstrip command show today's date, there way add together other controls label , progress bar statusstrip control??

yes, check :

https://social.msdn.microsoft.com/forums/windows/en-us/edbd92be-76ee-49b1-b7c6-f6522992a14a/using-toolstripcontrolhost-with-datetimepicker

[toolstripitemdesigneravailability(toolstripitemdesigneravailability.toolstrip)] public class toolstripdatetimepicker : toolstripcontrolhost { private flowlayoutpanel controlpanel; private datetimepicker picker = new datetimepicker(); public toolstripdatetimepicker() : base(new flowlayoutpanel()) { controlpanel = (flowlayoutpanel)base.control; controlpanel.backcolor = color.transparent; autosize = false; controlpanel.controls.add(picker); } public datetime value { { homecoming this.picker.value; } set { this.picker.value = value; } } protected override void onsubscribecontrolevents(control control) { base.onsubscribecontrolevents(control); } protected override void onunsubscribecontrolevents(control control) { base.onunsubscribecontrolevents(control); } }

c# winforms statusstrip

How to alter the SQL output messages -



How to alter the SQL output messages -

i have multiple insert / select statements part of single sql info import script. when run script output

(141926 row(s) affected) (124366 row(s) affected) (4 row(s) affected) (1 row(s) affected)

but want is

(141926 row(s) affected) - customers deleted (124366 row(s) affected) - customers inserted (4 row(s) affected) - customers missing lastly name etc (1 row(s) affected)

is there anyway in sql??

i agree @yorick de wid, in don' think can customise sql output.

the closest can think of in sql server "roll own", doing like:

declare @recordsaffected int <execute sql statement here> set @recordsaffected = @@rowcount print convert(varchar,@recordsaffected) + ' <your message here>'

sql

Set CSS style to GtkBox with python -



Set CSS style to GtkBox with python -

is posible alter background color of object gtkbox? far styles have worked in other objects gtkbox not work me know why? code

self.ventana = self.builder.get_object("ventana") self.header= self.builder.get_object("header") self.ventana.set_name('mywindow') self.header.set_name('header') self.style_provider = gtk.cssprovider() self.css=open(self.ruta+'/css/estilos.css','rb') self.css_data = self.css.read() self.style_provider.load_from_data(self.css_data) gtk.stylecontext.add_provider_for_screen(gdk.screen.get_default(),self.style_provider, gtk.style_provider_priority_application) /*********css styles *********/ #mywindow { background-color: #1d1d1d; } /*i seek whit: #mywindow #header, #mywindow gtkbox */ #header{ background-color: #ffffff; border-bottom: 1px solid white; }

the problem not gtk widgets draw own background. background determined underlying widget. behavior changed some widgets gtk+ 3.12.

so changing background color of gtk.box not work version < gtk+ 3.12. if using older version, alternative approach utilize gtk.viewport underneath gtk.box , alter color of viewport.

to set code:

box = gtk.box() viewport = gtk.viewport() viewport.add(box) #and cssprovder, stylecontext,...

css:

gtkviewport { background-color: red; )

python css python-3.x pygtk

r - How do I count / display the number of each outcome from a random sample? -



r - How do I count / display the number of each outcome from a random sample? -

i'm taking sample of size 1000 of different (pet) animals. code

pet <- sample(c("dog","cat","hamster","goldfish"), 1000, replace = true)

i want see how many times "dog" selected, "cat" selected, etc. i've tried summary(pet) wasn't much help / told me length 1000 , characters.

try in r:

> table(pet) pet cat dog goldfish hamster 241 284 225 250

r sample

html - Scale image with page that's larger than the page in CSS -



html - Scale image with page that's larger than the page in CSS -

i have image want resize when width of page/screen changes.

this code want:

.section { position:relative; min-width:600px; max-width:1200px; height:auto; margin-left:auto; margin-right:auto; overflow: hidden; } .image { position:relative; display:inline-block; vertical-align:top; width:100%; height:auto; } <div class="section"> <img src="long_img.jpg" class="image"/> </div>

the problem is, image 2560px wide, , section 1200px. image gets squashed horizontally fit, scales height down. but, when page @ it's max width(1200) want image @ total height(400). need image hang on edge, still automatically resize.

the reason don't crop image because want scroll css animation.

i've tried .image{ margin-right:-1360; } had no effect.

use media query after css have there. remove 100% declaration , allow image it's natural size.

@media(min-width:1200px) { .section img { width: auto; display: block; } }

also, take away overflow:hidden containing div.

see fiddle example.

html css layout scaling

python - How to NOT load whole file into memory during upload -



python - How to NOT load whole file into memory during upload -

am using bottle create upload api. script below able upload file directory got 2 issues need address. 1 how can avoid loading whole file memory other how set maximum size upload file?

is possible continuously read file , dump has been read file till upload complete? upload.save(file_path, overwrite=false, chunk_size=1024) function seems load whole file memory. in tutorial, have pointed out using .read() is dangerous.

from bottle import bottle, request, run, response, route, default_app, static_file app = bottle() @route('/upload', method='post') def upload_file(): function_name = sys._getframe().f_code.co_name try: upload = request.files.get("upload_file") if not upload: homecoming "nothing upload" else: #get file_name , extension file_name, ext = os.path.splitext(upload.filename) if ext in ('.exe', '.msi', '.py'): homecoming "file extension not allowed." #determine folder save upload save_folder = "/tmp/{folder}".format(folder='external_files') if not os.path.exists(save_folder): os.makedirs(save_folder) #determine file_path file_path = "{path}/{time_now}_{file}".\ format(path=save_folder, file=upload.filename, timestamp=time_now) #save upload file in chunks upload.save(file_path, overwrite=false, chunk_size=1024) homecoming "file saved {0}{1} '{2}'.".format(file_name, ext, save_folder) except keyboardinterrupt: logger.info('%s: ' %(function_name), "someone pressed cnrl + c") except: logger.error('%s: ' %(function_name), exc_info=true) print("exception occurred111. location: %s" %(function_name)) finally: pass if __name__ == '__main__': run(host="localhost", port=8080, reloader=true, debug=true) else: application = default_app()

i tried doing file.write same case. file getting read memory , hangs machine.

file_to_write = open("%s" %(output_file_path), "wb") while true: datachunk = upload.file.read(1024) if not datachunk: break file_to_write.write(datachunk)

related this, i've seen property memfile_max several so posts claim 1 set maximum file upload size. i've tried setting seems not have effect files no matter size going through.

note want able receive office document plain extensions or zipped password.

using python3.4 , bottle 0.12.7

basically, want phone call upload.read(1024) in loop. (untested):

with open(file_path, 'wb') dest: chunk = upload.read(1024) while chunk: dest.write(chunk) chunk = upload.read(1024)

(do not phone call open on upload; it's open you.)

this answer includes more illustration sof how read big file without "slurping" it.

python bottle

jquery - Removing a parent row if a specific value is found -



jquery - Removing a parent row if a specific value is found -

i have table without specific class or id, , i've remove table rows have links within specific attribute value (href*=...) within table, or matter, anywhere on web site. can rid of links, not row has link within it. how can css? if not, jquery or js?

there no css parent selector, it's not possible css alone.

you can jquery though, using attribute selectors:

$('table a[href=somethingspecific]').closest('tr').remove();

or, select anchors , filter them (quicker):

$('table a').filter(function(){ homecoming $(this).attr('href') == 'somethingspecific'; }).closest('tr').remove();

jquery css3

Cordova. I use push notification or scheduller? -



Cordova. I use push notification or scheduller? -

i want develop app works cordova follows. on server side database of messages , these messages should delivered devices correspond owners posts. question this, service on side of phone checking time time if there messages him or have server send these messages push, not know right way since never made similar application . give thanks you.

sending messages through force best way.

drawbacks client side checking:- if write code on client side(in phone) check messages time time, need handle events when app not in use, managing scheduler when net connection not available etc.

advantage of force server:- incase of force receive notification when app not in use, user know new messages received him , notification sent automatically received whenever user online.

i have used practice several apps , had received feedback on usabiltiy

cordova push-notification schedule

android - finish() on an Activity closes app then briefly shows previous Application -



android - finish() on an Activity closes app then briefly shows previous Application -

in app, activity1 launches activity2 "startactivityforresult()".

when activity2 done, next code called:

activity2.java

private void finishactivity(final boolean accepted) { intent returnintent = new intent(); setresult(accepted ? result_ok : result_canceled, returnintent); finish(); }

activity1 receives callback, , if result not result_ok, finishes.

activity1.java

@override protected void onactivityresult(int requestcode, int resultcode, intent data) { super.onactivityresult(requestcode, resultcode, data); if (requestcode == globals.request_code_tos) { if (resultcode != result_ok) finish(); } }

after activity1 finishes app closes, expected.

the problem --

however, after app closes, instead of going home screen, previous application on stack briefly launches forward, closes also! home screen.

in android bug tracker, see similar bug listed case when button pressed, believe same calling finish():

https://code.google.com/p/android/issues/detail?id=71067

i'm seeing on nexus 5, running 4.4.4.

is bug? or there workarounds behavior?

edit --

to clarify behavior desire:

in google maps, if decline tos popup, app closes , go straight home screen. there no awkward flash opened app.

this decidedly same issue one linked in question (i've been next months, own nexus 5 myself). fixed in aosp, particular prepare doesn't seem have found way n5 yet. i've got fingers crossed prepare in lollipop, we'll see when rolls out.

as workaround, don't think exists @ moment, although if i'm wrong on love know - work on app myself similar (manually calls finish() bottom-most activity in stack when closed via button).

android android-activity activity-finish

Location of HHVM Config File -



Location of HHVM Config File -

i have built hhvm source code. can not configure hhvm-fastcgi. not find ini file configuration.

hhvm binary located @ /usr/local/bin. wanna run hhvm nginx. purpose adding custom php extension hhvm. source code @ /home/vagrant/dev/hhvm. operation scheme ubuntu 14.04.

here default ini file. have seek creating it.

file /etc/hhvm/server.ini ; php options pid = /var/run/hhvm/pid ; hhvm specific hhvm.server.port = 9001 hhvm.server.type = fastcgi hhvm.server.default_document = index.php hhvm.log.level = warning hhvm.log.always_log_unhandled_exceptions = true hhvm.log.runtime_error_reporting_level = 8191 hhvm.log.use_log_file = true hhvm.log.file = /var/log/hhvm/error.log hhvm.repo.central.path = /var/run/hhvm/hhvm.hhbc hhvm.mysql.typed_results = false hhvm.debug.full_backtrace = true hhvm.debug.server_stack_trace = true hhvm.debug.server_error_message = true hhvm.debug.translate_source = true

hhvm

C++ beginner program not working -



C++ beginner program not working -

i'm starting larn c++ c++ primer book. wrote basic code first tutorial, it's not working. i'm using windows 8 , orwell dev-c++ 5.8.2.

#include <iostream> int main() { std::cout << "enter 2 numbers:" << std::endl; int v1 = 0, v2 = 0; std::cin >> v1 >> v2; std::cout << "the sum of " << v1 << " , " << v2 << " " << v1 + v2 << std::endl; system("pause"); homecoming 0; }

this not homecoming when run it, pauses text "press key continue.." , exits.

c++

check with Matlab if object is exsting -



check with Matlab if object is exsting -

matlab code:

for n = 1:length(data) if exist('data{n}.sid') array{n} = data{n}.sid else array{n} = 0 end end

result:

array = [0] [0] [0] [0] [0] [0] [0]

but in first , sec struct of "data", "hk1", resp. "hk1.sid" exists , contains "1"!

how have alter code, array looks this?...

array = [1] [1] [0] [0] [0] [0] [0]

content of data:

>> info info = [1x1 struct] [1x1 struct] [1x1 struct] [1x1 struct] [1x1 struct] [1x1 struct] [1x1 struct] >> data{2} ans = sid: 1 hk1: [1x1 struct] >> data{4} ans = pack_id: [1x1 struct] pack_seq_ctrl: [1x1 struct]

as see, data{2} includes "sid", data{4} doesn't include "sid"...

instead of exist('data{n}.sid'), utilize isstruct(data{n}) && isfield(data{n}, 'sid').

exist attempting check whether variable exists literally called data{n}.sid. that's not valid variable name, returns false , never through status wanted.

matlab

java - SWT/JFace TextCellEditor Field Assist Not Working -



java - SWT/JFace TextCellEditor Field Assist Not Working -

i trying execute code block extending textcelleditor , using org.eclipse.jface.fieldassist fire content proposal. code executing fine content proposal pop not beingness fired. cell not editable. please allow me know wrong here?

public class snippet060textcelleditorwithcontentproposal { private static class color { public string name; public color(string name) { this.name = name; } public string tostring() { homecoming name; } } public static class textcelleditorwithcontentproposal extends textcelleditor { private contentproposaladapter contentproposaladapter; private boolean popupopen = false; // true, iff popup open public textcelleditorwithcontentproposal(composite parent, icontentproposalprovider contentproposalprovider, keystroke keystroke, char[] autoactivationcharacters) { super(parent); enablecontentproposal(contentproposalprovider, keystroke, autoactivationcharacters); } private void enablecontentproposal( icontentproposalprovider contentproposalprovider, keystroke keystroke, char[] autoactivationcharacters) { contentproposaladapter = new contentproposaladapter(text, new textcontentadapter(), contentproposalprovider, keystroke, autoactivationcharacters); // hear popup open/close events able handle focus // events correctly contentproposaladapter .addcontentproposallistener(new icontentproposallistener2() { public void proposalpopupclosed( contentproposaladapter adapter) { popupopen = false; } public void proposalpopupopened( contentproposaladapter adapter) { popupopen = true; } }); } /** * homecoming {@link contentproposaladapter} of cell editor. * * @return {@link contentproposaladapter} */ public contentproposaladapter getcontentproposaladapter() { homecoming contentproposaladapter; } protected void focuslost() { if (!popupopen) { // focus lost deactivates cell editor. // must not happen if focus lost caused activating // completion proposal popup. super.focuslost(); } } protected boolean dependsonexternalfocuslistener() { // homecoming false; // otherwise, columnviewereditor install additional // focus listener // cancels cell editing on focus lost, if focus gets lost // due // activation of completion proposal popup. see bug 58777. homecoming false; } } private static class colornameeditingsupport extends editingsupport { private textcelleditorwithcontentproposal celleditor; public colornameeditingsupport(tableviewer viewer) { super(viewer); icontentproposalprovider contentproposalprovider = new simplecontentproposalprovider( new string[] { "red", "green", "blue" }); celleditor = new textcelleditorwithcontentproposal( viewer.gettable(), contentproposalprovider, null, null); } protected boolean canedit(object element) { homecoming (element instanceof color); } protected celleditor getcelleditor(object element) { homecoming celleditor; } protected object getvalue(object element) { homecoming ((color) element).name; } protected void setvalue(object element, object value) { ((color) element).name = value.tostring(); getviewer().update(element, null); } } public snippet060textcelleditorwithcontentproposal(shell shell) { final tableviewer viewer = new tableviewer(shell, swt.border | swt.full_selection); final table table = viewer.gettable(); table.setlinesvisible(true); table.setheadervisible(true); final tableviewercolumn colorcolumn = new tableviewercolumn(viewer, swt.left); colorcolumn.getcolumn().settext("color name"); colorcolumn.getcolumn().setwidth(200); colorcolumn.setlabelprovider(new columnlabelprovider()); colorcolumn.seteditingsupport(new colornameeditingsupport(viewer)); viewer.setcontentprovider(new arraycontentprovider()); columnviewereditoractivationstrategy activationsupport = new columnviewereditoractivationstrategy( viewer) { protected boolean iseditoractivationevent( columnviewereditoractivationevent event) { homecoming event.eventtype == columnviewereditoractivationevent.traversal || event.eventtype == columnviewereditoractivationevent.mouse_double_click_selection || event.eventtype == columnviewereditoractivationevent.programmatic || (event.eventtype == columnviewereditoractivationevent.key_pressed && event.keycode == keylookupfactory .getdefault().formalkeylookup( ikeylookup.enter_name)); } }; activationsupport.setenableeditoractivationwithkeyboard(true); /* * without focus highlighter, keyboard events not delivered * columnviewereditoractivationstragety#iseditoractivationevent(...) * (see above) */ focuscellhighlighter focuscellhighlighter = new focuscellownerdrawhighlighter( viewer); tableviewerfocuscellmanager focuscellmanager = new tableviewerfocuscellmanager( viewer, focuscellhighlighter); tableviewereditor.create(viewer, focuscellmanager, activationsupport, columnviewereditor.tabbing_vertical | columnviewereditor.keyboard_activation); viewer.setinput(createmodel()); } private color[] createmodel() { homecoming new color[] { new color("red"), new color("green") }; } /** * @param args */ public static void main(string[] args) { display display = new display(); shell shell = new shell(display); shell.setlayout(new filllayout()); new snippet060textcelleditorwithcontentproposal(shell); shell.open(); while (!shell.isdisposed()) { if (!display.readanddispatch()) display.sleep(); } display.dispose(); } }

this working expected, did'nt realize cells registered mouse double click action. double click brings pop up

java swt jface

debugging - CrossRider - Show Local Database is not updated until I refresh the page -



debugging - CrossRider - Show Local Database is not updated until I refresh the page -

show local database not updated until refresh page (in debug mode). after refresh page can see updated database.

the url http://crossrider.com/apps/43889/debug.

i'm using net explorer 11.

database debugging crossrider

javascript - Manually change state with ui-router in angular -



javascript - Manually change state with ui-router in angular -

i have search bar in app. anytime user makes search, i'd state alter /#/search/:query

to so, attach next function scope , trigger anytime query made:

this.searchitem = function searchitem(item) { $state.go('#/search/' + item) }

however results in next error:

error: couldn't resolve '#/search/query' state (current state) @ object.transition.to

what problem code? how can alter state without using anchors ui-router?

many thanks

you're passing url when need pass name of state. see ui-router wiki examples.

javascript angularjs angular-ui-router

move content including subfolders between folders in unix -



move content including subfolders between folders in unix -

i have path contain folders , subfolders:

~/public_html/myfolder/myfolder/

how move content ~/public_html/myfolder/myfolder/ ~/public_html/myfolder/

you can use:

mv ~/public_html/myfolder/myfolder/* ~/public_html/myfolder

run man mv more details.

unix

Swift Class with an optional value -



Swift Class with an optional value -

how can following:

i have class in swift

class book { var title: string var author: string? init(title: string, author: string?) { self.title = title self.author = author }

and in class i'm making phone call api retrieve list of books, though author not nowadays so

let title: string? = getbooktitle() allow author: string? = getbookauthor() book = new book(title: book, author: author)

i'm not confident approach, right way it? because have utilize (if let) every time want author of book

you have:

let title: string? = getbooktitle() allow author: string? = getbookauthor()

there's presumably no point in making title optional, tell present, depends upon how getbooktitle defined. furthermore, if these methods defined homecoming string or string?, appropriate, type here inferred, yielding:

let title = getbooktitle() allow author = getbookauthor()

next, have:

book = new book(title: book, author: author)

but, instantiation of new book object needs variable name (and new keyword not needed), yielding:

let book = book(title: book, author: author)

(use let if you're going set local book variable 1 time within scope. if you're going reset 1 time again , 1 time again without leaving function, utilize var. bottom line, utilize let whenever can.)

finally, say:

is right way it? because have utilize (if let) every time want author of book.

yes, appropriate utilize optional author. and, yes, means have disclose optional if let or equivalent syntax when want utilize it. note, don't have optional binding syntax, if let, if don't want, rather utilize if , perform forced unwrapping (e.g. !), if want. need disclose 1 way or other.

you technically utilize implicitly unwrapped optional (!), , automatically unwrapped every time utilize it. think standard optional syntax makes meaning more clear (specifically, author may nil).

swift

php - file_put_contents failed to open stream: Permission denied -



php - file_put_contents failed to open stream: Permission denied -

i error while trying file_put_contents().

apache working apache group, started sudo rights. user in apache group. dirs , files have 755 chmod.

file exists.

locally works fine, on remote centos server not. why? how debug thing?

this can solved changing directory permission.

run command like

chmod 777 database (the directory)

you can utilize getcwd()" find directory path.

please have here

php linux file-permissions permission-denied

c# - Remove non-word characters and leading numbers from string -



c# - Remove non-word characters and leading numbers from string -

i have text field feeds label through code. user types text field, automatically parse text, , strip out non-word characters text , place label.

private void text_keyup(object sender, keyeventargs e) { label.content = regex.replace(text.text, @"[^\w]", "").tolower(); }

however, have constraint label field, , can't figure out how it. current regex have makes label can have lowercase word characters. however, need create sure first character in label not number. have tried ^[^a-za-z][^\w], isn't working. got ideas?

the original problem says "replace {an english language letter} with.." , not "replace {a number} with.."; after update still problematic because considers 2 operations compound - replace non-a-z only if not followed word character.

compare rewriting so:

var filtered = text.text; filtered = regex.replace(filtered, @"\w+", ""); // trim non-word characters filtered = regex.replace(filtered, @"^\d+", ""); // remove number(s) @ start label.content = filtered.tolower();

do note that, default, in c#/.net escapes \w , \d (and opposites) unicode-aware. makes them different javascript / pcre / java / perl, etc., more english-centric.

c# regex

http - Download Stream with RestSharp and ResponseWriter -



http - Download Stream with RestSharp and ResponseWriter -

i donwnload stream restsharp using responsewriter.

var client = new restclient var request = new restrequest(); // ... request.responsewriter = (ms) => { // how observe status code }; var response = client.execute(request);

how can found out http status code in responsewriter? there improve way download stream?

you can check response.statuscode , response.statusdescription after executing request.

interestingly, if utilize downloaddata method described here https://github.com/restsharp/restsharp/wiki/other-usage-examples there no way access info far can tell.

http stream http-status-codes restsharp

python - IOError: Can't read data (Can't open directory) - Missing gzip compression filter -



python - IOError: Can't read data (Can't open directory) - Missing gzip compression filter -

i have never worked hdf5 files before, , started received illustration files. i've been checking out basics h5py, looking @ different groups in these files, names, keys, values , on. works fine, until want @ datasets saved in groups. .shape , .dtype, when seek accessing random value indexing (e.g. grp["dset"][0]), next error:

ioerror traceback (most recent phone call last) <ipython-input-45-509cebb66565> in <module>() 1 print geno["matrix"].shape 2 print geno["matrix"].dtype ----> 3 geno["matrix"][0] /home/sarah/anaconda/lib/python2.7/site-packages/h5py/_hl/dataset.pyc in __getitem__(self, args) 443 mspace = h5s.create_simple(mshape) 444 fspace = selection._id --> 445 self.id.read(mspace, fspace, arr, mtype) 446 447 # patch output numpy /home/sarah/anaconda/lib/python2.7/site-packages/h5py/h5d.so in h5py.h5d.datasetid.read (h5py/h5d.c:2782)() /home/sarah/anaconda/lib/python2.7/site-packages/h5py/_proxy.so in h5py._proxy.dset_rw (h5py/_proxy.c:1709)() /home/sarah/anaconda/lib/python2.7/site-packages/h5py/_proxy.so in h5py._proxy.h5py_h5dread (h5py/_proxy.c:1379)() ioerror: can't read info (can't open directory)

i've posted problem in h5py google group, suggested there might filter on dataset don't have installed. hdf5 file created using gzip compression, should portable standard, far understood. know might missing here? can't find description of error or similar problems anywhere, , file, including problematic dataset, can opened hdfview software.

edit apparently, error occurs because, reason, gzip compression filter not available on system. if seek create illustration file gzip compression, happens:

--------------------------------------------------------------------------- valueerror traceback (most recent phone call last) <ipython-input-33-dd7b9e3b6314> in <module>() 1 grp = f.create_group("subgroup") ----> 2 grp_dset = grp.create_dataset("dataset", (50,), dtype="uint8", chunks=true, compression="gzip") /home/sarah/anaconda/lib/python2.7/site-packages/h5py/_hl/group.pyc in create_dataset(self, name, shape, dtype, data, **kwds) 92 """ 93 ---> 94 dsid = dataset.make_new_dset(self, shape, dtype, data, **kwds) 95 dset = dataset.dataset(dsid) 96 if name not none: /home/sarah/anaconda/lib/python2.7/site-packages/h5py/_hl/dataset.pyc in make_new_dset(parent, shape, dtype, data, chunks, compression, shuffle, fletcher32, maxshape, compression_opts, fillvalue, scaleoffset, track_times) 97 98 dcpl = filters.generate_dcpl(shape, dtype, chunks, compression, compression_opts, ---> 99 shuffle, fletcher32, maxshape, scaleoffset) 100 101 if fillvalue not none: /home/sarah/anaconda/lib/python2.7/site-packages/h5py/_hl/filters.pyc in generate_dcpl(shape, dtype, chunks, compression, compression_opts, shuffle, fletcher32, maxshape, scaleoffset) 101 102 if compression not in encode: --> 103 raise valueerror('compression filter "%s" unavailable' % compression) 104 105 if compression == 'gzip': valueerror: compression filter "gzip" unavailable

does have experience that? installation of hdf5 library h5py bundle didn't seem go wrong...

can't comment - reputation low.

i had same issue, ran "conda update anaconda" , problem gone.

python linux hdf5 anaconda h5py

android - How to customize dialog background? -



android - How to customize dialog background? -

i want implement regular functional dialog, text , drawable on top of grayness overlay.

i did research, wondering if knows improve way of doing it. here few thoughts:

1) dirtiest way ditch dialog , create view false dialog. easy, to the lowest degree preferable because dialogs different on different android versions. nice reuse of dialog stuff has been implemented.

2) improve way reuse parts of dialog xml file, it's still "reinventing wheel" bit much.

3) great if inflate layout background , dialog.setbackground couldn't find that.

4) tried inflating layout , setting using .setview() on alertdialog.builder seems alters dialog itself, not background.

android dialog alertdialog

php - Error "Array to string conversion" - Query to Database with Image Upload -



php - Error "Array to string conversion" - Query to Database with Image Upload -

the script:

<?php include("connect.php") ?> <?php if (isset($_post['submit'])) { $j = 0; //variable indexing uploaded image $target_path = "uploads/"; //declaring path uploaded images ($i = 0; $i < count($_files['file']['name']); $i++) {//loop individual element array $validextensions = array("jpeg", "jpg", "png"); //extensions allowed $ext = explode('.', basename($_files['file']['name'][$i]));//explode file name dot(.) $file_extension = end($ext); //store extensions in variable $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set target path new name of image $j = $j + 1;//increment number of uploaded images according files in array if (($_files["file"]["size"][$i] < 100000) //approx. 100kb files can uploaded. && in_array($file_extension, $validextensions)) { if (move_uploaded_file($_files['file']['tmp_name'][$i], $target_path)) {//if file moved uploads folder echo $j. ').<span id="noerror">image uploaded successfully!.</span><br/><br/>'; } else {//if file not moved. echo $j. ').<span id="error">please seek again!.</span><br/><br/>'; } } else {//if file size , file type incorrect. echo $j. ').<span id="error">***invalid file size or type***</span><br/><br/>'; } } ($i = 0; $i < count($_files['file']['name']); $i++) { $tqs = "insert images (`image_file`) values ('" . $_files['file']['name'] . "')"; $tqr = mysqli_query($dbc, $tqs); } } ?>

the error message:

notice: array string conversion in c:\xampp\htdocs\gallerysite\multiple_image_upload\upload.php on line 37

it part here:

for ($i = 0; $i < count($_files['file']['name']); $i++) { $tqs = "insert images (`image_file`) values ('" . $_files['file']['name'] . "')"; $tqr = mysqli_query($dbc, $tqs); }

this script uses javascript multiple image upload.

i looking insert file name mysql database, yet getting error message above.

i have been looking @ tutorials, tutorials utilize "$_files['file']['name']" in query string insert file name database.

any suggestions?

php mysql

c - Store zeros from ints and use them later -



c - Store zeros from ints and use them later -

i have 3 sensors each provide either 0 or 1 (repeatedly in loop). stored individually int variables. these printed using following:

print ("%d%d%d", sensor1, sensor2, sensor3);

i want store each combination (ex: 010, 001, 110, etc.) temporarily can utilize else (i want have switch or can different operation depending on value of sensor combination). can't store int since drops 0s in front.

how can store these combinations?

you can utilize construction bit field this.

struct bit{ bool sensor1 : 1; bool sensor2 : 1; bool sensor3 : 1; }; int main(void) { struct bit bit = {0, 1, 0}; printf ("%d%d%d", bit.sensor1, bit.sensor2, bit.sensor3); }

c

javascript - How to provide audio preview in Safari without loading file into memory -



javascript - How to provide audio preview in Safari without loading file into memory -

i have web page allows users select multiple .wav files using file select button of form. each .wav displayed using next markup:

<audio src="blob:f3xyz808-1a65-440e-8e5f-b5djfht4ad1a" controls=""></audio>

this works fine in chrome , firefox. in safari, however, if seek load many .wavs @ 1 time stops loading. using javascript console can see memory safari using grows each .wav , can reach upwards of 2gb. chrome, memory usage not increment significantly. seems chrome , ff stream files disk. possible safari?

edit: looks possible solution first problem include: preload="none" in sound tag

on separate related note: seems browsers decode sound files, @ to the lowest degree extent, when added sound tag, because if file invalid complain. possible access decoded info without creating sound buffer in memory. specifically, want create graph of files' volume level vs. time. currently, decoding arraybuffer using web sound api. uses lot of memory. possible volume level info .wav's raw binary data?

i realize question has shortcomings. little vague on of concepts.

any tips or suggestions great help. give thanks you.

javascript audio safari html5-audio web-audio

javascript - How to display selected value of a dropdown alone in uppercase? -



javascript - How to display selected value of a dropdown alone in uppercase? -

i want display other options of dropdown in little case, except selected one. selected 1 should displayed in uppercase.

select{ text-transform: uppercase; } option{ text-transform: lowercase !important; }

i think, cannot style alternative elements. there other alternatives other custom drop-down?

it's working fine in ipad since ipad's default behaviour same expectation. it's not fine in android.

you can see dropdown in fiddle.

you can utilize jquery text() function :

class="snippet-code-js lang-js prettyprint-override">$("select").change(function () { $(this).find("option").text(function (i, text) { homecoming $(this).is(":selected") ? text.touppercase() : text.tolowercase() }); }).trigger("change"); class="snippet-code-html lang-html prettyprint-override"><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select> <option>one</option> <option>two</option> </select>

javascript jquery css css3

using jquery and ajax how to insert text box value in database in cake php? -



using jquery and ajax how to insert text box value in database in cake php? -

how can insert text box value in database using jquery , ajax in cake php ? have tried lot not success.

you can handle this:

ajaxurl controller/action

$.ajax({ type : "post", url : ajaxurl data: {"input1" : $("input[name='text-box']").val()} }).done(function(data){ console.log(data); });

then in controller

public function action(){ $this->autorender = false; $this->request->onlyallow('ajax'); $input = $_post["input1"]; //do database input here homecoming suceess/failure;

}

jquery ajax cakephp

Boost 1.55 Python with Windows Visual Studio 2013, Link Error -



Boost 1.55 Python with Windows Visual Studio 2013, Link Error -

i download boost1.55 zip official website , build command bootstrap , b2. , tried illustration code, has link error.

1>link : fatal error lnk1104: cannot open file 'libboost_python-vc120-mt-gd-1_55.lib'

below did.

new project win32 console application, dll empty.

add include path, library path in vc++ directories below.

include directories: c:\boost\boost_1_55_0;c:\python27\include library directories: c:\boost\boost_1_55_0\libs;c:\python27\libs

.

#define boost_python_static_lib #include <boost/python.hpp> using namespace boost::python; struct world { void set(std::string msg) { this->msg = msg; } std::string greet() { homecoming msg; } std::string msg; }; boost_python_module(hello) { class_<world>("world") .def("greet", &world::greet) .def("set", &world::set); }

edit

if add together library directory, c:\boost_1_55_0\stage\liblike reply below, create many errors happen, around 200 below part of errors.

1>------ build started: project: hello, configuration: debug win32 ------ 1> hello.cpp 1>c:\python27\include\pymath.h(22): warning c4273: 'round' : inconsistent dll linkage 1> c:\program files (x86)\microsoft visual studio 12.0\vc\include\math.h(516) : see previous definition of 'round' 1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\xtgmath.h(190): warning c4273: '_hypot' : inconsistent dll linkage 1> c:\program files (x86)\microsoft visual studio 12.0\vc\include\math.h(538) : see previous definition of '_hypot' 1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\xtgmath.h(206): warning c4273: 'round' : inconsistent dll linkage 1> c:\program files (x86)\microsoft visual studio 12.0\vc\include\math.h(516) : see previous definition of 'round' 1>c:\boost_1_55_0\boost\python\opaque_pointer_converter.hpp : warning c4819: file contains character cannot represented in current code page (949). save file in unicode format prevent info loss 1>c:\boost_1_55_0\boost\python\return_opaque_pointer.hpp : warning c4819: file contains character cannot represented in current code page (949). save file in unicode format prevent info loss 1> creating library c:\users\user\documents\visual studio 2013\projects\hello\debug\hello.lib , object c:\users\user\documents\visual studio 2013\projects\hello\debug\hello.exp 1>hello.obj : error lnk2019: unresolved external symbol __imp__pystring_fromstringandsize referenced in function "public: struct _object * __thiscall boost::python::to_python_value,class std::allocator > const &>::operator()(class std::basic_string,class std::allocator > const &)const " (??r?$to_python_value@abv?$basic_string@du?$char_traits@d@std@@v?$allocator@d@2@@std@@@python@boost@@qbepau_object@@abv?$basic_string@du?$char_traits@d@std@@v?$allocator@d@2@@std@@@z) 1>libboost_python-vc120-mt-gd-1_55.lib(builtin_converters.obj) : error lnk2001: unresolved external symbol __imp__pystring_fromstringandsize 1>libboost_python-vc120-mt-gd-1_55.lib(str.obj) : error lnk2001: unresolved external symbol __imp__pystring_fromstringandsize 1>libboost_python-vc120-mt-gd-1_55.lib(function_doc_signature.obj) : error lnk2001: unresolved external symbol __imp__pystring_fromstringandsize 1>libboost_python-vc120-mt-gd-1_55.lib(list.obj) : error lnk2001: unresolved external symbol __imp___py_nonestruct 1>libboost_python-vc120-mt-gd-1_55.lib(tuple.obj) : error lnk2001: unresolved external symbol __imp___py_nonestruct 1>libboost_python-vc120-mt-gd-1_55.lib(function_doc_signature.obj) : error lnk2001: unresolved external symbol __imp___py_nonestruct 1>libboost_python-vc120-mt-gd-1_55.lib(object_protocol.obj) : error lnk2001: unresolved external symbol __imp___py_nonestruct 1>libboost_python-vc120-mt-gd-1_55.lib(pickle_support.obj) : error lnk2001: unresolved external symbol __imp___py_nonestruct 1>libboost_python-vc120-mt-gd-1_55.lib(dict.obj) : error lnk2001: unresolved external symbol __imp___py_nonestruct 1>libboost_python-vc120-mt-gd-1_55.lib(str.obj) : error lnk2001: unresolved external symbol __imp___py_nonestruct 1>libboost_python-vc120-mt-gd-1_55.lib(from_python.obj) : error lnk2001: unresolved external symbol __imp___py_nonestruct 1>libboost_python-vc120-mt-gd-1_55.lib(function.obj) : error lnk2001: unresolved external symbol __imp___py_nonestruct 1>libboost_python-vc120-mt-gd-1_55.lib(module.obj) : error lnk2001:

the "library directory" should reference c:\boost_1_55_0\stage\lib instead of c:\boost\boost_1_55_0\libs.

python-2.7 windows-8 visual-studio-2013 boost-python

css - align center two elements different width -



css - align center two elements different width -

how create 2 elements aligned @ same distance line in center should in center of wrapper. wrapper width not fixed , may change. http://jsfiddle.net/x2b2ax37/2/

<div id="block"> <div id="wrapper"> <span id="div1">2222</span> <span id="div2">2 %</span> </div> <div id="wrapper"> <span id="div1">11</span> <span id="div2">100 %</span> </div> <div id="wrapper"> <span id="div1">21</span> <span id="div2">0 %</span> </div> </div>

1 - initial 2 - expect

you accomplish this:

(updated .classes instead of #ids)

jsfiddle - demo

class="snippet-code-css lang-css prettyprint-override">.wrapper { position: relative; } .div1 { border: 1px solid #f00; right: 50%; position: absolute; } .div2 { border: 1px solid #000; position: relative; left: 50%; display: inline-block; } .block { border: 1px solid green; width: 200px; } class="snippet-code-html lang-html prettyprint-override"><div class="block"> <div class="wrapper"> <span class="div1">2222</span> <span class="div2">2 %</span> </div> <div class="wrapper"> <span class="div1">11</span> <span class="div2">100 %</span> </div> <div class="wrapper"> <span class="div1">21</span> <span class="div2">0 %</span> </div> </div>

css css3

wpf - FlowDocument: Insert Hyperlink and keep formatting -



wpf - FlowDocument: Insert Hyperlink and keep formatting -

how insert hyperlink flowdocument @ specific position? new hyperlink should have same formatting surrounding text - except color (should blue) , underline (should underlined). after inserting hyperlink, cursor should right after new hyperlink.

things i've tried:

textpointer caretposition = richtextbox.caretposition; textpointer insertposition = caretposition.isatinsertionposition ? caretposition : caretposition.getinsertionposition(logicaldirection.forward); string linktitle = "stack overflow"; run run = new run(linktitle); hyperlink link = new hyperlink(run, insertposition); link.isenabled = true; link.navigateuri = new uri(@"http://www.stackoverflow.com"); richtextbox.caretposition = run.contentend;

this works, new hyperlink not have formatting of it's surrounding text.

this.caretposition = this.caretposition.getpositionatoffset(0, logicaldirection.forward); insertposition.inserttextinrun(linktitle); hyperlink link = new hyperlink(insertposition, insertposition.getpositionatoffset(linktitle.length)); link.isenabled = true; link.navigateuri = new uri(@"http://www.stackoverflow.com"); textpointer positionafterlink = link.contentend.getpositionatoffset(1); if (!positionafterlink.isatinsertionposition) positionafterlink = caretposition.getinsertionposition(logicaldirection.forward); richtextbox.caretposition = positionafterlink;

this way, formatting kept. sometimes, caretposition not set behind end of new link, stays in front end of new link. also, doesn't robust me.

has done that? right way this?

i edit first code.the richtextbox.selection textrange having method called getpropertyvalue allowing format properties such fontstyle, fontweight, fontsize (and think that's enough). can set achieved format info newly created hyperlink:

textpointer caretposition = richtextbox.caretposition; textpointer insertposition = caretposition.isatinsertionposition ? caretposition : caretposition.getinsertionposition(logicaldirection.forward); string linktitle = "stack overflow"; //try getting format info var fstyle = (fontstyle) richtextbox.selection .getpropertyvalue(control.fontstyleproperty); var fweight =(fontweight)richtextbox.selection .getpropertyvalue(control.fontweightproperty); var fsize = (double)richtextbox.selection .getpropertyvalue(control.fontsizeproperty); //create new link run run = new run(linktitle); hyperlink link = new hyperlink(run, insertposition); link.fontstyle = fstyle; link.fontweight = fweight; link.fontsize = fsize; //remaining code ...

to create link have default style (blue color , underlined), have set richtextbox's property isdocumentenabled true. after inserting, may want phone call focus() on richtextbox.

wpf hyperlink insert formatting flowdocument

asp.net - FileUload is static object or no? -



asp.net - FileUload is static object or no? -

i upload image fileupload , save them db. code:

uploadhelper.savefile(fileupload1, drop_doc.selectedvalue.tostring(), session("traceno"), _userslog)

fileupload1 in toolbox asp.net. want know file upload users upload images concurrent static object or no? concurrency occurred or no?

asp.net file-upload webforms

php - How I can allow only one IP by .htaccess in nginx admin? -



php - How I can allow only one IP by .htaccess in nginx admin? -

this question has reply here:

how can allow access single ip address via nginx.conf? 1 reply

please, how can allow 1 ip .htaccess in nginx admin ?

like in apache.

order deny,allow deny allow 111.222.333.444

but work in apache only

i want command's works in nginx admin ..

so can owner of ip, browse folder , files

note: utilize nginx admin on servers http://www.nginxcp.com/installation-instruction/

help me please

thanks.

edit nginx.conf:

server { ... allow 111.222.333.444; deny all; ... }

ps: nginx not back upwards .htaccess

if want limit specified directories:

server { ... location /users/111 { allow 111.222.333.444; deny all; } location /users/123 { allow 222.333.444.111; deny all; } ... }

php apache .htaccess nginx

vb.net - Windows Service and WPF Application Side by Side -



vb.net - Windows Service and WPF Application Side by Side -

i developing application using wpf (vb.net) ,the application listens event (this working fine) ,the event returns variable passed web service when web service response arrives , dialog window appears showing values response these questions : how run listening part of code windows service ? cant service part initiate gui display response web service ?

the service communicate application run user. services can't show ui components. way did this: 1. have service application running listens event. 2. service application implements interface defines methods , properties i'm going utilize communicate ui application.

public interface imyservice { string mystring { get; } string mymethod(); }

the service implements interface , marshalbyrefobject:

public class myservice : marshalbyrefobject, imyservice {/*...*/}

when service starts, register channel communication calling these 2 methods in constructor of service:

private static void registerchannel() { seek { tcpserverchannel channel = new tcpserverchannel(mynamespace.api.myservicechannels.myservicechannel); channelservices.registerchannel(channel, false); } grab { } //to suppress exception when channel registered } private static void registerremotableclass() { seek { remotingconfiguration.registerwellknownservicetype(typeof(myservice), "myservice", wellknownobjectmode.singleton); } grab { } }

in gui application, seek connect service:

public void getservice() { seek { string tcpaddress = myservicechannels.myapptcpaddress; channelservices.registerchannel(new tcpclientchannel(), false); _serviceapp = (imyservice)activator.getobject(typeof(imyservice), tcpaddress); } grab (exception ex) { //... } }

if went well, can access properties, methods , events of service application.

wpf vb.net windows

if statement - Lua: Coloring "Win" status fails -



if statement - Lua: Coloring "Win" status fails -

i've had function 2 years now, , can't seem figure out why it's not working colorizing. here's entire function, you'll see core parts aren't working below.

function showscoreboard() local function len(arg) homecoming string.len(arg) end local function tbuff(arg) if len(arg) < 3 homecoming arg.." " else homecoming arg end end local function sbuff(arg) if len(arg) < 2 homecoming " "..arg else homecoming arg end end local function cteam(t,s) local status = s or nil local forecolor = "" if status == "p" forecolor = "yellow" elseif status == "w" forecolor = "cyan" else forecolor = "limegreen" end homecoming "<color fore="..forecolor..">"..t.."</color>" end local function bcolor(i) local = or 0 if i%2 == 1 homecoming "maroon" else homecoming "navy" end end local scorestring = "" local allteams = {["atl"]=0,["was"]=0,["mia"]=0,["cle"]=0,["oak"]=0,["sd"]=0,["ind"]=0,["nyj"]=0,["ten"]=0,["sea"]=0,["phi"]=0,["den"]=0,["gb"]=0,["buf"]=0,["tb"]=0,["pit"]=0,["min"]=0,["hou"]=0,["det"]=0,["tb"]=0,["car"]=0,["chi"]=0,["stl"]=0,["nyg"]=0,["ari"]=0,["no"]=0,["kc"]=0,["sf"]=0,["ne"]=0} local byeweek = "" _,v in ipairs(nflscores.ss) allteams[v[5]] = 1 allteams[v[7]] = 1 end i,v in pairs(allteams) if v == 0 byeweek = byeweek .. "<color white>".. .."</color>\r" end end i,v in ipairs(nflscores.ss) local hteam = v[7] local ateam = v[5] local qgame = v[3] local hscre = v[8] or 0 local ascre = v[6] or 0 if v[4] qtime = "<color white>time: "..v[4].."</color>" else qtime = "" end local gposs = v[9] or "" if gposs ~= "" if gposs == hteam hteam = cteam(tbuff(hteam),"p") ateam = cteam(tbuff(ateam)) else ateam = cteam(tbuff(ateam),"p") hteam = cteam(tbuff(hteam)) end else hteam = cteam(tbuff(hteam)) ateam = cteam(tbuff(ateam)) end if qgame == "final" or qgame == "final overtime" if hscre > ascre hteam = cteam(tbuff(hteam),"w") ateam = cteam(tbuff(ateam)) elseif hscre < ascre ateam = cteam(tbuff(ateam),"w") hteam = cteam(tbuff(hteam)) else ateam = cteam(tbuff(ateam)) hteam = cteam(tbuff(hteam)) end if qgame == "final" qgame = "<color cyan>f</color>" elseif qgame == "final overtime" qgame = "<color cyan>f/ot</color>" end elseif qgame == "pregame" qgame = "<color cyan>pre</color>" elseif qgame == "halftime" qgame = "<color white>"..qgame.."</color>" else qgame = "<color white>q"..qgame.."</color>" end scorestring = scorestring .. "<color back="..bcolor(i) .. ">".. v[1] .. ": " .. ateam .. "<color white>: " .. sbuff(ascre) .. "</color> <color black>@</color> " .. hteam .. "<color white>: ".. sbuff(hscre) .."</color></color> " .. qgame .. " " .. qtime .. "\r" end homecoming scorestring .. "<color white>bye week:</color>\r"..byeweek end

the part isn't working is:

if hscre > ascre hteam = cteam(tbuff(hteam),"w") ateam = cteam(tbuff(ateam)) elseif hscre < ascre ateam = cteam(tbuff(ateam),"w") hteam = cteam(tbuff(hteam)) else ateam = cteam(tbuff(ateam)) hteam = cteam(tbuff(hteam)) end

the function cteam is:

local function cteam(t,s) local status = s or nil local forecolor = "" if status == "p" forecolor = "yellow" elseif status == "w" forecolor = "cyan" else forecolor = "limegreen" end homecoming "<color fore="..forecolor..">"..t.."</color>" end

now, colors "p" status fine. when status changes "w", fails, , life of me, cannot figure out why. missing something? code lot cleaner?

edit: haven't found issue problem, apparently "elseif status == "w" statement bypassed. when games beingness played, right team in possession shows yellow. however, after game over, both teams lime green, if no score higher other.

2nd edit: error listed in first reply has been corrected. still, doesn't solve issue. i'm still quite @ loss.

nothing jumps out , can't test here here things check:

you mention cteam works correctly during game, , it's 1 time game on cteam doesn't give right final result. logic of cteam correct. problem must in code calls cteam: cteam ever called s equals "w": never happen if hscre , ascre same. there typo in branch code calls cteam:

if hscre > ascre hteam = cteam(tbuff(hteam),"w") ateam = cteam(tbuff(ateam)) elseif hscre < ascre ateam = cteam(tbuff(ateam,"w")) -- err hteam = cteam(tbuff(hteam)) else ateam = cteam(tbuff(ateam)) hteam = cteam(tbuff(hteam)) end

the line tagged err should be:

ateam = cteam(tbuff(ateam),"w")

about cleaning code: post question on stackoverflow's code review forum.

if-statement lua

android - How to refer to data in a previous viewpager -



android - How to refer to data in a previous viewpager -

i have android project using fragments , viewpager. using separate countdown timer every page, runs when view of page 'onscreen'. @ first time every page same, after while page 1 might 20 seconds left, page 2 60 seconds , on.

my problem don't know how save remaining time, moment user swipes next page. using onpagestatelistener has next code, saving new value of questionid , old value of new time. how refer value of questionid , matching newtime-value of page in view before user swiped?

viewpager.setonpagechangelistener(new viewpager.onpagechangelistener() { public void onpagescrollstatechanged(int state) { if (state == viewpager.scroll_state_dragging) { savetime(); } } public void onpagescrolled(int position, float arg1, int arg2) {} public void onpageselected(int pos) { questionid = mquestions.get(pos).getnr() runtime(); } }); public void savetime(){ mquestions.get(questionid).settime(newtime); } public void runtime(){ if (mtimer != null) { mtimer.cancel(); mtimer = null; } mtimer = new countdowntimer(90000, 1000) {//millisinfuture, countdowninterval public void ontick(long millisuntilfinished) { newtime = (millisuntilfinished/1000); } public void onfinish() { } }.start(); }

first of can utilize sharedpreferences.

besides, of course of study can save info in adapter utilize viewpager, can save info in db or create singleinstance in parent activity or fragment.

android android-fragments android-viewpager

python - Execute a function randomly -



python - Execute a function randomly -

consider next functions:

def a(): print "a" def b(): print "b"

is there way pick function run randomly? tried using:

random.choice([a(),b()])

but returns both functions, want homecoming 1 function.

only phone call selected function, not both of them:

random.choice([a,b])()

below demonstration:

>>> import random >>> def a(): ... print "a" ... >>> def b(): ... print "b" ... >>> random.choice([a,b])() >>> random.choice([a,b])() b >>>

your old code called both functions when list [a(),b()] created, causing python print both a , b. afterwards, told random.choice take list [none, none]1, nothing. can see demonstration below:

>>> [a(),b()] b [none, none] >>>

the new code uses random.choice randomly select function object list [a,b]:

>>> random.choice([a,b]) <function b @ 0x01afd970> >>> random.choice([a,b]) <function @ 0x01afd930> >>>

it calls function.

1functions homecoming none default. since a , b lack return-statements, each homecoming none.

python function random

c# 4.0 - Adding third party application dependency in visual studio 2012 -



c# 4.0 - Adding third party application dependency in visual studio 2012 -

in application requirement of .net framework 4.5 run on other machine. how possible when application beingness install .net framework installed automatically?

you can set in dependency adding reference of .net 4.0 framework.

c#-4.0