Saturday 15 January 2011

r - counting number of observations into a dataframe -



r - counting number of observations into a dataframe -

i want create new column in dataframe states number of observations particular group. have surgical procedure (hrg.code) , multiple consultants perform procedure (consultant.code) , length of remain patients in in days.

using

sourcedata2$meanvalue<-with(sourcedata2,ave(lengthofstaydays., hrg.code, consultant.code fun=mean))

i can new column (meanvalue) shows mean length of remain per consultant per procedure. need. however, i'd know how many occurances of each procedures each consultant performed new column in same info frame.

how generate number of observations. there doesn't appear fun = observations or fun = freq capability.

you may try:

tbl <- table(sourcedata2[,3:2]) #gives frequency of each `procedure` i.e. `hrg.code` done every `consultant.code` tbl # hrg.code #consultant.code b c # 1 1 0 # b 4 2 1 # c 0 0 1 # d 1 1 1 # e 2 0 0 as.data.frame.matrix(tbl) #converts `table` `data.frame`

if want total unique procedures done each consultant.code in long form.

with(sourcedata2, as.numeric(ave(hrg.code, consultant.code, fun=function(x) length(unique(x))))) # [1] 3 3 3 2 1 3 3 3 3 1 1 3 3 3 2 data sourcedata2 <- structure(list(lengthofstaydays = c(2l, 2l, 4l, 3l, 4l, 5l, 2l, 4l, 5l, 2l, 4l, 2l, 4l, 4l, 2l), hrg.code = c("c", "a", "a", "b", "a", "a", "b", "c", "a", "a", "c", "a", "b", "b", "a"), consultant.code = c("b", "b", "b", "a", "e", "b", "d", "d", "d", "e", "c", "b", "b", "b", "a")), .names = c("lengthofstaydays", "hrg.code", "consultant.code"), row.names = c(na, -15l), class = "data.frame")

r data.frame frequency

asp.net mvc 4 - SaaS Billing and Multi-tenant starter kit -



asp.net mvc 4 - SaaS Billing and Multi-tenant starter kit -

i'm finished solution built asp.net mvc. apart few bits , pieces, have security do. wondering if there sort of starter code somewhere can build application (or build current files into) following:

subscription page tenants (think called tenants, see note below), assign administrator account. a way invite others bring together , work on tenant's data. user groups , roles limit each of these other users can see/do. standard login/forgot password pages it doesn't need handle billing, if does, it's added bonus

my understanding of tenant here person signs , invite others access data. called vendor sometimes.

i'm sure there must out box, because above features of saas apps nowadays. i'm aware need add together clauses existing queries ensure tenants don't see each other's data.

any solutions anyhow know of? please allow me know. give thanks you

asp.net-mvc-4 saas starter-kits

c# - Display photos in dynamic folder asp.net -



c# - Display photos in dynamic folder asp.net -

i trying design photos manager website application need show of photos in folders base of operations on folder name , utilize 1 aspx page. found many tutorail can work display photos in folder dont know how display photos in folder on take galery, example: have folder photo on host server, in have 2 sub folders are: animal , flower. when click on animal folder, animal photos display on webpage , on when click on flower folder, flowers photos shown.

here code have: aspx page:

<asp:datalist id="datalist1" runat="server" repeatcolumns="5" backcolor="white" bordercolor="#999999" borderstyle="solid" borderwidth="1px" cellpadding="3" forecolor="black" width="100%"> <footerstyle backcolor="#cccccc" /> <selecteditemstyle backcolor="#000099" font-bold="true" forecolor="white" /> <headertemplate> <span class="style2">image gallary</span> </headertemplate> <headerstyle backcolor="black" font-bold="true" forecolor="white" /> <itemtemplate> <asp:imagebutton width="105px" id="image1" runat="server" borderstyle="solid" imageurl='<%# bind("name", "~/[foldername]/{0}") %>' height="94px" /> <br /> <asp:linkbutton id="hyperlink1" text='<%# bind("name") %>' commandargument='<%# bind("name") %>' runat="server" /> </itemtemplate> <footerstyle backcolor="white" forecolor="#333333" /> <itemstyle bordercolor="silver" borderstyle="dotted" borderwidth="1px" horizontalalign="center" verticalalign="bottom" backcolor="white" forecolor="#333333" /> </asp:datalist>

code behind

private void listimages() { directoryinfo dir = new directoryinfo(mappath("~/images")); // it's animal if click on animal , flower when click on flower. fileinfo[] file = dir.getfiles(); arraylist list = new arraylist(); foreach (fileinfo file2 in file) { if (file2.extension == ".jpg" || file2.extension == ".jpeg" || file2.extension == ".gif" || file2.extension == ".png") { list.add(file2); } } datalist1.datasource = list; datalist1.databind(); }

i tried add together list total path as: list.add(dir.tostring()+file2.tostring()) can not phone call aspx page <%# bind("name") %>, error wrong property name! :(

there 2 problem in code:

you need create property class name property. this:

public class imagetest { public string name {get;set;} }

then in bindlist method:

private void listimages() { directoryinfo dir = new directoryinfo(mappath("~/images/animal")); // it's animal if click on animal , flower when click on flower. fileinfo[] file = dir.getfiles(); // arraylist list = new arraylist(); list<imagetest> list = new list<imagetest>(); foreach (fileinfo file2 in file) { if (file2.extension == ".jpg" || file2.extension == ".jpeg" || file2.extension == ".gif" || file2.extension == ".png") { // list.add(file2); // list.add(dir.tostring() + file2.tostring()); list.add(new test() { name = "http://localhost:58822/images/animal/" + file2.tostring() // localhost path site url }); } } datalist1.datasource = list; datalist1.databind(); }

also need remove ~/[foldername]/{0}") %>' code , maintain simple

imageurl='<%# bind("name") %>'

c# asp.net

ios - Scrolling UICollectionView blocks main thread -



ios - Scrolling UICollectionView blocks main thread -

i have video decoder playing h264 using avsamplebufferdisplaylayer , works until scroll uicollectionviewcontroller on same view controller. appears block main thread causing app crash. have tried putting code in block on separate queue using dispatch_async still have same blocking problem along farther performance issues on decoder.

dispatch_async(samplequeue, ^{ [samplebufferqueue addobject:(__bridge id)(samplebuffer)]; if ([avlayer isreadyformoremediadata]) { cmsamplebufferref buffer = (__bridge cmsamplebufferref)([samplebufferqueue objectatindex:0]); [samplebufferqueue removeobjectatindex:0]; [avlayer enqueuesamplebuffer:buffer]; buffer = null; nslog(@"i frame"); [avlayer setneedsdisplay]; while ([samplebufferqueue count] > 0 && [avlayer isreadyformoremediadata]) { cmsamplebufferref buffer = (__bridge cmsamplebufferref)([samplebufferqueue objectatindex:0]); [samplebufferqueue removeobjectatindex:0]; [avlayer enqueuesamplebuffer:buffer]; buffer = null; nslog(@"i frame buffer"); [avlayer setneedsdisplay]; } } else { nslog(@"avlayer not accepting info (i)"); } });

is there way give task priority on user interface actions scrolling collection view etc? apologies lack of understanding reasonably new ios.

turns out uicollectionview blocking delegate calls nsurlconnection on main thread. solved problem:

nsurlconnection *connection = [[nsurlconnection alloc] initwithrequest:request delegate:self];

changed to

nsurlconnection *connection = [[nsurlconnection alloc] initwithrequest:request delegate:self startimmediately:no]; [connection scheduleinrunloop:[nsrunloop currentrunloop] formode:nsrunloopcommonmodes]; [connection start];

ios grand-central-dispatch

c# - Control.Invoke method not returning -



c# - Control.Invoke method not returning -

i'm trying parallelize code create run faster. far, it's been headaches , no results.

i want update several datagridviews @ same time :

parallel.invoke( () => updatedgv1(), () => updatedgv2(), () => updatedgv3() );

i have tried using easy (but not optimal) way recommended everywhere on web (like here http://msdn.microsoft.com/en-us/library/ms171728(v=vs.85).aspx ).

private void updatedgv1() { /* stuff */ assignvalue(this.dgv1, colpos, rowpos, value); /* in loop */ } delegate void assignevaluecallback(datagridview dgv, int columnpos, int rowpos, string valeur); public void assignvalue(datagridview dgv, form form, int columnpos, int rowpos, string value) { if (dgv.invokerequired) { assignevaluecallbackd = new assignevaluecallback(assignvalue); dgv.invoke(d, new object[] { dgv, columnpos, rowpos, value }); } else { dgv[columnpos, rowpos].value = value; } }

the main thread gets stuck @ "parallel.invoke(...)" call, waiting other threads finish.

the threads created "parallel.invoke(...)" stuck @ point:

mscorlib.dll!system.threading.waithandle.internalwaitone(system.runtime.interopservices.safehandle waitablesafehandle, long millisecondstimeout, bool hasthreadaffinity, bool exitcontext) mscorlib.dll!system.threading.waithandle.waitone(int millisecondstimeout, bool exitcontext) system.windows.forms.dll!system.windows.forms.control.waitforwaithandle(system.threading.waithandle waithandle) system.windows.forms.dll!system.windows.forms.control.marshaledinvoke(system.windows.forms.control caller, system.delegate method, object[] args, bool synchronous) system.windows.forms.dll!system.windows.forms.control.invoke(system.delegate method, object[] args) etc

why stuck?

i assume you're calling parallel.invoke ui thread. if so, that's problem.

parallel.invoke blocks until calls finish... means you're blocking ui thread. tasks you're starting can't complete, because control.invoke blocks until phone call on ui thread has finished - subtasks waiting ui thread become available in order update ui, ui thread waiting subtasks finish.

you could prepare using begininvoke instead of invoke (and may want anyway) it's fundamentally bad thought utilize parallel.invoke in ui thread, exactly because blocks.

c# .net-4.0

excel - adding a dynamic cell reference in vba -



excel - adding a dynamic cell reference in vba -

i using next code insert formula cell using vba. code inserts hyperlink static text leading file path , @ end of file path want able add together dynamic cell reference, instance , number of row.

in cell in column have names of folders. using destrow define current row number. question how can right formula when link clicked opens link right folder name of row clicked? thanks

ws2.range("s" & destrow).formula = "=hyperlink(""\\uksh000-file06\purchasing\new_supplier_set_ups_&_audits\attachments\"" & k" & destrow & ",""attached"")"

try,

ws2.range("s" & destrow).formula = "=hyperlink(""\\uksh000-file06\purchasing\new_supplier_set_ups_&_audits\attachments\" & ws2.range("k" & destrow).value & """,""attached"")"

fwiw, hate working quoted strings well.

addendum: should adding static filename after dynamic folder:

ws2.range("s" & destrow).formula = "=hyperlink(""\\uksh000-file06\purchasing\new_supplier_set_ups_&_audits\attachments\" & ws2.range("k" & destrow).value & "\audit.xls"",""attached"")"

excel vba hyperlink

ios - Asset Catalog UIImage ImageNamed: was nil -



ios - Asset Catalog UIImage ImageNamed: was nil -

i have 2 assets catalogs in app. 1 in source directory of app , other 1 linked project , target membership set.

when load image linked assetscatalog with

[uiimage imagenamed:@"icon_close"];

the image nil

when load image form asset catalog in sourc directory loaded

can help me have no thought why image not loaded.

in old projects work fine when create project xcode 6 dose not work.

ios xcode uiimage asset-catalog

angularjs - How to create complex query parameters in Restangular -



angularjs - How to create complex query parameters in Restangular -

i need create complex query string in restangular.

http://vdmta.rd.mycompany.net//people?anr=smith&attrs=givenname,displayname,name,cn

how do this?

so far ok getting far ?anr=smith using this:

return restangular.all('/people').getlist({anr:searchterm});

the lastly part attrs=x,y,x lets me command attributes want in search , alter per request make.

any advice appreciated.

regards

i

you should able add together query parameter value comma separated list of attributes.

var attributes = ['givenname' , 'displayname']; // attributes require request var attributesasstring = attributes.join(); homecoming restangular.all('/people').getlist({ anr : searchterm, attrs: attributesasstring });

angularjs rest restangular

javascript - angularjs: detect when ng-repeat finishes when rows added in the middle -



javascript - angularjs: detect when ng-repeat finishes when rows added in the middle -

every solution posted refers detecting when ng-repeat finishes leans on scope.$last value, this:

angular.module('fooapp') .directive('onlastrepeat', function () { homecoming function (scope, element, attrs) { if (scope.$last) { settimeout(function () { scope.$emit('onrepeatlast', element, attrs); }, 1); } }; })

the problem solution works if append end of list. if insert info in middle, scope.$last false , have no thought when angularjs has finished renedering newly bound rows. have solution work regardless of ng-repeat renders data?

example:

html:

<button ng-click="addtolist()"></button> <table> <tbody> <tr ng-repeat="foo in list" on-last-repeat><td><span>{{foo}}</span></td></tr> </tbody> </table>

controller code:

$scope.addtolist = function() { $scope.list.splice(1, 0, 4); } $scope.list = [1, 2, 3];

if click button in illustration above code $scope.last false in directive supposed trigger when rendering done.

could utilize this?

angular.module('fooapp') .directive('onlastrepeat', function () { homecoming function (scope, element, attrs) { if (scope.$middle) { settimeout(function () { scope.$emit('onrepeatmiddle', element, attrs); }, 1); } if (scope.$last) { settimeout(function () { scope.$emit('onrepeatlast', element, attrs); }, 1); } }; })

javascript angularjs

How and when the type gets resolved for generic methods in java? -



How and when the type gets resolved for generic methods in java? -

i expect next unit test fail classcastexception, passing.

the class has generic method sec parameter , homecoming value of type v.

on calling method sec time, type of sec parameter v integer, homecoming type should integer. @ runtime returns string value.

import java.util.hashmap; import java.util.map; import org.junit.test; public class genericmethodtest { private class nongenericclass { private final map<object, object> mymap = new hashmap<>(); <k, v> v addgeneric(k key, v value) { v existingv = (v) mymap.get(key); // why no classcastexception on above line, when type of v integer, mymap.get(key) returns value of // type string? if (existingv == null) { mymap.put(key, value); homecoming value; } homecoming existingv; } } @test public void test() { nongenericclass nongenericclass = new nongenericclass(); nongenericclass.addgeneric("one", "one"); // string valuestring = (string) nongenericclass.addgeneric("one", integer.valueof(1)); // compiler error expected, if above line uncommented - cannot cast integer string. // no error @ run-time, , below phone call returns value of type string. nongenericclass.addgeneric("one", integer.valueof(1)); } }

this due type erasure. basically, types of k , v aren't known @ execution time. cast v unchecked - , should have received warning @ compile-time (possibly suggesting compile -xlint).

if want cast checked @ execution time, you'll need relevant class object, @ point can utilize class.cast check it.

see type erasure in java generics faq more information, along "can cast parameterized type?".

java generics methods

java - lucene main function not found -



java - lucene main function not found -

i running lucene library text analysis project (i relatively new java). there problem main function (or command).

the lucene version using 3.0.0, , compiled jar file. jar file in same folder main class file indexer.java.

i first run compile code:

javac -cp \lucene-core-3.0.0.jar indexer.java

and worked correctly , created indexer.class file in same directory.

then run same sort of command:

java -cp \lucene-core.3.0.0.jar indexer

this time command line output says don't have main class indexer:

could not find or load main class indexer

i checked original java code, there main method defined:

import org.apache.lucene.index.*; import java.io.ioexception; import java.io.file; import org.apache.lucene.store.directory; import org.apache.lucene.store.fsdirectory; import org.apache.lucene.analysis.standard.*; import org.apache.lucene.util.version; import org.apache.lucene.document.document; import org.apache.lucene.document.field; import java.io.filereader; public class indexer { private indexwriter writer; private void indexfile(file f) throws exception{ system.out.println("indexing " + f.getcanonicalpath()); document doc = getdocument(f); if(doc != null){ writer.adddocument(doc); } } public indexer(string indexdir) throws ioexception{ directory dir = fsdirectory.open(new file(indexdir)); author = new indexwriter(dir,new standardanalyzer(version.lucene_30), true,indexwriter.maxfieldlength.unlimited); } protected document getdocument(file f) throws exception{ document doc = new document(); doc.add(new field("contents", new filereader(f))); doc.add(new field("filename", f.getname(), field.store.yes, field.index.not_analyzed)); doc.add(new field("fullpath", f.getcanonicalpath(), field.store.yes, field.index.not_analyzed)); homecoming doc; } protected boolean acceptfile(file f){ homecoming f.getname().endswith(".txt"); } public int index(string datadir) throws exception{ file[] files = new file(datadir).listfiles(); for(int = 0; < files.length;i++){ file f = files[i]; if(!f.isdirectory() && !f.ishidden() && f.exists() && f.canread() && acceptfile(f)){ indexfile(f); } } homecoming writer.numdocs(); } public void close() throws ioexception{ writer.close(); } public static void main(string[] args) throws exception{ if(args.length != 2){ throw new exception("usage: java " + indexer.class.getname()+" <index dir><data dir"); } string indexdir = args[0]; string datadir = args[1]; long start = system.currenttimemillis(); indexer indexer = new indexer(indexdir); int numindexed = indexer.index(datadir); indexer.close(); long end = system.currenttimemillis(); system.out.println("indexing " + numindexed + " files took " + (end-start)+ " milliseconds."); } }

what wrong code/command?

the jvm doesn't include current directory in runtime classpath when 1 explicitly specified. try

java -cp ".:lucene-core.3.0.0.jar" indexer

java lucene

Having no luck with data NASM -



Having no luck with data NASM -

section .data map db 1 section .text start: cmp byte [map], 1 je exit jmp start exit: ret

i'm having no luck reading data. mean assemble binary dos com format , when start it freezes. can tell me i'm doing wrong?

dos com files expected loaded @ address 0x100. should include line org 0x100 @ start of code.

nasm

delphi - installing JVCL (3.45) for XE2 error when loading the group project -



delphi - installing JVCL (3.45) for XE2 error when loading the group project -

i installed jcl , experience issues jvcl (release 3.45) installation. if load "d16 packages.groupproj" grouping project file, bunch of popup warnings missing classes, e.g.

tjvcontextprovider tjvsendmailaction tjvxchecklistbox tjvcontrolcollapseaction tjvformstorage tjvlistbox tjvlabel tjvbrowserforfolderaction tjvspinedit tjvfullcolorcircle

this reported in previous threads, did not see comment how handle issue here.

i gratefull if provide me useful hint here. in advance valuable help here.

delphi delphi-xe2 jvcl

sql - sqlite count of distinct occurences -



sql - sqlite count of distinct occurences -

what best way of writing sqlite query count occurrences of colc after selecting distinct cola's ?

select cola, colb, colc mytable cola in ('121', '122','123','124','125','126','127','128','129');

notice cola needs distinct.

although close, these results incorrect.

it should return: 123 cat 1 124 b dog 1 125 e snake 2 126 f fish 1 127 g snake 2

with t ( select cola, min(colb) colb, max(colc) colc mytable cola in ('121', '122','123','124','125','126','127','128','129') grouping cola ) select t.*, c.colc_count t bring together ( select colc, count(*) colc_count t grouping colc ) c on c.colc = t.colc

explanation:

first subquery (inside with) gets desired result without count column. sec subquery (inside join) counts each colc value repetition in desired result , count returned final result.

there helpful with clause result of first subquery used in 2 places. more info: https://www.sqlite.org/lang_with.html

query sqlite before version 3.8.3:

select t.*, c.colc_count ( select cola, min(colb) colb, max(colc) colc mytable cola in ('121', '122','123','124','125','126','127','128','129') grouping cola ) t bring together ( select colc, count(*) colc_count ( select max(colc) colc mytable cola in ('121', '122','123','124','125','126','127','128','129') grouping cola ) c grouping colc ) c on c.colc = t.colc

sql sqlite

methods as properties of an object in javascript -



methods as properties of an object in javascript -

i need create javascript function private variable has setter , getter methods. tried:

function createsecretholder(secret) { this._secret = secret; var getsecret = function(){ homecoming this._secret; } var setsecret = function(secret){ this._secret = secret; } }

and version with:

this.getsecret = function()...

and

this.sesecret = function()...

it not passing test suite on code wars. like

var obj = createsecretholder(secret); obj.getsecret(); obj.setsecret(newsecret);

and others hidden. error typeerror: cannot read property 'getsecret' of undefined , cannot phone call method setsecret

createsecretholder() doesn't return value createsecretholder(secret) returns undefined.

so var obj = createsecretholder(secret); sets obj undefined. hence error "cannot read property 'getsecret' of undefined" when seek access obj.getsecret().

even if returned object, have declared getsecret using var within function. variables described way scoped function. when seek access outside function, in obj.getsecret(), won't work.

you seem misunderstand how this works. not create private variable.

there number of ways this. here's one:

function createsecretholder(mysecret) { var secret = mysecret; homecoming { getsecret: function(){ homecoming secret; }, setsecret: function (mysecret){ secret = mysecret; } }; }

javascript object

ember.js - Ember: Programatically set queryParams in Mixin -



ember.js - Ember: Programatically set queryParams in Mixin -

i'm trying programatically define queryparams in ember.mixin.

the mixin has method called when controller holding mixin initialized.

setupqueryparams: (params) -> params.foreach (param) => @get('queryparams').push(param)

later in action defined on mixin phone call @transitiontoroute({queryparams: {someparam: 'something'}}) nil happens. when explicitly define queryparams, works.

queryparams resolved off proto of class, not instance, init functionality wouldn't applied in time ember resolve it.

this means late binding of queryparams isn't possible in way want.

ember.js

android - Preview image in my list of files -



android - Preview image in my list of files -

i have list of files in app , each 1 of them has icon or image next title. want icon preview image of file , i've used next method:

imageview image = (imageview) vi.findviewbyid(r.id.icon); image.setimagebitmap(mediastore.images.thumbnails.getthumbnail( activity.getcontentresolver(), long.valueof(r.drawable.img_file), mediastore.images.thumbnails.micro_kind, (bitmapfactory.options) null));

this code doesn't work in app, there no image in icon.

can help me, please? thanks.

android thumbnails

javascript - JS scripts are not executing -



javascript - <head> JS scripts are not executing -

i'm using jquery mobile, , navigate through pages minimum of loading amount of scripts everytime page beingness loaded, mean import once general scripts of pages (jquery.js, jquery_mobile.js, main.js etc...) ,

so have index.html next code :

<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0"> <title>hybrid app</title> <link rel="stylesheet" href="jquerymobile/jquery.mobile-1.4.4.css" /> <link rel="stylesheet" href="jquerymobile/jquery.mobile.icons-1.4.4.css" /> <link rel="stylesheet" href="css/jquery.mmenu.css" /> <link rel="stylesheet" href="css/main.css" /> <script>window.$ = window.jquery = wljq;</script> <script type="text/javascript" src="js/jquery-2.1.1.js"></script> <script type="text/javascript" src="jquerymobile/jquery.mobile-1.4.4.js"></script> <script type="text/javascript" src="js/jquery.mmenu.min.js"></script> <script type="text/javascript" src="js/initoptions.js"></script> <script type="text/javascript" src="sharedresources/customersobject.js"></script> <script type="text/javascript" src="js/main.js"></script> <script type="text/javascript" src="js/messages.js"></script> </head> <body style="display: none;"> <div data-role="page" id="page"> <link rel="stylesheet" href="css/pages/splash-view.css" /> <div data-role="header" id="header" data-position="fixed"></div> <div data-role="content" id="pagecontent"> <div id="splash-wrapper"> <div class="splash-content"> <a href="pages/faqs-view.html" data-role="button" data-inline="true" data-theme="b" id="loginaction">login</a> </div> </div> </div> <div data-role="footer" id="footer" data-position="fixed"></div> <nav id="menu"> <ul data-role="listview" data-inset="true"> <!-- list of items in slide sidebar menu (called drawer menu in andorid --> </ul> </nav> <script src="js/pages/splash-view.js"></script> </div> </body>

so when clicking on link go external html file located in : pages/faqs-view.html next code :

<div data-role="page" id="page" data-url="pages/faqs-view.html"> <link rel="stylesheet" href="css/pages/faqs-view.css"> <div data-role="header" id="header" data-position="fixed"></div> <div data-role="content" id="pagecontent"> <div id="faqs-wrapper"> <div class="faqs-content"> <div data-role="collapsible-set" data-corners="false" data-collapsed-icon="arrow-r" data-expanded-icon="arrow-d" id="faq-set"> </div> </div> </div> </div> <div data-role="footer" id="footer" data-position="fixed"></div> <nav id="menu"> <p class="employee-name">welcome, ali</p> <ul data-role="listview" data-inset="true"> <!-- list of items in slide sidebar menu (called drawer menu in andorid --> </ul> </nav> <script src="js/pages/faqs-view.js"></script>

the problem when loading faqs-view.html page, can see none of scripts included in <head> beingness executed, have tried set them after <body> tag, it's same, but css files beingness interpreted.

how can accomplish ? give thanks you.

worklight-based applications single page applications. means should never navigate away index.html. doing cause app lose context worklight framework, begin fail.

if you'd add together multi-page navigation application, can using api provided 3rd-party frameworks. here using jquery mobile.

you've changed loading order of scripts. shouldn't.

use worklight studio wizard in order create app template jquery mobile (new project > new hybrid application (click on "configure javascript libraries" > select library add))

keep initoptions.js, main.js , messages.js default, @ bottom

the index.html get template jquery mobile

if want replace bundled jquery, need comment out (slide #6) next script tag: <script>window.$ = window.jquery = wljq;</script>. worklight bundled jquery 1.9.x.

for bare-bones illustration of multi-page navigation in worklight-based application, using jquery mobile, take @ project.

as navigate between pages, replace contents of data-role="page". scripts have been loaded. can load additional scripts per required when loading specific page.

javascript jquery html jquery-mobile worklight

serial port - Java MODBUS RTU master example code -



serial port - Java MODBUS RTU master example code -

i need write modbus rtu master app in java back upwards 03 - read holding registers , 16 - write multiple registers.

i found 3 java libraries: jamod, j2mod, modbus4j. seek of these libraries (i spend 4 hours) , still doesn't work.

do know step-by-step tutorial or illustration code?

i'm using usb->rs-485 converter. if testing in qmodbus, works good.

thank you.

import java.io.file; import com.serotonin.io.serial.serialparameters; import com.serotonin.modbus4j.modbusfactory; import com.serotonin.modbus4j.modbusmaster; import com.serotonin.modbus4j.code.datatype; import com.serotonin.modbus4j.code.registerrange; import com.serotonin.modbus4j.exception.modbusinitexception; public class modbus4jtest { public static void main(string[] args) throws exception { modbusfactory mill = new modbusfactory(); serialparameters params = new serialparameters(); params.setcommportid("/dev/ttyusb1"); params.setbaudrate(9600); params.setdatabits(8); params.setstopbits(1); params.setparity(0); modbusmaster master = factory.creatertumaster(params); master.settimeout(2000); master.setretries(0); long start = system.currenttimemillis(); // don't start if rtu master can't initialized. seek { master.init(); } grab (modbusinitexception e) { system.out.println( "modbus master init error: " + e.getmessage()); return; } seek { system.out.println("reg. 1001 value:" + master.getvalue(7, registerrange.holding_register, 1000, datatype.four_byte_float_swapped)); // more above until required register values read. // .. } { master.destroy(); } system.out.println("time elapsed: " + (system.currenttimemillis() - start) + "ms"); } }

.

import java.io.file; import com.ghgande.j2mod.modbus.modbuscoupler; import com.ghgande.j2mod.modbus.io.modbusserialtransaction; import com.ghgande.j2mod.modbus.msg.modbusrequest; import com.ghgande.j2mod.modbus.msg.readinputregistersrequest; import com.ghgande.j2mod.modbus.msg.readinputregistersresponse; import com.ghgande.j2mod.modbus.net.serialconnection; import com.ghgande.j2mod.modbus.util.serialparameters; import com.serotonin.modbus4j.msg.readholdingregistersrequest; import com.serotonin.modbus4j.msg.readholdingregistersresponse; // -djava.library.path="/usr/lib/jni/" public class j2mod { public static void main(string[] args) throws exception { file lock = new file("/var/lock/lck..ttyusb0"); lock.delete(); file lock1 = new file("/var/lock/lck..ttyusb1"); lock1.delete(); serialconnection con = null; // connection modbusserialtransaction trans = null; // transaction //readinputregistersrequest req = null; // request readholdingregistersrequest req = null; readholdingregistersresponse res = null; //readinputregistersresponse res = null; // response string portname = null; // name of serial port used int unitid = 0; // unit identifier talking int ref = 0; // reference, start reading int count = 0; // count of ir's read int repeat = 1; // loop repeating transaction seek { portname = "/dev/ttyusb1"; //system.setproperty("gnu.io.rxtx.serialports", portname); unitid = 2; ref = 0; count = 4; } grab (exception ex) { ex.printstacktrace(); system.exit(1); } // 2. set master identifier // modbuscoupler.createmodbuscoupler(null); modbuscoupler.getreference().setunitid(1); // 3. setup serial parameters serialparameters params = new serialparameters(); params.setportname(portname); params.setbaudrate(9600); params.setdatabits(8); params.setparity("none"); params.setstopbits(1); params.setencoding("rtu"); params.setecho(false); // 4. open connection con = new serialconnection(params); con.open(); // 5. prepare request req = new readholdingregistersrequest(unitid, ref, count); //req = new readinputregistersrequest(ref, count); //req.setunitid(unitid); //req.setheadless(); // 6. prepare transaction trans = new modbusserialtransaction(con); trans.setrequest(req); int k = 0; { trans.execute(); res = (readinputregistersresponse) trans.getresponse(); //res = (readholdingregistersresponse) trans.getresponse(); (int n = 0; n < res.getwordcount(); n++) { system.out.println("word " + n + "=" + res.getregistervalue(n)); } k++; } while (k < repeat); // 8. close connection con.close(); } }

java serial-port rxtx modbus

python - Invalid Syntax (Strings and Float complications!) -



python - Invalid Syntax (Strings and Float complications!) -

i can't seem figure out. help appreciated.

pitcherspeed=float(round((40908/tempspeed),2)) output=output+temppitcher+ "\t" +str(round(float(tempspeed), 2)) + "\t" +str(round(float(pitcherspeed), 2)) +"\n"

i having issues above 2 lines. no matter alter them. error out. need help determining heck wrong them!

here of code (if needed):

output="" pitcherspeed=1 temppitcher=input("enter name of next contestant, or nil exit: ") fastestspeed=0 slowestspeed=0 if temppitcher=="": exit() fastestpitcher=temppitcher slowestpitcher=temppitcher tempspeed=float(input("enter time " +str(temppitcher) + "'s speed in milliseconds: ")) fastestspeed=tempspeed slowestspeed=tempspeed while temppitcher!="": output="" temppitcher=input("enter name of next contestant, or nil exit: ") tempspeed=input("enter time " +str(temppitcher) + "'s speed in milliseconds: ") pitcherspeed=float(round((40908/tempspeed),2)) output=output+temppitcher+ "\t" +str(round(float(tempspeed), 2)) + "\t" +str(round(float(pitcherspeed), 2)) +"\n" if temppitcher!="": tempspeed=input("enter time " +str(temppitcher) + "'s speed in milliseconds: ") if tempspeed==fastestspeed: fastestspeed=tempspeed fastestpitcher=temppitcher if tempspeed==slowestspeed: slowestspeed=tempspeed slowestpitcher=temppitcher print("name" + "\t" +"time" +"\t" +"speed" + "\n" + "===========================" + "\n") print(output) print("slowest pitcher " +str(slowestpitcher) +"at" +str(slowestspeed) +"miles per hour") print("fastest pitcher " +str(fastestpitcher) +"at" +str(slowestspeed) +"miles per hour")

i receive error message: traceback (most recent phone call last): file "c:/users/whitney.meulink/desktop/programpractice.py", line 17, in pitcherspeed=float(round((40908/tempspeed),2)) typeerror: unsupported operand type(s) /: 'int' , 'str'

the line:

pitcherspeed=float(round((40908/tempspeed),2)

is missing closing bracket.

pitcherspeed=float(round((40908/tempspeed),2))

it case error on previous line.

python

http - TCP receives packets, but it ignores them -



http - TCP receives packets, but it ignores them -

i have unusual networking problem. actual network configuration quite complex, because using openstack , docker build virtual network. however, problem not there, because capturing on host's interface , see packet in right way.... reasons not know, seems tcp ignoring them, though have been received: doesn't send ack them , doesn't send info application.

in trials, sent http request html page server jetty (ip 192.168.4.3) host (192.168.4.100).

what see capturing on 192.168.4.100 wireshark is:

192.168.4.100 -> syn -> 192.168.4.3 192.168.4.3 -> syn, ack -> 192.168.4.100 192.168.4.100 -> ack -> 192.168.4.3 192.168.4.100 -> / http/1.1 -> 192.168.4.3 192.168.4.3 -> ack -> 192.168.4.100 192.168.4.3 -> fragment 1 of http 200 ok response -> 192.168.4.100 192.168.4.3 -> fragment 2 of http 200 ok response -> 192.168.4.100 192.168.4.3 -> fragment 3 of http 200 ok response (psh) -> 192.168.4.100 192.168.4.3 -> retransmission of fragment 3 of http 200 ok response (psh) -> 192.168.4.100 192.168.4.3 -> retransmission of fragment 1 of http 200 ok response -> 192.168.4.100 192.168.4.3 -> retransmission of fragment 1 of http 200 ok response -> 192.168.4.100 192.168.4.3 -> retransmission of fragment 1 of http 200 ok response -> 192.168.4.100 192.168.4.3 -> retransmission of fragment 1 of http 200 ok response -> 192.168.4.100 192.168.4.3 -> retransmission of fragment 1 of http 200 ok response -> 192.168.4.100 192.168.4.3 -> retransmission of fragment 1 of http 200 ok response -> 192.168.4.100 192.168.4.100 -> ack of fragment 1 -> 192.168.4.3 192.168.4.3 -> retransmission of fragment 2 of http 200 ok response -> 192.168.4.100 192.168.4.3 -> retransmission of fragment 3 of http 200 ok response (psh) -> 192.168.4.100 192.168.4.3 -> retransmission of fragment 2 of http 200 ok response -> 192.168.4.100 192.168.4.3 -> retransmission of fragment 2 of http 200 ok response -> 192.168.4.100 192.168.4.3 -> retransmission of fragment 2 of http 200 ok response -> 192.168.4.100 192.168.4.3 -> retransmission of fragment 2 of http 200 ok response -> 192.168.4.100 192.168.4.3 -> retransmission of fragment 2 of http 200 ok response -> 192.168.4.100 192.168.4.3 -> retransmission of fragment 2 of http 200 ok response -> 192.168.4.100 192.168.4.100 -> ack of fragment 2 -> 192.168.4.3 192.168.4.3 -> retransmission of fragment 3 of http 200 ok response (psh) -> 192.168.4.100 192.168.4.3 -> retransmission of fragment 3 of http 200 ok response (psh) -> 192.168.4.100 192.168.4.3 -> retransmission of fragment 3 of http 200 ok response (psh) -> 192.168.4.100 192.168.4.3 -> retransmission of fragment 3 of http 200 ok response (psh) -> 192.168.4.100 192.168.4.3 -> retransmission of fragment 3 of http 200 ok response (psh) -> 192.168.4.100 192.168.4.3 -> retransmission of fragment 3 of http 200 ok response (psh) -> 192.168.4.100 192.168.4.100 -> ack of fragment 3 -> 192.168.4.3

this big problem, because there 40 seconds between request , lastly ack coincides moment application (telnet in case) gets data.

i have checked checksum , correct...

so don't know why happens , do! have tried different os hosts (a windows 8 mobile phone, mac osx, ubuntu 14.04, ...), nil changes. if send same request docker of virtual network, works fine.

any thought problem be?

thanks!

ps here can see screenshot of capture:

update

one thing think can interesting have made analogous capture, when http request sent 192.168.4.3 192.168.4.100. capture taken 1 time again on 192.168.4.100 interface , seems 1 time again 192.168.4.100 ignores packets receives (look @ 3 way handshake example). , found no reason again.

i managed solve problem. post here solution can useful if has same problem.

the problem disabled tso (tcp-segmentation-offload) on virtual bridge dockers attached command:

ethtool -k iface_name tso off

it turns off tso, whereas checksumming offload remains on. evidently, creates problem , though wireshark showed me tcp checksum ok, wasn't. host ignored packet due bad tcp checksum.

to turn off tso , checksumming too, used command:

ethtool --offload iface_name rx off tx off

and works.

http networking tcp docker openstack

java - Connecting Postgresql running on GCE from app engine -



java - Connecting Postgresql running on GCE from app engine -

i've googled lot couldn't find answer. i'm building application android backend on google appengine, need geospatial database use. decide utilize postgis, running on google compute engine instance. it's running on own computer , visible outside (tested). connect local dev app engine server (from computer), when deploy backend couldn't.

i tied utilize simple db connection. load driver:

static{ seek { class.forname("org.postgresql.driver"); } grab (classnotfoundexception e) { e.printstacktrace(); } }

and build connection:

public connection getconnection() throws sqlexception { if(mconnection == null || mconnection.isclosed()) { mconnection = drivermanager.getconnection(connectionurl, "....", "...."); } system.out.println("gis connection alive? "+ !mconnection.isclosed()); homecoming mconnection; }

i'm using postgresql-9.3-1102.jdbc4.jar.

i found post info restrictions, can't believe there's no simple way connect outer database. nice if around socketing quotas.

please help me!

believe it. not supported utilize protocol. utilize cloud sql or build https-based service on vm.

java postgresql google-app-engine jdbc google-compute-engine

android - Trying to send JSON requests, get java.lang.IllegalStateException: Target host must not be null, or set in parameters -



android - Trying to send JSON requests, get java.lang.IllegalStateException: Target host must not be null, or set in parameters -

i error when seek button click.

11-05 22:12:30.797 31048-31048/applicatoin w/system.err﹕ java.lang.illegalstateexception: target host must not null, or set in parameters. scheme=null, host=null, path=172.27.123.71 11-05 22:12:30.797 31048-31048/applicatoin w/system.err﹕ @ org.apache.http.impl.client.defaultrequestdirector.determineroute(defaultrequestdirector.java:591) 11-05 22:12:30.797 31048-31048/applicatoin w/system.err﹕ @ org.apache.http.impl.client.defaultrequestdirector.execute(defaultrequestdirector.java:293) 11-05 22:12:30.797 31048-31048/applicatoin w/system.err﹕ @ org.apache.http.impl.client.abstracthttpclient.execute(abstracthttpclient.java:555) 11-05 22:12:30.797 31048-31048/applicatoin w/system.err﹕ @ org.apache.http.impl.client.abstracthttpclient.execute(abstracthttpclient.java:487) 11-05 22:12:30.797 31048-31048/applicatoin w/system.err﹕ @ applicatoin.mainactivity$1.onclick(mainactivity.java:79) 11-05 22:12:30.797 31048-31048/applicatoin w/system.err﹕ @ android.view.view.performclick(view.java:4438) 11-05 22:12:30.797 31048-31048/applicatoin w/system.err﹕ @ android.view.view$performclick.run(view.java:18422) 11-05 22:12:30.797 31048-31048/applicatoin w/system.err﹕ @ android.os.handler.handlecallback(handler.java:733) 11-05 22:12:30.797 31048-31048/applicatoin w/system.err﹕ @ android.os.handler.dispatchmessage(handler.java:95) 11-05 22:12:30.797 31048-31048/applicatoin w/system.err﹕ @ android.os.looper.loop(looper.java:136) 11-05 22:12:30.797 31048-31048/applicatoin w/system.err﹕ @ android.app.activitythread.main(activitythread.java:5017) 11-05 22:12:30.797 31048-31048/applicatoin w/system.err﹕ @ java.lang.reflect.method.invokenative(native method) 11-05 22:12:30.797 31048-31048/applicatoin w/system.err﹕ @ java.lang.reflect.method.invoke(method.java:515) 11-05 22:12:30.797 31048-31048/applicatoin w/system.err﹕ @ com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:779) 11-05 22:12:30.797 31048-31048/applicatoin w/system.err﹕ @ com.android.internal.os.zygoteinit.main(zygoteinit.java:595) 11-05 22:12:30.797 31048-31048/applicatoin w/system.err﹕ @ dalvik.system.nativestart.main(native method)

i trying send json post request server. here code:

package applicatoin; import android.app.activity; import android.os.bundle; import android.view.menu; import android.view.menuitem; import android.widget.button; import android.widget.edittext; import android.view.view; import android.view.view.onclicklistener; import org.apache.http.httpentity; import org.apache.http.httpresponse; import org.apache.http.client.httpclient; import org.apache.http.client.methods.httppost; import org.apache.http.entity.stringentity; import org.apache.http.impl.client.defaulthttpclient; import org.apache.http.protocol.basichttpcontext; import org.apache.http.protocol.httpcontext; import org.apache.http.util.entityutils; public class mainactivity extends activity { button sendipbutton; //button sending ip address edittext medit; //get info user enters in form //textview mtext; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); /*get reference views*/ sendipbutton = (button) findviewbyid(r.id.sendip); medit = (edittext) findviewbyid(r.id.enterip); /*add click listener button "sendipbutton"*/ sendipbutton.setonclicklistener(new onclicklistener() { @override public void onclick(view arg0) { //add json logic here string ip = (medit).gettext().tostring(); string json = "{\"lights\": [{\"lightid\": 1, \"red\":242,\"green\":116,\"blue\":12, \"intensity\": 0.5}],\"propagate\": true}"; httpclient httpclient = new defaulthttpclient(); httpcontext httpcontext = new basichttpcontext(); httppost httppost = new httppost(ip); seek { stringentity se = new stringentity(json); httppost.setentity(se); httppost.setheader("accept", "ms3/json"); httppost.setheader("content-type", "ms3/json"); httpresponse response = httpclient.execute(httppost, httpcontext); httpentity entity = response.getentity(); string jsonstring = entityutils.tostring(entity); } grab (exception e){ e.printstacktrace(); } medit = (edittext)findviewbyid(r.id.enterip); //get text form? } }); // addlisteneronbutton(); //added button send ip address } public void sendjsontest(view view){ switch (view.getid()){ case r.id.sendip: string ip = (medit).gettext().tostring(); string json = "{\"lights\": [{\"lightid\": 1, \"red\":242,\"green\":116,\"blue\":12, \"intensity\": 0.5}],\"propagate\": true}"; httpclient httpclient = new defaulthttpclient(); httpcontext httpcontext = new basichttpcontext(); httppost httppost = new httppost(ip); seek { stringentity se = new stringentity(json); httppost.setentity(se); httppost.setheader("accept", "ms3/json"); httppost.setheader("content-type", "ms3/json"); httpresponse response = httpclient.execute(httppost, httpcontext); httpentity entity = response.getentity(); string jsonstring = entityutils.tostring(entity); } grab (exception e){ e.printstacktrace(); } break; } } public void sendjsontest(string ip) { string json = "{\"lights\": [{\"lightid\": 1, \"red\":242,\"green\":116,\"blue\":12, \"intensity\": 0.5}],\"propagate\": true}"; httpclient httpclient = new defaulthttpclient(); httpcontext httpcontext = new basichttpcontext(); httppost httppost = new httppost(ip); seek { stringentity se = new stringentity(json); httppost.setentity(se); httppost.setheader("accept", "ms3/json"); httppost.setheader("content-type", "ms3/json"); httpresponse response = httpclient.execute(httppost, httpcontext); httpentity entity = response.getentity(); string jsonstring = entityutils.tostring(entity); } grab (exception e){ e.printstacktrace(); } } @override public boolean oncreateoptionsmenu(menu menu) { // inflate menu; adds items action bar if present. getmenuinflater().inflate(r.menu.menu_main, menu); homecoming true; } @override public boolean onoptionsitemselected(menuitem item) { // handle action bar item clicks here. action bar // automatically handle clicks on home/up button, long // specify parent activity in androidmanifest.xml. int id = item.getitemid(); //noinspection simplifiableifstatement if (id == r.id.action_settings) { homecoming true; } homecoming super.onoptionsitemselected(item); } }

i not sure cause of error is. button identify text in text field, when seek httprequest, scheme error. json in right format. server doesn't request.

use seprate classes sending json request show 1 single demo bundle applicatoin; import android.app.activity; import android.os.bundle; import android.view.menu; import android.view.menuitem; import android.widget.button; import android.widget.edittext; import android.view.view; import android.view.view.onclicklistener; import org.apache.http.httpentity; import org.apache.http.httpresponse; import org.apache.http.client.httpclient; import org.apache.http.client.methods.httppost; import org.apache.http.entity.stringentity; import org.apache.http.impl.client.defaulthttpclient; import org.apache.http.protocol.basichttpcontext; import org.apache.http.protocol.httpcontext; import org.apache.http.util.entityutils; public class mainactivity extends activity { button sendipbutton; //button sending ip address edittext medit; //get info user enters in form //textview mtext; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); /*get reference views*/ sendipbutton = (button) findviewbyid(r.id.sendip); medit = (edittext) findviewbyid(r.id.enterip); /*add click listener button "sendipbutton"*/ sendipbutton.setonclicklistener(new onclicklistener() { @override public void onclick(view arg0) { //add json logic here new sendrequest().execute(); medit = (edittext)findviewbyid(r.id.enterip); //get text form? } }); // addlisteneronbutton(); //added button send ip address } } class sendrequest extends asynctask<void, void, void> { @override protected void doinbackground(void... params) { string ip = (medit).gettext().tostring(); string json = "{\"lights\": [{\"lightid\": 1, \"red\":242,\"green\":116,\"blue\":12, \"intensity\": 0.5}],\"propagate\": true}"; httpclient httpclient = new defaulthttpclient(); httpcontext httpcontext = new basichttpcontext(); httppost httppost = new httppost(ip); seek { stringentity se = new stringentity(json); httppost.setentity(se); httppost.setheader("accept", "ms3/json"); httppost.setheader("content-type", "ms3/json"); httpresponse response = httpclient.execute(httppost, httpcontext); httpentity entity = response.getentity(); string jsonstring = entityutils.tostring(entity); } grab (exception e){ e.printstacktrace(); } } }

android json post

activemq - How to monitor PooledConnectionFactory (via JMX?) -



activemq - How to monitor PooledConnectionFactory (via JMX?) -

i have client app consuming queue in activemq cluster. app running in tomcat 7 , uses camel (v2.10.3) , spring 3.1.2. utilize pooledconnectionfactory connect.

everything works while (sometimes days), of connections go away in pool (the activemq broker web console shows no consumers. figured idletimeout issue, adding suggested config didn't help. upgraded activemq-pool-5.10.0.jar, no luck.

so, i'm trying find out going on , hoping utilize jmx, can not find related mbeans (via jconsole) pool registers. there way monitor/control pool via jmx (or another/better way)?

my config fyi:

<bean id="jmsconnectionfactory" class="org.apache.activemq.activemwsslconnectionfactory"> <property name="brokerurl" value="failover://ssl://...."/> </bean> <bean id="pooledconnectionfactory" class="org.apache.activemq.pool.pooledconnectionfactory" init-method="start" destroy-method="stop"> <property name="connectionfactory" ref="jmsconnectionfactory"/> <property name="idletimeout" value="0"/> </bean>

as simple sounds, don't see other alternative other turn on trace level logging class. check out logs of question.

activemq jmx

windows - Run program in subfolders -



windows - Run program in subfolders -

i'm trying write windows batch script run 2 programs through bunch of folders. i'm not expert @ shell scripting seek best.

here's i'm trying run through each folder...

the input program1 .extension1 file produces .extension2 file run through program2 generate need.

before run script cd folder. programs copied folder because work in current working directory.

copy c:\program1 . re-create c:\program2 . %i in (*.extension1) program1 "%i" %i in (*.extension2) program2 "%i"

the info folder shown above contains hundreds of folders need run programme in. i'd able in 1 big batch script.

class="lang-dos prettyprint-override">@echo off setlocal set "sourcedir=u:\sourcedir\one" pushd "%sourcedir%" /r %%a in (*.ext1) ( pushd "%%~dpa" echo(c:\program1 "%%~nxa" popd ) popd goto :eof

you need alter setting of sourcedir suit circumstances.

in probability, need - or @ least, framework.

note routine echo required commands. allows harmless test (on representative sub-tree) ensure process should work on entire tree.

changing echo(c:\program1 c:\program1 should execute first programme on each .ext1 file in sub-tree. unusual programme check file exists within same directory executable - if won't take path, "the current directory" assumed.

you don't whether programme program1 produces file called whatever.ext2 whatever.ext1 or whether produces somethingradicallydifferent.ext2. in probability, same name used.

if case, run sec program, add together after

echo(c:\program1 "%%~nxa"

echo(c:\program2 "%%~na.ext2"

otherwise, repeat entire block, changing ext1 ext2

(i'll assume can figure out i've abbreviated extensions)

if, on off-chance program(s) need in same directory, replace

echo(c:\program1 "%%~nxa"

with

echo n|c:\program1 . >nul 2>nul echo(program1 "%%~nxa"

(and ditto programme 2, obviously). here n echoed copy, copy take place once. improved theoretical requirement anyway since it's 99.9999% executing c:\program? work quite happily.

windows batch-file cmd

javascript - syntax error on safari after bundling code -



javascript - syntax error on safari after bundling code -

hi have javascript function that's throwing syntax error on safari code works in other browsers (chrome, ff). receiving error after inbuild minification process bundling of .net.

error: syntaxerror: unexpected token 'function'

before bundling :

function btnstatus($btn, $status) { if ($status) { $btn.prop('disabled', false); } else { $btn.attr('disabled', true); } homecoming false; }

after bundling :

function btnstatus(n, t) { homecoming t ? n.prop("disabled", !1) : n.attr("disabled", !0), !1}

can show me insight of error!

actual problem not due btnstatus function. it's because of minification process of asp.net on bundling. when disabled minification process works. don't understand why safari producing error not other browsers.

fortunately disabling minification on bundling explain in stack overflow here @rudi visser answer.

javascript jquery .net safari asp.net-bundling

having command in sql -



having command in sql -

when write sql command:

select year, count(book_id) books pages > 200 grouping year having avg(pages) > 400

the "having avg(pages) > 400" - calculate pages average of books in year, or books pages more 200?

where clause filters rows , gives books pages >200 , having clause applied these books.

sql

Restarting while loop after false boolean in Java? -



Restarting while loop after false boolean in Java? -

i'm new java , i'm running bit of trouble. i'm doing assignment school requires find largest of 10 numbers. numbers between 0-9. believe got part down. problem i'm trying add together feature not required assignment. trying loop restart after boolean statement false , gives error message. after type invalid value in, gives error message, after press "ok" continues on next number. want start @ origin of loop.

here's code:

package largest;

import java.util.scanner;

import javax.swing.joptionpane; public class largestmain {

public static void main(string[] args) { int number = 0; string numstr = ""; int []myarray = new int[10]; int count = 1; int largest = 0; boolean valid = false; while(valid == true);// loop check validity { for(int = 0; < myarray.length; i++) { myarray[i] = + 1; numstr = joptionpane.showinputdialog("please come in number " + count++ + ":"); number = integer.parseint(numstr);//converts string value integer if(number >= largest) { largest = number; } //if/else if statements checks if values entered equal 0-9 if(number >= 0 && number <= 9) { valid = true; } else if ((!(number >= 0 && number <= 9))) { valid = false; } if (valid == false) { joptionpane.showmessagedialog(null, "invalid input...try again!!!", "results", joptionpane.yes_option); continue; } } joptionpane.showmessagedialog(null, "the largest number is: " + largest, "results", joptionpane.plain_message); } }

}

i end loop here adding return

if (valid == false) { joptionpane.showmessagedialog(null, "invalid input...try again!!!", "results", joptionpane.yes_option); return; }

i want larn how restart loop beginning. tried search different topics, none helped me solve problem. help in advance!

since you're beginner , trying learn, have done review of code , enclosed comments might help you. have posted updated code below.

declarations: should declare variable in innermost closure requires it. except largest, other can go within for.

your array variable did not create sense have. since you're keeping track of largest go , not finding @ end.

control: /loop check validity/ needs strictly around input part, not whole program, can repeat input statements till you're satisfied.

public static void main(string[] args) { int largest = 0; for(int = 1; <= 10; i++) { boolean valid = false; while (!valid) { string numstr = joptionpane.showinputdialog("please come in number " + + ":"); int number = integer.parseint(numstr); //converts string value integer if (number >= 0 && number <= 9) { valid = true; } else { joptionpane.showmessagedialog(null, "invalid input...try again!!!", "results", joptionpane.yes_option); } } if (number > largest) { largest = number; } } joptionpane.showmessagedialog(null, "the largest number is: " + largest, "results", joptionpane.plain_message); }

java while-loop boolean-expression

Android: Why 'invalid' region is called so? -



Android: Why 'invalid' region is called so? -

this extension of question what invalid part in android?

what criterion part become 'valid'?

invalid means part contains outdated info , has redrawn during next view.draw() call.

you can invalidate part calling view.invalidate(rect rect) method. method makes supplied rectangle area invalid, during next draw() frame, view have redraw area. 1 time redrawn (right after view.draw() call) part becomes valid again.

calling view.invalidate() makes whole view area invalid. trigger android phone call view.draw() method. schedule draw-request , execute possible.

android android-layout

zend framework2 - How to get ResultSet element in ZF2 -



zend framework2 - How to get ResultSet element in ZF2 -

how can lastly element of resultset in zend framework 2?

i can lastly element if convert object array want maintain object , lastly element.

it's bit tricky task because resultset iterator (and cannot rewinded), think solution alter query sort in different order, if describe utilize case more clearly, maybe work out improve approach.

zend-framework2 resultset

c# - Web Api - The 'ObjectContent type failed to serialize -



c# - Web Api - The 'ObjectContent type failed to serialize -

i have next web api action.

public ihttpactionresult get() { var units = enum.getvalues(typeof(unittype)).cast<unittype>().select(x => new { id = (int32)x, description = x.attribute<descriptionattribute>().description }); homecoming ok(units); }

basically, returning values , descriptions of enum.

i checked units list , right values.

however, when phone call api next error:

<error><message>an error has occurred.</message> <exceptionmessage>the 'objectcontent`1' type failed serialize response body content type 'application/xml; charset=utf-8'.</exceptionmessage> <exceptiontype>system.invalidoperationexception</exceptiontype> <stacktrace/><innerexception><message>an error has occurred.</message> <exceptionmessage>type '<>f__anonymoustype0`2[system.int32,system.string]' cannot serialized. consider marking datacontractattribute attribute, , marking of members want serialized datamemberattribute attribute. if type collection, consider marking collectiondatacontractattribute. see microsoft .net framework documentation other supported types.</exceptionmessage>

why?

update

i have:

public ihttpactionresult get() { ilist<enummodel> units = enum.getvalues(typeof(unittype)).cast<unittype>().select(x => new enummodel((int32)x, x.attribute<descriptionattribute>().description)).tolist(); homecoming ok(units); } // public class enummodel { public int32 id { get; set; } public string description { get; set; } public enummodel(int32 id, string description) { id = id; description = description; } // enummodel } // enummodel

i error:

<error> <message>an error has occurred.</message> <exceptionmessage>the 'objectcontent`1' type failed serialize response body content type 'application/xml; charset=utf-8'.</exceptionmessage> <exceptiontype>system.invalidoperationexception</exceptiontype> <stacktrace/><innerexception> <message>an error has occurred.</message> <exceptionmessage>type 'helpers.enummodel' cannot serialized. consider marking datacontractattribute attribute, , marking of members want serialized datamemberattribute attribute. if type collection, consider marking collectiondatacontractattribute. see microsoft .net framework documentation other supported types.</exceptionmessage> <exceptiontype>system.runtime.serialization.invaliddatacontractexception</exceptiontype>

any thought why?

i might wrong, innerexception seems suggesting anonymous types can't serialized.

try declaring class such as

public class enuminfo { public int id { get; set; } public string description { get; set; } public enuminfo(int id, string description) { id = id; description = description; } }

and turning select phone call

[...].select(x => new enuminfo((int32)x, x.attribute<descriptionattribute>().description);

c# asp.net-web-api

python - Correct way to test for numpy.dtype -



python - Correct way to test for numpy.dtype -

i'm looking @ third-party lib has next if-test:

if isinstance(xx_, numpy.ndarray) , xx_.dtype numpy.float64 , xx_.flags.contiguous: xx_[:] = ctypes.cast(xx_.ctypes._as_parameter_,ctypes.pointer(ctypes.c_double))

it appears xx_.dtype numpy.float64 fails:

>>> xx_ = numpy.zeros(8, dtype=numpy.float64) >>> xx_.dtype numpy.float64 false

what right way test dtype of numpy array float64 ?

this bug in lib.

dtype objects can constructed dynamically. , numpy time. there's no guarantee anywhere they're interned, constructing dtype exists give same one.

on top of that, np.float64 isn't dtype; it's a… i don't know these types called, types used build scalar objects out of array bytes, found in type attribute of dtype, i'm going phone call dtype.type. (note np.float64 subclasses both numpy's numeric tower types , python's numeric tower abcs, while np.dtype of course of study doesn't.)

normally, can utilize these interchangeably; when utilize dtype.type—or, matter, native python numeric type—where dtype expected, dtype constructed on fly (which, again, not guaranteed interned), of course of study doesn't mean they're identical:

>>> np.float64 == np.dtype(np.float64) == np.dtype('float64') true >>> np.float64 == np.dtype(np.float64).type true

the dtype.type will identical if you're using builtin types:

>>> np.float64 np.dtype(np.float64).type true

but 2 dtypes not:

>>> np.dtype(np.float64) np.dtype('float64') false

but again, none of guaranteed. (also, note np.float64 , float utilize exact same storage, separate types. , of course of study can create dtype('f8'), guaranteed work same dtype(np.float64), doesn't mean 'f8' is, or ==, np.float64.)

so, it's possible constructing array explicitly passing np.float64 dtype argument mean same instance when check dtype.type attribute, isn't guaranteed. , if pass np.dtype('float64'), or inquire numpy infer data, or pass dtype string parse 'f8', etc., it's less match. more importantly, definitely not np.float64 dtype itself.

so, how should fixed?

well, docs define means 2 dtypes equal, , that's useful thing, , think it's useful thing you're looking here. so, replace is ==:

if isinstance(xx_, numpy.ndarray) , xx_.dtype == numpy.float64 , xx_.flags.contiguous:

however, extent i'm guessing that's you're looking for. (the fact it's checking contiguous flag implies it's going go right internal storage… but why isn't checking c vs. fortran order, or byte order, or else?)

python numpy

security - Use git to secure web project directories -



security - Use git to secure web project directories -

i working on cms project set on insecure server numerous other projects out of control.

recently js files have been placed, replaced , edited adding malicious code unknown attackers through unknown vector. - hoster refused see problem or help finding loophole. client refused alter hoster or upgrade total blown root server harden myself.(sigh) secure project thought of making publicly accessible directories git monitored notified of changes via hook , repair whole thing simple reset.

question: there reason should not this? might open new security issues don't see now?

you shouldn't utilize such servers. if can alter files on file system, might alter configuration of web- or application server or executables git. if scheme corrupted in such way, cannot trust output of git.

in general git can check integrity of repository (see git fsck). furthermore can show differences between working directory , index (see git status). pitfalls: attacker can create local commits. in case fsck passes , output of git status empty. hence have verify still have same ref.

if have ignored directories or files atttacker might utilize them inject code in application. illustration web frameworks ruby on rails have own tmp directory , utilize cache responses. directory ignored , hence git doesn't care if manipulates these files.

depending on webservers configuration simple git clone your_repo in webroot might publish content of .git directory. in case have published source , finish history (a clone of repository contains whole history including author names , email addresses).

ofcourse shouldn't give user write permissions on repository cloned from. otherwise attacker might force local commits repository. might hard observe such commits, because might utilize email addresses, name , commit messages history. can avoided using signed commits , checking them.

if aware of these pitfalls, git assures integrity of source code expect. doesn't monitor state, doesn't actively tell if changed. if checkout , go away, git doesn't prevent else changing files. can come , see changes , maybe revert them.

git security content-management-system

matplotlib - Combined legend entry for plot and fill_between -



matplotlib - Combined legend entry for plot and fill_between -

this similar matlab: combine legends of shaded error , solid line mean, except matplotlib. illustration code:

import numpy np import matplotlib.pyplot plt x = np.array([0,1]) y = x + 1 f,a = plt.subplots() a.fill_between(x,y+0.5,y-0.5,alpha=0.5,color='b') a.plot(x,y,color='b',label='stuff',linewidth=3) a.legend() plt.show()

the above code produces legend looks this:

how can create legend entry combines shading fill_between , line plot, looks (mockup made in gimp):

mpl supports tuple inputs legend can create composite legend entries (see lastly figure on this page). however, of polycollections--which fill_between creates/returns--are not supported legend, supplying polycollection entry in tuple legend won't work (a prepare anticipated mpl 1.5.x).

until prepare arrives recommend using proxy artist in conjunction 'tuple' legend entry functionality. utilize mpl.patches.patch interface (as demonstrated on proxy artist page) or utilize fill. e.g.:

import numpy np import matplotlib.pyplot plt x = np.array([0, 1]) y = x + 1 f, = plt.subplots() a.fill_between(x, y + 0.5, y - 0.5, alpha=0.5, color='b') p1 = a.plot(x, y, color='b', linewidth=3) p2 = a.fill(np.nan, np.nan, 'b', alpha=0.5) a.legend([(p2[0], p1[0]), ], ['stuff']) plt.show()

matplotlib legend

mysql - difference between timestamps in two consecutive rows in single table -



mysql - difference between timestamps in two consecutive rows in single table -

i want time difference between timestamps 2 consecutive rows of bellow table single query :

i tried query inefficient , giving server timeout...

class="lang-sql prettyprint-override">select t1.t_id id1, t2.t_id id2, t1.timestamp timestamp1, t2.timestamp timestamp2, timestampdiff(second, t1.timestamp, t2.timestamp) diff (select * `track`) t1, (select * `track` `t_id` != (select `t_id` `track` limit 1)) t2 ( t1.t_id - 1 ) = t2.t_id

join table itself, (haven't tried, idea)

select t1.t_id id1, t2.t_id id2, t1.timestamp timestamp1, t2.timestamp timestamp2, timestampdiff(second, t1.timestamp, t2.timestamp) diff track t1 bring together track t2 on (t2.t_id = t1.t_id - 1)

mysql sql

ios - warning: Attempt to present modal when notification is called -



ios - warning: Attempt to present modal when notification is called -

i calling presentmodal method on viewdidappear using :

[[nsnotificationcenter defaultcenter] addobserver:self selector:@selector(presentmodal) name:@"xxxxxxx" object:nil]; -(void)presentmodal { pickermodalviewcontroller *pickermodalviewcontroller = [appdelegate.window.rootviewcontroller.storyboard instantiateviewcontrollerwithidentifier:@"pickermodalviewcontroller"]; pickertype = 2; pickermodalviewcontroller.choices = self.localarray; pickermodalviewcontroller.buttontag = pickertype; pickermodalviewcontroller.delegate = self; self.pickerpresenter = self; if (self.pickerpresenter) { [self.pickerpresenter presentviewcontroller:pickermodalviewcontroller animated:yes completion:nil]; } }

when picker presented gives me waring in both device , simulator

warning: attempt nowadays pickermodalviewcontroller: 0x10ec7280 on uinavigationcontroller: 0x90ad610 while presentation in progress!

the warning says you, wrong. avoid warning can utilize delegate property of uinavigationcontroller , implement

- (void)navigationcontroller:(uinavigationcontroller *)navigationcontroller didshowviewcontroller:(uiviewcontroller *)viewcontroller animated:(bool)animated

ios iphone

Opencv Ruby Highgui - build gem "manually" -



Opencv Ruby Highgui - build gem "manually" -

i've followed of steps question: highgui , ruby

opencv installed via brew, , rb_webcam installed via gem install.

require "opencv" require "rb_webcam" capture = webcam.new

the error is:

/users/swills/.rvm/rubies/ruby-2.1.1/lib/ruby/gems/2.1.0/gems/nice-ffi-0.4/lib/nice-ffi/library.rb:98:in `load_library': not load highgui. (loaderror) /users/swills/.rvm/rubies/ruby-2.1.1/lib/ruby/gems/2.1.0/gems/rb_webcam-0.3.0/lib/rb_webcam.rb:7:in `<module:highgui>' /users/swills/.rvm/rubies/ruby-2.1.1/lib/ruby/gems/2.1.0/gems/rb_webcam-0.3.0/lib/rb_webcam.rb:4:in `<top (required)>' /users/swills/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:135:in `require' /users/swills/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:135:in `rescue in require' /users/swills/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:144:in `require' gem_testing.rb:3:in `<main>'

in other stackoverflow post above, the user made post said they-

"solved downloading gem here https://github.com/tyounanmoti/rb_webcam , building , installing manually."

my question is, how solve building , installing manually?

(especially if 'gem install rb_webcam' isn't considered manual installation).

ruby opencv highgui

eclipse - How to paste Youtube Playlist into a ListView - Android? -



eclipse - How to paste Youtube Playlist into a ListView - Android? -

how set playlist of youtube within listview?

in order open video each entry in listview

you consult info how playlist data: youtube api v2.0 – playlists - youtube — google developers http://goo.gl/1brmzw

how fill listview, docs helpful: list view | android developers http://goo.gl/cqwvb

android eclipse listview youtube playlist

django - How to get my database to reflect changes made to models.py? -



django - How to get my database to reflect changes made to models.py? -

i made alter models, , cannot life of me figure out how database reflect models. far have tried following:

python manage.py shelldb select * sqlite_master type='table'; drop table appname_modelname;

when tried got: "unknown command: shelldb".

i tried:

python manage.py dbshell drop table accounts_userreview;

no error, db still doesn't reflect models.

finally, altogether deleted database dragging trash , doing syncdb, made me create new superuser, still database created not reflect changes models.

i'm @ loss here, else can here? also, i'm new learning django, there kind of layer in between models , database? assume there since deleting , rebuilding database didn't work.

would appreciate advice here.

if on django < 1.7 , have utilize migration tool i.e. - south . django 1.7 has inbuilt migration.

for more info migrations

django django-models

c# - AND statement in mySQL -



c# - AND statement in mySQL -

this question has reply here:

what nullreferenceexception , how prepare it? 21 answers

i'm trying run query in mysql database c#. want column prioritysettings returned when 3 previous columns within values. query works, 1 variable @ time, @ moment can specify value of 1 of columns. and statements correct?

string query = "select prioritysetting {database} handling ='" + handling + "'" + "and corner ='" + corner + "'" + "and powerfulness ='" + powerfulness + "'";

some more code;

mysqldatareader sqlreader; string handling = overorunderinput; string corner = cornerpartinput; string powerfulness = onoroffpowerinput; string query = "select prioritysetting {database} handling ='" + handling + "'" + " , corner ='" + corner + "'" + " , powerfulness ='" + powerfulness + "'"; mysqlcommand getrecords = new mysqlcommand(query, connection); connection.open(); sqlreader = getrecords.executereader(); while (sqlreader.read()) { seek { seek { suggestions[i] = (sqlreader.getstring(0)); } grab { } i++; } grab (mysqlexception ex) { messagebox.show(ex.tostring()); }

and error;

system.nullreferenceexception: object reference not set instance of object.

seem space required before each and.

c# mysql

c++ - No events from notify icon -



c++ - No events from notify icon -

my application running in background shows it's activity via notification icon in scheme tray. wanted add together popup-menu notification icon. unfortunately not receive events it. that's i'm doing create icon , event handler:

first create invisible window utilize it's event handler

zeromemory(&wc,sizeof(wndclassex)); wc.cbsize=sizeof(wndclassex); wc.lpfnwndproc=wndproc; wc.hinstance=hinstance; wc.lpszclassname=l"mycl"; registerclassex(&wc); hwnd=createwindowex(ws_ex_clientedge,l"mycl",l"mywn",ws_overlappedwindow,cw_usedefault, cw_usedefault,1,1,null,null,hinstance,null);

next create , show icon itself:

zeromemory(&nidata,sizeof(notifyicondata)); nidata.cbsize=sizeof(notifyicondata); nidata.uid=idi_aaaa; // icon's identifier nidata.uflags=nif_icon|nif_message|nif_tip; nidata.hicon=(hicon)loadimage(hinstance,makeintresource(idi_aaaa),image_icon, getsystemmetrics(sm_cxsmicon),getsystemmetrics(sm_cysmicon), lr_defaultcolor); nidata.hwnd=hwnd; nidata.ucallbackmessage=my_tray_icon_message; shell_notifyicon(nim_add,&nidata);

and event handler assigned invisible window , have assumed events icon should arrive too:

lresult callback wndproc(hwnd hwnd,uint msg,wparam wparam,lparam lparam) { switch(msg) { case wm_close: destroywindow(hwnd); break; case wm_destroy: postquitmessage(0); break; case my_tray_icon_message: // should related notification icon never called switch (lparam) { case wm_lbuttondown: case wm_rbuttondown: case wm_contextmenu: break; } break; default: homecoming defwindowproc(hwnd,msg,wparam,lparam); } homecoming 0; }

anybody thought wrong here?

c++ windows winapi events messages

node.js - Dustjs if condition for json -



node.js - Dustjs if condition for json -

how can set proper status check based on json data

i'm sending json object node layer dust template, based on object value want hide/show data. nodejs frameworke used krajenjs 0.7.5

1.{ access : { home : false} } 2.{ access : { home : false} }

worked fine 2

{@if cond="{access.home}"} <div>home</div> {/if}

how create work 1 using if condition notation

or

like below not work [[--------update----------]] works fine

{?access.home} <div>home</div> {/access.home} {^access.home} <div>home</div> {/access.home}

node.js dust.js kraken.js

c# - Modifying data member in loop of IList modifies other of elements of IList -



c# - Modifying data member in loop of IList modifies other of elements of IList -

i'm confused problem , not sure how title question.

i've created ilist of 1 of classes , used .add() populate ilist. 1 time ilist populated need iterate through ilist trivial check of values , set 1 of info members of each element 0.00.

the issue setting info fellow member of 1 element setting same info fellow member of next elements. here illustration of code:

public class myclass { private int _id; private string _modelname; private double _price; public int id { { homecoming _id; } set { _id = value; } } public string modelname { { homecoming _modelname; } set { _modelname= value; } } public double cost { { homecoming _price; } set { _price = value; } } }

i using myclass this:

ilist<myclass> myclasses = new list<myclass>(); myclasses.add( new myclass { id = 1, modelname = "model1", cost = 119310.05 }); myclasses.add( new myclass { id = 2, modelname = "model1", cost = 119310.05 }); myclasses.add( new myclass { id = 3, modelname = "model1", cost = 119310.05 }); myclasses.add( new myclass { id = 4, modelname = "model1", cost = 119310.05 }); myclasses.add( new myclass { id = 5, modelname = "model2", cost = 19810.32 }); myclasses.add( new myclass { id = 6, modelname = "model2", cost = 19810.32 }); myclasses.add( new myclass { id = 7, modelname = "model2", cost = 19810.32 }); foreach( myclass myclass in myclasses ) { ... ... myclass.price = 0.00; ... ... }

ok, above code extremely simple representation of actual code. happening when set myclass.price = 0.00; in foreach loop of cost info members matching modelname getting changed 0.00. so, in foreach loop when set element id = 1 cost = 0.00 seeing in ilist:

myclasses.add( new myclass { id = 1, modelname = "model1", cost = 0.00 }); myclasses.add( new myclass { id = 2, modelname = "model1", cost = 0.00 }); myclasses.add( new myclass { id = 3, modelname = "model1", cost = 0.00 }); myclasses.add( new myclass { id = 4, modelname = "model1", cost = 0.00 }); myclasses.add( new myclass { id = 5, modelname = "model2", cost = 19810.32 }); myclasses.add( new myclass { id = 6, modelname = "model2", cost = 19810.32 }); myclasses.add( new myclass { id = 7, modelname = "model2", cost = 19810.32 });

i sense totally stupid question asking , end finding as stupid reason happening. i've used f11 step every line of code involved , don't see anyplace cost getting set in other elements. matter, myclass braindead existence of beingness contained in ilist.

it seems beingness caused in loop itself. i've tried approach same behavior:

for (int p = 0; p < myclasses.count; p++ ) { ... ... myclass[p].price = 0.00; ... ... }

i've added watch:

myclasses[p].price myclasses[p + 1].price myclasses[p + 2].price myclasses[p + 3].price myclasses[p + 4].price

stepping through loop shows when myclasses[p].price set 0.00 of other elements' cost fellow member set 0.00.

is there possible explanation behavior other there beingness causing in class? perchance ilist?

the obvious reply question copying same reference single instance of myclass each unique modelname value, list has same instance in multiple times. without proper concise-but-complete code example, it's impossible sure.

c# ilist

python - Choosing items from a list on a percent basis -



python - Choosing items from a list on a percent basis -

i trying create programme using python takes names list, , displays names list in random order, while using each name once. have gotten far, , made work next code:

import random drivers = [ "john doe", "bill smith", "trent baxter", "ray olson", ] random.shuffle(drivers) position in drivers: print(position)

ouput:

bill smith john doe ray olson trent baxter

this works, have programme assign values each name create them more, or less picked, while still choosing each name once.

answer using standard modules:

from itertools import accumulate random import uniform class probitem(object): def __init__(self, value, prob): self.value = value self.prob = prob def pick(items): accum = list(accumulate(item.prob item in items)) rand = uniform(0, accum[-1]) i, prob in enumerate(accum): if rand < prob: homecoming items.pop(i).value drivers = [ probitem("john doe", 23.7), probitem("bill smith", 17), probitem("trent baxter", 12.43), probitem("ray olson", 9.99), ] while (drivers): print(pick(drivers))

depending on necessities, it's improve build generator...

python

jquery - adding values with sGlide plugin -



jquery - adding values with sGlide plugin -

i trying add together values of 3 slider bars together. have function add together them no matter phone call function breaks page. values of each slider counting live when load page nan value of total if slider starts @ position other 0.

<!doctype html> <html><head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=560, user-scalable=0;">

<title>sglide - working</title> <link rel="stylesheet" href="main.css" /> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript" src="sglide.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('#slider1').sglide({ 'width': 85, 'height': 60, 'image': 'img/knob.png', //'startat': 'slider3 o.value', 'colorstart': '#3333ff', 'colorend': '#000080', 'buttons': true, drag: function(o){ $('input[type=text][id="amount1"]').val(o.value); }, onbutton: function(o){ $('input[type=text][id="amount1"]').val(o.value); } }); $('#slider2').sglide({ 'width': 85, 'height': 60, 'image': 'img/knob.png', //'startat': 'slider3 o.value', 'colorstart': '#360', 'colorend': '#693', 'buttons': true, drag: function(o){ $('input[type=text][id="amount2"]').val(o.value); }, onbutton: function(o){ $('input[type=text][id="amount2"]').val(o.value); } }); $('#slider3').sglide({ 'width': 85, 'height': 60, 'image': 'img/knob.png', 'startat': 40, 'colorstart': '#cc99cc', 'colorend': '#4c1a4c', 'buttons': true, drag: function(o){ $('input[type=text][id="amount3"]').val(o.value); }, onbutton: function(o){ $('input[type=text][id="amount3"]').val(o.value); } }); function update() { $amount1 = $("#slider1").val(o.value); $amount2 = $("#slider2").val(o.value); $amount3 = $("#slider3").val(o.value); $total = $amount1 + $amount2 + $amount3; //$("#amount").val($amount1); //$("#amount2").val($amount2); //$("#amount3").val($amount3); $("#total").val($total); } }); </script> </head><body> <div id="slider1" class="slider_bar"></div><input id="amount1" type="text" /><br /><br /> <div id="slider2" class="slider_bar"></div><input id="amount2" type="text" /><br /><br /> <div id="slider3" class="slider_bar"></div><input id="amount3" type="text" /><br /><br /> <br /> <h3>total</h3> <input id="total" type="text" /> </body></html>

first of not calling update function anywhere in code. if want update total textbox when bar dragged, need phone call function within every drag event.

also setting value drag event parameter text fields trying slider object. haven't worked sglide when debugged code, value of sliders didn't homecoming value expected improve values text fields.

in end update function should this.

function update() { $amount1 = $('input[type=text][id="amount1"]').val(); $amount2 = $('input[type=text][id="amount2"]').val(); $amount3 = $('input[type=text][id="amount3"]').val(); $total = parsefloat($amount1) + parsefloat($amount2) + parsefloat($amount3); $("#total").val($total); }

also stated before need phone call function in drag events.

hope helps...

jquery

asp.net mvc - MVC 5 / Bootstrap App - Modal Dialog Auto expand? -



asp.net mvc - MVC 5 / Bootstrap App - Modal Dialog Auto expand? -

i've got next html in mvc 5 / bootstrap app. can see, attempting display photo in modal dialog. works fine. but, if photo wider dialog, extends beyond bounds of dialog. there way can have dialog expand, point, display scroll bars, based on size of contents (image)?

<div class="modal fade" id="viewphotodialog" tabindex="-1"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h4>ask experts</h4> </div> <div class="modal-body"> <img src="@url.action("getphoto", new { asktheexpertid = @model.asktheexpertid })" alt="" title=""/> </div> <div class="modal-footer"> <button class="btn btn-primary" data-dismiss="modal">close</button> </div> </div> </div> </div>

you can add together .img-responsive class img (gives max-width:100% , auto height). modal width, there 2 alternative classes modal-lg , modal-sm can add together @ .modal-dialog http://getbootstrap.com/javascript/#modals

asp.net-mvc twitter-bootstrap