Posts

Showing posts from March, 2013

python - Find dicts from lists the have the closest value in a faster/better way -

i tried searching response not find 1 though i'm sure must have been asked before. must not searching correct phrases. my problem have 2 large lists of dicts , trying match dicts in list dict in list b has closest value particular key, in case timestamp . timestamps dicts may or may not same, , want proceed acting on dict list if has match list b timestamp value within 15 of it's timestamp. dictionaries not identical in structure both contain timestamp key value pair. first tried similar this: for itema in lista: closestitemb = min(listb, key=lambda x :abs(x["timestamp"])-int(itema["timestamp")) if(abs(itema['timestamp'] - closestitemb['timestamp']) < 15: #write info both dicts csv file this extremely slow large lists. realized lists both ordered timestamp should possible speed significantly my thought process on first loops through search entire list b closest , next time through search through small slice b

Malformed JSON string when using perl and earthexplorer -

i'm working usgs's earthexplorer setup batch downloads of landsat scenes based on spatial coordinates. provide wonderful handy script @ https://earthexplorer.usgs.gov/inventory/example/json-download_data-pl great. i'm working on cluster, , despite installing perl modules properly, when run script following output: running script... error: error: malformed json string, neither array, object, number, string or atom, @ character offset 0 (before "lwp support htt...") @ ./dl.pl line 182 this seems curious. way of explanation, script starts out with #!/usr/bin/perl #use strict; use warnings; use 5.010; use json; use scalar::util qw(looks_like_number reftype dualvar ); use lwp::useragent; use getopt::long qw(getoptions); ($username, $password); $username = "myusername_filled_in"; $password = "mypassword_filled_in"; getoptions( 'username=s' => \$username, 'password=s' => \$password, ) or die "error

excel vba - Custom Sorting a Collection of Class by Class Property -

i have dilemma i'm not sure how approach head-on. have 3 classes a segment class, has dictionary of customer classes, in turn have dictionaries of product classes. dictionary of customer classes needs sorted property of sumpoundssold . i don't know start. hints? i've figured out , answered below. ainwood posting chip pearson's code sorting collections/dictionaries! chip pearson has this page on vba dictionaries . includes how convert collections, arrays , ranges dictionaries (or each other), , how sort dictionaries. the (quite long!) code dictionary sorting follows: use: public sub sortdictionary(dict scripting.dictionary, _ sortbykey boolean, _ optional descending boolean = false, _ optional comparemode vbcomparemethod = vbtextcompare) '''''''''''''''''''''''''''''''''''''''''&#

Prioritizing queues among multiple queues in celery? -

we using celery our asynchronous background tasks , have 2 queues different priority tasks. have 2 cluster of nodes serving them separately. things working expected. question: we low priority tasks. optimized resource utilization, wondering there way configure workers(listening high priority queue) listen both queues. take jobs higher priority queue long job there? , fallback low priority queue otherwise. i have gone through priority based task scheduling discussed @ celery task priority . but questions prioritize queues not tasks within queue.

rest - Get aws bucket content listing using Postman - "Get Bucket (Version 2)" RestAPI -

i using postman send aws s3 restapi "get bucket (version 2)" bucket listing. name of bucket "test-bucket-1.ahadomain.com" (ahadomain.com dummy nonexistent domain used when naming bucket in aws). user credentials using has permissions make s3 calls. following info on page - http://docs.aws.amazon.com/amazons3/latest/api/v2-restbucketget.html i using endpoint : https://test-bucket-1.s3.us-east-1.amazonaws.com sending following headers : content-type, host, x-amz-content-sha256, x-amz-date, authorization do need add "list-type" query parameter or header? if query parameter, how state in url. i getting following response, not contain listing of content, info bucket itself: <?xml version="1.0" encoding="utf-8"?> <listallmybucketsresult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <owner> <id>6893100ea2b48696e8ccc3aa17414f4325cf59b574474ad9de0bcb0d139590c9</id>

javascript - Trying to retrieve data attributes after sorting between two lists using Rubaxa JS -

i sorting data between 2 lists using rubaxa sortable library. actually, unable track record of dragging , dropping between 2 lists. question how can updated orders of data attributes of list dropping element. here code on js fiddle: https://jsfiddle.net/wpplugindev/53vhp34e/22/ code: js: sortable.create(byid('foo'), { group: "words", animation: 150, store: { get: function (sortable) { var order = localstorage.getitem('foo'); console.log('foo', order); return order ? order.split('|') : []; }, set: function (sortable) { var order = sortable.toarray(); localstorage.setitem('foo', order.join('|')); } }, onadd: function (evt) { console.log('onadd.foo:', [evt.item, evt.from]); }, onupdate: function (evt) { console.log('onupdate.foo:', [evt.item, evt.from]); }, onremove: function (evt) { console.log('onremove.foo:', [evt.i

mysql - Search for field contents contained in other records -

i have list table having on 200,000 rows city column. assume contains following data: rowid city 1 toronto 2 milton 3 hamilton 4 delhi 5 new delhi 6 markham i want find records city contained in row, e.g. milton (row 2) contained in hamilton (row 3) , delhi (row 4) contained in new delhi (row 5). expect following output: rowid city rowid2 city2 2 milton 3 hamilton 4 delhi 5 new delhi can single query output looking for? thanks. assume table name 'cities'. following sql query should work: select c2.rowid, c2.city, c1.rowid, c1.city cities c1 inner join cities c2 on instr(c1.city,c2.city) , c1.rowid != c2.rowid

java - Form submit in Spring MVC 3 - explanation -

i'm having problems understanding how form submit in spring 3 mvc work. what want do, create controller take user's name , display him. , somehow have done don't understand how works. so.. i have form looks this: <form:form method="post" modelattribute="person"> <form:label path="firstname">first name</form:label> <form:input path="firstname" /> <br /> <form:label path="lastname">last name</form:label> <form:input path="lastname" /> <br /> <input type="submit" value="submit" /> </form:form> i have controller looks this: @controller public class homecontroller { @requestmapping(value = "/", method = requestmethod.get) public string showhellopage(model model) { model.addattribute("person", new person()); return "home"; } @requ

can i use while loop inside another while loop in php -

i'm creating comment system in project. want each posted question have comment. able post comment, having problem displaying comment it's respective answers. able display 1 row not row of comment. try use while loop nested inside while echo's each question, hangs. when use if displays first row of comment of each question. so question how can display them all? <div class="answer"> <?php include 'db.php'; $sql = "select * answers questionrid in(select id question id='$qid')"; $result = mysqli_query($con,$sql); if($result){ while($ro = mysqli_fetch_assoc($result)){ ?> <div class="a_view"> <pre> <?php echo $ro["answer"]; ?> </pre> </div> <div class="ans_comment"> <?php if($ro["id"]){ $id = $ro["id"]; $sqli

java - How can I switch activities when clicking a date using a DatePicker in Android Studio? -

i new android studio, , know how switch activity after clicking date using datepicker? or, @ least, make text appear on screen after clicking date. have read documentation datepicker , looked @ tutorials , reason, still lost on this. advice appreciated. (edit) alright, did more work , found out missing onclicklistener. problem text date changes if click on border of datepicker , not actual date. currently, code follows: activity.xml <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.constraintlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.wes19_000.working_on_it.mainmenu"> <datepicker android:id="@+id

asp.net - Azure Active Directory Flow for Web App Launched from Office 365 -

which of azure active directory authentication flows use single-tenant web application needs call microsoft graph api , launched office 365 app launcher? office 365 using same tenant web app, , i'm using azure ad v1 endpoint. example tried not quite work scenario, because expects user not signed-in already. i tried example: https://github.com/microsoftgraph/aspnetcore-connect-sample it works correctly when going application directly, clicking icon in office 365 app launcher displays following error: exception: openidconnectauthenticationhandler: message.state null or empty. is solution sign user out , re-authenticate them in order authorization code cache, or should use "on behalf of" flow instead? it seems set login url directly url of home page app without state parameter. to fix issue, home page of app recommend set. example, code sample should https://localhost:44334 . if want protect web app , allow authenticate users visit, can replace co

Rest assured 3.0.3 maven dependency in IntelliJ IDEA not working -

i new using intellij. setup project structure level 8 , added sdk , required fields. in pom have maven dependency restassured 3.0.3 can see dependency jar not working in project. import failing. please help. i had same issues in eclipse when first time installed it. clean worked me , closing , opening again.

Hex String to Reg File/Import Fail -

explanation okay, gist of i'm trying accomplish. wrote batch file named str2hex2reg.bat (refer below batch script) called during installation of program, this: str2hex2reg.bat c:\users\%username%\appdata\local\temp\libfile.dll this batch file take filepath string , convert hex , save it's output registry file following: windows registry editor version 5.00 [hkey_local_machine\software\company\program\component\settings] "fullpath"=hex:43,3a,5c,55,73,65,72,73,5c,44,65,76,69,6e,5c,41,70,70,44,61,74,61,5c,4c,6f,63,61,6c,5c,54,65,6d,70,5c,6c,69,62,46,69,6c,65,2e,64,6c,6c i quite pleased wrote batch file function , work correctly until point. problem okay here's run problem. key fullpath has string converted hex output , when open reg file looks correct; however, know fullpath key needs value this: [hkey_local_machine\software\company\program\component\settings] "fullpath"=hex:43,3a,5c,55,73,65,72,73,5c,44,65,76,69,6e,5c,41,\

itunesconnect - How to add in-app purchases to the first version of an app -

i have seen quesqion on answers did not solve problem different. hi, kknow have submit in-app purchases first version of app. so, mistake, submitted review binary without adding in-apps. ten seconds later remembered , when allowed reject binary did. as rejecting binary page reloaded on arcane itunes connected , 1 nano second options add in-app purchases appered , vanished. the problem appears in-app purchase being in waiting review, out of sync binary state. old bug of infamous itunesconnect. now, unable reject in-app purchase make options appear on app section, can add in-app purchases review , unable submit binary apple. the options have right is: contacting apple, did 2 days ago , still waiting. delete in-app , create again new bundle id , rewrite app deal new in-apps, make me happy. the pathetic part of entry app on itunesconnect second 1 because app first created without in-apps , apple rejected it, forcing me rewrite part of app include in-apps because hav

java - Firebase realtime Database -

Image
i have question i'm new in android app development. here mainactivity.java package com.koridevbrowser.app; import android.app.alertdialog; import android.content.dialoginterface; import android.graphics.bitmap; import android.os.bundle; import android.support.v7.app.appcompatactivity; import android.support.v7.widget.toolbar; import android.view.keyevent; import android.view.menu; import android.view.menuinflater; import android.view.menuitem; import android.webkit.webchromeclient; import android.webkit.websettings; import android.webkit.webview; import android.webkit.webviewclient; import android.widget.progressbar; import android.widget.textview; import android.widget.toast; import com.google.firebase.database.datasnapshot; import com.google.firebase.database.databaseerror; import com.google.firebase.database.databasereference; import com.google.firebase.database.firebasedatabase; import com.google.firebase.database.valueeventlistener; public class mainactivity extend

c++ - Best fit a circle from a binary image using contours or any other technique -

Image
i've have binary image computed algorithms. there hole in image , want best fit circle in hole. tried using bestminenclosingcircle function don't give best results. here binary image here function here expected i want exclude part here code finding contours vector<vec4i> hierarchy; vector<vector<point> > contours; findcontours(src, contours, hierarchy, retr_tree, chain_approx_simple, point(0, 0)); check code below #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include "opencv2/imgproc.hpp" #include <iostream> using namespace cv; using namespace std; int main(int, char** argv) { mat src, src_gray; /// load source image , convert gray src = imread("e:/test/iffz9.png"); resize(src, src, size(), 0.25, 0.25); /// convert image gray , blur cvtcolor(src, src_gray, color_bgr2gray); blur(src_gray, src_gray, size(3, 3));

c++ - Call a function with user arguments as function name and its arguments -

i new c++, , appreciate if me this. suppose have few functions defined: double square(float x) {return x*x} double cube (float x) {return x*x*x} read_lib(const string &file_name) now, when user inputs square 10 , want call square function, 10 argument, , return 100 . similarly, when user inputs cube 3 , want return 27 . similarly, when user inputs read_lib /path/to/file/library.gz , want process file. here code: int main() { string quote; while(quote != "quit") { cout << "enter: - "; string sa[70]; getline(cin, quote); istringstream iss(quote); int count = 0; while(iss){ string sub; iss>>sub; if(sub == "") break; sa[count] = sub; cout << "sub "<<count <<" " << sa[count]<<endl; count ++; } string str = sa[0] +

c - GCC inline assembler using memory references -

i'm trying write inline assembly instruction load variable contents of register using pointer variable instead of direct reference. the code using direct reference works fine , looks this: int x; int *y = &x; int z = 1; __asm__ __volatile__ ("mov %%edx, %0;"::"r"(z):); __asm__ __volatile__ ("mov %0, %%edx;":"=r" (x)::); printf("\n%x\n", x); disasm: 0x000000000040052d <+0>: push %rbp 0x000000000040052e <+1>: mov %rsp,%rbp 0x0000000000400531 <+4>: sub $0x10,%rsp 0x0000000000400535 <+8>: lea -0x10(%rbp),%rax 0x0000000000400539 <+12>: mov %rax,-0x8(%rbp) 0x000000000040053d <+16>: movl $0x1,-0xc(%rbp) 0x0000000000400544 <+23>: mov -0xc(%rbp),%eax

sql - MySQL BEFORE INSERT trigger to turn duplicate primary keys inserts into updates -

i'm trying execute query in database through phpmyadmin create trigger avoid_duplicated_sharing before insert on sharingevents each row begin if ( select count(*) sharingevents shared_note_id = new.shared_note_id , shared_to = new.shared_to > 0 ) delete sharingevents shared_note_id = new.shared_note , shared_to = new.shared_to end if; end but phpmyadmin gives me following error: mysql said: #1064 - have error in sql syntax; check manual corresponds mariadb server version right syntax use near 'end if' @ line 7 two questions: what's wrong script? after before insert trigger, insert operation performed? in case doesn't have remove insert sharingevents (select * new); i solve following code: delimiter $$ create trigger avoid_duplicated_sharing before insert on sharingevents each row begin if ( select count(*) sharingevents shared_note_id = new.shared_note_id , shared_to = new.shared_to > 0 ) delete sharingev

vb.net - Attempting to create code in Visual Basic to connect to a specific table in SQL Server, where to start? -

imports system.data.sqlclient imports system.data public class form1 inherits system.windows.forms.form 'create ado.net objects. private myconn sqlconnection private mycmd sqlcommand private myreader sqldatareader private results string private sub form1_load(sender object, e eventargs) handles mybase.load 'create connection object. myconn = new sqlconnection("initial catalog=contacts;" & "data source=) 'create command object. mycmd = myconn.createcommand mycmd.commandtext = "select " end sub end class that have far , getting info google. first project in vb. boss man wants me become programmer. unsure how initial catalog , data source bit written. i'm no expert on this, try this: imports system.data.sqlclient public class form1 private sub form1_load(sender object, e eventargs) handles mybase.load dim ssqlcommand string = "select yo

.net - c# System.Data.Entity.Spatial - does it require SqlServerSpatial.dll? (Azure WebJobs) -

have project ef6.0 models using dbgeometry types. on dev system sql client tools installed, works fine. deployed azureweb job, can't expect can put files in system folders. when run on vm in our network, getting unable load dll 'sqlserverspatial.dll' exceptions. line that's generating this: var line = dbgeometry.fromtext(wkt); i tried installing sqlservertypes nuget package sqlservertypes.utilities.loadnativeassemblies(appdomain.currentdomain.basedirectory); , making dlls copy always in sqlservertypes folder. deploy, copied entire debug folder across network - files guaranteed there. same results. i removed sqlservertypes , ran fine on system still (likely due sql client tools), , no change. why application using \packages\entityframework.6.1.3\lib\net45\entityframework.dll looking sqlservertypes? thanks

JAXB unmarshal Collection (Set) -

i testing marshalling , unmarshalling following java objects: framework class: @xmlrootelement (name = "framework") @xmlaccessortype(xmlaccesstype.field) @entity public class framework implements comparable<framework>, serializable { private static final long serialversionuid = 1l; @xmltransient @id @generatedvalue(strategy = generationtype.auto) private long id; private string frameworkname; private string frameworkversion; private string frameworkdescription; @xmlelementwrapper(name = "framework-domains") private set<frameworkdomain> frameworkdomainlist = new hashset<>(); @xmlelementwrapper(name = "framework-comments") private set<comment> comments = new hashset<>(); (contains getters, setters , nuber of functions without additional annotation) domain class: @xmlrootelement(name = "domain") @xmlaccessortype(xmlaccesstype.field) @entity public class frame

java - Using "TouchDown" for a specific area with GestureListener from LibGDX? -

is possible register input specific area of screen (like say, texture region) in libgdx using gesture listener class? i using touchdown method so: @override public boolean touchdown(float x, float y, int pointer, int button) { if(gameisover) { restart(); } if (gameisnotover) { if (x == regionobject.getregionx()){ system.out.println("touched"); } } } where regionobject texture region. works first part (gameisover), since registers touch on whole screen. but can't work on specific area. should use inputmultiplexer? or should else entirely? is possible @ gesturelistener/detecter? any specific use of gesturelistener ? touch can detected using inputprocessor or using adapter class (inputadapter) specific area need bound, can use sprite , holds geometry, color, , texture information drawing. sprite sprite=new sprite(textureregion); if(sprite.getboundingrectangle().co

reactjs - How i can use DropDown from Materialize css in React -

how can use dropdown materialize css in react component? when click on button, there no dropdown content code below: import react , {component} 'react'; import 'materialize-css'; export default class extends component{ opendropdown(){ $('.dropdown-button').dropdown({ induration: 300, outduration: 225, constrainwidth: false, // not change width of dropdown of activator hover: true, // activate on hover gutter: 0, // spacing edge beloworigin: false, // displays dropdown below button alignment: 'left', // displays dropdown edge aligned left of button stoppropagation: false // stops event propagation } ); } render(){ return( <div classname="input-field col s12"> <a classname='dropdown-button btn'

r - tmap: Unsightly white borders Mac/Rstudio -

Image
when doing this: library(tmap) data("europe") tm_shape(europe)+ tm_polygons(col="black",lwd = na) i'm getting unsightly white borders tmap. tried tm_fill , tm_polygons . , border.col=na or lwd=0 . this happens in rstudio when i'm exporting pdf or png . thin white lines getting crazy , appreciate help. thanks! r version 3.4.0 (2017-04-21) platform: x86_64-apple-darwin16.5.0 (64-bit) running under: macos sierra 10.12.5 matrix products: default blas:/system/library/frameworks/accelerate.framework/versions/a/frameworks/veclib.framework/versions/a/libblas.dylib lapack: /usr/local/cellar/openblas/0.2.19_1/lib/libopenblasp-r0.2.19.dylib locale: [1] de_de.utf-8/de_de.utf-8/de_de.utf-8/c/de_de.utf-8/de_de.utf-8 attached base packages: [1] stats graphics grdevices utils datasets methods base loaded via namespace (and not attached): [1] compiler_3.4.0 tools_3.4.0 update goal choropleth map. setting border-color 1 specific

xml - How to deploy zip file to Nexus repository via Maven -

i have zip file want deploy nexus repository. created pom.xml file , settings.xml file this. able upload nexus seems deployed jar file when put in <packaging>zip</packaging> element, maven doesn't recognize it. how can accomplish goal of deploying zip file nexus? appreciated. contents of directory: 1. content.zip 2. pom file 3. settings file pom.xml: <project> <modelversion>4.0.0</modelversion> <groupid>com.company.ct.ty16.archive</groupid> <artifactid>contentzip</artifactid> <version>0.0.1-snapshot</version> <name>deploy-zip-file</name> <description>deploy zipped content file on jenkins nexus</description> ... ... ... </project> note: not using maven build content.zip file, upload it i think can use mvn deploy file - https://maven.apache.org/guides/mini/guide-3rd-party-jars-remote.html

vb.net - How to disable all buttons inside a TabControl -

i apreciate community, suffering programmer's block , have attempted solve issue in many ways, no avail. i created demo (mockup) of larger project , have temporarily stored here: demo of issue what happening: if press exeggcute button buttons 1 thru 4 (in tabpage1 , tabpage2 ) disabled, , tabpage s. what should happen: if press exeggcute button buttons 1 thru 4 (in tabpage1 , tabpage2 ) should changed capital letters; however, change should affect buttons , not tabpages titles. buttons being disabled proof of concept; goal make text caps. this code using: ctl.text = ucase(ctl.text) - not work, why? need buttons shown in uppercase; however, option disable them works. why? public class form1 private sub btnexeggcute_click(sender object, e eventargs) handles btnexeggcute.click dim ctl control = 0 controls.count - 1 ctl = controls(i) if typeof ctl tabcontrol j = 0 controls.count - 1

TornadoFX TreeView cell factory not being called -

this related my previous question . i have treeview in center pane of borderpane layout. treeview populated selection of element list in left pane. center view looks this: class centerview : view() { override val root = treeview<istoryitem>() init { with(root) { root = treeitem(controller.storyset) setcellfactory { object : storyeditorcell() { init { system.out.println("creating storyeditorcell") ondragdetected = eventhandler {...} ondragover= eventhandler {...} ondragentered= eventhandler {...} ... } } } cellformat { ... } populate { ... } } } } the setcellfactory function being called but, reason, init of factory never being called. drag/drop handlers never set , treecell isn&

node.js - JavaScript Polling until getting specific result? -

i trying add polling application using link https://davidwalsh.name/javascript-polling (and many others). i have access following implemented api: client.get('url') // returns promise result of getting result url // application working on, // url returns json looks following // {status: done or in progress, other values...} // when status done other values use in application client.post('url', {data: passanydatahere}) // sends post request result of sending data url // starts specific job one of problems have run while trying adapt javascript polling code linked above, when find out status done, have no way of returning result outside of promise. can give me tips on how this? (polling until find specific value, , return value use later) let me give example export default function somefunction() { let = client.get('/status'); a.then( dataresult => { if (dataresult.status == "done") { //*

javascript - How do I switch connections using Node JS and mssql -

i have situation need query multiple sql servers bunch of data. so, iterating on sql servers first , iterating on queries have run. in caller function, have below code config.servers.foreach((element) => { sqlserver = element.server; element.queries.foreach(function(configquery) { jsonkey = configquery.key; sqlquery = configquery.query sqldatabase = configquery.database; var out; if (configquery.parameter) { sqlquery = sqlquery + " " + configquery.parameter + " = '" + partnumber + "'"; } sqlhelper.sqlfun(sqlquery, sqlserver, sqldatabase, jsonkey, callback) }) and sqlfun referes below function let connection ; function poolit (sqlquery,sqlserver,databasename) { if(!connection) { //sqlserver_temp = sqlserver //instead of checking if connection defined //we have check if connection open var dbconfiguration = { driver: 'msnodesqlv8', server: s