Sunday, 15 January 2012

java - How to expand entries in a TableViewer -



java - How to expand entries in a TableViewer -

i created eclipse plugin simple hashtable:

private hashtable<string, packageobject> _packagetabelle;

i filled table

_packagetabelle.put(packageid,new packageobject(packageid, stageid));

the result table entries. display colum in tableviewer.

for example:

package id: stageid: 1 10 2 20 3 30 4 40 5 50

now want expand column clicking in front end of it. result should this:

package id: stageid: 1 10 --> bundle id def stageiddef 3 7 bla bla 2 20 3 30 4 40 5 50

does have idea?

the "_viewer" tableview.

_viewer = new tableviewer(parent, swt.multi | swt.h_scroll | swt.v_scroll | swt.full_selection); _viewer.setcontentprovider(new viewcontentprovider()); _viewer.setlabelprovider(new viewlabelprovider()); _viewer.setsorter(new namesorter()); _viewer.setinput(packagetabelle.getinstance().getpackageobjects()); table table = _viewer.gettable(); table.setheadervisible(true); table.setlinesvisible(true); table.getverticalbar().setvisible(true); // tabellenstruktur aufbauen tablecolumn column = new tablecolumn(table, swt.left); column.settext("package"); column.setwidth(100); column.addselectionlistener(new columnsortlistener(1, _viewer)); column = new tablecolumn(table, swt.center); column.settext("stage"); column.setwidth(100); column.addselectionlistener(new columnsortlistener(2, _viewer)); column = new tablecolumn(table, swt.left); column.settext("beschreibung"); column.setwidth(400); column.addselectionlistener(new columnsortlistener(3, _viewer));

java tableview hashtable

php version upgrade from 5.3 to 5.4.x which creates issue in login validation -



php version upgrade from 5.3 to 5.4.x which creates issue in login validation -

this code gives me fatal error: phone call undefined function session_register() after php version upgrade please 1 help me in matter $host="localhost"; // host name $username=""; // mysql username $password=""; // mysql password $db_name=""; // database name $tbl_name=""; // table name // connect server , select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select db"); // username , password sent form $myusername=$_post['myusername']; $mypassword=$_post['mypassword']; // protect mysql injection (more detail mysql injection) $myusername = stripslashes($myusername); $mypassword = stripslashes($mypassword); $myusername = mysql_real_escape_string($myusername); $mypassword = mysql_real_escape_string($mypassword); $sql="select * $tbl_name username='$myusername' , password='$mypassword'"; $result=mysql_query($sql); // mysql_num_row counting table row $count=mysql_num_rows($result); // if result matched $myusername , $mypassword, table row must 1 row if($count==1){ // register $myusername, $mypassword , redirect file "login_success.php" session_register("myusername"); session_register("mypassword"); header("location:operator.php"); } else { header("location: http://"); } ?>

this code every target page operator.php fatal error: phone call undefined function session_register()

<?php session_start(); if(!session_register(myusername)){ header("location:login.html"); }

change:

session_register("myusername");

to:

$_session["myusername"] = $myusername;

and other calls.

php validation login

java - PostPersist setting the transeint field to null -



java - PostPersist setting the transeint field to null -

i have entity contain transient fields used after persisting of entity. problem when post persist called these fields turned null. normal in jpa? if ,how can allow fields remain not null?

java jpa eclipselink

javascript - Add "http" to embedded Vimeo iframe -



javascript - Add "http" to embedded Vimeo iframe -

i'm using vimeo's oembed api replace the thumbnail embedded video on click.

the src attribute in embedded <iframe> html doesn't contain "http". instead, it's rendered src="//player.vimeo.com/video/00000000". prevents video loading.

do have update url automatically? after going through vimeo faq, seems issue http / https.

how can work around this?

var src= ('https:' == document.location.protocol ? 'https://' : 'http://') +'//player.vimeo.com/video/00000000'

javascript jquery iframe

sql - Composite primary key with foreign keys out to different tables -



sql - Composite primary key with foreign keys out to different tables -

sql 2008 r2. have 3 tables.

**person** personid int **address** addressid int address varchar **personaddress** personid int primary key references person.personid addressid int primary key references address.addressid

i have read when there composite primary key, reference should include both columns. , yet, works me. management studio not throw error , can insert rows these tables without duplicates , adhering constraints.

is practise?

the fk should/must reference key columns of referenced table. personaddress doing 2 times.

sql sql-server tsql

php - Continuing through loop without having to wait foreach file to load -



php - Continuing through loop without having to wait foreach file to load -

i'm using for loop speed script. problem each process happens within of loop takes several minutes load. possible move on next sequence in loop if previous 1 hasn't completed? know php isn't multi-threaded language, perhaps python improve choice.

ini_set('memory_limit', '2048m'); ini_set('max_execution_time', 0); $list = file_get_contents('auth.txt'); $list = nl2br($list); $exp = explode('<br />', $list); $count = count($exp); for($i=0;$i<$count;$i++) { $auth = $exp[$i]; echo 'trying '.$auth.' \n'; // takes several minutes. possible move on next 1 before has completed? exec('python test.py --auth='.$auth); }

use & run script in background:

exec('python test.py --auth='.$auth . ' > /dev/null 2>&1 &');

php loops

javascript - Count characters of input and increment a variable after x characters -



javascript - Count characters of input and increment a variable after x characters -

i adding angularjs project , need count length of textarea, incrementing total number of "pages" (messaging app) every 160 characters - , decrementing if text deleted.

getting length of textarea angular simple:

<textarea ng-model="message" class="form-control" name="message" id="message" cols="30" rows="2"></textarea> <span class="help-block"><strong>characters</strong>: <% message.length > 0 ? message.length : 0 %></span>

i'm guessing best place handle logic determine number of pages in javascript code cannot figure out how link ng-model code. help appreciated.

there's no need ng-change, can in dom directly:

<textarea ng-model="message" class="form-control" name="message" id="message" cols="30" rows="2"></textarea> <span class="help-block"><strong>characters</strong>: {{ (message.length - message.length % 160) / 160 + 1 }}</span>

jsfiddle: http://jsfiddle.net/eemd3/

edit

to include other details simple add together them in calculation:

{{ (message.length - message.length % 160 + user.name + agency.nickname + ...) / 160 + 1 }}

javascript angularjs

How do you place an item behind another item in android? -



How do you place an item behind another item in android? -

i'd place imageview behind imagebutton. what's best way go doing this?

i believe easiest way wrap both imageview , imagebutton in framelayout. eg:

<framelayout android:layout_width="match_parent" android:layout_height="wrap_content" > <imageview android:layout_width="match_parent" android:layout_height="match_parent" android:src="@drawable/your_image" /> <imagebutton android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" /> </framelayout>

android

plsql - PLS-00103: Encountered the symbol “CREATE” -



plsql - PLS-00103: Encountered the symbol “CREATE” -

its showing error in 27 line create or replace function buffalo

declare random_number number(4); user_number number(4); cow number(1); buffaloes number(1):=0; begin random_number:=uniquetest(random_number); /*random_number:=dbms_random.value(1000,9999);*/ dbms_output.put_line(random_number); user_number:=&user_number; while(user_number!=random_number) loop buffaloes:=buffalo(user_number,random_number); dbms_output.put_line('0'||'c'||buffaloes||'b'); buffaloes:=0; user_number:=0; user_number:=&user_number; end loop; end; /*error in line */ create or replace function buffalo (user_number in number,random_number in number) homecoming number user_comparision number(1); random_comparision number(1); buffaloes number(1); user_number1 number(4):=user_number; random_number1 number(4):=random_number; begin while(user_number!=random_number) loop user_comparision:=user_number1 mod 10; random_comparision:=random_number1 mod 10; user_number1:=user_number1/10; random_number1:=random_number1/10; if(user_comparision = random_comparision) buffaloes:=buffaloes+1; end if; end loop; homecoming buffaloes; end;/

it showing error in create statement. can help me in solving error.

tell how solve create statement error.

it showing error in create statement. can help me in solving error.

tell how solve create statement error.

you should create 2 scripts of it. you're starting off anonymous block, calling function buffalo, while hasn't been created yet.

both anonymous block , function seem creating infinite loop way, i'm not sure you're trying accomplish here.. without knowing background of problem it's impossible give solution.

plsql

ios - How to get JSON out of AFNetworing 2.0 GET Method -



ios - How to get JSON out of AFNetworing 2.0 GET Method -

i using afnetworking create bunch of api calls @ 1 time instagram. using afnetworking 2.0 afhttpsessionmanager request.

i using loop create url requires location id searching. loop makes in case 3 separate api calls , stores each response in array.

i create mutable array store objects in array. need mutable array 1 time has 3 objects in it. have tried passing info method, same problem - can't utilize array until previous method done running.

-(void)sendgetrequestforlocationmedia:(nsmutablearray*)mutablearray{ (int = 0; i<3; i++) { nsstring *getlocationmediastring = [[nsstring alloc]initwithformat:@"locations/%@/media/recent?client_id=%@", self.locationidobjectarray[i], client_id]; nslog(@"getlocationmediastring %@", getlocationmediastring); [[lpauthclient sharedclient]get:getlocationmediastring parameters:nil success:^(nsurlsessiondatatask *task, id responseobject) { { nshttpurlresponse *httpresponse = (nshttpurlresponse *)task.response; if (httpresponse.statuscode == 200) { dispatch_async(dispatch_get_main_queue(), ^{ _locationmediaarray = responseobject[@"data"]; if (!_locationmediajsonarray) { _locationmediajsonarray = [[nsmutablearray alloc]init]; } (nsdictionary *dictionary in _locationmediaarray) { [_locationmediajsonarray addobject:dictionary]; } }); } } } failure:^(nsurlsessiondatatask *task, nserror *error) { nslog(@"failure %@", error); }]; } }

ios arrays json afnetworking-2

r - How to use or/and in dplyr to subset a data.frame -



r - How to use or/and in dplyr to subset a data.frame -

i subset data.frame combination of or/and. code using normal r function.

df <- expand.grid(list(a = seq(1, 5), b = seq(1, 5), c = seq(1, 5))) df$value <- seq(1, nrow(df)) df[(df$a == 1 & df$b == 3) | (df$a == 3 & df$b == 2),]

how convert them using filter function in dplyr package? suggestions.

dplyr solution:

load library:

library(dplyr)

filter status above:

df %>% filter(a == 1 & b == 3 | == 3 & b ==2)

r dplyr

Node.js w/ fibers eat all RAM when fibers are created in a tight loop -



Node.js w/ fibers eat all RAM when fibers are created in a tight loop -

the next program, when run, progressively eats ram:

var fiber = require('fibers'); function f() { console.log('in fiber'); } (;;) { var fiber = new fiber(f); fiber.run(); }

apparently, fibers created never garbage-collected. how can create sure past fibers deallocated in timely fashion?

node.js node-fibers

Unable to shutdown mongodb server - unexpected error: "shutdownServer failed: unauthorized" at src/mongo/shell/assert.js:7 -



Unable to shutdown mongodb server - unexpected error: "shutdownServer failed: unauthorized" at src/mongo/shell/assert.js:7 -

i trying shutdown 1 of mongodb instance in 3 node replica set. config file has auth set 1. have admin business relationship has useradminanydatabase role , logged admin database account. when run db.shutdownserver() next error

db.shutdownserver() assert failed : unexpected error: "shutdownserver failed: unauthorized" error: printing stack trace @ printstacktrace (src/mongo/shell/utils.js:37:15) @ doassert (src/mongo/shell/assert.js:6:5) @ assert (src/mongo/shell/assert.js:14:5) @ db.shutdownserver (src/mongo/shell/db.js:346:9) @ (shell):1:4 mon jun 23 12:52:51.839 assert failed : unexpected error: "shutdownserver failed: unauthorized" @ src/mongo/shell/assert.js:7

i created user has both dbadminanydatabase , useradminanydatabase roles , gets same error.

can help me error?

if running mongodb 2.4 user clusteradmin role needed run db.shutdownserver(). total list of user roles mongodb 2.4 available here: http://docs.mongodb.org/v2.4/reference/user-privileges/

if on mongodb 2.6 utilize hostmanager role instead. see next page 2.6 roles: http://docs.mongodb.org/manual/reference/built-in-roles/

mongodb shutdown

Create working copy from git bare repository -



Create working copy from git bare repository -

i understood, bare repository sharing among different developers or machines. possible create working re-create bare repository, e.g. new developer joins project?

the point of bare repository there no working re-create -- makes things pushing easier. every developer clones repository, pulls changes , pushes alter there.

the whole point of systems git developers don't share single resource on disk, rather can modify personal copies @ , still share changes each other.

git

c# - How to assign value to custom field on AddItem -



c# - How to assign value to custom field on AddItem -

i have custom field written in c#. custom field inherits spfieldtext. work well, until want add together info splist , assign value on powershell.

my ps code:

... $newitem = $splist.additem() ... $newitem["customfield"] = $value --> error $newitem.update() object reference not set instance of object. + $newitem["customfield"] = $value + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + categoryinfo : operationstopped: (:) [], nullreferenceexception + fullyqualifiederrorid : system.nullreferenceexception

all other (native) column types work well, can´t assign custom field type. checked if column present. is.

$newitem.fields.containsfield["customfield"] returns true.

then checked xmlscheme , custom inherited field there.

could please suggest option, how handle - assign value custom fields?

c# list powershell sharepoint sharepoint-2013

jboss - WildFly - Files\Java\jdk1.7.0_40"" was unexpected at this time -



jboss - WildFly - Files\Java\jdk1.7.0_40"" was unexpected at this time -

i'm trying start wildfly 8 custom start.bat file calls standalone.bat , custom property file. when run start.bat error in command line:

c:\pwserver8>propworks_start.bat c:\pwserver8\bin>call standalone.bat -p=../propworks/conf/propworks.properties -b 10.10.100.122 calling "c:\pwserver8\bin\standalone.conf.bat" files\java\jdk1.7.0_40"" unexpected @ time.

i've done search "was unexpected @ time" within files in wildfly folder nil turned couldn't pinpoint error coming from. here custom start.bat , afterwards property file. if knows what's going on big help.

propworks_start.bat

c: cd c:\pwserver8\bin set java_home="c:\program files\java\jdk1.7.0_40" phone call standalone.bat -p=../propworks/conf/propworks.properties -b 10.10.100.122

propworks.properties

#propworks configuration properties #wed jun 18 17:18:03 edt 2014 propworks.bind.address=10.10.100.122 propworks.database.class=oracle10g propworks.database.connection.sql=select 1 dual propworks.database.desc=support@mcosrvorcl001 propworks.database.dialect=com.airit.propworks.server.dialect.pworacledialect propworks.database.driver=oracle propworks.database.password=-5522f65bbe2cc1c6 propworks.database.schema=uc2014 propworks.database.url=jdbc\:oracle\:thin\:@10.10.201.10\:1521\:bsdev propworks.database.user=uc2014 propworks.http.port=8080 propworks.indb.use=none propworks.jdk.home=c\:\\program files\\java\\jdk1.7.0_40 propworks.messaging.port=5445 propworks.remoting.port=4447 archiver.enabled=n orafin.database.driver=oracle orafin.database.password= orafin.database.user= org.quartz.datasource.quartz.jndiurl=java\:/propworksds org.quartz.datasource.quartz_no_tx.jndiurl=java\:/quartzds org.quartz.jobstore.class=org.quartz.impl.jdbcjobstore.jobstorecmt org.quartz.jobstore.datasource=quartz org.quartz.jobstore.driverdelegateclass=org.quartz.impl.jdbcjobstore.stdjdbcdelegate org.quartz.jobstore.nonmanagedtxdatasource=quartz_no_tx org.quartz.jobstore.selectwithlocksql=select * {0}locks lock_name \= ? update org.quartz.jobstore.tableprefix=qrtz_ org.quartz.scheduler.instancename=defaultquartzscheduler org.quartz.scheduler.rmi.export=false org.quartz.scheduler.rmi.proxy=false org.quartz.scheduler.xatransacted=false org.quartz.threadpool.class=org.quartz.simpl.simplethreadpool org.quartz.threadpool.threadcount=3 org.quartz.threadpool.threadpriority=9 psfin.database.driver=oracle psfin.database.password= psfin.database.user= pwarchiver.database.driver=oracle pwarchiver.database.password= pwarchiver.database.user=

two solutions:

1) move java folder not have spaces in it. 2) double quote path when set

set java_home=""c:\program files\java\jdk1.7.0_40""

jboss jboss7.x wildfly wildfly-8

parsing - Java DateTime parse -



parsing - Java DateTime parse -

i have next code parse date , time format

simpledateformat sdfclient = new simpledateformat("yyyymmddhhmmss.s"); simpledateformat sdfformat = new simpledateformat("dd/mm/yyyy hh:mm:ss"); pmlist.add(sdfclient.format(sdfformat.parse(pmdata[k].retrievaltime)));

wanna alter format sdfclient reason eclipse throws error:

java.text.parseexception: unparseable date: "20140623135000.0" @ java.text.dateformat.parse(dateformat.java:357) @ com.syntronic.client.generatecsv.writepmdata(generatecsv.java:220) @ com.syntronic.client.generatecsv.writemedata(generatecsv.java:187) @ com.syntronic.client.generatecsv.<init>(generatecsv.java:87) @ com.syntronic.client.client.main(client.java:213)

anyone knows reason why?

it should other way around:

pmlist.add(sdfformat.format(sdfclient.parse(pmdata[k].retrievaltime)));

explanation:

pmlist.add( sdfformat.format( <-- gives string 23/06/2014 01:50:00 sdfclient.parse( <-- gives date corresponding time 20140623135000.0 pmdata[k].retrievaltime <-- time 20140623135000.0 ) ) );

java parsing date time

java - JSONP executes error block while making an ajax call during page load even though the status is 200 OK -



java - JSONP executes error block while making an ajax call during page load even though the status is 200 OK -

during page load jsonp executes error block while making ajax phone call though status 200 ok , error text "parseerror". same ajax phone call executes success block when called on click event ui.

$.ajax({ crossdomain : true, type : "get", contenttype : "application/json; charset=utf-8", datatype : "jsonp", jsonpcallback : 'success', url : "rest/getrecommendation", cache: false, timeout : 15000, : function(data) { }, error : function(responsedata, textstatus, errorthrown) {

java jquery

Save custom objects when activty stops on Android -



Save custom objects when activty stops on Android -

i've written little andorid app. app uses vector of custom objects , displays them in listview. want save objects when activity send background. best way this. in vector 25 objects. every object has boolean, 2 long, , 2 strings.

thanks help

do need them saved when app shuts downwards or when activity goes background?

if objects parcelables utilize save , restore instance state methods:

@override protected void onsaveinstancestate(bundle outstate) { super.onsaveinstancestate(outstate); outstate.putparcelablearraylist("objectsarray", myobjects); // if array of parceleble objects } @override protected void onrestoreinstancestate(bundle savedinstancestate) { super.onrestoreinstancestate(savedinstancestate); myobjects= savedinstancestate.getparcelablearraylist("objectsarray"); }

here illustration of parcelable object

public class knusersketch implements parcelable{

public int id; public int user; public string url; public int views; public int locations; public knusersketch(jsonobject obj) { id = knsafejsonutilties.safegetinteger(obj, "id"); user = knsafejsonutilties.safegetinteger(obj, "user"); views = knsafejsonutilties.safegetinteger(obj, "views"); locations = knsafejsonutilties.safegetinteger(obj, "locations"); url = knsafejsonutilties.safegetstring(obj, "url"); log.v("json","jsonobject: "+obj.tostring()); url.replace("https:", "http:"); } public knusersketch(){ id=-1; user=-1; views = 0; url =""; } public knusersketch(parcel p){ id= p.readint(); user = p.readint(); url = p.readstring(); views = p.readint(); locations = p.readint(); } @override public int describecontents() { // todo auto-generated method stub homecoming 0; } @override public void writetoparcel(parcel dest, int flags) { // todo auto-generated method stub dest.writeint(id); dest.writeint(user); dest.writestring(url); dest.writeint(views); dest.writeint(locations); } public static final parcelable.creator<knusersketch> creator = new creator<knusersketch>() { public knusersketch createfromparcel(parcel source) { homecoming new knusersketch(source); } public knusersketch[] newarray(int size) { homecoming new knusersketch[size]; } };

}

android android-activity storage

java - How to write the result of a rule, into a model (in Jena)? -



java - How to write the result of a rule, into a model (in Jena)? -

i working on project need create rules using jena freamwork.

i have created rules , work should. can see output on screen storing result model of ontology have.

i have code :

@prefix ex: <http://www.semanticweb.org/prova_rules_m#> . @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . @prefix xsd: <http://www.w3.org/2001/xmlschema#> . @include <owl> [pippo: (?p http://www.semanticweb.org/prova_rules_m#anni_persona ?x) <- (?p rdf:type ex:persona) (?p http://www.semanticweb.org/prova_rules_m/persona#data_nascita ?c) mydiffdateyear(?c,"2014-06-18t00:00:00.0"^^xsd:datetime,?x) ]

in illustration using custom built-in have created previously. returns number of years of difference between 2 dates. can see output in screen next code :

string percorsofile ="./prova_rules_m_rdf.owl"; string rulefile= "./prova_rules_m_rdf_7_diffdate.txt"; model rawmodel = modelfactory.createdefaultmodel(); //create resource (empty model) resource configuration = rawmodel.createresource(); // set engine mode configuration.addproperty(reasonervocabulary.proprulemode, "hybrid"); // set rules file configuration.addproperty(reasonervocabulary.propruleset, rulefile); list<rule> rules = rule.rulesfromurl(rulefile); genericrulereasoner reasonerrule = (genericrulereasoner) genericrulereasonerfactory.theinstance().create(configuration); reasonerrule.setrules(rules); model modelrule= filemanager.get().loadmodel(percorsofile); //create inference model infmodel infmodelrule = modelfactory.createinfmodel(reasonerrule, modelrule); //force starting rule execution infmodelrule.prepare(); //write downwards result in rdfxml form infmodelrule.write(system.out);

how can write result of info property "anni_persona" within model (and not output) ?

thank you.

the way backwards chaining inference rule works when associated model (in case, infmodelrule), inferred tripled available when attempts read model.

for example, if asked if infmodelrule.contains(...) triple know inferred , see in output, you'll true result. model doesn't need separate step 'write' result.

if write model disk instead of standard out (psudocode):

try( final fileoutputstream out = new fileoutputstream(new file("blah.rdf")) ){ infmodelrule.write(out); }

... you'll see triples inferred there well. if later read file model without reasoner attached, triples remain.

java jena rules ontology protege

c# - How to ignore nested enums from mapping -



c# - How to ignore nested enums from mapping -

i have several reference entities nested enums convenience. example:

public class statusa { public enum values { active = 1, inactive = 2, inprogress = 3 } } public class statusb { public enum values { sent = 1, accepted = 2, expired = 3 } } public class entitya { public statusa.values status {get; set;} } public class entityb { public statusb.values status {get; set;} }

i'm getting next exception @ time of model configuration: the type 'statusa+values' , type 'statusb+values' both have same simple name of 'values' , cannot used in same model. types in given model must have unique simple names. utilize 'notmappedattribute' or phone call ignore in code first fluent api explicitly exclude property or type model.

trying prepare found out notmappedattribute not applicable enums. tried fluent api .ignore<t> (which requires ref type, not enum) , .ignore(ienumerable<type>), no luck. google search not helpful.

is there other way exclude enums model?

you should enumeration type in model if include property of type. if that, there cannot way of ignoring type, without ignoring property. , testing shows ignoring property sufficient ignore type.

here's minimal finish test programme exception you're getting:

using system.data.entity; using system.data.entity.infrastructure; public class { public int id { get; set; } public e p { get; set; } // #1 public enum e { } } public class b { public int id { get; set; } public e p { get; set; } // #2 public enum e { } } static class programme { static void main() { var modelbuilder = new dbmodelbuilder(dbmodelbuilderversion.latest); modelbuilder.entity<a>(); modelbuilder.entity<b>(); var model = modelbuilder.build(new dbproviderinfo("system.data.sqlclient", "2012")); } }

it should obvious long #1 , #2 both part of model, cannot avoid mapping enumeration types. , if remove either #1 or #2 (or both), or mark them notmapped attribute, see no longer exception you're getting now.

you may able avoid renaming enumeration type if can avoid mapping property of type, so:

public class { public int id { get; set; } public int pasint { get; set; } [notmapped] public e p { { homecoming (e) pasint; } set { pasint = (int) value; } } public enum e { } }

this old approach required when ef didn't back upwards enumeration types @ all. unfortunately, approach mean query context.as.where(a => a.p == e.c) won't work, because model doesn't know p property. need written context.as.where(a => a.pasint == (int)e.c). depending on needs, may enough, though.

c# entity-framework ef-code-first entity-framework-6 ef-fluent-api

jquery - Removing div rows which have same class identifiers dynamically -



jquery - Removing div rows which have same class identifiers dynamically -

i'm trying remove div row clicking delete problem rows have same class name don't know how individually remove rows.

<div class="divtable"> <div class="divtablerow"> <div class="divtablecell"> row 1 </div> <div class="divtablecell"> <span class="delete-size-row">delete</span> </div> </div> <div class="divtablerow"> <div class="divtablecell"> row 2 </div> <div class="divtablecell"> <span class="delete-size-row">delete</span> </div> </div> </div>

i can has unique identifiers won't work me. need dynamic solution.

$(".delete-size-row").click(function() { $('#removerow-unique').hide(); });

you can utilize .closest() find parent div class divtablerow can hide it.

code

$(".delete-size-row").click(function () { $(this).closest('.divtablerow').hide(); });

in event handler this refers element invoked event handler.

jquery html

android - Fatal Exception AsyncTask doInBackground -



android - Fatal Exception AsyncTask doInBackground -

this main activity code when run code says unfortunately programme has stopped working .. in logcatit says: error occurred executing doinbackground()..

please help asap.

and echoed recieved json values , fetched , added array list.. guys it's frustrating not beingness able figure out please again

import java.util.arraylist; import java.util.hashmap; import java.util.list; import org.apache.http.namevaluepair; import org.apache.http.message.basicnamevaluepair; import org.json.jsonarray; import org.json.jsonexception; import org.json.jsonobject; import android.app.activity; import android.app.fragment; import android.app.progressdialog; import android.content.context; import android.os.asynctask; import android.os.bundle; import android.support.v4.util.arraymap; import android.util.log; import android.view.layoutinflater; import android.view.menu; import android.view.menuitem; import android.view.view; import android.view.viewgroup; import android.widget.adapterview; import android.widget.adapterview.onitemclicklistener; import android.widget.listview; import android.widget.toast; public class mainactivity extends activity { private static final string url="http://10.0.3.2/other"; static string title = "username"; static string desciption = "password"; @override protected void oncreate(bundle savedinstancestate) { // todo auto-generated method stub super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); new getdata().execute(); } @override public boolean oncreateoptionsmenu(menu menu) { // todo auto-generated method stub homecoming super.oncreateoptionsmenu(menu); } private class getdata extends asynctask<string, void, void>{ progressdialog pdialog; jsonparser jsp=new jsonparser(); jsonobject job; arraylist<hashmap<string, string>> arraylist; customadapter adapter; @override protected void onpreexecute() { // todo auto-generated method stub super.onpreexecute(); pdialog=new progressdialog(mainactivity.this); pdialog.setindeterminate(false); pdialog.settitle("please wait"); pdialog.setmessage("loading"); pdialog.show(); } @override protected void doinbackground(string... params) { // todo auto-generated method stub list<namevaluepair> param = new arraylist<namevaluepair>(); param.add(new basicnamevaluepair("tag", "all")); job= jsp.getjsonfromurl(url, param); try{ jsonarray jarr= job.getjsonarray("names"); (int = 0; < jarr.length(); i++) { hashmap<string, string> map = new hashmap<string, string>(); job = jarr.getjsonobject(i); // retrive json objects map.put("username", job.getstring("username")); map.put("password", job.getstring("password")); log.e("jsob", job.tostring()); // set json objects array arraylist.add(map); } } catch(jsonexception e){ e.printstacktrace(); } homecoming null; } @override protected void onpostexecute(void result) { // todo auto-generated method stub super.onpostexecute(result); listview lv= (listview) findviewbyid(r.id.list); adapter = new customadapter(mainactivity.this, arraylist); lv.setadapter(adapter); pdialog.dismiss(); } } }

you not initializing arraylist.

android android-asynctask

asp.net mvc - ActionFilterAttribute mvc need to call One time -



asp.net mvc - ActionFilterAttribute mvc need to call One time -

i have scenario need check security each menu item if user 'a' allowed access menu or not , reason created class inherited actionfilterattribute

public class securityfilter : actionfilterattribute { public override void onactionexecuting(actionexecutingcontext filtercontext) { log("onactionexecuting", filtercontext.routedata); } }

and using class on controller

[securityfilter] public class xyzcontroller : controller { public actionresult index() { homecoming view(); } }

now problem in view have @html.action() calls e.g

@html.action("com")

which results in calling onactionexecuting method again, want phone call 1 time when menu link clicked , method menu redirecting not other action method render within view

when called using @html.action ischildaction property of filtercontext true. can rely on determine whether want or not:

public override void onactionexecuting(actionexecutingcontext filtercontext) { if (filtercontext.ischildaction) return; log("onactionexecuting", filtercontext.routedata); }

see msdn

asp.net-mvc asp.net-mvc-4 action action-filter actionfilterattribute

Getting R Plots into a Separate Non-R Window -



Getting R Plots into a Separate Non-R Window -

is there way r plots pop-up in separate window outside of rgui?

x11() in rstudio not in rgui.

thanks

if run cairo device cairodevice bundle graph shows in separate window (at to the lowest degree test on windows did).

if run rgui (on windows) in sdi mode instead of mdi mode standard graphics device different window command line (but scripts, help, etc. well).

the tkrplot bundle has tools creating graphs in separate tk window.

you send graph file, utilize shell.exec open viewer graphics file in separate window.

there may other ways well.

r plot window

Ruby on Rails, Michael Hartl Ch. 2 -



Ruby on Rails, Michael Hartl Ch. 2 -

i'm new in rails, i'm next tutorials michael hartl. i'm stuck on chapter 2 problem begins section 2.2

i generate users scaffold instructed in text, , utilize rake db:migrate apply migrations database. attempting view users after starting server gives me error:

execjs::runtimeerror in users#index showing c:/sites/rails_projects/demo_app/app/views/layouts/application.html.erb line #6 raised: (in c:/railsinstaller3.0/ruby2.0.0/lib/ruby/gems/2.0.0/gems/turbolinks-1.1.1/lib/assets/javascripts/turbolinks.js.coffee) extracted source (around line #6): 3 4 5 6 7 8 9 <head> <title>demoapp</title> <%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %> <%= javascript_include_tag "application", "data-turbolinks-track" => true %> <%= csrf_meta_tags %> </head> <body> rails.root: c:/sites/rails_projects/demo_app application trace | framework trace | total trace app/views/layouts/application.html.erb:6:in `_app_views_layouts_application_html_erb___308270545_35424396'

it same thing if effort view of other pages michael's tutorial instructs. i'm not sure begin trying debug this. help appreciated.

git repository here: https://github.com/tritonis/demo_app

i've stumbled problem before. installing therubyracer gem fixed me.

in gemfile, add: gem 'therubyracer', platforms: :ruby

then, in terminal, execute: bundle install , restart server. problem should fixed.

hope helped!

ruby-on-rails ruby ruby-on-rails-3 railstutorial.org

javascript - Add and Remove div using jquery does not work -



javascript - Add and Remove div using jquery does not work -

i using simple script add together , remove div using jquery. doesn't work. there need include files?? can help me.

here code

<html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script language="javascript"> $(function() { var scntdiv = $('#p_scents'); var = $('#p_scents p').size() + 1; $('#addscnt').live('click', function() { $('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + +'" value="" placeholder="input value" /></label> <a href="#" id="remscnt">remove</a></p>').appendto(scntdiv); i++; homecoming false; }); $('#remscnt').live('click', function() { if( > 2 ) { $(this).parents('p').remove(); i--; } homecoming false; }); }); </script> </head> <body> <h2><a href="#" id="addscnt">add input box</a></h2> <div id="p_scents"> <p> <label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="input value" /></label> </p> </div> </body> </html>

i've refactored code bit next html:

<body> <h2><a href="#" id="addscnt">add input box</a></h2> <div id="p_scents"> <p> <input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="input value" /> </p> </div> </body>

and next javascript:

$(function() { var scntdiv = $('#p_scents'); var = $('#p_scents p').size(); $("#addscnt").on("click",function(){ i++; $('<p><input type="text" id="p_scnt'+i+'" size="20" name="p_scnt_' + +'" value="" placeholder="input value" ><a href="#" class="remscnt">remove</a></p>').appendto(scntdiv); }); $("#p_scents").on("click",".remscnt", function(){ // items need deleted encapsulated within parent item. can utilize parent() remove everything. $(this).parent().remove(); i--; }); });

you can see working illustration here: http://jsfiddle.net/u7qwa/36/

javascript jquery

java - JTextPane autoscroll works only one time -



java - JTextPane autoscroll works only one time -

i have 2 jtextpane , set them autoscroll vertically, reason don't undertstand 1 working.

what reason?

jtextpane texta = new jtextpane(); texta.setname(text); texta.setcontenttype("text/html"); defaultcaret caret = (defaultcaret)texta.getcaret(); caret.setupdatepolicy(defaultcaret.always_update); jscrollpane filler = new jscrollpane (texta, jscrollpane.vertical_scrollbar_always, jscrollpane.horizontal_scrollbar_never); jtextpane textb = new jtextpane(); textb.setname(text + "_t"); textb.setfont(texta.getfont()); defaultcaret caret_t = (defaultcaret)textb.getcaret(); caret_t.setupdatepolicy(defaultcaret.always_update); jscrollpane filler_t = new jscrollpane (textb, jscrollpane.vertical_scrollbar_always, jscrollpane.horizontal_scrollbar_never); panel.add(filler); panel.add(filler_t);

filler_t (textb) 1 working

you have not used layout panel. jscrollpane filler_t placed on jscrollpane filler , jtextpane texta not visible.

use layout, illustration add together lines in code:

panel.setlayout(new borderlayout(0, 0)); panel.add(filler,borderlayout.north); panel.add(filler_t,borderlayout.center);

your window like:

full running code:

import java.awt.borderlayout; import java.awt.eventqueue; import javax.swing.jframe; import javax.swing.jpanel; import javax.swing.jscrollpane; import javax.swing.jtextpane; import javax.swing.border.emptyborder; import javax.swing.text.defaultcaret; public class testscroll extends jframe { private jpanel panel; public static void main(string[] args) { eventqueue.invokelater(new runnable() { public void run() { seek { testscroll frame = new testscroll(); frame.setvisible(true); } grab (exception e) { e.printstacktrace(); } } }); } public testscroll() { setdefaultcloseoperation(jframe.exit_on_close); panel = new jpanel(); panel.setborder(new emptyborder(5, 5, 5, 5)); panel.setlayout(new borderlayout(0, 0)); setcontentpane(panel); jtextpane texta = new jtextpane(); texta.setname("text"); texta.setcontenttype("text/html"); defaultcaret caret = (defaultcaret)texta.getcaret(); caret.setupdatepolicy(defaultcaret.always_update); jscrollpane filler = new jscrollpane (texta, jscrollpane.vertical_scrollbar_always, jscrollpane.horizontal_scrollbar_never); jtextpane textb = new jtextpane(); textb.setname("text" + "_t"); textb.setfont(texta.getfont()); defaultcaret caret_t = (defaultcaret)textb.getcaret(); caret_t.setupdatepolicy(defaultcaret.always_update); jscrollpane filler_t = new jscrollpane (textb, jscrollpane.vertical_scrollbar_always, jscrollpane.horizontal_scrollbar_never); panel.add(filler,borderlayout.north); panel.add(filler_t,borderlayout.center); pack(); } }

also improve understanding read layoutmanagers

java swing jscrollpane jtextpane autoscroll

c# - The filename, directory name, or volume label syntax is incorrect. (Exception from HRESULT: 0x8007007B) -



c# - The filename, directory name, or volume label syntax is incorrect. (Exception from HRESULT: 0x8007007B) -

i'm receiving error when code path, dont understand whe happend, think im doing right.

code:

string newuri = imagegalleryuri.replace("ms-appdatalocal/", ""); //replace part of string nonspace character. newuri = newuri.replace("/", "\\"); newuri = newuri.replace("%20", " "); //replace ascii code space actual space. reason i'm getting invalid character error %20. storagefolder folder = windows.storage.applicationdata.current.localfolder; storagefile storagefile = await folder.getfileasync(newuri); datapackage dp = new datapackage(); //create datapackage containing clipboard content. dp.setbitmap(randomaccessstreamreference.createfromfile(storagefile)); clipboard.setcontent(dp); await successdialog.showasync();

the error in line: newuri = ms-appdata:\local\books\assets\recursos para el docente\matematicas\9\esp\1\0\geometria_page_04.png

storagefile storagefile = await folder.getfileasync(newuri);

maybe seek this:

newuri = uri.escapedatastring(newuri);

instead of:

newuri = newuri.replace("%20", " ");

c# winrt-xaml

javascript - Can a variable change value during single function call (from the outside?) -



javascript - Can a variable change value during single function call (from the outside?) -

i have been meaning read entire ecma5-6 spec, cough, maybe y'all can help me instead!

can variable changed "the outside" on course of study of execution of single phone call in javascript?

pseudo-javascript example:

window.foo = true; startsomeloopmutatingfoo(); function f() { var = window.foo; // insert long, blocking work here, none of mutates window.foo var b = window.foo; // 1 time again if (a != b) { totalmindexplosion() } }

will mind blown? totalmindexplosion() called under conceivable circumstance?

here's js fiddle facilitate mind fracking: http://jsfiddle.net/mf3rc/

i'm looking resources larn when asynchronous methods executed, direct answers, or questions of clarity.

thanks so!

no, totalmindexplosion() not called.

when executed, code in closure (function) blocks process, there no chance execute other code.

example:

function(){ var = 1; window.settimeout(function(){console.log(a);}, 0); = 2; }()

this log 2 instead of 1, timeout 0 second. console.log function called after total function executed, time, variable 'a' has been set 2.

javascript

sql server - Concatenate rows from a complex select in SQL -



sql server - Concatenate rows from a complex select in SQL -

rdbms sql server 2008.

i have 3 tables. simplify this:

nominationorder table:

nominationorderid | nominationid 1 | 5 2 | 9

nominationorderitem table:

nominationorderitemid | nominationorderid | giftid 1 | 1 | 6 2 | 1 | 3 3 | 1 | 9

gift table:

giftid | giftname | 3 | tvset 6 | tabletpc 9 | littleponny

so, there's nomination. each nomination may have 1 nomination order. each nomination order may have many nomination order items, each of them references gift order.

i'm making study reporting services , need display info each nomination gift in single row, showing gift names concatenated.

currently looks this:

nominationid | nominationorderid | giftname 5 | 1 | tvset 5 | 1 | tabletpc 5 | 1 | littleponny

i need this:

nominationid | nominationorderid | giftname 5 | 1 | tvset, tabletpc, littleponny

a simplified illustration of current sql query:

select nn.nominationid ,n_o.nominationorderid ,g.name giftname dbo.nomination nn left bring together dbo.nominationorder n_o on n_o.nominationid = nn.nominationid left bring together dbo.nominationorderitem noi on noi.nominationorderid = n_o.nominationorderid left bring together dbo.gift g on g.giftid = noi.giftid

how can rewrite create output in single string , concatenate gift names?

you can utilize cte :

with ctetbl (nominationid, nominationorderid, giftname) ( query here)

and concatenate rows same nominationid , nominationorderid for xml path('') , after replace first comma , stuff:

select t.nominationid , t.nominationorderid , stuff( ( select ', ' + giftname ctetbl nominationid = t.nominationid , nominationorderid = t.nominationorderid order giftname desc xml path('') ), 1, 1, '') ctetbl t grouping t.nominationid , t.nominationorderid sqlfiddle

sql sql-server sql-server-2008 concatenation

Checking if the Checkbox is checked or not dynamically in c# -



Checking if the Checkbox is checked or not dynamically in c# -

i have created checkbox dynamically button code

private void btn_add_record_click(object sender, eventargs e)q2 { checkbox deletecheckbox = new checkbox(); point p_request = new point(nxcheckbox, nycheckbox); deletecheckbox.location = p_request; deletecheckbox.name = "ch"+record_id+""; }

then checked manually need check specific checkbox name "ch"+record_id+" checked or not dynamically using code

string chechboxname = "ch1"; checkbox deletechechbox = new checkbox(); deletechechbox.name = chechboxname; if (deletechechbox.checked) { // code }

when debug code, doesn't come in if statement .. why ?

you're checking if box checked before gets checked. add together

deletechechbox.checkedchanged += deletechechboxcheckedchanged;

and add together method deletechechboxcheckedchanged can test whether or not it's been checked. can use

deletechechbox.checked = true;

to check box through code.

edit: checkbox it's name have either store global variable or through controls array in form.

foreach (control command in this.controls) { if (control.name == "ch1") { checkbox deletechechbox = (checkbox)control; if (deletechechbox.check) { //to code } } }

c#

tableview - View-Based NSTableView in Swift - How to -



tableview - View-Based NSTableView in Swift - How to -

i have nstableview cells view-based.

datasource & delegate connected, i'm not able display cell's textfield string value.

this code in objective-c, working:

- (nsinteger)numberofrowsintableview:(nstableview *)tableview { homecoming 10; } - (nsview *)tableview:(nstableview *)tableview viewfortablecolumn:(nstablecolumn *)tablecolumn row:(nsinteger)row { nstablecellview *cell = [tableview makeviewwithidentifier:@"list" owner:self]; [cella.textfield setstringvalue:"hey, cell"]; homecoming cell; }

and here code in swift, not working :

func numberofrowsintableview(atableview: nstableview!) -> int { homecoming 10 //casual number } func tableview(tableview: nstableview!, cellforrowatindexpath indexpath: nsindexpath!) -> nstablecellview! { var cell = tableview.makeviewwithidentifier("list", owner: self) nstablecellview! // setup cell without forcefulness unwrapping cell.textfield.stringvalue = "hey, cell" println("method called") //never printed homecoming cell }

this result: (table on right side of image)

note comment //setup cell without forcefulness unwrapping it makes no sense, forgot delete it.

what missing ?

edit: tried next no success:

func numberofrowsintableview(atableview: nstableview!) -> int { homecoming 10 } func tableview(tableview: nstableview!, objectvaluefortablecolumn tablecolumn: nstablecolumn!, row: int) -> anyobject { var cell = tableview.makeviewwithidentifier("list", owner: self) nstablecellview cell.textfield.stringvalue = "hey cell" homecoming cell; }

thank all. alberto

after hours of search, discovered method works !

func tableview(tableview: nstableview, viewfortablecolumn: nstablecolumn, row: int) -> nsview { var cell = tableview.makeviewwithidentifier("list", owner: self) nstablecellview cell.textfield.stringvalue = "hey, cell" homecoming cell; }

tableview swift cell

java short circuit operators -



java short circuit operators -

my uncertainty precedence of short circuit operators.

classic illustration of short circuit operator below.

if(denom != 0 && num/denom > 10 )

here usage of shorthand operator allows prevent partition 0 error because num/denom never executed.

now question java says '/' operator has higher precedence '&&' , how come left side of '&&' evaluated before '/'.?

/ has higher precedence >, has higher precedence &&. so, expression

a && b / c > 0

is same as

a && (b / c) > 0

which same

a && ((b / c) > 0)

the look evaluated left right.

if a false, entire look false, without evaluating sec term.

if a true, b / c first evaluated, , result compared 0.

java operators

.net - ADFS - asynchronous requests -



.net - ADFS - asynchronous requests -

i inquire if possible somehow send asynchronous requests in adfs adapter? current state is, have html page, fill info , press send, response not come immediately, takes while, , period of time blocked. there possibility prevent this? thinking ajax, read not easy. may of have dealt problem? suggestions welcome.

thank you

adfs "locked down" scheme security reasons.

you can tinker around margins , sense of pages have no real access authentication core.

given adfs provides claims drive user authorization various pages , functionality have in each of them, wouldn't able much anyway while wait.

.net ajax servlets request adfs

java - Mockito Matcher parameters showing as undefined -



java - Mockito Matcher parameters showing as undefined -

i trying mock method contained in main class of application. i'd test when parameters submitted successfully, application calls right method, uploadfiles. when - thenreturn pair shown below:

nrclient nrclient = (nrclient)mockito.mock(nrclient.class); mockito.when(nrclient.uploadfiles("df49acbc8", anylist(), "dl")).thenreturn("");

this shows runtime exception: "the method anystring() undefined type maintest." have imports:

import org.mockito.mockito; import org.mockito.matchers;

so why method undefined? there issue in implementation?

i have tried anystring() , anyint() same result.

you should getting compile-time error, not exception (unless actual exception you've got unresolved compile-time error).

just importing org.mockito.matchers means can utilize name matchers mean org.mockito.matchers anywhere in class. if want import methods, need static wildcard import:

import static org.mockito.matchers.*;

or specific methods:

import static org.mockito.matchers.anystring; import static org.mockito.matchers.anylist;

or qualify method name in calling code instead:

mockito.when(nrclient.uploadfiles("df49acbc8", matchers.anylist(), "dl")) .thenreturn("");

java junit mocking mockito

java - Trying to exit in android. Stack is not correctly cleared -



java - Trying to exit in android. Stack is not correctly cleared -

i have been spending lots of hours figuring reason why top of stack not cleared yet.

well tried following:

intent intent = new intent(actionbaractivity.this, mainactivity.class); intent.addcategory(intent.category_home); intent.setflags(intent.flag_activity_new_task); intent.addflags(intent.flag_activity_clear_top); startactivity(intent);

and turned me mainactivity. when seek press button, programme not exit, instead turns me first page of actionbaractivity.

let me more specific:

in mainactivity phone call actionbaractivity. in actionbaractivity have search bar , come in query there , print value of query.

if think how work below:

mainactivity -> actionbaractivity1 -> actionbaractivity2 -> actionbaractivity3 -> ..

in actionbaractivity have alternative brings me mainactivity.

so said when run application way above, bring me mainactivity.

nice far, when press button expect exit, instead goes actionbaractivity1. uncertainty stack not erased.

what should in case. thanks

i'm assuming you've seen post: android: clear stack , not want

the flag_activity_new_task creating new task stack. when nail "back" activity in stack, android goes previous task - has calling activity @ top.

if remove flag, mainactivity in task stack , brought top. , "back" removes , brings calling activity. far, expected android behavior.

edit: since commented have 2 activities, 1 alternative "finish()" actionbaractivity after starts mainactivity this:

startactivity(intentmainactivity); finish();

to behavior want many activities or in situations, need utilize set_result , finish activities in stack when nail button go mainactivity. in other words, android assumes want maintain activities when new ones start. in case don't, have tell activity destroy itself.

i.e. phone call setresult(done) , utilize startactivityforresult , check "done" flag in onactivityresult method.

then this:

mainactivity -> actionbaractivity1 -> actionbaractivity2 -> actionbaractivity3 -> mainactivity

becomes:

mainactivity -> actionbaractivity1 -> actionbaractivity2 -> actionbaractivity3 -> phone call "done" destroy actionbaractivity3 destroy actionbaractivity2 destroy actionbaractivity1 mainactivity remains

for example, in actionbaractivity2:

startactivityforresult(intentactionbaractivity3, actionbaractivity2_id);

then in actionbaractivity3:

public void exitbutton(view view) { setresult(my_done_flag); finish(); }

and in actionbaractivity2:

protected void onactivityresult(int requestcode, int resultcode, intent data) { if (requestcode == actionbaractivity2_id && resultcode == my_done_flag) { setresult(my_done_flag, data); finish(); } }

and on activities want "close" when button pressed.

java android

apache pig - Performance profiling in Pig Scripts -



apache pig - Performance profiling in Pig Scripts -

some of pig scripts take long time execute info on run map cut down jobs huge. so, thinking of ways speed script . can suggest ideas , set thoughts . there lot of grouping fields involved while grouping info based on combination of 2 or 3 fields.

one thought can think of having 1 field while doing grouping by

data = grouping (int) (random()*100) reducers, field1, field2 etc

will help involve more number of reducers introducing 1 field in grouping by. know output part file sizes become lesser , overall speedify running time of pig scripts.

apache-pig

sorting - PHP Table Creation (Multidimensional Arrays) -



sorting - PHP Table Creation (Multidimensional Arrays) -

i have 4 arrays first beingness table headings there six:

array(6) { [0]=> string(3) "who", [1]=> string(4) "what", [2]=> string(4) "when", [3]=> string(5) "where", [4]=> string(3) "why", [5]=> string(3) "how" }

and 3 other arrays contain coinciding values. want take values of first array create them keys of array value or array so:

array(6) { ["who"]=> array(0) {}, ["what"]=> array(0) {}, ["when"]=> array(0) {}, ["where"]=> array(0) {}, ["why"]=> array(0) {}, ["how"]=> array(0) {} }

and populate arrays coinciding values much table. illustration of 1 of other arrays be:

array(6) { [0]=> string(3) "red", [1]=> string(4) "blue", [2]=> string(4) "green", [3]=> string(6) "yellow", [4]=> string(3) "black", [5]=> string(3) "white" }

for sake of simplicity going 3 arrays have exact same value 1 above.

in end want resulting array be:

array(6) { ["who"]=> array(3) { [0]=> string(3) "red", [1]=> string(3) "red", [2]=> string(3) "red" }, ["what"]=> array(3) { [0]=> string(4) "blue", [1]=> string(4) "blue", [2]=> string(4) "blue" }, ["when"]=> array(3) { [0]=> string(5) "green", [1]=> string(5) "green", [2]=> string(5) "green" }, ["where"]=> array(3) { [0]=> string(6) "yellow", [1]=> string(6) "yellow", [2]=> string(6) "yellow" }, ["why"]=> array(3) { [0]=> string(5) "black", [1]=> string(5) "black", [2]=> string(5) "black" }, ["how"]=> array(3) { [0]=> string(5) "white", [1]=> string(5) "white", [2]=> string(5) "white" } }

the code working follows:

... //tokens generated above (this in loop) foreach ($tokens $token) { if ($i == 0) { $table[$token] = array(); } else { foreach ($table $col) { $table[$col][$i] = $token; } } } $i = $i + 1;

all generates array(0) {}

it'd appreciated if point out flaw in logic.

edit:

here table like:

_________________________________________ | | | when | | why | how | ----------------------------------------- | reddish | bluish | green| yellow|black|white| ----------------------------------------- | reddish | bluish | green| yellow|black|white| ----------------------------------------- | reddish | bluish | green| yellow|black|white| -----------------------------------------

try array_fill_keys() function

$tokens= array('who', 'what', 'when', 'where', 'why', 'how'); $table = array('red', 'blue', 'green', 'yellow','black', 'white'); $a = array_fill_keys($tokens, $table); print_r($a);

php sorting multidimensional-array

java - addCookie() not working in Tomcat 7 -



java - addCookie() not working in Tomcat 7 -

currently in process migrate application tomcat 6 tomcat 7. in flow there part add together cookie servlet jsp in method of servlet. neither adding cookie nor throwing exception. cross check have tried add together cookie within jsp forcefully. got same result.

servlet.java

public void logon( string username, string password, string ip, httpservletresponse response) throws exception, logonfailure { system.out.println(" input received ::"+response); system.out.println("attachment :::"+getnextattachment()); authenticatorticketwrapper wrapper = new authenticatorticketwrapper( username, password, ip, "" + getnextattachment(), ); // if no exception thrown must of managed log on. string userid = "" + this.getnextid(); system.out.println("user id within logon method ::"+userid); wrapper.setusername(userid); //wrapper.set m_cache.put( userid, wrapper ); // add together cookie users browser seek { system.out.println("cookiename in logon method :"+cookiename); response.addcookie( new cookie(this.cookiename + this.creation_id, userid) ); response.addcookie( new cookie(this.cookiename + this.creation_key, wrapper.getusercookiekey() ) ); } grab (exception e) { // todo: handle exception system.out.println("failed add together cookie, exception " + se); } }

catalina.policy

// permission examples/samples - see context xml files grant codebase "file:${catalina.home}/webapps/creationweb/-" { permission java.security.allpermission; };

can please allow me know if missing anything?

i've used code such next set cookies in tomcat 7

cookie usercookie = new cookie("somename", "somevalue"); usercookie.setmaxage(99999999999); usercookie.setpath("/"); resp.addcookie(usercookie);

in above example, resp httpservletresponse. code tested , working tomcat 7 , in jdk 1.7

java jsp tomcat servlets cookies

android - null pointer error- Unable to start activity ComponentInfo -



android - null pointer error- Unable to start activity ComponentInfo -

i'm getting null pointer exception , i'm confused. can help me please? if need more information,please allow me know.thanks in advance help.here's activity file:

public class androidbuildingmusicplayeractivity extends activity implements oncompletionlistener, seekbar.onseekbarchangelistener { private imagebutton btnplay; private imagebutton btnforward; private imagebutton btnbackward; private imagebutton btnnext; private imagebutton btnprevious; private imagebutton btnplaylist; private imagebutton btnrepeat; private imagebutton btnshuffle; private seekbar songprogressbar; private textview songtitlelabel; private textview songcurrentdurationlabel; private textview songtotaldurationlabel; // media player private mediaplayer mp; // handler update ui timer, progress bar etc,. private handler mhandler = new handler();; private songsmanager songmanager; private utilities utils; private int seekforwardtime = 5000; // 5000 milliseconds private int seekbackwardtime = 5000; // 5000 milliseconds private int currentsongindex = 0; private boolean isshuffle = false; private boolean isrepeat = false; private arraylist<hashmap<string, string>> songslist = new arraylist<hashmap<string, string>>(); @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.player); // player buttons btnplay = (imagebutton) findviewbyid(r.id.btnplay); btnforward = (imagebutton) findviewbyid(r.id.btnforward); btnbackward = (imagebutton) findviewbyid(r.id.btnbackward); btnnext = (imagebutton) findviewbyid(r.id.btnnext); btnprevious = (imagebutton) findviewbyid(r.id.btnprevious); btnplaylist = (imagebutton) findviewbyid(r.id.btnplaylist); btnrepeat = (imagebutton) findviewbyid(r.id.btnrepeat); btnshuffle = (imagebutton) findviewbyid(r.id.btnshuffle); songprogressbar = (seekbar) findviewbyid(r.id.songprogressbar); songtitlelabel = (textview) findviewbyid(r.id.songtitle); songcurrentdurationlabel = (textview) findviewbyid(r.id.songcurrentdurationlabel); songtotaldurationlabel = (textview) findviewbyid(r.id.songtotaldurationlabel); // mediaplayer mp = new mediaplayer(); songmanager = new songsmanager(); utils = new utilities(); // listeners songprogressbar.setonseekbarchangelistener(this); // of import mp.setoncompletionlistener(this); // of import // getting songs list songslist = songmanager.getplaylist(); // default play first song playsong(0); /** * play button click event * plays song , changes button pause image * pauses song , changes button play image * */ btnplay.setonclicklistener(new view.onclicklistener() { @override public void onclick(view arg0) { // check playing if(mp.isplaying()){ if(mp!=null){ mp.pause(); // changing button image play button btnplay.setimageresource(r.drawable.btn_play); } }else{ // resume song if(mp!=null){ mp.start(); // changing button image pause button btnplay.setimageresource(r.drawable.btn_pause); } } } }); /** * forwards button click event * forwards song specified seconds * */ btnforward.setonclicklistener(new view.onclicklistener() { @override public void onclick(view arg0) { // current song position int currentposition = mp.getcurrentposition(); // check if seekforward time lesser song duration if(currentposition + seekforwardtime <= mp.getduration()){ // forwards song mp.seekto(currentposition + seekforwardtime); }else{ // forwards end position mp.seekto(mp.getduration()); } } }); /** * backward button click event * backward song specified seconds * */ btnbackward.setonclicklistener(new view.onclicklistener() { @override public void onclick(view arg0) { // current song position int currentposition = mp.getcurrentposition(); // check if seekbackward time greater 0 sec if(currentposition - seekbackwardtime >= 0){ // forwards song mp.seekto(currentposition - seekbackwardtime); }else{ // backward starting position mp.seekto(0); } } }); /** * next button click event * plays next song taking currentsongindex + 1 * */ btnnext.setonclicklistener(new view.onclicklistener() { @override public void onclick(view arg0) { // check if next song there or not if(currentsongindex < (songslist.size() - 1)){ playsong(currentsongindex + 1); currentsongindex = currentsongindex + 1; }else{ // play first song playsong(0); currentsongindex = 0; } } }); /** * button click event * plays previous song currentsongindex - 1 * */ btnprevious.setonclicklistener(new view.onclicklistener() { @override public void onclick(view arg0) { if(currentsongindex > 0){ playsong(currentsongindex - 1); currentsongindex = currentsongindex - 1; }else{ // play lastly song playsong(songslist.size() - 1); currentsongindex = songslist.size() - 1; } } }); /** * button click event repeat button * enables repeat flag true * */ btnrepeat.setonclicklistener(new view.onclicklistener() { @override public void onclick(view arg0) { if(isrepeat){ isrepeat = false; toast.maketext(getapplicationcontext(), "repeat off", toast.length_short).show(); btnrepeat.setimageresource(r.drawable.btn_repeat); }else{ // create repeat true isrepeat = true; toast.maketext(getapplicationcontext(), "repeat on", toast.length_short).show(); // create shuffle false isshuffle = false; btnrepeat.setimageresource(r.drawable.btn_repeat_focused); btnshuffle.setimageresource(r.drawable.btn_shuffle); } } }); /** * button click event shuffle button * enables shuffle flag true * */ btnshuffle.setonclicklistener(new view.onclicklistener() { @override public void onclick(view arg0) { if(isshuffle){ isshuffle = false; toast.maketext(getapplicationcontext(), "shuffle off", toast.length_short).show(); btnshuffle.setimageresource(r.drawable.btn_shuffle); }else{ // create repeat true isshuffle= true; toast.maketext(getapplicationcontext(), "shuffle on", toast.length_short).show(); // create shuffle false isrepeat = false; btnshuffle.setimageresource(r.drawable.btn_shuffle_focused); btnrepeat.setimageresource(r.drawable.btn_repeat); } } }); /** * button click event play list click event * launches list activity displays list of songs * */ btnplaylist.setonclicklistener(new view.onclicklistener() { @override public void onclick(view arg0) { intent = new intent(getapplicationcontext(), playlistactivity.class); startactivityforresult(i, 100); } }); } /** * receiving song index playlist view * , play song * */ @override protected void onactivityresult(int requestcode, int resultcode, intent data) { super.onactivityresult(requestcode, resultcode, data); if(resultcode == 100){ currentsongindex = data.getextras().getint("songindex"); // play selected song playsong(currentsongindex); } } /** * function play song * @param songindex - index of song * */ public void playsong(int songindex){ // play song seek { mp.reset(); mp.setdatasource(songslist.get(songindex).get("songpath")); mp.prepare(); mp.start(); // displaying song title string songtitle = songslist.get(songindex).get("songtitle"); songtitlelabel.settext(songtitle); // changing button image pause image btnplay.setimageresource(r.drawable.btn_pause); // set progress bar values songprogressbar.setprogress(0); songprogressbar.setmax(100); // updating progress bar updateprogressbar(); } grab (illegalargumentexception e) { e.printstacktrace(); } grab (illegalstateexception e) { e.printstacktrace(); } grab (ioexception e) { e.printstacktrace(); } } /** * update timer on seekbar * */ public void updateprogressbar() { mhandler.postdelayed(mupdatetimetask, 100); } /** * background runnable thread * */ private runnable mupdatetimetask = new runnable() { public void run() { long totalduration = mp.getduration(); long currentduration = mp.getcurrentposition(); // displaying total duration time songtotaldurationlabel.settext(""+utils.millisecondstotimer(totalduration)); // displaying time completed playing songcurrentdurationlabel.settext(""+utils.millisecondstotimer(currentduration)); // updating progress bar int progress = (int)(utils.getprogresspercentage(currentduration, totalduration)); //log.d("progress", ""+progress); songprogressbar.setprogress(progress); // running thread after 100 milliseconds mhandler.postdelayed(this, 100); } }; /** * * */ @override public void onprogresschanged(seekbar seekbar, int progress, boolean fromtouch) { } /** * when user starts moving progress handler * */ @override public void onstarttrackingtouch(seekbar seekbar) { // remove message handler updating progress bar mhandler.removecallbacks(mupdatetimetask); } /** * when user stops moving progress hanlder * */ @override public void onstoptrackingtouch(seekbar seekbar) { mhandler.removecallbacks(mupdatetimetask); int totalduration = mp.getduration(); int currentposition = utils.progresstotimer(seekbar.getprogress(), totalduration); // forwards or backward seconds mp.seekto(currentposition); // update timer progress 1 time again updateprogressbar(); } /** * on song playing completed * if repeat on play same song 1 time again * if shuffle on play random song * */ @override public void oncompletion(mediaplayer arg0) { // check repeat on or off if(isrepeat){ // repeat on play same song 1 time again playsong(currentsongindex); } else if(isshuffle){ // shuffle on - play random song random rand = new random(); currentsongindex = rand.nextint((songslist.size() - 1) - 0 + 1) + 0; playsong(currentsongindex); } else{ // no repeat or shuffle on - play next song if(currentsongindex < (songslist.size() - 1)){ playsong(currentsongindex + 1); currentsongindex = currentsongindex + 1; }else{ // play first song playsong(0); currentsongindex = 0; } } } @override public void ondestroy(){ super.ondestroy(); mp.release(); }

}

and here's logcat:

06-19 02:22:17.080: d/androidruntime(837): shutting downwards vm 06-19 02:22:17.080: w/dalvikvm(837): threadid=1: thread exiting uncaught exception (group=0xb2a12ba8) 06-19 02:22:17.330: d/dalvikvm(837): gc_for_alloc freed 68k, 5% free 3143k/3292k, paused 204ms, total 216ms 06-19 02:22:17.360: w/mediaplayer-jni(837): mediaplayer finalized without beingness released 06-19 02:22:17.370: e/androidruntime(837): fatal exception: main 06-19 02:22:17.370: e/androidruntime(837): process: com.androidhive.musicplayer, pid: 837 06-19 02:22:17.370: e/androidruntime(837): java.lang.runtimeexception: unable start activity componentinfo{com.androidhive.musicplayer/com.androidhive.musicplayer.androidbuildingmusicplayeractivity}: java.lang.nullpointerexception 06-19 02:22:17.370: e/androidruntime(837): @ android.app.activitythread.performlaunchactivity(activitythread.java:2195) 06-19 02:22:17.370: e/androidruntime(837): @ android.app.activitythread.handlelaunchactivity(activitythread.java:2245) 06-19 02:22:17.370: e/androidruntime(837): @ android.app.activitythread.access$800(activitythread.java:135) 06-19 02:22:17.370: e/androidruntime(837): @ android.app.activitythread$h.handlemessage(activitythread.java:1196) 06-19 02:22:17.370: e/androidruntime(837): @ android.os.handler.dispatchmessage(handler.java:102) 06-19 02:22:17.370: e/androidruntime(837): @ android.os.looper.loop(looper.java:136) 06-19 02:22:17.370: e/androidruntime(837): @ android.app.activitythread.main(activitythread.java:5017) 06-19 02:22:17.370: e/androidruntime(837): @ java.lang.reflect.method.invokenative(native method) 06-19 02:22:17.370: e/androidruntime(837): @ java.lang.reflect.method.invoke(method.java:515) 06-19 02:22:17.370: e/androidruntime(837): @ com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:779) 06-19 02:22:17.370: e/androidruntime(837): @ com.android.internal.os.zygoteinit.main(zygoteinit.java:595) 06-19 02:22:17.370: e/androidruntime(837): @ dalvik.system.nativestart.main(native method) 06-19 02:22:17.370: e/androidruntime(837): caused by: java.lang.nullpointerexception 06-19 02:22:17.370: e/androidruntime(837): @ com.androidhive.musicplayer.songsmanager.getplaylist(songsmanager.java:25) 06-19 02:22:17.370: e/androidruntime(837): @ com.androidhive.musicplayer.androidbuildingmusicplayeractivity.oncreate(androidbuildingmusicplayeractivity.java:77) 06-19 02:22:17.370: e/androidruntime(837): @ android.app.activity.performcreate(activity.java:5231) 06-19 02:22:17.370: e/androidruntime(837): @ android.app.instrumentation.callactivityoncreate(instrumentation.java:1087) 06-19 02:22:17.370: e/androidruntime(837): @ android.app.activitythread.performlaunchactivity(activitythread.java:2159) 06-19 02:22:17.370: e/androidruntime(837): ... 11 more

songmanager file:

public class songsmanager { // sdcard path final string media_path = new string("/sdcard/"); private arraylist<hashmap<string, string>> songslist = new arraylist<hashmap<string, string>>(); // constructor public songsmanager(){ } /** * function read mp3 files sdcard * , store details in arraylist * */ public arraylist<hashmap<string, string>> getplaylist(){ file home = new file(media_path); if (home.listfiles(new fileextensionfilter()).length > 0) { (file file : home.listfiles(new fileextensionfilter())) { hashmap<string, string> song = new hashmap<string, string>(); song.put("songtitle", file.getname().substring(0, (file.getname().length() - 4))); song.put("songpath", file.getpath()); // adding each song songlist songslist.add(song); } } // homecoming songs list array homecoming songslist; } /** * class filter files having .mp3 extension * */ class fileextensionfilter implements filenamefilter { public boolean accept(file dir, string name) { homecoming (name.endswith(".mp3") || name.endswith(".mp3")); } } }

your nullpointerexception throws @ line: songslist.add(song);(line 25)

you seems forgot create new instance songslist

android nullpointerexception

mysql - Optimizing left join select query of large data in SQL -



mysql - Optimizing left join select query of large data in SQL -

i know if there faster or improve way of handling next situation:

i find myself struggling optimize execution time of lengthy select query, need create left joins each unique field per record (basically pivoting table). there way minimize single join/pivot cut down time taken retrieve data?

i need create provision 50 custom fields, times out on 30000 odd records (this indexes on relevant columns)

i appreciate help (that includes correcting title i'm not sure how state otherwise) in advance.

below code setup little example:

create table customfield ( id int identity (1,1) not null, fieldname varchar(50) not null, fieldordernumber int not null); alter table [dbo].[customfield] add together constraint [pk_customfield] primary key clustered ( [id] asc )with (pad_index = off, statistics_norecompute = off, sort_in_tempdb = off, ignore_dup_key = off, online = off, allow_row_locks = on, allow_page_locks = on, fillfactor = 90) on [primary]

go

create table fieldvalue ( id int identity (1,1) not null, customfieldid int not null, personid int not null, fieldvalue varchar(50)); alter table [dbo].[fieldvalue ] add together constraint [pk_fieldvalue] primary key clustered ( [id] asc )with (pad_index = off, statistics_norecompute = off, sort_in_tempdb = off, ignore_dup_key = off, online = off, allow_row_locks = on, allow_page_locks = on, fillfactor = 90) on [primary]

go

create table person ( id int identity (1,1) not null, personname varchar (50) not null); alter table [dbo].[person] add together constraint [pk_person] primary key clustered ( [id] asc )with (pad_index = off, statistics_norecompute = off, sort_in_tempdb = off, ignore_dup_key = off, online = off, allow_row_locks = on, allow_page_locks = on, fillfactor = 90) on [primary]

go

insert person (personname) values ('marc'); insert person (personname) values ('john'); insert customfield (fieldname, fieldordernumber) values ('bloodtype',1); insert customfield (fieldname, fieldordernumber) values ('eyecolour',2); insert fieldvalue (customfieldid , personid, fieldvalue) values (1,1, 'a+'); insert fieldvalue (customfieldid , personid, fieldvalue) values (1,2, 'o-'); insert fieldvalue (customfieldid , personid, fieldvalue) values (2,1, 'blue'); insert fieldvalue (customfieldid , personid, fieldvalue) values (2,2, 'hazel'); listfieldvalues (fieldordernumber, fieldname, personid, fieldvalue) ( select cf.fieldordernumber, cf.fieldname, fv.personid, fv.fieldvalue customfield cf left bring together fieldvalue fv on cf.id = fv.customfieldid ) select p.id, p.personname, lvf.fieldvalue column1, --bloodtype lvf2.fieldvalue column2 --eyecolour person p left bring together listfieldvalues lvf on p.id = lvf.personid , lvf.fieldordernumber =1 left bring together listfieldvalues lvf2 on p.id = lvf2.personid , lvf2.fieldordernumber = 2

first need create indexes on identity columns. create indexes on columns you're joining. these tips improve execution time.

mysql sql sql-server

c++ - Is std::random_shuffle reproducable across different compilers? -



c++ - Is std::random_shuffle reproducable across different compilers? -

i using std::random_shuffle function custom random number generator that, same seed, returns same sequence of random numbers across compilers.

however, i'm concerned std::random_shuffle may not utilize same algorithm between different compilers, , therefore, same seed, result won't same.

can rely on std::random_shuffle producing same output across different compilers same sequence of random numbers provided? if not, alternatives?

not using c++11 or boost.

from reading "25.3.12 random shuffle" in c++11 standard (the 1 have here) conclude strictly spoken guarantee can not made. requirement algorithm "that each possible permutation of elements has equal probability of appearance". not have swap elements front end back, example, , iterators random access iterators other order possible. (that said, i'd surprised if implementation wouldn't go first -> last, it's not guaranteed.)

c++

google cloud endpoints configure "service accounts" for Google OAuth 2.0 endpoint supports server-to-server interactions -



google cloud endpoints configure "service accounts" for Google OAuth 2.0 endpoint supports server-to-server interactions -

i implementing cloud endpoints python app, need expose restapi in secure way https (this authomatic), consumer of endpoint java application (not web browser or app android or ios), , questions if there way limit consume od services application.

i've seen "service account" oauth don't know if can utilize problem , if possible don't know how configure it.

thanks lot.

google-cloud-endpoints service-accounts

class - PHP Static var not working -



class - PHP Static var not working -

i'm working on captcha class , i'm done, there 1 thing doesn't work

in file set form, start line:

include 'captcha.php'; $captcha = captcha::trycaptcha(2,4,'#000', '#ffffff');

and captch construct:

static $do_generate = true; function __construct($aantal_letters = 2, $aantal_cijfers = 4, $voorgrond = '#000000', $achtergond = '#ffffff') { session_start(); if (self::$do_generate == true) { $letters = substr(str_shuffle('abcdeghjklmnpqrstuvwxyz'),0 ,$aantal_letters); $cijfers = substr(str_shuffle('23456789'),0 ,$aantal_cijfers); $imgbreed = 18 * ($aantal_letters + $aantal_cijfers); $_session['imgbreed'] = $imgbreed; $_session['captcha'] = $letters . $cijfers; $_session['voorgrond'] = $this->hex2rgb($voorgrond); $_session['achtergond'] = $this->hex2rgb($achtergond); } }

so in other words set stuff in session if static var $do_generate == true

so when post form, captcha getting checked procesor.php

like this:

if (captcha::captcha_uitkomst() == true) { echo "great"; } else { echo "wrong";

}

and captcha function checks etered captcha code:

static function captcha_uitkomst() { if (strcmp($_session['captcha'], strtoupper(str_replace(' ', '', $_post['captcha-invoer']))) == 0) { homecoming true; } else { echo "test"; self::$do_generate = false; homecoming false; } }

if come in right captcha code, it's good, works echo great. if wrong echo wrong,

perfect, but.... when go form (hit backspace 1 history back) come in right captcha, regenerates new captcha.

in class: captcha_uitkomst see made self::do_generate false , echo 'test' works when it's false, (just checking)

what doing wrong

when nail "back", page reloaded. new captcha.

the premise of question fundamentally flawed, have randomly assumed shouldn't happen, whereas in reality entirely design.

it wouldn't effective captcha if repeatedly wrong go , seek again; bot start brute forcing and learning experience.

php class static

internet explorer 8 - JQuery file upload iframe method -



internet explorer 8 - JQuery file upload iframe method -

i'd set cross-domain file upload solution ie8 compatible. i've been using blueimp's jquery file upload plugin iframe transport option.

the upload works well, i'm not able results of upload server side. redirect alternative result.html file parsing seems solution, problem not have access server hosting form deploy html file. in case, there other way retrieve results of upload without deploying html file origin server?

inside javascript file can add together event listener (for non-jquery way see answer)

$(window).on('message', function(e){ var info = e.originalevent.data || e.originalevent.message; info = json.parse(data); //only if did json.stringify info sent //do need message send. });

next when upload done can either write page or redirect iframe page has content on it.

window.parent.postmessage('file upload done', '*');

if need send more info parent need json.stringify content first (old ie , ff don't allow objects, strings.)

window.parent.postmessage(json.stringify({'success': true, 'id': 1942}), '*');

jquery internet-explorer-8 cross-domain jquery-file-upload

javascript - Node.js OpenShift EACCESS error -



javascript - Node.js OpenShift EACCESS error -

i can't app start properly, getting eaccess error:

error: hear eacces

here's code:

var server_port = process.env.openshift_nodejs_port || 8080 var server_ip_address = process.env.openshift_nodejs_ip || '127.0.0.1' var app = require('express')(); var server = require('http').server(app); var io = require('socket.io')(server); server.listen(server_port); app.get('/', function (req, res) { res.sendfile(__dirname + '/index.html'); }); io.on('connection', function (socket) { socket.emit('news', { hello: 'world' }); socket.on('my other event', function (data) { console.log(data); }); });

nothing special here, openshift's node variables used in right way.

server_ip_address should used. otherwise, uses default ip on openshift, 127.0.0.1. alter from:

server.listen(server_port);

to:

server.listen(server_port, server_ip_address);

or

server.listen(server_port, server_ip_address, function() { console.log('%s: node server started on %s:%d ...', new date(), server_ip_address, server_port); });

javascript node.js socket.io openshift socket.io-1.0

logic of restore a binary tree based on travseral results, java -



logic of restore a binary tree based on travseral results, java -

can help explain logic of how draw original binary tree based on traversal results? know pre-order , in-order traversal, can't figure out start question. many in advance!

a binary tree has pre-order traversal result: a,b,d,h,i,e,f,c,g,k,j (treenodes) , same tree gives next in-order traversal: b,h,i,d,a,c,f,e,k,g,j. can draw tree structure?

you have combine both informations. start:

pre-order starts root => a. in-order can see nodes belong left , right subtree a:

left - b,h,i,d

right - c,f,e,k,g,j

from pre-order can see: left kid of b. in-order can see nodes belong left , right subtree of b:

left - none

right - h,i,d

continue...

java tree binary traversal

sql - How to fire a trigger after the SPROC has completed execution? -



sql - How to fire a trigger after the SPROC has completed execution? -

i have written trigger sends email 1 time row insert performed.

alter trigger tr_sendmailondatarequest on datarequest after insert begin set nocount on; declare @dr_id int, @dr_fullname varchar(200), @dr_email varchar(200), @dr_phone varchar(20), @ut_name varchar(50), @dr_usertypeother varchar(50) = null, @d_name varchar(200), @dr_requestdate datetime, @uf_linkedfiles varchar(max), @drn_names varchar(200), @dr_description varchar(1200), @dr_createdon datetime, @analystmaillist varchar(max), @tablehtml nvarchar(max), @downloadlink varchar(max) = n'none' select @dr_id = max(dr_id) dbo.datarequest select @dr_fullname = dr_fullname, @dr_email = dr_email, @dr_phone = dr_phone, @ut_name = ut_name, @dr_usertypeother = dr_usertypeother, @d_name = d_name, @dr_requestdate = dr_requestdate, @uf_linkedfiles = uf_linkedfiles, @drn_names = drn_names, @dr_description = dr_description, @dr_createdon = dr_createdon dbo.fn_getdatarequest(@dr_id) select @analystmaillist = dbo.fn_getanalystsmaillist() if (len(@uf_linkedfiles) > 0) begin set @downloadlink = n'<a href="http://localhost:8500/workrequest/index.cfm?event=downloads.index&id=' + cast(@dr_id varchar(10)) + n'&k='+ substring(master.dbo.fn_varbintohexstr(hashbytes('sha', ':be9[dcv9wf~w!?xx4jo0oxlbz@0p4+[~z0do|:u,of!13^xzb')), 3, 32) + n'">downloads</a>' end set @tablehtml = n'<h1>data request</h1>' + n'<ul>' + n'<li>full name: ' + @uf_linkedfiles + n'</li>' + n'<li>email: ' + @dr_email + n'</li>' + n'<li>phone: ' + cast(@dr_phone varchar(20)) + n'</li>' + n'<li>user type: ' + @ut_name + n'</li>' + n'<li>user type other: ' + coalesce(@dr_usertypeother, n'none') + n'</li>' + n'<li>reuest date: ' + convert(varchar(20), @dr_requestdate, 107) + n'</li>' + n'<li>downloads: ' + @downloadlink + n'</li>' + n'</ul>'; begin exec msdb.dbo.sp_send_dbmail @profile_name = 'example', @recipients = 'john doe<jdoe@example>', --@recipients = @analystmaillist, @reply_to = @dr_email, @subject = 'email test', @body_format = 'html', @body = @tablehtml end end go

the above trigger fired when there row insert operation on table datarequest. after row insert operation, take identity element generated after insert operation , utilize foreign key, , insert other values in different table. finally, utilize values both tables , create email sent.

i wasn't getting values other tables (e.g. @uf_linkedfiles), realized trigger beingness fired after insert in first table before insert in second table, no values available when sending email.

so how create sure trigger fired after sproc insert activities in multiple tables has completed transaction.

here table diagram -

instead of using trigger, have included email sending code in sproc rows beingness inserted.

sql sql-server triggers

c# - Build a disposable method at runtime -



c# - Build a disposable method at runtime -

my programme creates in anytime new methods (using methodbuilder array of byte\il) executes them 1 time , discard reference them. found don't affected gc. there way allow gc collect them or dispose them?

i found problem create new method, need load it's assembly can't unloaded after. need run methods on main appdomain. (it creates objects or modifying some) there alternative methodbuilder , execute byte\il anyway?

use dynamicmethod if need emit method can garbage collected later. docs:

defines , represents dynamic method can compiled, executed, , discarded. discarded methods available garbage collection.

if need build type dynamically need define dynamic assembly can collected. utilize assemblybuilder.definedynamicassembly assemblybuilderaccess.runandcollect option. there restrictions on can in collectible assembly detailed here.

c# reflection.emit

javascript - Why does my for loop only push to array when the loop has no brackets -



javascript - Why does my for loop only push to array when the loop has no brackets -

i have written next function should log array origin @ "0" , ending function's argument (in case "40") console.

function range(num) { var holder = []; for(var = 0; <= num; i++) { holder.push(i); homecoming holder; } } console.log(range(40));

this instead logs "undefined". have noticed however, removing loop's brackets this:

function range(num) { var holder = []; for(var = 0; <= num; i++) holder.push(i); homecoming holder; } console.log(range(40));

causes function work correctly, great except not understand why function works. can explain?

the return needs outside loop or leave function after first push

function range(num) { var holder = []; for(var = 0; <= num; i++) { holder.push(i); } homecoming holder; // must outside } console.log(range(40));

a single statement in loop not need brackets recommended have them anyway. here above single statement.

function range(num) { var holder = []; for(var = 0; <= num; i++) holder.push(i); homecoming holder; // must outside } console.log(range(40));

javascript arrays for-loop