Wednesday, 15 June 2011

webdriver - When running the web driver script using Java from jar file, i am getting error - java.lang.IllegalArgumentException -



webdriver - When running the web driver script using Java from jar file, i am getting error - java.lang.IllegalArgumentException -

when running web driver script using java jar file, getting error:

java.lang.illegalargumentexception:cannot find elements when xpath look null.

i error while running test executable jar file in command prompt. not error while running eclipse.

the code using:

webelement element = driver.findelement(by.xpath(or.getproperty("fp_simg_id"))); string src = ((javascriptexecutor)driver).executescript("return arguments[0].attributes['src'].value;", element).tostring(); string[] s=src.split("="); system.out.println("value retrieved image source: "+s[1]);

and error received:

c:\project_700creditsolution\700credit>java -jar loginfpwd.jar log4j:warn no appenders found logger (org.apache.http.impl.conn.tsc cm.threadsafeclientconnmanager). log4j:warn please initialize log4j scheme properly. exception in thread "main" java.lang.reflect.invocationtargetexception @ sun.reflect.nativemethodaccessorimpl.invoke0(native method) @ sun.reflect.nativemethodaccessorimpl.invoke(unknown source) @ sun.reflect.delegatingmethodaccessorimpl.invoke(unknown source) @ java.lang.reflect.method.invoke(unknown source) @ org.eclipse.jdt.internal.jarinjarloader.jarrsrcloader.main(jarrsrcloa der.java:58) caused by: java.lang.illegalargumentexception: cannot find elements when xpa th look null. @ org.openqa.selenium.by.xpath(by.java:112) @ com.ode.login.login_fpwd.main(login_fpwd.java:99) ... 5 more c:\project_700creditsolution\700credit>

any help appreciated.

java webdriver selenium-webdriver

QTP clicking on webbutton closed the dialog -



QTP clicking on webbutton closed the dialog -

i'm on page has pop-up. there list in pop-up. should firstly select element in list, link gets activated , click on link. pop-up appears. now, have click on button in new pop-up. button captured qtp store under page object.

the statement simple:

browser(browser).page(page).webbutton("button").click

but problem is, after clicking on webbutton, new pop-up disappears, , value selected in list of main pop-up reset default (none selected). , in debug mode, there no problem...

i tried solutions, "replaytype" still makes pop-up closed, "devicereplay", "abs_x" , "abs_y" returned getroproperty not same values captured using object spy. cannot click on right position.

could enlighten me here how can resolve this?

thanks lot

allen

you have write descriptive programme click on button on particular pop-up. spy button , write script in qtp, dont store object in object repository.

for button, utilize html tag or name identify object

qtp

java - Schema in sql with spring jdbc -



java - Schema in sql with spring jdbc -

is necessary set schema in sql queries? simplejdbctemplate seems work on local schema fails in other machine. reason? database oracle , running on jboss as.

the sql syntax dependent on type of database. oracle not need specify schema if referenced object (e.g. table, view) in current schema or local or public synonym exists it. if not have reference object [schema].[object].

java spring jdbc

perl - assning the first column of the file to hash key and the rest to hash value -



perl - assning the first column of the file to hash key and the rest to hash value -

i have file follows:

23 line number 23 2 line number 2 87 line number 87 28 line number 28 4 line number 4 83 line number 83

i need take first column hash keys , sec hash value. should sort file using hash keys

this easy: split line @ whitespace 2 pieces. first part $key, rest $value.

we sort keys of %hash alphabetically, , print out data.

#!/usr/bin/perl utilize strict; utilize warnings; %hash; while (<>) { chomp; # remove newline ($key, $value) = split ' ', $_, 2; $hash{$key} = $value; } # or shorter: # %hash = map {chomp; split ' ', $_, 2} <>; @sorted_keys = sort keys %hash; $key (@sorted_keys) { print "$key $hash{$key}\n"; } # or shorter: # print "$_ $hash{$_}\n" sort keys %hash;

the input can provided via stdin or file named in command line argument.

output input provided:

2 line number 2 23 line number 23 28 line number 28 4 line number 4 83 line number 83 87 line number 87

if want numerical sorting, alter sort keys sort {$a <=> $b} keys.

perl

c - undefined reference to `readline' -



c - undefined reference to `readline' -

this question has reply here:

'undefined reference' errors when compiling against library 1 reply

i'm having problem trying run gnu readline library sample code available in wikipedia. here goes:

#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <readline/readline.h> #include <readline/history.h> int main() { char* input, shell_prompt[100]; // configure readline auto-complete paths when tab key hit. rl_bind_key('\t', rl_complete); for(;;) { // create prompt string user name , current working directory. snprintf(shell_prompt, sizeof(shell_prompt), "%s:%s $ ", getenv("user"), getcwd(null, 1024)); // display prompt , read input (n.b. input must freed after use)... input = readline(shell_prompt); // check eof. if (!input) break; // add together input history. add_history(input); // stuff... // free input. free(input); } }

i'm working on restricted environment readline not available, had download sources, compile , install home dir.

this construction within home directory:

.local ├── include │   └── readline │      ├── chardefs.h │      ├── history.h │      ├── keymaps.h │      ├── readline.h │      ├── rlconf.h │      ├── rlstdc.h │      ├── rltypedefs.h │      └── tilde.h └── lib    ├── libhistory.a    ├── libhistory.so -> libhistory.so.6    ├── libhistory.so.6 -> libhistory.so.6.2    ├── libhistory.so.6.2   ├── libreadline.a    ├── libreadline.so -> libreadline.so.6    ├── libreadline.so.6 -> libreadline.so.6.2    └── libreadline.so.6.2

the problem is, when phone call gcc throws me error:

$ gcc hello.c -o hello_c.o -i /home/my-home-dir/.local/include /tmp/cckc236e.o: in function `main': hello.c:(.text+0xa): undefined reference `rl_complete' hello.c:(.text+0x14): undefined reference `rl_bind_key' hello.c:(.text+0x60): undefined reference `readline' hello.c:(.text+0x77): undefined reference `add_history' collect2: error: ld returned 1 exit status

there reply here, i'm not using netbeans , i'm not quite sure how specify path library on command line.

i tried tell linker libraries are, result still same:

$ gcc hello.c -o hello_c.o -i /home/my-home-dir/.local/include -xlinker "-l /home/my-home-dir/.local/lib" /tmp/cceiepmr.o: in function `main': hello.c:(.text+0xa): undefined reference `rl_complete' hello.c:(.text+0x14): undefined reference `rl_bind_key' hello.c:(.text+0x60): undefined reference `readline' hello.c:(.text+0x77): undefined reference `add_history' collect2: error: ld returned 1 exit status

any ideas might missing here?

you need link againts actual library using -lreadline in gcc arguments

c readline libreadline

c# - Entity Framework database-first doesn't create the correct model -



c# - Entity Framework database-first doesn't create the correct model -

i'm trying utilize database-first approach ef 5.0 , doesn't create right model me.

here info structure:

forums

users

posts

relationships

the problem

the main problem one-to-one relationships in forums , posts table. model doesn't recognize parentforumid , replyto nullables , hence creates one-to-many relationship between tables (forum-forum , post-post).

also, when trying manually alter one-to-one relationship, error:

error 113: multiplicity not valid in role 'forum1' in relationship 'fk_forums_forums'. because dependent role properties not key properties, upper bound of multiplicity of dependent role must *. ...\models\entities\model1.edmx

the model in visual studio (before editing)

i tried using code-first approach produced poor database result, realized can configure behaviour of database creation couldn't find resource explains how configure correctly.

i'd rather utilize database-first approach since lets me customize database still generates wrong model many errors.

so question is:

what best approach so?

where can larn code first, database first thoroughly?

why visual studio produce such model?

why when seek alter model fit needs gives me error described before?

where can larn migration tools? functions can utilize configure database creation?

question 1: depends.

if have code written, or prefer write objects first, go route.

if on other-hand, prefer doing db schema first, all-means, that.

it matters not, take what's comfortable you.

c# entity-framework code-first database-first

java - Hungarian Algorithm: How to cover 0 elements with minimum lines? -



java - Hungarian Algorithm: How to cover 0 elements with minimum lines? -

i trying implement hungarian algorithm in java. have nxn cost matrix. next this guide step step. have costmatrix[n][n] , 2 arrays track covered rows , covered cols - rowcover[n], rowcolumn[n] (1 means covered, 0 means uncovered)

how can cover 0s minimum number of lines? can point me in right direction?

any help/suggestion appreciated.

check 3rd step of algorithm in wikipedia article (section matrix interpretation) , explain way compute minimal amount of lines cover 0's

update: next way obtain minimum number of lines cover 0's:

class="lang-java prettyprint-override">import java.util.arraylist; import java.util.list; public class minlines { enum linetype { none, horizontal, vertical } private static class line { int lineindex; linetype rowtype; line(int lineindex, linetype rowtype) { this.lineindex = lineindex; this.rowtype = rowtype; } linetype getlinetype() { homecoming rowtype; } int getlineindex() { homecoming lineindex; } boolean ishorizontal() { homecoming rowtype == linetype.horizontal; } } private static boolean iszero(int[] array) { (int e : array) { if (e != 0) { homecoming false; } } homecoming true; } public static list<line> getminlines(int[][] matrix) { if (matrix.length != matrix[0].length) { throw new illegalargumentexception("matrix should square!"); } final int size = matrix.length; int[] zerosperrow = new int[size]; int[] zerospercol = new int[size]; // count number of 0's per row , number of 0's per column (int = 0; < size; i++) { (int j = 0; j < size; j++) { if (matrix[i][j] == 0) { zerosperrow[i]++; zerospercol[j]++; } } } // there should @ must size lines, // initialize list initial capacity of size list<line> lines = new arraylist<line>(size); linetype lastinsertedlinetype = linetype.none; // while there 0's count in either rows or colums... while (!iszero(zerosperrow) && !iszero(zerospercol)) { // search largest count of 0's in both arrays int max = -1; line linewithmostzeros = null; (int = 0; < size; i++) { // if exists count of 0's equal "max" in 1 has // same direction lastly added line, replace // // heuristic "fixes" problem reported @justinwyss-gallifent , @hkrish if (zerosperrow[i] > max || (zerosperrow[i] == max && lastinsertedlinetype == linetype.horizontal)) { linewithmostzeros = new line(i, linetype.horizontal); max = zerosperrow[i]; } } (int = 0; < size; i++) { // same above if (zerospercol[i] > max || (zerospercol[i] == max && lastinsertedlinetype == linetype.vertical)) { linewithmostzeros = new line(i, linetype.vertical); max = zerospercol[i]; } } // delete 0 count line if (linewithmostzeros.ishorizontal()) { zerosperrow[linewithmostzeros.getlineindex()] = 0; } else { zerospercol[linewithmostzeros.getlineindex()] = 0; } // 1 time you've found line (either horizontal or vertical) greater 0's count // iterate on it's elements , substract 0's other lines // example: // 0's x col: // [ 0 1 2 3 ] -> 1 // [ 0 2 0 1 ] -> 2 // [ 0 4 3 5 ] -> 1 // [ 0 0 0 7 ] -> 3 // | | | | // v v v v // 0's x row: {4} 1 2 0 // [ x 1 2 3 ] -> 0 // [ x 2 0 1 ] -> 1 // [ x 4 3 5 ] -> 0 // [ x 0 0 7 ] -> 2 // | | | | // v v v v // {0} 1 2 0 int index = linewithmostzeros.getlineindex(); if (linewithmostzeros.ishorizontal()) { (int j = 0; j < size; j++) { if (matrix[index][j] == 0) { zerospercol[j]--; } } } else { (int j = 0; j < size; j++) { if (matrix[j][index] == 0) { zerosperrow[j]--; } } } // add together line list of lines lines.add(linewithmostzeros); lastinsertedlinetype = linewithmostzeros.getlinetype(); } homecoming lines; } public static void main(string... args) { int[][] example1 = { {0, 1, 0, 0, 5}, {1, 0, 3, 4, 5}, {7, 0, 0, 4, 5}, {9, 0, 3, 4, 5}, {3, 0, 3, 4, 5} }; int[][] example2 = { {0, 0, 1, 0}, {0, 1, 1, 0}, {1, 1, 0, 0}, {1, 0, 0, 0}, }; int[][] example3 = { {0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 0, 0}, {0, 0, 1, 1, 0, 0}, {0, 1, 1, 0, 0, 0}, {0, 1, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0} }; list<int[][]> examples = new arraylist<int[][]>(); examples.add(example1); examples.add(example2); examples.add(example3); (int[][] illustration : examples) { list<line> minlines = getminlines(example); system.out.printf("min num of lines illustration matrix is: %d\n", minlines.size()); printresult(example, minlines); system.out.println(); } } private static void printresult(int[][] matrix, list<line> lines) { if (matrix.length != matrix[0].length) { throw new illegalargumentexception("matrix should square!"); } final int size = matrix.length; system.out.println("before:"); (int = 0; < size; i++) { (int j = 0; j < size; j++) { system.out.printf("%d ", matrix[i][j]); } system.out.println(); } (line line : lines) { (int = 0; < size; i++) { int index = line.getlineindex(); if (line.ishorizontal()) { matrix[index][i] = matrix[index][i] < 0 ? -3 : -1; } else { matrix[i][index] = matrix[i][index] < 0 ? -3 : -2; } } } system.out.println("\nafter:"); (int = 0; < size; i++) { (int j = 0; j < size; j++) { system.out.printf("%s ", matrix[i][j] == -1 ? "-" : (matrix[i][j] == -2 ? "|" : (matrix[i][j] == -3 ? "+" : integer.tostring(matrix[i][j])))); } system.out.println(); } } }

the of import part getminlines method, returns list lines cover matrix 0's entries. illustration matrices prints:

class="lang-none prettyprint-override">min num of lines illustration matrix is: 3 before: 0 1 0 0 5 1 0 3 4 5 7 0 0 4 5 9 0 3 4 5 3 0 3 4 5 after: - + - - - 1 | 3 4 5 - + - - - 9 | 3 4 5 3 | 3 4 5 min num of lines illustration matrix is: 4 before: 0 0 1 0 0 1 1 0 1 1 0 0 1 0 0 0 after: | | | | | | | | | | | | | | | | min num of lines illustration matrix is: 6 before: 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 1 0 0 0 1 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 after: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

i hopes give boost, rest of hungarian algorithm shouldn't hard implement

java algorithm logic hungarian-algorithm

javascript - Selected all child elements to hide, but wont unhide all elements on click -



javascript - Selected all child elements to hide, but wont unhide all elements on click -

i making jquery accordion next css-tricks tut here. modified code bit , selected elements within parent element , hid it. upon click reveal dd tags, not ul or h3 tag. sense has code on line 6 or 7 of js section don't understand js/jquery plenty know why. help appreciated.

example: http://jsfiddle.net/undee/

next selects next sibling of selected element, can utilize nextuntil method instead.

var $target = $this.parent().nextuntil('dt');

http://jsfiddle.net/bddch/

however, if wrap target elements element (like div element) next work expected.

javascript jquery html css accordion

sql server - Why UDF call with declared variables as parameters is ways faster than call with hardcoded parameters -



sql server - Why UDF call with declared variables as parameters is ways faster than call with hardcoded parameters -

i'm having following, in opinion, unusual problem. when phone call udf next way:

declare @contact_id uniqueidentifier declare @group_id uniqueidentifier set @group_id = 'ee57e2ad-204b-4078-afa4-11fa8375c2fd' set @contact_id = 'e6efcc9f-9d1c-4c38-a950-c45372f2a6d2' select count( id ) [countall] [document] [document] ([document].[id] in (select id [fs_document_view_ee57e2ad_204b_4078_afa4_11fa8375c2fd](@contact_id, @group_id)))

it runs 4s , next execution plan: fast

when phone call udf hard coded parameters this:

select count( id ) [countall] [document] [document] ([document].[id] in (select id [fs_document_view_ee57e2ad_204b_4078_afa4_11fa8375c2fd]('e6efcc9f-9d1c-4c38-a950-c45372f2a6d2', 'ee57e2ad-204b-4078-afa4-11fa8375c2fd')))

i execution plan: slow , takes 91s.

can explain me why happening?

the function calls 4 other nested functions passing them same parameters. it's related items view permissions.

thanks help in advance.

update

i used alternative 2 this article ivan g. mentioned.

the problem parameter sniffing , alternative 2 solved problem.

another method of resolving parameter sniffing issue disable parameter sniffing >altogether. not done switch or database option, can done >within script of stored procedure code. here illustration of how created >stored procedure parameter sniffing disabled:

drop proc [dbo].[displaybillinginfo] go create proc [dbo].[displaybillinginfo] @begindate datetime, @enddate datetime recompile declare @startdate datetime; declare @stopdate datetime; set @startdate = @begindate; set @stopdate = @enddate; select billingdate, billingamt billinginfo billingdate between @startdate , @stopdate;

to disable parameter sniffing, did alter way parameter values used within stored procedure. creating 2 different local variables (@startdate , @enddate) within procedure, setting variables passed parameters, , using local variables in between condition, able disable parameter sniffing. parameter sniffing disabled because optimizer not able identify parameters’ values in actual select statement. because sql server cannot tell parameter values used phone call stored procedure, optimizer creates generic plan based on statistics.

when execute stored procedure using code above, using either narrow range of dates or years’ worth of dates, compiled execution plan “index scan” operation. can tell parameter sniff turned off because know short range of dates have created index seek operation.

i believe due parametrization. first version of query parametrized, , sec 1 isn't. "queries parametrized requires less recompilation , dynamically built queries needs compilations , recompilation frequently" (source)

for version of query built parameters, execution plan created , reused: "if sql query has parameters, sql server creates execution plan tailored them improve performance, via process called 'parameter sniffing'. plan stored , reused since best execution plan" (source).

sql-server performance tsql user-defined-functions

rails jbuilder getting Called id for nil -



rails jbuilder getting Called id for nil -

i'm trying utilize jbuilder gem format json output.

controller

class locationscontroller < applicationcontroller def tree @locations = location.all end

tree.json.jbuilder

jbuilder.encode |json| json.id @location.id json.name @location.name end

test using url:

http://localhost:5000/locations/tree.json

results:

called id nil, mistakenly 4 -- if wanted id of nil, utilize object_id extracted source (around line #2): 1: jbuilder.encode |json| 2: json.id @location.id 3: json.name @location.name 4: end

you don't seem define @location in code have posted. should iterate on locations, jbuilder lets illustration this:

jbuilder.encode |json| json.locations @locations |location| json.id location.id json.name location.name end end

see docs if want flat array instead.

ruby-on-rails-3 jbuilder

Flex Force Uppercase in ComboBox -



Flex Force Uppercase in ComboBox -

i trying forcefulness uppercase in combobox

<s:combobox id="cbstocks" width="200" height="30" fontsize="16" dataprovider="{this.knownsymbols}" />

i tried setstyle approach suggested flexexamples without success

cbstocks.setstyle( "typographiccase", typographiccase.caps);

and

cbstocks.textinput.setstyle( "typographiccase", typographiccase.caps);

both throw exception rangeerror: property typographiccase value caps out of range

how forcefulness uppercase in combobox?

you can create custom formatter accomplish this:

public class capsformatter extends formatter { override public function format(value:object):string { homecoming value ? value.tostring().touppercase() : ""; } }

and utilize follows:

<fx:declarations> <f:capsformatter id="capsformatter"/> </fx:declarations> <s:combobox labelfunction="capsformatter.format"> <s:arraylist> <fx:string>hello</fx:string> <fx:string>world</fx:string> </s:arraylist> </s:combobox>

flex combobox uppercase

c# - List (Generic) using jquery -



c# - List (Generic) using jquery -

i have webmethod in asp.net project wanna pass listview in jquery ajax method dont how can observe elements of listview , using them.folowing code c# code.bt need jquery code

if (ck != null) { reqnum[0, 0] = "@requestingbranchid"; reqnum[0, 1] = ck["branchid"]; reqnum[1, 0] = "@providerbranchid"; reqnum[1, 1] = customer.tostring(); datatable dt = sqlcommands.filldata(out outstatus, out outmessage, "bsd.sw_boxes_stockofproviderandrequestingbranch", commandtype.storedprocedure, reqnum); list<datarow> rows = dt.rows.cast<datarow>().tolist(); int x=rows.count; homecoming rows; }

ok let's have datatable , want pass results of datatable javascript display results using ajax. first step need convert these results json format. can next method::

public string getjson(datatable dt) { system.web.script.serialization.javascriptserializer serializer = new system.web.script.serialization.javascriptserializer(); list<dictionary<string, object>> rows = new list<dictionary<string, object>>(); dictionary<string, object> row = null; foreach (datarow dr in dt.rows) { row = new dictionary<string, object>(); foreach (datacolumn col in dt.columns) { row.add(col.columnname, dr[col]); } rows.add(row); } homecoming serializer.serialize(rows); }

the next step parse result json string in javascript , guess easy part. can check question find out how parse json string objects safely turning json string object .if u want know more tell me.

c# asp.net jquery

How can I retrieve JSON from an HTTP endpoint, from within Excel on MacOS, and parse it? -



How can I retrieve JSON from an HTTP endpoint, from within Excel on MacOS, and parse it? -

i have seen how can send http post request server excel using vba?

and the macos-friendly response describes how retrieve info http endpoint using querytables. demonstrates how retrieve single string , stuff cell.

all good. retrieve more single value. it's big json string, , want post-process within excel vba before populating 1 or more cells.

how possible?

i can think of 1 way - place result of querytables thing hidden cell, , post-process hidden cell populate other cells. there few json libraries vba have not evaluated yet.

but seems pretty hacky. want not rely on storing json value in cell. i'd store variable in vba code. if using createobject("msxml2.serverxmlhttp"). (nb: createobject() not available within excel on macos).

and understand best reply here might be: get windows machine if want run apps within excel.

you can acutally utilize worksheets(0).querytable method in vba. have @ manual or google it. don't have store json string cell.

or have used

public function getwebsource(byref url string) string dim xml ixmlhttprequest on error resume next set xml = createobject("microsoft.xmlhttp") xml .open "get", url, false .send getwebsource = .responsetext end set xml = nil end function

to download json string.

look around parsers. somehting parsing json in excel vba should fill needs.

json excel vba excel-vba-mac

error java.sql.SQLException: Parameter index out of range -



error java.sql.SQLException: Parameter index out of range -

i still error don't provide value 1 parameter , don't have thought wrong.

ps("insert slide (presentation_id, duration, position, type) values (?, ?, ?, ?) ").set(this.getid()).set(slide.getduration()).set(slide.getposition()).set(slide.gettype().ordinal()).update();

in table not provide value 1 column autoincrement set.

everything seems alright me please give advice might wrong.

dont include auto inc fieldin column list.

ps("insert slide (duration, position, type) values (?, ?, ?) ").set(slide.getduration()).set(slide.getposition()).set(slide.gettype().ordinal()).update();

java

c# - Using the Select method for dynamic queries and expression trees -



c# - Using the Select method for dynamic queries and expression trees -

i attempting create dynamic query using look trees match next statement:

var items = data.where(i => i.coveragetype == 2).select(i => i.limitselected);

i can create method , result it; however, cannot create select method.

here method:

var parm = expression.parameter(typeof(baseclassdata), "basecoverage"); var querydata = data.asqueryable(); var left = expression.property(parm, "coveragetype"); var right = expression.constant(2m); var e1 = expression.equal(left, right); var wheremethod = expression.call( typeof(queryable), "where", new type[] { querydata.elementtype }, querydata.expression, expression.lambda<func<baseclassdata, bool>>(e1, new parameterexpression[] { parm }));

this using select method:

var selectparm = expression.property(parm, "limitselected"); var selectmethod = expression.call( typeof(enumerable), "select", new type[]{typeof(baseclassdata), typeof(decimal)}, wheremethod, expression.lambda<func<baseclassdata, decimal>>(selectparm, new parameterexpression[]{ parm}) );

when run code error:

no generic method 'select' on type 'system.linq.enumerable' compatible supplied type arguments , arguments. no type arguments should provided if method non-generic.

i have tried changing enumerable queryable , same error.

no need utilize expression.call, can straight build look tree instead; have create static method help me generate dynamic query:

public static void test(string[] args) { using (var db = new dbcontext()) { //query 1 var query1 = db.prizetypes.where(m => m.rewards == 1000).select(t => t.name); //query 2 equal query 1 expression<func<prizetype, bool>> predicate1 = m => m.rewards == 1000; expression<func<prizetype, string>> selector1 = t => t.name; var query2 = db.prizetypes.where(predicate1).select(selector1); console.writeline(predicate1); console.writeline(selector1); console.writeline(); //query 3 equal query 1 , 2 expression<func<prizetype, bool>> predicate2 = getpredicateequal<prizetype>("rewards", (int16)1000); expression<func<prizetype, string>> selector2 = getselector<prizetype, string>("name"); var query3 = db.prizetypes.where(predicate2).select(selector2); console.writeline(predicate2); console.writeline(selector2); //as can see, query 1 equal query 2 equal query 3 } } public static expression<func<tentity, bool>> getpredicateequal<tentity>(string fieldname, object fieldvalue) tentity : class { parameterexpression m = expression.parameter(typeof(tentity), "t"); var p = m.type.getproperty(fieldname); binaryexpression body = expression.equal( expression.property(m, fieldname), expression.constant(fieldvalue, p.propertytype) ); homecoming expression.lambda<func<tentity, bool>>(body, m); } public static expression<func<t, treturn>> getselector<t, treturn>(string fieldname) t : class treturn : class { var t = typeof(treturn); parameterexpression p = expression.parameter(typeof(t), "t"); var body = expression.property(p, fieldname); homecoming expression.lambda<func<t, treturn>>(body, new parameterexpression[] { p }); }

c# linq exception-handling expression-trees

Representing letters as numbers in java -



Representing letters as numbers in java -

i wondering how represent letters integers in java. working on problem have find mid letter between 2 lettered word. example, take word 'go' , provide each letter assigned integer value find midpoint letter. can help me out or point me in right direction go solving on how midpoint letter between 2 letter word?

that simple

int = 'a'; int c = 'c'; char mid = (char) ((a + c) / 2); system.out.println(mid);

prints

b

java numbers alphabet

windows - Include apsrtable (or stargazer) output in an Rmd file -



windows - Include apsrtable (or stargazer) output in an Rmd file -

i tried include summary of lm object in rmd file, using code next didn't work. help me that?

```{r summary_lm, results='asis', echo=false, comment=na} library(apsrtable) my_model <- lm(y ~ x, info = data.frame(y = rnorm(10), x = 1:10)) res <- apsrtable(my_model) # my_model linear regression model (lm) cat("$$latex \n",res,"\n$$ \n") ```

the $$ syntax applies math expressions, , trying set table in it, not work. apsrtable, far understand, latex only, latex , markdown different -- there little hope can redo latex exclusively markdown. think people invented $$ syntax markdown due fact supported mathjax, , note there many variants/flavors based on original markdown.

at moment may consider:

use xtable or ascii or r2html bundle generate html tables request bundle author of apsrtable back upwards html tables

windows r latex knitr rmarkdown

direct access to base class variables / objects c# -



direct access to base class variables / objects c# -

public class myworld { public int data; public void changedata() { info = 10; } } public class myrobot : myworld { public void robotchangesdata() { //how can create robot alter info in world? } }

i understand (more or less) should not done way, , has been asked one thousand times, every alter should through methods - but:

if remain world , robot example, later on want have method robot like: robot.movebox(25) robot has have access world, object box, , create updates drawing objects (meshes, shapes etc.) thing can come now, pass every method of robot (like movebox, or robotchangesdata) whole world + box + drawing stuff 'ref' , can alter then.. every method robot.movebox(25, ref myworldobject, ref myworldboxes,ref etc etc)

is right way go? or did miss important?

maybe illustration helps:

your robot base of operations class

public class robotbase { protected int data; // reference world protected world _world; public robotbase(world world) { _world = world; } public void changedata() { info = 10; } }

your robot class:

public class robot : robotbase { public robot(world world) : base(world) {} public void robotchangesdata() { //change info in base of operations info = 20; // alter info in world, object passed reference, no need farther "ref" declarations _world.terminate(); } }

your world class:

public class world { public void terminate() { // terminate world! noooess! } }

c#

How to add json data in a combobox column using c#? -



How to add json data in a combobox column using c#? -

this dummy json file.i want display name , mapped_name in datagridview.mapped_name combobox column.so suppose when name column contains button mapped_name column should contain combox box having options linklabel , button.

{"components":[ { "id":"1", "name":"button", "mapped_name":[ {"id":"1", "name":"linklabel" }, {"id":"2", "name":"button" } ] }, { "id":"2", "name":"listview", "mapped_name":[ {"id":"1", "name":"tabview" }, {"id":"2", "name":"listview" }, {"id":"3", "name":"tiles" } ] }

i suggest utilize json.net parse info , display it. can utilize jsontextreader class

see samples here check help

c# json

javascript - Is there a way to activate a transition on click event and not on hover for example? -



javascript - Is there a way to activate a transition on click event and not on hover for example? -

i'm struggling in finding non js solution problem. there way of activate css transition on click , not on :hover or others?

one possibility: can add together class holds transition on click. illustration using jquery - can accomplish programmatically using "raw" javascript only:

html container should animated

<div id="transtion"></div>

javascript

// bind click event element - can other element triggers … $('#transition').click(function() { // add together classname thats defined transition in css $(this).addclass('translate_left'); });

javascript html css css3

javascript - Jquery selected value of highlighted text -



javascript - Jquery selected value of highlighted text -

im trying create editor when highlight text on computer, jquery take selected value , throw tags around it, more specificity code or pre tags.

var selectedvalue = // set highlighted selection value $("#content").contents().find("body").append($("<pre></pre>").append(selectedvalue)) ;

i know how value between tags, need know how value.

well googling of few time , found out http://mark.koli.ch/2009/09/use-javascript-and-jquery-to-get-user-selected-text.html sure it.

example

response op comment

<script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript"> $(function() { var ifx = $('<iframe src="code/sample.html" height=200 width=200></iframe>').appendto(document.body); $(document.body).bind('mouseover', function() { var u_sel; if(window.getselection) { u_sel = ifx[0].contentwindow.getselection(); alert(u_sel); } }); }); </script>

javascript jquery

c++ - Is there any trick to detect if an object is created during execution of another destructor? -



c++ - Is there any trick to detect if an object is created during execution of another destructor? -

this kind of follow on why cant alexandrescu utilize std::uncaught_exception() implement scope_fail in scopeguard11?

i observe if creating myclass in destructor of class (or active destructor somewhere in phone call stack).

class myclass { public: myclass(){ assert(???what set here????); } } void f(){ myclass m; //whether asserts should context dependant } class otherclass{ ~otherclass(){ myclass m; //this should assert f(); //this should too; } } int main() { myclass m; //this should not assert f(); //this should not assert }

one effort might be:

assert(!std::uncaught_exception());

but work if destructor beingness invoked because of exception, not if invoked because object went out of scope.

you cannot observe , don't want to. it's not class's business. if phone call noexcept destructor, grab exceptions

c++ destructor uncaught-exception stack-unwinding

mongoid sortable list grouped by association -



mongoid sortable list grouped by association -

i have 2 models review , product. product has many reviews.

is there gem can sort reviews belonging product? far using mongoid-orderable sort reviews. doesn't have ability sort reviews of product.

thank you!

is review embedded document?

you can sort reviews during query using #sort based on field order of collection review or other field, created_at example.

my_product.reviews.order_by(:created_at)

mongoid sortable

c# - InsertAt() method doesn't update SQL table -



c# - InsertAt() method doesn't update SQL table -

i utilize line:

dataset.sometablename.rows.insertat(somerow, 0);

after line update sql table. inserted row not appear on sql server side.

any thought why inserted row doesn't appear on sql server side?

issue setadded method:

somerow.acceptchanges(); somerow.setadded();

as far know insertat doesn't perform rowstate modifications.

c# .net dataset

SQL Server : stored procedure or function -



SQL Server : stored procedure or function -

i have table 2 columns (a bool , b text), these columns can be:

both null if false, b should null if true, b should not null

there rules. want create stored procedure or function check these rules when row adding or updating (via trigger). better, stored procedure or function? if function, type? in general, variant best (return boolean or other way etc)?

i think you're after check constraint.

example:

alter table xxx add together constraint chk_xxx check ( (a null , b null) or (a = 0 , b null) or (a = 1 , b not null) ) ;

sql-server function stored-procedures

c# - Reading and Operating on a HDF5 File -



c# - Reading and Operating on a HDF5 File -

i found similar question @ c# hdf5 illustration code i'm having problem viewing hdf5 dataset contents correctly.

the dataset i'm looking @ contains string headers strings in first column , doubles in others.

here's code looks like:

public static void readh5(string path, string filename) { h5.open(); var fileid = h5f.open(path + filename, h5f.openmode.acc_rdonly); var groupid = h5g.open(fileid, "/example group/"); var datasetid = h5d.open(groupid, "events"); var dataspace = h5d.getspace(datasetid); var size = h5s.getsimpleextentdims(dataspace); var datatype = h5d.gettype(datasetid); double[,] dataarray = new double[size[0],11]; var wraparray = new h5array<double>(dataarray); h5d.read(datasetid, datatype, wraparray); console.writeline(wraparray); }

when debug , wraparray each element incredibly big or little doubles 10^300 10^-300 in value , don't know why. don't think id numbers of elements. i've tried changing datatype of wraparray , dataarray object still doesn't give me exact contents of dataset.

the output i'm getting wraparray looks like:

[0,0] 4.0633928641260729e+87 [0,1] 9.77854726248995e-320 [0,2] 1.52021104712121e-312

etc.

but want is:

[0,0] event1 [0,1] 2 [0,2] 56

etc.

after reading in dataset want loop through first column find specific strings, , corresponding elements in other columns. have figure out out.

for me worked checking actual datatype of dataset (using hdfview) , create arrays containing datatype instead of doubles.

c# hdf5

How can I easily format my data table in C++? -



How can I easily format my data table in C++? -

i'm not sure, think remember there beingness in java can specify how far left of window string or digit begins..

how format table? have (using setw):

bob doe 10.96 7.61 14.39 2.11 47.30 14.21 44.58 5.00 60.23 helen city 10.44 7.78 16.27 1.99 48.92 13.93 53.79 5.00 70.97 joe greenish 10.90 7.33 14.49 2.05 47.91 14.15 44.45 4.70 73.98

and ideally like:

bob doe blr 10.96 7.61 14.39 2.11 47.30 14.21 44.58 5.00 60.23 4:27.47 helen city cub 10.90 7.33 14.49 2.05 47.91 14.15 44.45 4.70 73.98 4:29.17 joe greenish usa 10.44 7.78 16.27 1.99 48.92 13.93 53.79 5.00 70.97 5:06.59

is way calculations? or there magical more simple way?

in c++, have 3 functions help want. there defined in <iomanip>. - setw() helps defined width of output. - setfill() fill rest character want (in case ' '). - left (or right) allow define alignment.

here code write first line :

#include <iostream> #include <iomanip> using namespace std; int main() { const char separator = ' '; const int namewidth = 6; const int numwidth = 8; cout << left << setw(namewidth) << setfill(separator) << "bob"; cout << left << setw(namewidth) << setfill(separator) << "doe"; cout << left << setw(numwidth) << setfill(separator) << 10.96; cout << left << setw(numwidth) << setfill(separator) << 7.61; cout << left << setw(numwidth) << setfill(separator) << 14.39; cout << left << setw(numwidth) << setfill(separator) << 2.11; cout << left << setw(numwidth) << setfill(separator) << 47.30; cout << left << setw(numwidth) << setfill(separator) << 14.21; cout << left << setw(numwidth) << setfill(separator) << 44.58; cout << left << setw(numwidth) << setfill(separator) << 5.00; cout << left << setw(numwidth) << setfill(separator) << 60.23; cout << endl; cin.get(); }

edit : cut down code, can utilize template function :

template<typename t> void printelement(t t, const int& width) { cout << left << setw(width) << setfill(separator) << t; }

that can utilize :

printelement("bob", namewidth); printelement("doe", namewidth); printelement(10.96, numwidth); printelement(17.61, numwidth); printelement(14.39, numwidth); printelement(2.11, numwidth); printelement(47.30, numwidth); printelement(14.21, numwidth); printelement(44.58, numwidth); printelement(5.00, numwidth); printelement(60.23, numwidth); cout << endl;

c++

calculating time in C - AIX machine -



calculating time in C - AIX machine -

i editing time value using variable of type struct tm (adding seconds tm->tm_sec), getting wrong results after doing mktime(&t).

doing in linux gets me proper results, in aix not. problem?

#include <stdio.h> #include <time.h> #include <langinfo.h> #include <locale.h> int main () { struct tm tm; struct tm *end; time_t t; char str[20] = {'\0'}; //if (strptime("7 feb 2013 01:47:30", "%d %b %y %h:%m:%s", &tm) == null) if (strptime("2012-10-17-01-07-30", "%y-%m-%d-%h-%m-%s", &tm) == null) {printf("error\n"); } tm.tm_sec = (tm.tm_sec + 1200); //tm.tm_sec = 12; //t = mktime(&tm); //t = t + 12; //end =localtime(&t); strftime(str,20,"%y %m %d %h %m %s",&tm); printf("str %s\n",str); homecoming 0; }

i believe right reply utilize time_t, big number representing time in seconds since midnight of 1 jan 1970. adding arbitrary number of seconds here becomes trivial.

i expect if adding seconds tm->tm_sec, overflows, , causes result incorrect. if unlucky, need ripple alter in seconds way through year (adding 5 seconds 31 dec 2013 23:59:56 take 01 jan 2014 00:00:01). of course of study can done, instead of:

t =+ 5;

you dozen steps along line of

tm.tm_sec += 5; if (tm.tm_sec >= 60) { tm.tm_sec -= 60; tm.tm_min += 1; if (tm.tm_min >= 60) { ... , on ... } }

it gets more interesting if overflow days in month, since have take business relationship of number of days in each month, 28, 29, 30 or 31 depending on month [and if it's leap-year or not].

c aix

javascript - Send iframe to back on IE -



javascript - Send iframe to back on IE -

this question has reply here:

youtube iframe wmode issue 9 answers

i'm building webpage has popup div (with javascript/jquery) show text, maintain having problem. behind popup, there youtube embedded video (iframe) on net explorer only, stays in front end of pop up. have tried using z-index property prepare nothing. on chrome works ie ruins it. have alternatives, fadding out popup or setting display "none" doesn't good.... thoughts on how send back?

tanks all, cheers.

try adding iframe url &wmode=opaque

alternatively seek ?wmode=transparent

explanation: http://www.scorchsoft.com/news/youtube-z-index-embed-iframe-fix

javascript jquery html css

PHP and MySQL, Query works in one not the other -



PHP and MySQL, Query works in one not the other -

i have query works in phpmyadmin not when beingness run through php

this query:

delete 'table' 'id' not in ( select distinct id ( select * 'table' order scoredesc limit 10 ) foo)

basically, sorts table score descending , keeps top 10 , deletes rest. can run fine trough phpmyadmin php code says no

this php script:

function add_highscore() { mysql_query("delete highscores id not in ( select distinct id ( select * highscores order score desc limit 10 ) foo)") or die('0'); echo "1"; mysql_close($table_id); }

there no problems connection, have more functions in script works.

any ideas? help appreciated!

cheers, jon

add top of script:

error_reporting(e_all);

and replace:

die('0');

with:

die(mysql_error());

and should help indicate variety of 'not working' script is.

php mysql mysqli

canvas - How to draw or write a text like MS-Paint in android using onTouch Event? -



canvas - How to draw or write a text like MS-Paint in android using onTouch Event? -

using pencil hi all, have created panel collection of different colors, pencil, eraser , different shapes similar ms-paint. able draw or write on screen using touch event method. when draw on screen (when touch screen), motionevent.action_down method calling. works fine. when release finger screen, motionevent.action_up method calling , works fine.

so, problem is, ms-paint couldnt able see drew or wrote before releasing finger on screen. example, can refer video link- using pencil. user can see when dragged shapes or trying draw pencil. also, in link user draws using pencil , visible without releasing finger on screen.

but, when draw on screen, 1 time released finger appears.

what need is, when user touch screen if he/she moves finger on screen, user must able see trying draw or write on screen.

for illustration : if seek write word "apple" on screen , trying set "a" . when write letter "a", invisible unless take finger screen. 1 time if released finger screen after drew letter"a" text or image has been appeared on screen drew.

so, have done motionevent.action_down , motionevent.action_up. work fine.

but, motionevent.action_move not working @ all.

this code,

@override public boolean ontouchevent(motionevent event) { if(event.getaction() == motionevent.action_down) { if(shape == shapeline) { graphicobject = new line(); ((line) graphicobject).getbegin().setx(event.getx()); ((line) graphicobject).getbegin().sety(event.gety()); } if(shape== shaperect) { graphicobject = new rectangle(); point temp = new point(event.getx(), event.gety()); endpoint = new point(); ((rectangle) graphicobject).settemppointofoneendrectangle(temp); } else if(event.getaction() == motionevent.action_move){ if(shape== shapeline) { final float x=event.getx(); final float y=event.gety(); } if(shape == shaperect) { endpoint.x=event.getx(); endpoint.y=event.gety(); invalidate(); }

anyone suggest me, action_move. have tried lot in code no changes , didnt find solution while moving. not know how this.. help/suggestions highly appreciated, thanks

can suggest me or ideas ?

i have googled lot , tried many possibilities.

any help/suggestions highly appreciated, !

basic thought when tap record point in variable,then within action_move record current point , draw line in between these 2 points.once done save point in previous point. sudo code:

point last; point current; ... case action_down: last=mouse.position; break; case action_move: current=mouse.position; drawline(current,last); last=current; break;

do way,your drawing should fine. n.b. remember,this sudo code. :p

edit. illustration 1 of app. pointed out should do:

public boolean ontouchevent(motionevent event) { int action = event.getaction(); switch(action & motionevent.action_mask) { case motionevent.action_down: initial.x=(int)event.getx(); initial.y=(int)event.gety(); break; case motionevent.action_move: current.x=(int)event.getx(); current.y=(int)event.gety(); //draw line using initial start , current end point //sudo code: drawline(initial,current) //now set initial current initial=current// continuity of drawing. break; } homecoming true; }

initial , current both point objects.

android canvas touch paint motionevent

.htaccess redirect to separate page for desktop -



.htaccess redirect to separate page for desktop -

i want direct desktop computers total browser /full/index.php. mobile browsers go /index.html.

right works in ie chrome total broswer still shows mobile site. thanks!

rewriteengine on rewritecond %{http_user_agent} (android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge\ |maemo|midp|mmp|opera\ m(ob|in)i|palm(\ os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows\ (ce|phone)|xda|xiino) [nc,or] rewritecond %{http_user_agent} ^(1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a\ wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r\ |s\ )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1\ u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp(\ i|ip)|hs\-c|ht(c(\-|\ |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac(\ |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt(\ |\/)|klon|kpt\ |kwc\-|kyo(c|k)|le(no|xi)|lg(\ g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-|\ |o|v)|zz)|mt(50|p1|v\ )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v\ )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-|\ )|webc|whit|wi(g\ |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-) [nc] rewriterule ^$ /index.html [l] rewriterule ^$ /full/soon.php [l]

.htaccess

javascript - Three.js: Get the Direction in which the Camera is Looking -



javascript - Three.js: Get the Direction in which the Camera is Looking -

i'm sure question has been duplicated many times, cannot find answers specific problem!

i'm creating game in using html5 , three.js, , have photographic camera rotates euler order of 'yxz'.

this photographic camera rotation up, down, left , right head. in first person view.

with euler order, z property in camera.rotation not used (always 0). x used specify pitch or latitude in radians, , y used depict longitude.

i have number of targets moving around user in spherical manner, photographic camera @ center of sphere. lets sphere has radius of 1000.

my aim calculate angle between photographic camera looking, , target is.

i wrote code calculates angle between 2 vectors:

var = new three.vector3(1,0,0); var b = new three.vector3(0,1,0); var theta = math.acos( a.dot(b) / a.length() / b.length() ); // theta = pi/2;

i have vector of target (targets[0].position).

the thing cannot figure out way vector of photographic camera looking.

i've looked @ vector3.applyprojection , applyeuler methods, , played around still cannot results.

i believe euler order must first changed 'xyz' before projections made? i've tried, , i'm not sure how this, documentation pretty hard understand.

say if photographic camera looking straight right, need vector radius distance away center in direction of current rotation.

so end 2 vectors, can calculations on!

thank in advanced!

the photographic camera looking downwards it's internal negative z-axis. create vector pointing downwards negative z-axis:

var vector = new three.vector3( 0, 0, -1 );

now, apply same rotation vector applied camera:

vector.applyquaternion( camera.quaternion );

you can angle in radians target so:

angle = vector.angleto( target.position );

edit: updated three.js r.59

javascript html5 vector three.js

Linux ANSI C simultaneous access to files and locking -



Linux ANSI C simultaneous access to files and locking -

i writing linux ansi c cgi-bin server programme simultaneous access files.

is possible distinguish between file existence , file locking? can't find reply google. i'd write programme tries open file few seconds if fd<0 (thinking file locked while). if file not exist it's fd <0. programme waste time waiting.

suppose few threads seek append same file no locking. 1 tries add together "aaaa", - "bbbb". can result file "aabbaabb"? or aaaabbbb or bbbbaaaa? or result unpredictable?

am assuming ieee std 1003.1-2001 might defer iso c standard...

in case fopen fails i.e. fd < 0 scheme sets error codes... can check error codes. in case of file non-existent, returned error be

enoent component of filename not name existing file or filename empty string.

for more reference visit: http://pubs.opengroup.org/onlinepubs/009695399/functions/fopen.html

for point 2: have been doing logging of info in scheme more 100 processes writing single file simultaneously have never seen merger of records(file opened in append mode). i.e. aaaabbbb

c linux file locking

python - How to set Content-Type header for 304 http response code? -



python - How to set Content-Type header for 304 http response code? -

so using few decorators django enable caching on api:

@require_get @cache_page(100) @cache_control(max_age=100, s_maxage=100) @csrf_exempt def my_api(request):

the problem is, 304 not modified response coming text/html content-type header. api returns application/json content-type header , consistent. there way tell django content type homecoming 304 response code?

the problem here https://github.com/django/django/blob/master/django/http/response.py#l411

write decorator add together mimetype again

def restoremime(fn): def wrapper(*args, **kwds): response = fn(*args, **kwds) response['content-type'] = your_mime_type homecoming response homecoming wrapper

python django

jQuery Mobile popup that doesn't move when scrolling the page -



jQuery Mobile popup that doesn't move when scrolling the page -

i using jquery mobile 1.3.0 rc1. have popup create programmatically @ bottom of page , close after few seconds using settimeout (toast notification). works well, if happen scroll page while popup displayed, popup gets scrolled too. popup not move, i.e. remain in position relative screen, not relative page. there way ?

i have tried playing data-position-to attribute in html element, positionto alternative of "open" method, , tried placing popup element within fixed transparent footer, none of these resulted in desired behavior.

i had similar problem lastly week. solved using modal dialog instead of popups.

for popups, find following.

$("#mypopup").on({ popupbeforeposition: function () { $('.ui-popup-screen').off(); } });

which helped me in prevention of closing dialog while user touched outside of popup. scrolling issue still there. changed popups modal dialogs. hope helps someone.

jquery-mobile popup scroll

asp.net mvc - MVC/Razor : Conditional nested html tag -



asp.net mvc - MVC/Razor : Conditional nested html tag -

i'd have html code status ("mybool") true :

<div> <fieldset> <legend> @sometext </legend> ... other stuffs </fieldset> <div>

and 1 when it's false :

<div> <b> @sometext </b> ... other stuffs <div>

i dont whave write se same code ("other stuffs") twice tried :

<div> @if(mybool) { <fieldset> <legend> } else { <b> } @sometext if (mybool) { </legend> } else { </b> } ...other stuff if (mybool) { </fieldset> } </div>

but compilation errors.

do see how want without having somethig :

@if(mybool) { <div> <fieldset> <legend> @sometext </legend> ... other stuffs </fieldset> <div> } else { <div> <b> @sometext </b> ... other stuffs <div> }

thank you.

the next might work using @: operator:

<div> @if (somecondition) { @:<fieldset> @:<legend> } else { @:<b> } @sometext if (somecondition) { @:</legend> } else { @:</b> } ... other stuffs @if (somecondition) { @:</fieldset> } </div>

or might seek following:

<div> @html.raw(somecondition ? "<fieldset><legend>" : "<b>") @sometext @html.raw(somecondition ? "</legend>" : "</b>") ... other stuffs @if (somecondition) { @:</fieldset> } </div>

html asp.net-mvc razor

PHP code to check if array is numeric is not working -



PHP code to check if array is numeric is not working -

i have next php:

<?php $array = array("1","2","3"); $only_integers === array_filter($array,'is_numeric'); // true if($only_integers == true) { echo 'right'; } ?>

for reason returns nothing. don't know i'm doing wrong.

thanks

is_int checks actual type of variable, string in case. utilize is_numeric numeric values regardless of variable type.

note next values considered "numeric":

"1" 1 1.5 "1.5" "0xf" "1e4"

i.e. floats, integers or strings valid representations of floats or integers.

edit: also, might have misunderstood array_filter, not homecoming true or false new array values callback function returned true. if($only_integers) works nonetheless (after fixed assignment operator) because non-empty arrays considered "true-ish".

edit 2: @sdc pointed out, should utilize ctype_digit if want allow integers in decimal format.

php arrays function integer numeric

wpf - Switch between different views, following MVVM pattern -



wpf - Switch between different views, following MVVM pattern -

i'm looking right way switch between different views. scenario similar widnows explorer on windows 8, can switch between 'extra big icons', 'small icons', 'details', etc. in windows 8 users 'view' ribbon of explorer (you can alter view in xp , 7).

in case, i've list of friends, , want allow user switch between 'small', 'large', , 'details' view.

assume view model has list of friends:

public class friendvm { public name { get; set; } public smallimage { get; set; } public largeimage { get; set; } }; public class mainvm : inotifypropertychanged { public observablecollection<friendvm> friends { get; set; } private string m_viewmode public string viewmode { { homecoming m_viewmode; } set { m_viewmode=value; this.propertychanged( new propertychangedeventarags("viewmode") ); } } }

in view, i've ribbon (on user can alter viewmode), header (showing details user), , list of friends. depends on view, want show:

when viewmode = "details" i've listview, gridview. when viewmode = "small" i've listview, itemspanel wrappanel, , bind image smallimage when viewmode = "large" i've listview wrappanel, using largeimage property.

here how xml looks (simplified):

<window x:class="friends.mainwindow" ... xmlns:f="clr-namespace:friends" ...> <window.datacontext> <f:mainvm /> <window.datacontext> <window.resources> <controltemplate x:key="details"> <listview itemssource="{binding path=friends}"> <listview.view> <gridview> ... </gridview> </listview.view> </controltemplate> <controltemplate x:key="small"> <listview itemssource="{binding path=friends}"> <listview.itemspanel><wrappanel orientation="horizontal" /> </listview> <listview.itemtemplate><datatemplate> <image source={binding smallpicture} width="32" height="32" /> </datatemplate></listview.itemtemplate> </controltemplate> <controltemplate x:key="large"> <listview itemssource="{binding path=friends}"> <listview.itemspanel><wrappanel orientation="horizontal" /> </listview> <listview.itemtemplate><datatemplate> <stackpanel> <image source="{binding largepicture}" width="200" height="200" /> <textblock text="{binding name}" /> </stackpanel> </datatemplate></listview.itemtemplate> </controltemplate> </window.resource> <dockpanel lastchildfill="true"> <ribbon ...> ... </ribbon> <stackpanel> ... header stuff </stackpanel> <contentcontrol x:name="friendlist" content="{binding friends}" ?????? /> </dockpanel> </window>

so, question do in ????? area. right now, i've template="{staticresource small}" , working. moreover, using code behind can alter template of other resourced template (using findresource). however, i'm not happy solution, sense doesn't go mvvm pattern. if "item" (a listbox item, tab item, etc.), utilize info template, , date template selector. since contentcontrol, , controltemplateselector seems broken design, i'm not sure should do.

or, if set list of friends "as is" in tree, maybe using info template (having targettype=f:friendlist) create work, don't want instantiate friend list. there 1 instance instantiated within datacontext element.

wpf mvvm

Unexpected exception upon serializing continuation Google Apps Script -



Unexpected exception upon serializing continuation Google Apps Script -

i started getting error "unexpected exception upon serializing continuation" on spreadsheet google apps script when trying debug. error seem start after created connection google cloudsql api. error still occurs after commenting out jdbc object constructor. appears others have had issue , needed google tech resolve issue.

i have searched of give-and-take boards solution issue no luck. chance there google tech out there take under hood me? post code if determine line triggering error.

edit:

ok, think have discovered error occuring. seems the

var response = urlfetchapp.fetch(url + nextpage,oauth_options);

in while loop. here entire function code.

function retrieveevents(endtimeminimum, updatedafter, orderby){ //var url = 'https://www.googleapis.com/calendar/v3/calendars/' + source_cal + '/events?key=' + api_key + "&futureevents=true&orderby=updated&sortorder=descending&updatedmin=" + last_sync_date_formated; //var url = 'https://www.googleapis.com/calendar/v3/calendars/' + source_cal + '/events?key=' + api_key + "&orderby=updated&sortorder=descending&updatedmin=" + last_sync_date_formated; var url = 'https://www.googleapis.com/calendar/v3/calendars/' + source_cal + '/events?key=' + api_key + "&singleevents=true"; if ((orderby != null) && (orderby != "")){ url += "&orderby=" + orderby; } else url += "&orderby=updated"; if ((updatedafter != null) && (updatedafter != "")){ url += "&updatedmin=" + updatedafter; } else url += "&updatedmin=" + last_sync_datetime; //if no endtimeminimum specified, current time used. if (endtimeminimum == null || endtimeminimum == ""){ endtimeminimum = date_rfc339("today"); } url += "&timemin=" + endtimeminimum; logger.log("request url:" + url); var largestring = ""; var events = new array(); var nextpage = ""; var jsonobj while(true){ var response = urlfetchapp.fetch(url + nextpage,oauth_options); largestring = response.getcontenttext(); if ((largestring != null) && (largestring != "")) { jsonobj = json.parse(largestring); } if ('items' in jsonobj) events = events.concat(jsonobj.items); if ('nextpagetoken' in jsonobj){ nextpage = "&pagetoken=" + jsonobj.nextpagetoken; continue; } break; } if (events.length == 0)return null; homecoming events; }

ok, able create problem go away removing seek grab block within function called within seek grab block in main function. no longer seeing "unexpected exception upon serializing continuation" when running programme debugger.

i wish had more solid reply on causes error , how right it.

google-apps-script google-calendar google-spreadsheet google-cloud-sql

how to do popup window pass value back to the background window in android -



how to do popup window pass value back to the background window in android -

i want utilize popupwindow in app.

click button1 can triggle window popup,

click btnback in popwindow close .

but failed in program.

also want send value in edittext in popwindow backgroung window

how can it? tks!

protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); final layoutinflater inflater = (layoutinflater) this.getsystemservice(context.layout_inflater_service); final popupwindow pw = new popupwindow( inflater.inflate(r.layout.activity_setting, null, false), 200, 200, true); setcontentview(r.layout.activity_memo); button bt1 = (button) findviewbyid(r.id.button1); button bt2 = (button) findviewbyid(r.id.btnback); bt1.setonclicklistener(new button.onclicklistener() { @override public void onclick(view v) { view layout = inflater.inflate(r.layout.activity_memo, listview); showatlocation(layout, gravity.center, 0, 0); } }); bt1.setonclicklistener(new button.onclicklistener() { @override public void onclick(view v) { pw.dismiss(); } }); }

you can have background activity listener of popup window. when button clicked in popup window, phone call method onbuttonclick(string text) on listener. since activity listener, text.

android return-value popupwindow

dos - undefined reference to dlopen using djgpp -



dos - undefined reference to dlopen using djgpp -

when tried compiled sqlite3 uding djgpp, gives error undefined reference dlopen, undefined reference dlclose, undefined reference dlsym etc. on linux if utilize -ldl problem olved. there no dl.a available in djgpp. how solve problem ?

you have disable parts of sqlite need back upwards loading executable objects dynamically. not familiar sqlite, looking @ source configuration options, i'd start sqlite_omit_load_extension.

dos dlopen djgpp

php - Curl SSL & Connection Timeout Intermittently in Facebook Graph API -



php - Curl SSL & Connection Timeout Intermittently in Facebook Graph API -

i think problem totally different rest questions on stackoverflow. searched , googled everywhere dint find accurate solution or reason it. hope info on here.

my facebook application using facebook php sdk , apps working fine of time. give sometime few errors in general. facebook apps fails fetch user info after authentication , take much time load, working totally fine previosly. sudden alter happen every app, in between authenticate users in minor case. see in error log, throws error like: curlexception: 28: ssl connection timeout curlexception: 28: operation timed out after 60000 milliseconds 0 bytes received uncaught curlexception: 28: ssl connection timeout curlexception: 28: connect() timed out! curlexception: 7: couldn't connect host

but unusual thing is, occur @ time sudden alter automatically stop , app start working fine , normal previous after 5 - 8hrs. confused may making such problem? rate limit facebook? did nslookup, ping, curl -v, api.facebook.com , gives output too. port , firewall rules ok. please help me friends

sometimes network connections fail. remote services fail. can't think of remote service phone call on http on net 3rd party's systems fail proof. must write software expect & handle gracefully. set reasonable timeouts, failures & prepared retry few times before giving up.

php facebook facebook-graph-api curl

java ee - Passwordless authentication on glassfish -



java ee - Passwordless authentication on glassfish -

i'm developing web application using glassfish has interfaced existing php web application uses joomla cms.

i utilize glassfish security roles secure ejb's doing users prompted login when leave joomla (that's used login) glassfish.

the idea: i'd login using user's cookie/username stored within user's browser.

question: what's best way accomplish result?

the solution using servlet capture cookies , logging in user with

request.login(username, password);

more details on official javaee tutorial: http://docs.oracle.com/javaee/6/tutorial/doc/glxce.html

java-ee authentication joomla glassfish ejb

android - SurfaceView in a Box -



android - SurfaceView in a Box -

i'm struggling find tutorial help me set surfaceview in box. pointer in right direction amazing - not looking hand hold through it.

i'd able apportion area @ top of screen illustration buttons etc , have surfaceview filling rest. however, when seek modify code i've used total screen surfaceview reference xml, goes bit wrong.

my code main activity follows (i've stripped out lot of bits think aren't relevant).

package com.example.mylistviewidea; import android.os.bundle; etc... public class mainactivity extends activity implements ontouchlistener { mylistview mylistview; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); mylistview = (mylistview) findviewbyid(r.id.surfaceview1); } class mylistview extends surfaceview implements runnable { surfaceholder myholder; thread mythread = null; boolean isrunning = false; // variables long dt; int myred; public mylistview(context context) { super(context); myholder = getholder(); } @override public void run() { // todo auto-generated method stub while (isrunning) { if (!myholder.getsurface().isvalid()) continue; canvas canvas = myholder.lockcanvas(); canvas.drawargb(128, 0, 0, 0); dt = systemclock.uptimemillis(); myred = (int) ((int) 128*(1+math.sin((double) dt/1000))); } } } }

my xml is:

<relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".mainactivity" > <surfaceview android:id="@+id/surfaceview1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_alignparentleft="true" /> <button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentright="true" android:layout_alignparenttop="true" android:text="@string/add_entries" /> <button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentright="true" android:layout_below="@+id/button1" android:text="@string/remove_entries" /> </relativelayout>

the error i'm getting is:

02-08 11:44:17.885: e/androidruntime(10523): java.lang.runtimeexception: unable start activity componentinfo{com.example.mylistviewidea/com.example.mylistviewidea.mainactivity}: java.lang.classcastexception: android.view.surfaceview cannot cast com.example.mylistviewidea.mylistview

thanks in advance help!

cheers,

mike

you should have custom view , utilize in xml.

first create view

class mylistview extends surfaceview implements runnable { surfaceholder myholder; thread mythread = null; boolean isrunning = true; // variables long dt; int myred; public mylistview(context context) { super(context); init(); } public mylistview(context context, attributeset attrs) { super(context, attrs); init(); } public mylistview(context context, attributeset attrs, int defstyle) { super(context, attrs, defstyle); init(); } private void init() { myholder = getholder(); myholder.settype(surfaceholder.surface_type_push_buffers); } @override public void run() { // todo auto-generated method stub while (isrunning) { if (!myholder.getsurface().isvalid()) continue; canvas canvas = myholder.lockcanvas(); canvas.drawargb(128, 128, 0, 0); dt = systemclock.uptimemillis(); myred = (int) ((int) 128 * (1 + math.sin((double) dt / 1000))); myholder.unlockcanvasandpost(canvas); } } }

change xml this

<relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".mainactivity" > <com.example.testant.mylistview android:id="@+id/surfaceview1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_alignparentleft="true" /> <button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentright="true" android:layout_alignparenttop="true" android:text="add_entries" /> <button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentright="true" android:layout_below="@+id/button1" android:text="remove_entries" />

and alter main activity

public class mainactivity extends activity { mylistview mylistview; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); mylistview = (mylistview) findviewbyid(r.id.surfaceview1); new thread(mylistview).start(); } }

note have bug lock canvas, should work fine.

android surfaceview

html - Fluid column arrangement -



html - Fluid column arrangement -

i'm trying show checkboxes in table style, need number of columns decided based on screen's width. if allow them rearrange on own, end this:

+-----------------------------------------------------+ | | | [] label1 [] label2 [] label3 [] label 4 | | [] label5 [] label6 [] label7 | | [] label8 []label9 [] label10 []label11 | | | +-----------------------------------------------------+

and need this:

+-----------------------------------------------------+ | | | [] label1 [] label2 [] label3 [] label4 | | [] label5 [] label6 [] label7 [] label8 | | []label9 [] label10 []label11 | | | +-----------------------------------------------------+

is possible accomplish this?

i don't care if columns same width or not, need total thing fill 100% of container.

#container { width:100%; height:auto; min-height:300px; padding:10px; } #container div { width:70px; float:left; display:inline-block; }

and here fiddle

html css

Select and display Image files from ListBox, to be display within PictureBox? C# -



Select and display Image files from ListBox, to be display within PictureBox? C# -

i trying create listbox (lstfiles) selectable, it's able display image file within picturebox (picturebox1) , alter after selecting file listbox, im creating webcam programme takes pictures works, having problem with displaying images.

i have tried many ways can't work selecting filename listbox

any help grateful give thanks you

this have far:

using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.drawing.imaging; using system.runtime.interopservices; using system.text; using system.windows.forms; using pinvoke; using system.io; namespace testavicap32 { public partial class form1 : form { public form1() { initializecomponent(); initializedeviceslist(); } private void initializedeviceslist() { splitcontainer1.panel1.enabled = true; splitcontainer1.panel2.enabled = false; foreach (capturedevice device in capturedevice.getdevices()) { cbodevices.items.add(device); } if (cbodevices.items.count > 0) { cbodevices.selectedindex = 0; } } private void btnstart_click(object sender, eventargs e) { int index = cbodevices.selectedindex; if (index != -1) { splitcontainer1.panel1.enabled = false; splitcontainer1.panel2.enabled = true; ((capturedevice)cbodevices.selecteditem).attach(pbimage); } } private void btnstop_click(object sender, eventargs e) { splitcontainer1.panel1.enabled = true; splitcontainer1.panel2.enabled = false; ((capturedevice)cbodevices.selecteditem).detach(); } private void btnsnapshot_click(object sender, eventargs e) { seek { image image = ((capturedevice)cbodevices.selecteditem).capture(); image.save(@"c:\webcapture\" + datetime.now.tostring("hh.mm.ss-dd-mm-yy") + ".png", imageformat.png); } grab (exception ex) { messagebox.show(ex.tostring(), "error", messageboxbuttons.ok, messageboxicon.error); } } private void btntimer_click(object sender, eventargs e) { timer1.enabled = true; btntimerstop.visible = true; btntimer.visible = false; } private void timer1_tick(object sender, eventargs e) { image image = ((capturedevice)cbodevices.selecteditem).capture(); image.save(@"c:\webcapture\" + datetime.now.tostring("hh.mm.ss-dd-mm-yy") + ".png", imageformat.png); } private void btntimerstop_click(object sender, eventargs e) { timer1.enabled = false; btntimer.visible = true; btntimerstop.visible = false; } private void form1_load(object sender, eventargs e) { btntimerstop.visible = false; foreach (driveinfo di in driveinfo.getdrives()) lstdrive.items.add(di); } private void lstfolders_selectedindexchanged(object sender, eventargs e) { lstfiles.items.clear(); directoryinfo dir = (directoryinfo)lstfolders.selecteditem; foreach (fileinfo fi in dir.getfiles()) lstfiles.items.add(fi); } private void lstdrive_selectedindexchanged(object sender, eventargs e) { lstfolders.items.clear(); seek { driveinfo drive = (driveinfo)lstdrive.selecteditem; foreach (directoryinfo dirinfo in drive.rootdirectory.getdirectories()) lstfolders.items.add(dirinfo); } grab (exception ex) { messagebox.show(ex.message); } } private void lstfiles_selectedindexchanged(object sender, eventargs e) { } private void picturebox1_click(object sender, eventargs e) { } private void openfiledialog1_fileok(object sender, canceleventargs e) { //i don't know if need this? } } }

try below... work....

private void lstfiles_selectedindexchanged(object sender, eventargs e) { picturebox1.image = image.fromfile(((fileinfo)lstfiles.selecteditem).fullname); }

c# listbox picturebox

java ee - unknown class in native SQL using Hibernate -



java ee - unknown class in native SQL using Hibernate -

i have bean class in not mapped database table. have used createsqlquery , addentity mapping result set. error is: unknown entity. used setresultsetmapping , error unknown entity. bean class have been introduced in hibernate.cfg.xml.

thanks.

check mapping - might have reference unknown class (codetemplate).

hibernate java-ee hibernate-mapping

Single-Select Checkbox group in Monotouch.Dialog -



Single-Select Checkbox group in Monotouch.Dialog -

i using code set checkbox grouping in monotouch table , update values based on items checked:

var applescheck = new checkboxelement ("apples", false, "purchase"); var orangescheck = new checkboxelement ("oranges", false, "purchase"); var purchases = new section () { applescheck, orangescheck }; applescheck.tapped += () => { orangescheck.value = false; }; orangescheck.tapped += () => { applescheck.value = false; };

however, although update checkbox item's value, checkbox appears still stays there when items value false. there way update well?

change events following

applescheck.tapped += () => { orangescheck.value = false; orangescheck.getactivecell().accessory = uitableviewcellaccessory.none; }; orangescheck.tapped += () => { applescheck.value = false; applescheck.getactivecell().accessory = uitableviewcellaccessory.none; };

the reason checkboxelement.value field, setting has no side effect. create alter need uitableviewcell associated element , apply alter there.

monotouch monotouch.dialog

javascript - Selectively extract data from multi-level JSON object -



javascript - Selectively extract data from multi-level JSON object -

i have multi-level json object contains array of 143 other objects.

running console.log(obj) on object displays:

0: object actftes: 0.00 actual: 11111 bud_month: "october" fy_cd: 2013 mission_name: "rst" __proto__: object 1: object actftes: 0.00 actual: 10000 bud_month: "fy total" fy_cd: 2013 mission_name: "rst"

etc.... through 143 objects. however, name/value pair mission_name:"rst" prevalent in first n objects.

for example, obj 43 contains:

43: object actftes: 0.00 actual: 10000 bud_month: "fy total" fy_cd: 2013 mission_name: "vao"

i have created next function, still returns total range of 143 values name/value pair related "bud_month".

function get_dataarray() { var arr = []; var i= 0; (i=0;i<jsonobj.row.length;i++) { if (jsonobj.row[i][name]="rst") { arr[i] = jsonobj.row[i]["bud_month"]; } } console.log(arr); homecoming arr; }

this returns:

["october", "fy total", "december", "january", "february", "march", "april", "may", "june", "july", "august", "september", "fy total", "october", "november", "december", "january", "february", "march", "april", "may", "june", "july", "august", "september", "november", "october", "november", "december", "january", "february", "march", "april", "may", "june", "july", "august", "september", "fy total", "october", "fy total", "december", "january", "february", "march", "april", "may", "june", "july", "august", "september", "fy total", "october", "november", "december", "january", "february", "march", "april", "may", "june", "july", "august", "september", "november", "october", "fy total", "december", "january", "february", "march", "april", "may", "june", "july", "august", "september", "fy total", "october", "november", "december", "january", "february", "march", "april", "may", "june", "july", "august", "september", "november", "october", "fy total", "december", "january", "february", "march", "april", "may", "june"…]

does have advice how homecoming value "bud_month" in objects containing name/value pair of mission_name:"rst" ?

if (jsonobj.row[i][name]="hst") { arr[i] = jsonobj.row[i]["bud_month"]; }

should be:

if (jsonobj.row[i][name]=="rst") { arr[i] = jsonobj.row[i]["bud_month"]; }

javascript json if-statement loops

html5 - When Javascript callbacks can't be used -



html5 - When Javascript callbacks can't be used -

i know you're not supposed blocking in javascript , i've never been unable refactor away having that. i've come across don't know how handle callbacks. i'm trying utilize downloadify html2canvas (this ie only, downloading info uris doesn't work in ie). have specify info function flash object knows download. unfortunately, html2canvas asynchronous. need able wait until onrendered event filled in before can info uri.

$('#snapshot').downloadify({ filename: function(){ homecoming 'timeline.png'; }, data: function(){ var d = null; html2canvas($('#timeline'),{ onrendered:function(canvas){ d = canvas.todataurl(); } }); //need able block until d isn't null homecoming d; }, swf: '../static/bin/downloadify.swf', downloadimage: '../static/img/camera_icon_32.png?rev=1', width: 32, height: 32, transparent: true, append: false });

i'm open suggestions on other ways this, i'm stuck.

edit - couple of comments have made seem more info on downloadify needed (https://github.com/dcneiner/downloadify). downloadify flash object can used trigger browser's save window. downloadify() function putting initializing flash object , sticking <object/> tag in element. since it's flash object, can't trigger events javascript without causing security violation.

i'm using ie download image of canvas element. in other browsers, can utilize info uri, ie special flower.

for poor soul spends entire night trying html5 feature work on ie9, here's ended using. can sorta-kinda away because aren't terribly concerned ie users getting less user friendly experience , internal application. but, ymmv.

basically, downloadify nil when homecoming string blank. so, due asynchronous nature of html2canvas's rendering, first time user clicks, nil happen. sec time (assuming render done, if not nil go on happen until is), value not blank , save proceeds. utilize oncancel , oncoplete callbacks blank out value 1 time again ensure next time user tries save, image not stale.

this doesn't business relationship event user changes dom in way in between clicks, don't know can done that. i'm not @ proud of this, ie is. works, plenty now.

var renderedpng = ''; var rendering = false; $('#snapshot').downloadify({ filename: function(){ homecoming 'timeline.png'; }, data: function(){ if(!rendering && renderedpng == ''){ rendering = true; html2canvas($('#timeline'),{ onrendered:function(canvas){ renderedpng = canvas.todataurl().replace('data:image/png;base64,',''); rendering = false; } }); } homecoming renderedpng; }, oncomplete:function(){ renderedpng = ''; }, oncancel: function(){ renderedpng = ''; }, datatype: 'base64', swf: '../static/bin/downloadify.swf', downloadimage: '../static/img/camera_icon_32.png?rev=1', width: 32, height: 32, transparent: true, append: false });

javascript html5 asynchronous html2canvas downloadify

c# - 'System.Reactive.Concurrency.Scheduler.NewThread' is obsolete -



c# - 'System.Reactive.Concurrency.Scheduler.NewThread' is obsolete -

i trying retrieve info database using entity-framework 5.0 code fast , reactive extensions (rx). writing next code that.

var obs = datacontext.getdatacontext().breakdowncauses.orderby(x => x.cause).toobservable(scheduler.newthread); obs.subscribeondispatcher().subscribe(x => itemcollection.add(slow(x))); breakdowncause slow(breakdowncause cs) { system.threading.thread.sleep(500); homecoming cs; }

but show me warning :

'system.reactive.concurrency.scheduler.newthread' obsolete: 'this property no longer supported due refactoring of api surface , elimination of platform-specific dependencies. please add together reference system.reactive.platformservices assembly target platform , utilize newthreadscheduler.default obtain instance of scheduler type. see http://go.microsoft.com/fwlink/?linkid=260866 more information.'

and @ runtime exception :

the calling thread cannot access object because different thread owns it.

please suggests me how can utilize reactive extensions (rx) in ef5.0 code fast in wpf application or batter way phone call database asynchronously.

you need phone call observeondispatcher instead of subscribeondispatcher. see here.

c# .net wpf entity-framework system.reactive

python - query to hierarchical mapper -



python - query to hierarchical mapper -

i have 2 models, related many-to-many, 1 of them hierarchical model:

#hierarchical model class tag(base): __tablename__ = "tags" id = column(integer, primary_key=true) name = column(string) tag.parent_id = column(integer, foreignkey(tag.id, ondelete='cascade')) tag.childs = relationship(tag, backref=backref('parent', remote_side=[tag.id]), cascade="all, delete") class subject(base): __tablename__ = "subjects" id = column(integer, primary_key=true, doc="id") name = column(string) tags = relationship(tag, secondary="tags_subjects", backref="subjects") #many-to-many relations model class tagssubjects(base): __tablename__ = "tags_subjects" id = column(integer, primary_key=true) tag_id = column(integer, foreignkey("tags.id")) subject_id = column(integer, foreignkey("subjects.id"))

so, i'll seek explain want do... want create 1 (or several) query, search subject's objects, have 'name' field value 'foo' or has related tags having names values 'foo' or has related tags, has 1 or more parents (or above hierarchy) tag 'name' value 'foo'

i've tried somethis this:

>>> subjects = session.query(subject).filter(or_( subject.name.ilike('%{0}%'.format('foo')), subject.tags.any( tag.name.ilike('%{0}%'.format('foo'))) )).order_by(subject.name).all()

but isn't right , "flat" query, without hierarchical feature :( how sqlalchemy's api? thanks!

p.s. i'm using sqlite backend

python sqlalchemy