Posts

Showing posts from September, 2015

elasticsearch - Is the order of operations guaranteed in a bulk update? -

i sending delete , index requests elasticsearch in bulk (the example adapted from docs ): { "delete" : { "_index" : "test", "_type" : "type1", "_id" : "1" } } { "index" : { "_index" : "test", "_type" : "type1", "_id" : "1" } } { "field1" : "value1" } the sequence above intended first delete possible document _id=1 , index new document same _id=1 . is order of actions guaranteed? in other words, example above, can sure delete not touch document index ed afterwards (because order not respected reason or another)? the delete operation useless in scenario, if index document same id, automatically , implicitly delete/replace previous document same id. so if document id=1 exists, sending below command replace (read delete , re-index it) { "index" : { "_index" : "test", "

cron - how to properly run Python script with crontab on every system startup -

i have python script should open linux terminal, browser, file manager , text editor on system startup. decided crontab suitable way automatically run script. unfortunately, doesn't went well, nothing happened when reboot laptop. so, captured output of script file in order clues. seems script partially executed. use debian 8 (jessie), , here's python script: #!/usr/bin/env python3 import subprocess import webbrowser def action(): subprocess.call('gnome-terminal') subprocess.call('subl') subprocess.call(('xdg-open', '/home/fin/documents/learning')) webbrowser.open('https://reddit.com/r/python') if __name__ == '__main__': action() here's entry in crontab file: @reboot python3 /home/fin/labs/my-cheatcodes/src/dsktp_startup_script/dsktp_startup_script.py > capture_report.txt here's content of capture_report.txt file (i trim several lines, since long, prints folder structures. seems came

java - Mock creation of Object inside method -

problem description i'm trying mock object creation inside of method. have loginfragment creating loginpresenterimpl inside of oncreate method, shown below: public class loginfragment extends basefragment { private loginpresenter mpresenter; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); mpresenter = new loginpresenterimpl(this); <<-- should mocked } } i have problems combining robolectricgradletestrunner , powermockrunner in 1 test after reading this post, found way how that, test this: baserobolectrictest.java @runwith(powermockrunner.class) @powermockrunnerdelegate(robolectricgradletestrunner.class) @config(constants = buildconfig.class, sdk = 21) @powermockignore({"org.mockito.*", "org.robolectric.*", "android.*"}) public abstract class baserobolectrictest { } test.java @preparefortest({loginpresenterimpl.class}) public class test exte

ios - label is not growing when the text is longer -

Image
i want view centered in superview grows due content in case label. don't want grow doesn't fit in screen anymore thats why pin left , right. i've put on test viewcontroller: import uikit import purelayout final class viewcontroller: uiviewcontroller { let container: uiview = { let container = uiview(forautolayout: ()) container.backgroundcolor = uicolor.blackcolor() container.clipstobounds = true return container }() let label: uilabel = { let label = uilabel(forautolayout: ()) label.textalignment = nstextalignment.center label.numberoflines = 1 label.textcolor = uicolor.redcolor() label.text = "this very long message" return label }() var rightview: uiview = { let view = uiview(forautolayout: ()) view.backgroundcolor = .redcolor() return view }() override func viewdidload() { super.viewdidload() self.co

Slow performance first queries on SQL Azure -

i have small database (50mb) , i'm on basic plan. there single user, need create many databases (always 1 per user) since used training purposes. each database created doing following statement: create database training1 copy of modeldatabase1 we seem getting very slow performance when first query database, afterwards seems acceptable. to give idea: have sp: startupevents runs when application started. query takes 25 seconds run first time. seems incredible since database small, , tables query calls don't contain many records. if run procedure afterwards executes immediately... how can avoid this?

mapreduce - Resource manager does not transit to active state from standby -

one spark job running more 23 days , caused resource manager crash. after restarting resource manager istance (there 2 of them in our cluster) both of them stayed in standby state. and getting error: error org.apache.hadoop.yarn.server.resourcemanager.resourcemanager failed load/recover state org.apache.hadoop.yarn.exceptions.yarnexception: application id application_1470300000724_40101 present! cannot add duplicate! we not kill 'application_1470300000724_40101' yarn resource manager not working. killed instances unix level on nodes dint work. have tried rebooting nodes , still same. somewhere 1 entry of job still there , preventing resource manager elected active. using cloudera 5.3.0 , can see issue has been addressed , resolved in cloudera 5.3.3. @ moment need workaround past now. to resolve issue can format rmstatestore executing below command: yarn resourcemanager -format-state-store but careful clear application history executed befor

serialization - Convert Any type in scala to Array[Byte] and back -

i have following question: i have variable value in program declared value. i want convert value byte array.. how can serialize byte array , back? found examples related other types such double or int, not any. this should need. it's pretty similar how 1 in java. import java.io.{bytearrayinputstream, bytearrayoutputstream, objectinputstream, objectoutputstream} object serialization extends app { def serialise(value: any): array[byte] = { val stream: bytearrayoutputstream = new bytearrayoutputstream() val oos = new objectoutputstream(stream) oos.writeobject(value) oos.close stream.tobytearray } def deserialise(bytes: array[byte]): = { val ois = new objectinputstream(new bytearrayinputstream(bytes)) val value = ois.readobject ois.close value } println(deserialise(serialise("my test"))) println(deserialise(serialise(list(1)))) println(deserialise(serialise(map(1 -> 2)))) println(deserialise(seri

android - Do we need to use background thread for retrieving data using firebase? -

i've android app i'm retrieving data fragment. , believe firebase manages asynchronous calls. still i've doubt if need write firebase code in background thread or not?. if need write background thread can please tell operations takes more time. eg: mdatabase = firebasedatabase.getinstance().getreference().child("blog"); i think performing on main ui thread may become risk full because setting connection between database may sometime take large time. the firebase database client performs network , disk operations off main thread. the firebase database client invokes callbacks code on main thread. so network , disk access database no reason spin own threads or use background tasks. if disk, network i/o or cpu intensive operations in callback, might need perform off main thread yourself.

how to print a string to UITextField in xcode ios -

i m having mobile number, saved in nsstring variable in program, want display in uitextfield when user gets window of user details in ios app. want disable editing of phone number. how can that? m using xcode 7.4.2 initially check string contains value or not , like yourmobilenumbertextfield.userinteractionenabled = true; if (yourstring.length > 0) { yourmobilenumbertextfield.text = yourstring; yourmobilenumbertextfield.userinteractionenabled = false; } swift yourmobilenumbertextfield.userinteractionenabled = true if yourstring.length > 0 { yourmobilenumbertextfield.text = yourstring yourmobilenumbertextfield.userinteractionenabled = false } update for hold previous value in app go nsuserdefault , step-1 when otp verification success save current mobile number in userdefaults [[nsuserdefaults standarduserdefaults] setobject:yourmobilenumbertextfield.text forkey:@"mobile"]; step-2 if second time user comes on page need call nsstri

python - Functions get called more and more times with reopening plugin -

i have qgis plugin written in python 2.7.3 pyqt 4.9.1, qt 4.8.1. when run plugin every function works fine. when close window , reopen again, every function happens twice. close/open again , goes 3 times, etc., etc. where should error here? def run(self) part looks this: def run(self): self.dlg.show() self.availablelayers() self.dlg.pushbutton_2.clicked.connect(self.openfile) self.dlg.pushbutton.clicked.connect(self.groupby) self.dlg.toolbutton_4.clicked.connect(self.togglerightpanel) if reload plugin clicking button "plugin builder", starts again one. i should mention wouldn't lose view user created (the plugin table viewer), rather able close window, open , have again there without cells being cleared. every time call connect , adds connection - if it's same slot. need move connections out of run() method , put them in setup method dialog, made once.

assembly - Registers modified by systemcall invoked through gcc's extended asm -

i using gcc's extended asm invoke system call. working on proprietary rtos on powerpc (freescale mpc5200b). according gcc's documentation should add registers assembly code uses - , neither input nor output - clobbers list, because gcc not analyse assembly code , not know registers being altered. the problem don't know registers system call alters. in fact i'm observing case system call alters register holding pointer. after system call has returned, pointer in register being used, leads invalid memory access. how should deal situation? for future readers: the general answer can find registers altered system call in documentation of system's abi. for system (freescale mpc5200b) found answer ibm application note 'developing powerpc embedded application binary interface (eabi) compliant programs'. so added registers marked volatile (namely r3..r12, f0..f13 , flags register) clobbers list.

hook - If the Wordpress session has timed out then run function -

i found examople: add_action( 'auth_cookie_expired', 'action_auth_cookie_expired' ); // define auth_cookie_expired callback function action_auth_cookie_expired( $rest_cookie_collect_status ) { echo 'ok'; wp_redirect( '/' ); }; but not work, when session timeout, , see popup login window add_action( 'auth_cookie_expired', 'action_auth_cookie_expired' ); // define auth_cookie_expired callback function action_auth_cookie_expired( $rest_cookie_collect_status ) { // set login session limit in seconds return year_in_seconds; // return month_in_seconds; // return day_in_seconds; // return hour_in_seconds; echo 'ok'; wp_redirect( '/' ); } please modify code according above code:

html - :hover triggered directly after page reload on Firefox (but not on Mac OS X Chrome) -

please check this codepen a) firefox , b) chrome. proceed follows: move mouse on link click link , not move mouse cursor @ afterwards wait until page has reloaded. if haven't moved mouse cursor, still above link after page has reloaded. firefox apply :hover styles now. chrome (mac os x) display element in it's non-hovered state (which prefer in scenario). anyone here has idea browser right, , how 1 browser mimic other's behaviour? for current scenario, i'd know how avoid :hover being triggered directly after page reload . i'd quite unhappy if had resort javascript that. for completeness' sake, here's demo's code: <a href="https://codepen.io/connexo/pen/pejbqj" target="_top">this codepen</a> a { color: #333; background-color: #ddd; display: inline-block; line-height: 40px; padding: 20px; text-decoration: none; transition-duration: .4s; &:before { content: "non-hove

caching - Android: How to access/manage cached files after an app restart? -

looking @ docs when comes caching, seems i'm supposed use createtempfile() , if call succeeds, creates empty file. , if called again same arguments, won't return same filename. so if restart app, not have way retrieve temporary file? if wanted implement lru algorithm removing files cache, creating normal (non-temporary) file key value pairs of filenames , timestamps seem reasonable? (since don't think android updates sort last accessed times files) i'd manage cached files in memory alone. create separate directory cache files , use in memory lru singleton class managing files. each time app restarted, scan cache directory , reload lru cache directory contents. loose cache statistics on restart, if that's bad thing can handled when paused. managing cache in memory faster writing , re-writing key-value pair file. how many files intend keep in cache?

osx - Testing IPv6 from iPhone -

i need test ipv6 connection iphone app. followed this , running alright. testing ipv6 fails "no ipv6 address detected". one thing not clear is: doc says should use nat64 network - suppose means connecting name of wi-fi network created? any or have had issues this? as per apple compliance not connecting ipv6 endpoint, ipv6 network continues provide access ipv4 content through translation (dns64/nat64). simply, provider network ipv4 , translating ipv6 network per apple compliance.if have actual ipv6 testing succeed.

Spring Security add Authorities -

we have migrated spring security 3.0.5 3.2.5. using below code adding authorities. userdetails loadeduser = new userdetails(); loadeduser.getauthorities().add(new grantedauthorityimpl("role_admin")); now code giving below error the method add(capture#1-of ? extends grantedauthority) in type collection not applicable arguments (grantedauthorityimpl) can 1 please me issue ? there reason why interface grantedauthority provides getter not setter, objects meant immutable. enforce logout/login on permission change , set authorities on object creation this .

c++ - How can I determine if UBSAN has been compiled in using clang or gcc? -

we use following code determine if -fsanitize=address has been specified @ compile time clang , gcc. how determine if -fsanitize=undefined has been specified? bool issanitized = false; #if defined(__has_feature) #if __has_feature(address_sanitizer) issanitized = true; #endif #elif defined(__sanitize_address__) issanitized = true; #endif i suggest file bug asan github (or gcc bugzilla) (we have defined asan , tsan makes sense cook 1 ubsan well). seems option pass custom define -fsanitize-undefined in makefile.

drupal 8 - Form redirects to page /form_action_cc611e1d -

i installed contact_storage module can set redirect path when completing form, whenever complete form apparently ignores whatever have filled redirect path field , sends me "/form_action_cc611e1d". i have no idea comes from, reference find path in code in bigpipe core module, except module has not been active in project. i've cleared cache 100 times no avail. have idea how resolve this? it seems redirect happens when attaching js library in hook_form_form_id_alter() of form, js adds html (no form controls div's) , click handlers. this happens in 1 of our 6 templates though there must else interfering, unfortunately ran out of time further investigate this. to fix form added request uri form again: function schade_forms_alter(&$form, \drupal\core\form\formstateinterface $form_state, $form_id){ //attach js $form['#attached'] = array( 'library' => array( 'insusite_forms/form', ), );

vba - Set font size of text -

i send text outlook email shows in font size 10. i have set @ 11 rest of email. signature set 11 well. i using this. ebody_tekst = "<font face= calibri size= 11px color=#000000>" & _ but still text show @ fontsize 10. probably may want try this: <body style=font-size:11pt;font-family:calibri>text</body>

java - write a gradle script that saves all the dependency into the ${projectDir}/lib folder -

so have gradle script gets dependencies following repository repositories { maven { url 'http://repository.paychex.com:8081/artifactory/repo1-cache' } ivy { url 'http://repository.paychex.com:8081/artifactory/repo1 cache' layout 'pattern', { artifact '[organization]/[module]/[revision]/[type]/[module]-[revision].jar' } } mavenlocal() } so when run customized gradle task wrote task showmecache << { configurations.compile.each { println } } it show jars being saved locally on c:\users\administrator.gradle\caches\modules-2\files-2.1*** i want write gradle task put dependencies given project ${projectdir}/lib folder instead of default location provided gradle. appreciated. thanks you can write copy task purpose: task copylibs(type: copy) { configurations.compile 'lib' } keep in mind still download , use resolved dependencies gradle cach

c++ - PCL registration of clouds -

i'm trying pairwise register clouds 3d template, warnings [pcl::sampleconsensusmodelregistration::computesampledistancethreshold] covariance matrix has nan values! input cloud finite? [pcl::randomsampleconsensus::computemodel] no samples selected! followed signal sigsegv, segmentation fault: 0x00007ffff344114d in pcl::registration::transformationestimationsvd<pcl::pointxyzrgba, pcl::pointxyzrgba, float>::estimaterigidtransformation(pcl::constclouditerator<pcl::pointxyzrgba>&, pcl::constclouditerator<pcl::pointxyzrgba>&, eigen::matrix<float, 4, 4, 0, 4, 4>&) const () my code is: registration->setinputsource(source); registration->setinputtarget(target); registration->setmaxcorrespondencedistance(0.3); registration->setransacoutlierrejectionthreshold(0.00001); registration->settransformationepsilon(10e-6); registration->setmaximumiterations(400); registration->setransaciteration

c# - Repository generic method GetById using eager loading -

i using entity framework , create generic getbyid method in repository class eager loading: here method uses lazy-loading: public virtual tentity getbyid(object id) { return dbset.find(id); } i know method find not support eager loading, how possible modify method use eager loading, use method follows(for example): _unitofwork.myrepository.getbyid(includeproperties: "users"); one possible way use firstordefault predicate on dbset include s. it's not hard build manually predicate using expression.equal method, main challenge how key property name. luckily can use objectcontext methods that, implementation (assuming have access concrete dbcontext instance): public virtual tentity getbyid(object id, params string[] includeproperties) { var propertyname = ((system.data.entity.infrastructure.iobjectcontextadapter)dbcontext).objectcontext .createobjectset<tentity>().entityset.elementtype.keymembers.single().name; var

How can I back up Google Datastore for efficient restoration? -

google datastore has backup utility . far slow operational database, taking hours run backup or restoration of few dozen gb. also, google recommends disabling cloud datastore writes during backup, again impossible operational database. how can backup datastore if there data corruption, can rapidly restore, losing @ few minutes of transactions? it seems essential part of full-strength database system. (other databases provide append-only storage or periodic backups augmented differential backup or transaction log or realtime mirroring, though doesn't handle case of data corruption bug writes database.) the backup utility starts mapreduce jobs in background parallelize backup/restore , perform faster. however, seems shard entities namespace. if data on 1 or few namespaces process can slow. you implement own parallel backup/restore mecanism using tool appengine mapreduce 1 or cloud dataflow 2 make faster.

php - Extending ORM classes in CakePHP 3 -

i extend query class in order create function customcontain() available in every table model. how should it? i want use blemethod() in table models in cakephp. have add code of function? have implements blemethod? unlike cake2 cake3 not feature application level class appmodel other classes inherit from. have 2 options: trait behavior the behavior can loaded globally models using model.initialize event. , loading behavior inside events callback. read these pages: creating behavior event system model / table callbacks but that's not want customcontain() indicates me want setup contains often. well, use finders. finders can combined: $this->table->find('foo')->find('mycontains')->all(); each custom find add query object. can add custom contains way. read custom finder methods .

regex - How do I force lines to be a certain length? -

i have text file contains large list of 5-digit numbers. lines contain more 1 5-digit number without newline separating them 12345 23456 34567 4567856789 67890 ... 837460174975917 ... i'm trying find regular expression can use sed add newlines in-between numbers. the desired output be: 12345 23456 34567 45678 56789 67890 ... 83746 01749 75917 ... i've played around bit, best can figure out ^([0-9]{5}) replaced $1/r/n. however, adds newline after every digit, , i'd need remove blank lines afterwards not optimal because of size of file. light weight solution using fold : sample input: cat filename 12345 23456 34567 4567856789 solution using fold: cat filename|fold -w5 12345 23456 34567 45678 56789 update(as suggested kenavoz): avoid unnecessary use of cat , pipe fold -w5 filename

rest - How to have logout for a stateless RESTful API -

so title says, i'm working on stateless restful api. authentication, i'm planning on using json web tokens. simplicity task. my 1 challenge, however, figuring out how log users out. on 1 hand, tokens have timeouts, , once timed out boom, no longer valid, easy logout. if want user able have logout button can press log them out. this desire have stateless server conflicts i'm trying do. thing can think of having value in databasee, version #, included in jwt hash, , every login/logout, gets changes. way hashes no longer match. i'm not sure if that's effective way job done. any suggestions appreciated.

mysql - PHP Inserting DB values into values in a class -

i want pull values db , insert them variables in class. is best , ideal way create db class , reference class within main class set protected values values db? if(!empty($s)){ $_client_id=$s['api_id']; $_client_secret=$s['api_password']; $_client_id=$s['api_secret']; $_access_token=$s['api_token']; $_username=$s['api_user']; } class myclass { protected $_client_id = '20123123'; protected $_client_secret = '76fesresg45grgerg3g34'; protected $_username = 'letshe' the best way use pdo's ability manipulate objects. get rid of mysqli, , use pdo objects right out of sql: class myclass { protected $client_id; protected $client_secret; protected $username } $sql = "select * my_class id=1"; $myclassinstance = $pdo->query($sql)->fetchobject('myclass'); $sql = "select * my_class"; $myclasscollection =

maven - Spring roo deleting all .aj files upon opening the console in source directory -

this respect existing roo project. imported maven project in sts, changed java version 7 6 , updated maven runs neatly. no issues . but tried opening roo console in source directory , boom it starts deleting .aj files without me trigerring anything. this how sequence goes. deleted / / / that_ .aj - not required governor or else says empty , generated .aj files gets deleted. when close shell , try reopening hoping roo generate files. not happen @ all. any on highly appreciated. new spring roo and configured use 2.0.0.m1 using m2 version , guessing not issue here. roo 2.0 contain api changes , less add-ons previous version release won't backward compatible version 1.3 ( https://spring.io/blog/2015/03/30/looking-ahead-to-spring-roo-2-0 ) so, api changes being done in each milestone, whom incompatible between them. if started project roo 2.0.0.m1 should continue using version. good luck,

Simple shiny audio file example does not render -

i'm having difficulty basic set-up audio , video tags in shiny . seems files in correct locations, no output being rendered , many of other inputs (such displaying controls) ignored. here simple reproducible example. in working directory source file stored have www/clip.mp3 file (any file replicate issue). library(shiny) app <- list(ui = shinyui(fluidpage( textoutput('text'), tags$audio(src = "clip.mp3", type = "audio/mp3", autoplay = true, controls = true) ) ), server = shinyserver(function(input, output) { output$text <- rendertext({ c(getwd(), file.exists(paste0(getwd(), '/www/clip.mp3'))) }) }) ) runapp(app) for me, output shows working/dir/path true , nothing else. looks in correct position according documentation ( http://shiny.rstudio.com/articles/tag-glossary.html ), yet nothing being rendered audio tag (even requested controls). everything fine pr

javascript - altjs react store connection not working -

i'm trying connect stores actual app in order provide data , react state changes. sadly though, store connection seems faulty. @connecttostores class app extends component { static getstores() { return [categorystore, userstore, localizationstore]; } static getpropsfromstores() { return { ...categorystore.getstate(), ...userstore.getstate(), ...localizationstore.getstate() }; } static componentdidconnect(props, context) { ca.fetchcategories(); la.fetchlocales(); } the componentdidconnect never gets used when running project. according this: https://github.com/altjs/connect-to-stores/issues/6 function should run stores have been connected. had working partially putting action in componentwillmount, states aren't updated properly. think store connect isn't set properly. i tried both es7 decorator / es6 normal implementation. i have no clue why data stores

android - How to disable manual sliding-out of navigation view -

i have 2 navigation views in activity. 1 enters right , other enters left. in navigtionview enters from left, different fragments started when when items clicked. , also, same navigationview has menu items common launched fragments. don't have problem one. now, navigationview enters right has menu items peculiar particular fragment started when first item in left entering navigationview clicked. means that, when clicked first item in left entering navigation drawer, fragament started, , items in right entering navigationview has items related fragment. so, right navigationview stared when menuitem in toolbar clicked. , menu item not visible when other fragments (apart aforementioned) in view. the problem have that, when right entering navigationview cannot launched through menuitem in other fragments, can still started sliding right edge of screen. want totally disable sliding feature of right entering navigationview, can launched when menu item clicked. codes ac

java - When using a Builder Pattern why shouldn't I reuse the builder-object to access the object configuration? -

when using builder pattern why shouldn't reuse builder-object access object configuration? example: normal way: objecta(objectbuilder b) { this.a = b.geta(); } public object geta(){ return this.a; } but why can't use this: objecta(objectbuilder b) { this.builder = b; } public object geta(){ return this.builder.geta(); } thanks :) a large reason using builder build immutable object: builder mutable, thing builds isn't (necessarily). if delegate builder, instance mutable again: has reference same instance of objectbuilder can change objecta . means checks on validity of state of objecta @ construction time can invalidated. if want mutable object, there no need builder: have setters on objecta .

android - com.google.api.client.googleapis.json.GoogleJsonResponseException: 500 Internal Server Error -

i getting 500 internal server error while calling app engine endpoint android client. in code looks fine , confused error. calling endpoint api: try { return myapiservice.updateuseraction(userid1, userid2, action).execute().getdata(); } catch (ioexception e) { return e.getmessage(); } useractionendpoint (simplest form): @apimethod(name = "updateuseraction") public defaultstringbean updateuseraction(@named("firstuserid") string firstuserid, @named("seconduserid") string seconduserid, @named("action") string action) { defaultstringbean response = new defaultstringbean(); response.setdata("200"); return response; } and defaultstringbean: public class defaultstringbean { private string result; public string getdata() { return result; } public void setd

c# - Entity-Framework auto update -

i try implement entity-framework project! project plugin-based not know object have save database. i have implemented so: public class databasecontext : dbcontext { public databasecontext() : base() { database.initialize(true); } protected override void onmodelcreating(dbmodelbuilder modelbuilder) { foreach( plugindto plugin in backendcontext.current.pluginmanager._plugins) { foreach(type obj in plugin.plugin.getplugindatabaseobjects()) { type typ = typeof(entitytypeconfiguration<>).makegenerictype(obj); list<methodinfo> l = modelbuilder.gettype().getmethods().tolist<methodinfo>(); methodinfo m_entitiy = modelbuilder.gettype().getmethod("entity").makegenericmethod(new type[] { obj }); var configobj = m_entitiy.invoke(modelbuilder, null); methodinfo m_totable = configobj.gettype().getmethod("totable"

data modeling - WinBUGS error: vector valued relation z must involve consecutive elements of variable -

i trying model multivariate probit model binary data. have been trying winbugs in return gives me error. ideas or suggestion warmly welcomed. model{ (i in 1:ns){ ## loop on studies for (k in 1:2){ ### loop on arm (j in 1:2){ ### loop on outcomes r[i,k,j] ~ dbin(p[i,k,j],n[i,k,j]); ## likelihood function p[i,k,j] <- phi(z[i,k,j]) z[i,k,1:2] ~ dmnorm(theta[i,1:2],with[i,,])i(-5, 5) #latent variable (z<0) or probit link theta[i,1] <- alpha[i,k,1] + beta[i,k,1] theta[i,2] <- alpha[i,k,2] + beta[i,k,2] } ###close loop on outcomes } ###close loop on arms alpha[i,2,1] <- 0 alpha[i,2,2] <- 0 alpha[i,1,1:2] ~ dnorm(0,.0001) beta[i,2,1:2] ~ dmnorm(d[1:2],prec[,]) beta[i,1,1] <- 0 beta[i,1,2] <- 0 ## priors on within study cov matrix with[i,1:2,1:2] <- inverse(cov.mat[i,1:2,1:2]) #define elements of within-study covariance matrix cov.mat[i,1,1] <- 1 cov.mat[i,2,2] &

sql server - Spatial index not helping SQL Query (very slow performance) -

Image
i'm trying test performance of spatial indexes on latitude/longitude values in table of 1.7 million postcodes. i've created geography column , added index it, query using spatial index dramatically (at least 100x) slower 1 using 'normal' index on lat/long columns in same table, yet query plan shows index being used. here query: declare @point geography set @point = geography::stgeomfromtext('point(-1.31548 51.06390)', 4326) select postcode , location.stdistance(@point) dist dbo.postcodes with(index(ix_postcodes_spatialindex)) location.stintersects(@point.stbuffer(200)) = 1 order location.stdistance(@point) how can go debugging what's happening here? edit: accepted of defaults when creating index: create spatial index [ix_postcodes_spatialindex] on [dbo].[postcodes] (location) using geography_auto_grid on [primary] query plan: (you may need zoom in ;)

python - KeyError when data encoded as string -

after struggle plotting code, end following minimal working example: import pandas import matplotlib.pyplot plt data = { 'foo': ['2', '335', '3'], 'bar': [1, 2, 1], } pandas.dataframe(data).plot.scatter('foo', 'bar') # keyerror plt.show() which raise keyerror: 'foo' . however, if use integers in foo data instead of strings: 'foo': [2, 335, 3], i expected scatterplot, without error. what rationale dataframe behavior ? can understand data must in same format. why raise (very laconic) keyerror in case ?

swift - Terminating app due to uncaught exception 'NSUnknownKeyException' -

i'm trying built simple calculator , got exception. has clue? code: class viewcontroller: uiviewcontroller { @iboutlet weak var display: uilabel! var userisinthemiddleoftyping = false @ibaction func touchdigit(sender: uibutton) { let digit = sender.currenttitle! if userisinthemiddleoftyping { let textcurrentlyindisplay = display.text! display.text = textcurrentlyindisplay + digit } else { display.text = digit } userisinthemiddleoftyping = true } } go viewcontroller scene on left -> right click on "view controller" -> check if outlets links each others (if 1 have warning symbol, delete it) -> rebuild projects

spring boot - WildFly 10, JCache - method caching -

i have simple application using spring boot. wanted allow method caching jsr107 - jcache. of tutorial put code : @cacheresult(cachename = "testpoc") public country getcountry(integer id){ system.out.println("---> loading country code '" + id + "'"); return new country(id, "x", "title"); } with pom file ... <dependencies> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-web</artifactid> <version>1.4.0.release</version> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-cache</artifactid> <version>1.4.0.release</version> </dependency> <dependency> <groupid>javax.cache</groupid> <artifactid>cache-api</artifa

saml 2.0 - SAML2 SP EntityID -

i have clients use saml idp providers okta , centrify. implemented saml, , want know information should send them when asking entityid. sp consume url app.mycompany.com/saml/consume, think entityid same consume url. question if should send diferent entityid each customer. example client clienta.app.mycompany.com/saml/consume, company b clientb.app.mycompany.com/saml/comsume. thanks help. what need send them entityid saml service provider. depending have used implement this, can obtained in different ways. if yo have of shelf software export metadatafile id located inside. if built yourself, depends. id give in issuer field when send messages idp.

Change all null to '' in array of Objects (javascript) -

i have array of objects shown below object {results:array[3]} results:array[3] [0-2] 0:object id=null name: "rick" value: "34343" 1:object id=2 name: null value: "2332" 2:object id=2 name:'mike' value: null as can see, in 1 object have id null, 2nd object has name null , 3rd object has value null. each object has property null. i want loop through of these , replace null ''. can let me know how achieve this... you needed google looping through objects. here's example: looping through every key (if keys unknown or want same keys) for (var i=0; i<arr.length; i++) { var obj = arr[i]; if (typeof obj === 'object') { (k in obj) { v = obj[k]; if (v

django - using python reserved keyword as variable name -

im trying send sms using webservice , webservice document suggest : response = client.service.sendsms( fromnum = '09999999' , tonum = '0666666666666', messagecontent = 'test', messagetype = 'normal', user = 'myusername', pass = '123456' , ) to fair dont have document python php/asp i've converted php sample unlike me may know pass reserved keyword of python so cant have variable name pass becuz syntax error ! is there way around trhis or should switch webservice ? wish put variable names in quotation mark or you can pass in arbitrary strings keyword arguments using **dictionary call syntax: response = client.service.sendsms( fromnum = '09999999' , tonum = '0666666666666', messagecontent = 'test', messagetype = 'normal',

ios - How do I configure identityData of NEVPNProtocolIKEv2 with String certificate? -

i using networkextension framework creating application, connect vpn server via nevpnprotocolikev2. after research, found tutorial working networkextension framework, , try follow it. ( http://ramezanpour.net/post/2014/08/03/configure-and-manage-vpn-connections-programmatically-in-ios-8/ ) but, stuck when configure identitydata of protocol. here m code: self.vpnmanager.loadfrompreferenceswithcompletionhandler { [unowned self] (error) in if error != nil { printerror("\(error?.errordescription)") return } let p = nevpnprotocolikev2() p.username = server.username p.serveraddress = server.serverurl // password persistent reference keychain self.createkeychainvalue(server.password, foridentifier: keychainid_password) p.passwordreference = self.searchkeychaincopymatching(keychainid_password) p.authenticationmethod = nevpnikeauthenticationmethod.none self.createkeychainvalue(kvpnsecret, foridentifier: keychainid_psk) p.sharedsecretreference = self.searchkeychai

python - How to pass dictionary to functions? -

i want pass dictionary user defined functions , need calculation based on dictionary values. not working me functions works fine without using functions. not sure, wrong code. please? no error message. input: "13-07-2016 12:55:46",user,192.168.10.100,192.168.10.20,connect,200,"www.abc.com" "13-07-2016 12:57:50",user,192.168.10.100,192.168.10.20,connect,200,"www.abc.com" "13-07-2016 13:00:43",user,192.168.10.100,192.168.10.20,connect,200,"www.abc.com" "13-07-2016 13:01:45",user,192.168.10.100,192.168.10.20,connect,200,"www.abc.com" "13-07-2016 13:02:57",user,192.168.10.100,192.168.10.20,connect,200,"www.abc.com" "13-07-2016 13:04:59",user,192.168.10.100,192.168.10.20,connect,200,"www.abc.com" "13-07-2016 13:06:51",user,192.168.10.100,192.168.10.20,connect,200,"www.abc.com" "13-07-2016 13:07:56",user,192.168.

Jquery link to show divs in sequence one at a time? -

i have page 5 divs. 1 of them shown default - other 4 hidden css. have button i'd able click , show div one @ time in sequence. in other words... 1st click of link shows div #2, second click adds div #3, third click show div #4 , final click have 5 divs visible. i'm fine show/hide aspect how can link move on show next div in sequence? a simple way implement number divs assigning ids div1, div2, div3 ... then it's matter of keeping track of count of visible divs. in click event handler of button, increment count , generate id of next div displayed. also add check see if count of visible divs equal total divs displayed. var visibledivscount = 1; var totaldivscount = 5 function displaynextdiv() { if(visibledivscount < totaldivscount) { visibledivscount += 1; $("#div"+visibledivscount).show(); } } $("#button").click(function(){ displaynextdiv(); });

jQuery Validate plugin: Can using the "depends" tag return an int? -

here example of rule declaration in rules object: myfieldobj: { maxlength: { depends: function(element) { if($("#intranetapplication").is(":checked") == true) { return 32; } else if($("#internetapplication").is(":checked") == true) { return 25; } } } } basically, code setting max length of myfieldobj validated based on user choice of question. however, code not seem work. know can return boolean values using code (e.g): myfieldobj: { maxlength: { depends: function(element) { if($("#intranetapplication").is(":checked") == true) { return true; } else if($("#internetapplication").is(":checked") == true) { return false; } } } } but work integers well? just remove depends property , use function method's parameter... myfiel

java - RXJava - combineLatest without losing any result -

i want combine 2 observables, 1 emits n items , other 1 1. combinelatest wait until both observables have @ least emitted 1 item , combines latest emitted items until both observable have finished. consider following chronologically order: observable -> emits result a1 observable -> emits result a2 observable b -> emits result b1 combinelatest combine result 2 of observable 1 result 1 of observable 2 (can tester here easily: http://rxmarbles.com/#combinelatest ). what need i need combine items of 2 observables, no matter 1 faster. how can that? result should (always, independent of observable starts emitting items first!): a1 combined b1 a2 combined b1 note untested: create replaysubject observable sequence a . each value emits on sequence b combine value replay subject create new observable of pair <a, b> . flat map these observables , return result. public static <a, b> observable<pair<a, b>> permutation(

c# - How do I read/write ListView ItemTemplate field using jQuery? -

i have been struggling this, put stripped down version show problems having. start generic class member class shown below: public class member { public member() { number = string.empty; name = string.empty; email = string.empty; phone = string.empty; } public string number { get; set; } public string name { get; set; } public string email { get; set; } public string phone { get; set; } public string linknumber { { var result = string.empty; if (!string.isnullorempty(number)) { result = string.format("<a class=\"showpopup\" id=\"{0}\">{0}</a>", number); } return result; } } } i want display in asp.net framework 4.6 webform using listview control. aside: there jsfiddle tool works asp.net? can't asp.net render there, post html here, in sections. in head o

ssh - Using Expect how do I exit foreach function after EOF -

after following script reads inventory file , completes commands testcommands file, foreach function looking more information inventory file process , errors rather ending. #!/usr/bin/expect set timeout 5 # open , read hosts file set fp [open "inventory_2ps"] set hosts [split [read $fp]"\n"] close $fp # commands run in server set fh [open "testcommands"] set commands [split [read $fh] "\n"] close $fh # set login variable set user "xxxxxxx"; set pw "xxxxxxx"; # spawn server login foreach host $hosts { spawn ssh $user@$host expect "$ " send "su - xxxxxx\n" expect "password: " send "$pw\n" expect "$ " send "xxxxxx -nobash\r" expect "> " foreach cmd $commands { send "$cmd\n" expect "> " } expect eof receives error after last host login/exit: