Posts

Showing posts from July, 2012

generics - Java passing Comparator to constructor -

if want pass constructor comparator can compare on 2 different types, should parameter of constructor this?: public myclass(comparator<?> comp) { this.comp = comp; } then comparator class: public namecomparator implements comparator<string> { @override public int compare(string s1, string s2) { return s1.compareto(s2); } } then whenever instantiate class do: myclass myclass = new myclass(new namecomparator()); is correct way go doing this? thanks edit: here's relevant code: public class bst<t> { /* binary search tree */ ... private comparator<t> c; /* pass in comparator constructor*/ public bst(comparator<t> c) { this.c = c; } comparator: public class namecomparator implements comparator<string> { @override public int compare(string s1, string s2) { return s2.compareto(s1); } } when creating bst: bst bst = new bst(new namecomparator()); your requirements seem bi

c++ - C++11 regex::icase inconsistent behavior -

coming perl-like regular expressions, expected below code match regex'es in 8 cases. doesn't. missing? #include <iostream> #include <regex> #include <string> using namespace std; void check(const string& s, regex re) { cout << s << " : " << (regex_match(s, re) ? "match" : "nope") << endl; } int main() { regex re1 = regex("[a-f]+", regex::icase); check("aaa", re1); check("aaa", re1); check("fff", re1); check("fff", re1); regex re2 = regex("[a-f]+", regex::icase); check("aaa", re2); check("aaa", re2); check("fff", re2); check("fff", re2); } running gcc 5.2: $ g++ -std=c++11 test.cc -o test && ./test aaa : match aaa : match fff : nope fff : match aaa : match aaa : match fff : match fff : nope

Text manipulation in Python -

i have following list in python : [{"coefficient": -1.0, "compartment": "c", "molecule": "a", "evidence": []}, {"coefficient": -1.0, "compartment": "c", "molecule": "b", "evidence": []}, {"coefficient": -1.0, "compartment": "c", "molecule": "c", "evidence": []}, {"coefficient": 1.0, "compartment": "c", "molecule": "d", "evidence": []}, {"coefficient": 1.0, "compartment": "c", "molecule": "e", "evidence": []}, {"coefficient": 1.0, "compartment": "c", "molecule": "f", "evidence": []}] i want convert : a + b + c --> d + e + f which easiest way in python? the rules are: if coefficient negative, want treat co

python - Sha256 returning incorrect hash values? -

i'm trying hash bitcoin private key checksum, , 2 different libraries in python (hashlib + pycrypto) returning same incorrect result (after 1 hash). in linux terminal, correct hash result line: echo -n 8018ac3e7343f016890c510e93f935261169d9e3f565436429830faf0934f4f8e4 | xxd -r -p | sha256sum -b result: cd358f378809b3043ded3782d849fbad70f92a2dadefafd985d9aef443752e57 however, hashlib, pycrypto, , online sha2 hash tool return value: 5d6dce0f36a50abe51ee435ac11dac05f7879c1cd1ca5bc7aae706e5a3776d4a i'm not sure why returning different values. here 2 wif-keys generated them, top 1 using command line function, second using python; second 1 invalid (not accepted wallet softwares). 5j19pgytjzus7voaqjxdjuggwxsnqj18gwswvfvqjzqqgtxzf2v 5j19pgytjzus7voaqjxdjuggwxsnqj18gwswvfvqjzqqgvdc8hm import hashlib print( hashlib.sha256("8018ac3e7343f016890c510e93f935261169d9e3f565436429830faf0934f4f8e4").hexdigest() ) print( hashlib.sha256("8018ac3e7

service - Spring Boot app with embedded init.d script not starting on reboot -

spring boot has handy feature embed init.d starup script executable jar if configure maven plugin so: http://docs.spring.io/spring-boot/docs/current/reference/html/deployment-install.html#deployment-install so "installing" spring boot app (executable fat jar) service in centos 6.6 using above method. so far good. create link jar , set permissions: sudo ln -s /path/to/myapp.jar /etc/init.d/my-service sudo chmod 0755 /etc/init.d/my-service and can start application: sudo service my-service start however, want app come on startup, use chkconfig utility: sudo chkconfig --add my-service sudo chkconfig my-service on no errors commands, when reboot centos service not auto-start. running: sudo service my-service status shows: not running running: chkconfig --list my-service shows: my-service 0:off 1:off 2:on 3:on 4:on 5:on 6:off everything looks good, it's not starting. @ point can manually start service "sudo servi

machine learning - Python/Keras/Theano wrong dimensions for Deep Autoencoder -

i'm trying follow deep autoencoder keras example . i'm getting dimension mismatch exception, life of me, can't figure out why. works when use 1 encoded dimension, not when stack them. exception: input 0 incompatible layer dense_18: expected shape=(none, 128), found shape=(none, 32)* the error on line decoder = model(input=encoded_input, output=decoder_layer(encoded_input)) from keras.layers import dense,input keras.models import model import numpy np # size of encoded representations encoding_dim = 32 #nput layer input_img = input(shape=(784,)) #encode layer # "encoded" encoded representation of input encoded = dense(encoding_dim*4, activation='relu')(input_img) encoded = dense(encoding_dim*2, activation='relu')(encoded) encoded = dense(encoding_dim, activation='relu')(encoded) #decoded layer # "decoded" lossy reconstruction of input decoded = dense(encoding_dim*2, activation='relu')(encode

scala - how to get ClassTag[Long] from 10L -

using following code: val clz = 10l.getclass val classtag(clz) only boxed type: java.lang.long is there better solution? or impossible in scala? what makes think boxed? not: scala> classtag(10l.getclass).runtimeclass.getname res15: string = long scala> classtag(10l.getclass).runtimeclass == java.lang.long.type res17: boolean = true scala> classtag(10l.getclass).runtimeclass == new java.lang.long(10).getclass res18: boolean = false

cookieless - How to solve [Serve the following static resources from a domain that doesn't set cookies] -

i'm struggling in don't know @ all. when time ping website, got result: [serve following static resources domain doesn't set cookies:] . and, result caused images used background images. tried google topic answers seem difficult understand of. here knows , simple solution fix up? i'll try , give high level overview haven't given lot of specifics in question. that message suggesting if website www.company.com , should load static content www.companycdn.com . , new site ( www.companycdn.com ) simple static website not serve cookies. to this, need upload static resource (e.g. images) second domain. and update paths of images new domain. example, instead of this: <img src="logo.jpg"/> , should change <img src="//www.companycdn.com/logo.jpg"/> this answer has more information: https://webmasters.stackexchange.com/questions/1772/how-do-i-set-up-a-cookie-less-domain

swift - Adding and Displaying Integers in a Label -

i'm making scoring app can keep track of score different board games or such playing. here code have far. override func viewdidload() { super.viewdidload() } @iboutlet weak var scoretextfield: uitextfield! @iboutlet weak var scoretotal: uilabel! @ibaction func buttonpressed(sender: anyobject) { if let number = int(scoretextfield.text!){ scoretotal.text = "\(number)" } } i want able type in textfield , when button pressed add both previous number , 1 in textfield , display result in label. can me please? thank you! if let number = int(scoretextfield.text!){ let previousscoretext = scoretotal.text if previousscoretext == nil || previousscoretext.isempty == true { previousscoretext = "0" } scoretotal.text = "\(int(previousscoretext!)! + number)" }

C++ Beginner else statement not working -

i'm designing simple rpg me started in c++ coding, else statement not working, , feel code bulkier should be. wonderful people give me tips on how improve code , how fix else statement. aware of "system("cls")" hatred across everything, put there because makes more cleaner other methods. i'm still complete novice @ c++ way #include <iostream> #include <windows.h> #include <string> using namespace std; int save = 0; int menuinput; int raceinput; string race; int cont1; int main(void) { int save = 0; int menuinput; int raceinput; string race; int cont1; cout << "(insert generic rpg name here) \n"; if (save == 1){ cout << "main menu\n"; cout << "[1.] continue\n"; cout << "[2.] new game\n"; cout << "[3.] options\n"; cin >> menuinput;

ruby form_for password field not submitted to params hash -

Image
working through ruby on rails tutorial hartl right now. the password field displaying weirdly, , when submit information can see params hash doesn't display password key (but displays else). what's going on? views/users/new.html.erb: <h1> sign </h1> <div class = "row"> <div class = "col-md-6 col-md-offset-3"> <%= form_for(@user) |f| %> <%= render 'shared/error_messages' %> <%= f.label :name %> <%= f.text_field :name, class: 'form-control'%> <%= f.label :email %> <%= f.email_field :email, class: 'form-control'%> <%= f.label :password %> <%= password_field :password, class: 'form-control'%> <%= f.label :password_confirmation, "confirmation" %> <%= f.password_field :password_confirmation, class: 'form-control'%> <%= f.s

java - How to fix Error: Unresolved compilation problems: Syntax error on token "rs" -

can please tell me compilation error "exception in thread "main" java.lang.error: unresolved compilation problems: syntax error on token "rs", delete token method getstring(int) undefined type string @ selecttest.main" in below java code //selecttest.java import java.sql.*; public class selecttest1 { public static void main(string args[])throws exception { class.forname("sun.jdbc.odbc.jdbcodbcdriver"); connection con = drivermanager.getconnection("jdbc:odbc:oradsn","system","123"); statement st = con.createstatement(); resultset rs = st.executequery("select*from student"); { while(rs.next()) { system.out.println(rs.getint(1)+" "+rs.getstring(2)+" "rs.getstring(3)); } rs.close(); st.close(); con.close(); } } }

reporting services - SSRS - Display current grouping field values in report page header -

i'm using sql server data tools 2012 (visual studio 2010) , have multi-tab report page break on each combination of salesterritory , producttype. i can label worksheet tabs of resulting downloaded excel spreadsheet adding group-level pagename property expression in properties window concatenates 2 current grouping criteria values: =lookup(fields!salesregionid.value, fields!salesregionid.value, fields!salesregioncode.value, "salesregion") + " " + lookup(fields!producttypeid.value, fields!producttypeid.value, fields!producttypename.value, "producttype") what i'd add same string page header of each report page. can't add above expression in text box since "field references outside of data region must contained within aggregate functions specify dataset scope." so, how scope references in order display same string on both current tab , page header of each worksheet? it turns out pagename propert

SQL Server Merge replication: "Thread xxxx successfully re-established connection to Subscriber xxxxxx" -

Image
i have problems sql server merge replication , not work. not long ago, working. encountered problem. , data transmission can not give up. setting timeout agent profiles raised , therefore not have transaction in waiting.

mysql - Error using phpMyAdmin with Amazon RDS -

we have amazon rds instance , want manage phpmyadmin. i've got phpmyadmin running, there seems issues configuration can't figure out. my setup: ubuntu 14.04 php 7.0 apache 2.4 phpmyadmin 4.6.2 i did not install phpmyadmin apt-get because going install php5 , mysql stuff. downloaded site. my config.inc.php below: <?php $cfg['blowfish_secret'] = ''; /* must fill in cookie auth! */ $i = 0; $i++; /* authentication type */ $cfg['servers'][$i]['auth_type'] = 'cookie'; /* server parameters */ $cfg['servers'][$i]['host'] = 'path.to.rds.amazon.com'; $cfg['servers'][$i]['connect_type'] = 'tcp'; $cfg['servers'][$i]['compress'] = false; $cfg['servers'][$i]['allownopassword'] = false; i did not make other changes elsewhere. did not create phpmyadmin database. because read blogs issue database structure can't find script creates phpmyadmin

android - Unable to get package name in appium -

Image
i using appium mobile app testing when choose apk file not able see package name,launch activity name in appium drop downs,please find below screen shot .please 1 provide solution this. assuming had setup right the issue space in apk path . make sure don't have space in apk path. your path : e:\appium tutorials\apk\futurepay.apk i suggest rename folder appiumtutorials. path be e:\appiumtutorials\apk\futurepay.apk that should help!

c++ - Can Hippomocks set expectations for the same MockRepository in different source files? -

i have multiple tests in multiple files able call separately-compiled utility method file sets same expectations each test. however, hippomocks seems have problem setting expectations same mockrepository in different source files. here's simple example: file1.cpp is: void setotherexpectations(mockrepository &mocks); int method45() { return -45; } int method88() { return -88; } test(testofsettingvalueinanothersourcefile) { mockrepository mocks; mocks.oncallfunc(method45).return(45); mocks.oncallfunc(method88).return(88); setotherexpectations(mocks); testequal(45, method45()); // failed condition: (expected: <45>, actual: <8888> } file2.cpp is: int methodint(int) { return -145; } int methodchar(char) { return -188; } void setotherexpectations(testframework::mockrepository &mocks) { mocks.oncallfunc(methodchar).return(8888); // line mocks.oncallfunc(methodint).return(9999); // line b } if swap line ,

html - JQuery: append and appendTo doesn't work? -

this question has answer here: uncaught referenceerror: $ not defined? 32 answers $("body").append("<p>hi</p>"); $("<p>hello</p>").appendto("body"); <body> <p></p> </body> what doing wrong? append , appendto doesn't work. here's codepen: http://codepen.io/chiz/pen/meadew please try 1 works perfectly! $(document).ready(function() { $("body").append("<p>hi append</p>"); $("<p>hello appendto</p>").appendto("body"); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

css - HTML: Show placeholder first in input type date -

is possible me show placeholder in input first? right now, can see placeholder when click on input box, want when load page, placeholder can read instantly. rather mm/dd/yyyy, should show birth date when page loaded 1 thank you! <input placeholder="your date" type="text" onfocus="(this.type='date')" onblur="(this.type='text')" id="date"> read page how simulate placeholder functionality on input date field?

java - How to rectify the conflicts which occur at concurrent transactions in PostgreSQL -

i have function checks maximum value of pid , inserts database. but raises conflict while have concurrent transactions! so how can avoid conflict! create table tablea( sno serial, pid integer, ppid integer, pname text ); --this function checks maximum value of pid , inserts database. create or replace function insert_details(_pname text) returns void $body$ declare _pid int; begin _pid := (select max(pid) tablea); _pid := coalesce(_pid, 0) + 1; insert tablea(pid,pname) values(_pid,_pname); end; $body$ language plpgsql volatile cost 100; --(sub party)this function checks maximum value of ppid , inserts database.(sub-party) create or replace function insert_details(_pid int,_pname text) returns void $body$ declare _ppid int; begin _ppid := (select max(ppid) tablea pid=_pid); _ppid := coalesce(_ppid, 0) + 1; insert tablea(pid,ppid,pname) values (_pid,_ppid,_pname); end; $body$ language plpgsql volatile cost 100; my req

asp.net mvc - angularjs access denied when calling remote webapi using $resource -

i not sure if have cors issue angular app calling webapi. asp.net mvc/angular app1 , web api hosted on same iis server. example, url app1 https://example.com/app1 . web api url http://example.com/wcf_webapi/clinicaluserprofile/api/ {usernetworkname}. on mvc view page there <div ng-include=" 'path angular view template' "></div> uses $resource data webapi. in visual studio 2013 ide when hit f5 debug on development workstation works expected. can see call web api in ie developer tools' network tab. however, when publish app1 iis server, web api call doesn't seem made. instead, saw access denied in ie developer tools console. have mvc/angular app2 on same iis in different folder identical angular code. url app2 https://example.com/app2 . doesn't access denied. can help? thanks. here config.js /// <reference path="c:\users\myname\source\repos\apps\app1\scripts/angular.js" /> (function() { 'use strict'

memory - Detect swapping in python -

what best way determine if computer running script using swap memory? should cross-platform possible. 1 solution run program top subprocess, hope there's better way. you can use module psutil . not module in standard library though , have install using pip package manager. pip install psutil the swap usage data can gathered using psutil.swap_memory() . returns named tuple. >>> import psutil >>> psutil.swap_memory() sswap(total=2097147904l, used=886620160l, free=1210527744l, percent=42.3, sin=1050411008, sout=1906720768)

windows - Android Studio and Git - How do I GPG-sign my commits? -

according this link , need include -s switch sign commit using gpg key, don't see how can use in android studio. how sign commits in android studio? edit: appreciate osx solutions coming along, i'd see answer works windows. i use mac documents , stuff. after make test follow steps , works please remember restart android studio after follow steps: are tired off write password each commit??? follow link: https://github.com/pstadler/keybase-gpg-github after edit gpg.conf nano ~/.gnupg/gpg.conf add following lines use-agent no-tty default-key <your key id> after made configuration , if use macos. should: ln -s /usr/local/cellar/libgcrypt/1.7.0_1 /usr/local/opt/libgcrypt ln -s /usr/local/cellar/libgpg-error/1.22 /usr/local/opt/libgpg-error ln -s /usr/local/cellar/libassuan/2.4.2 /usr/local/opt/libassuan ln -s /usr/local/cellar/pth/2.0.7 /usr/local/opt/pth execute source ~/.profile make 1 commit using

ssl - HTTPS version 1 vs v2 - differences -

what major differences between https 1.x vs https 2.x ? tls , ssl part came in version 2.x ? is http/2 ( https://en.wikipedia.org/wiki/http/2 ) called https 2? http 1.1 ( https://tools.ietf.org/html/rfc2068 ) called https 1? there no https 1.x or https 2.x. there http 1.0, http 1.1 , http/2. https means of these http protocols encapsulated inside tls connection. the tls part same of these. there restrictions regarding protocol versions, ciphers , tls compression when using tls http/2, see rfc 7540, section 9.2 details. , make easier server know major http protocol version used inside tls connection client should use alpn tls extension tell server supports http/2.

PHP Query in MongoDB doesn't work -

i have been trying fix problem since days , can't solve it. i'm trying use mongo db first time , here's problem: $id = utf8_encode($_post['mongo']); $query=array("id" => $id); $conn = new mongo("mongodb://localhost:27017"); $database = $conn->test; $collection = $database->pages; $doc = $collection->findone($query); the $id variable set 2, findone doesn't return anything. if try example change id value in array 2 [$query=array("id" => 2);] db returns document need. it's mystery ahah. can see error? thanks l after connect should select document $id = utf8_encode($_post['mongo']); $query=array("id" => $id); $m = new mongoclient('mongodb://localhost:27017'); $db = $m->selectdb('yourdocumentname'); $collection = new mongocollection($db, 'yourcollectionname'); $doc = $collection->findone($query); var_dump($doc);

c# - Deserializing XML into object returns null values -

i trying deserialize xml document code using returning null value each time. i have xml this <?xml version="1.0" encoding="utf-8"?> <registrationopendata xmlns:i="http://www.w3.org/2001/xmlschema-instance" xmlns="http://example.gov"> <description>registration data collected abc xyz</description> <informationurl>http://www.example.com/html/hpd/property-reg-unit.shtml</informationurl> <sourceagency>abc department of housing</sourceagency> <sourcesystem>premisys</sourcesystem> <startdate>2016-02-29t00:03:06.642772-05:00</startdate> <enddate i:nil="true" /> <registrations> <registration xmlns:i="http://www.w3.org/2001/xmlschema-instance"> <registrationid>108260</registrationid> <buildingid>4731</buildingid> </registration> </registrations> </registrationopendata> to deserialize it, have crea

networking - What does the -P flag do for iperf? -

what do? if -p 100 on client side, does open 100 ports , make 100 connections given server in parallel? is what's used simulate server maintaining "x (simultaneous) connections in parallel"? note: answer iperf 2 related. iperf 3 single threaded. yes, if client computer supports threads there 100 traffic threads , 1 reporter thread. traffic threads send traffic server threads "in parallel" , reporter thread output statistics stdout per -i value. how "in parallel" depends upon cpu cores , os scheduling. more cores can allow more traffic threads run in parallel. when cores exhausted threads scheduled underlying os scheduler. (note: in 2.0.8 or greater , linux, traffic threads can set realtime scheduling using -z or --realtime.) bob

c# - EditorWindow implementation needs reimport to load asset -

i try extend unity editor custom editorwindow implementations. follows loosely this guide . i try save asset containing serialized objects sort of database. that works fine! however. if close unity , reopen it db = (figuredb)assetdatabase.loadassetatpath("assets/logic/database/figuredb.asset", typeof(figuredb)); doesnt load asset file unless manually reimport editorwindow implementation within unity (rightclick on cs-file -> reimport). i code in visual studio (whether matters or not.... suspected line-endings-problem, doesnt seem case) after reopening unity see within inspector (while selecting asset) the associated script can not loaded. please fix compile errors , assign valid script (even though there no compile time errors visible) any suggestions? if more info necessary gladly provide them, doesnt seem code problem rather ide-problem. do had use this? assetdatabase.importasset("assets/logic/database/figuredb.asset", importass

Gnuplot-Plotting only colorbox -

Image
i plotting several heatmaps using gnuplot . however, not not using group plot in gnuplot have decided better in latex individual heatmaps obtained. need gnuplot plot/figure colorbox (nothing colorbox ). there way in gnuplot? eg. if heatmaps 5-12: unset key set view map set style data pm3d set style function pm3d set xtics norangelimit 1 unset ytics unset ztics set title "colorbox heatmaps" set xrange [ 5.0000 : 12.0000 ] noreverse nowriteback unset colorbox splot (x-5)/(12-5) or if want vertical: set size ratio 3 unset key set view map set style data pm3d set style function pm3d unset xtics set ytics norangelimit 1 unset ztics set title "colorbox heatmaps" set yrange [ 5.0000 : 12.0000 ] noreverse nowriteback unset colorbox splot (y-5)/(12-5)

layout - How to save the position of a dragged ImageView in Android? -

following situation: i have layout imageview s on it. user can drag them around. have button add new imageview s. when clicking overview can choose image. overview activity ends , return fragment. now problem: because fragment initialized again when returning other activity, positions of imageview s put in place before lost. whats best way save positions of dragged imageview s? margins of each , save them? have sqlite db running think it's overkill save position of each imageview there. well question app remember positions in case of restart? if do, need use sort of persistent storage, such database, file or sharedpreferences . if not, cache them in memory, in hashmap example. to positions, in ondraglistener : public boolean ondrag(view v, dragevent event) { final int action = event.getaction(); switch(action) { // ... case dragevent.action_drop: float x = event.getx; float y = event.gety;

javascript - Responsive Menu not working (Menu is closing) -

i have menu in html/css/javascript , when click on menu try go 1 of pages in menu, nothing redirects , menu closes. though in html added tags href these pages html: <div id="pattern" class="pattern menu-link" style="max-width:574px; min-width:300px;"> <a href="#"><span style="font-size:27px; font-weight: bold; padding-top: 20px;" id="menustylish">&#9776; menu</span></a> <nav id="menu" role="navigation"> <ul> <li><a style="color:white;" href="index.html">homepage</a></li> <li><a style="color:white;" href="login.html">log in</a></li> <li><a style="color:white;" href="signup.html">sign up</a></li> </ul> </nav> </div> css: a { color: #daddde; text-decoration: none; }

ssl - Safari fails to give response when using HTTP/2 -

i'm newcomer nginx (been using apache in past). at moment i'm trying setup cache front apache backend, think (based on my, far, experience nginx) switch use nginx. as turn on http2 safari cannot response. in error log there nothing indicates problem , if turn on access log , check there can see safari client many, many connections, it's keeps refreshing page. i've tried numerous of nginx versions noticed there might problem latest stable. tried downgrading 1.9.14 upgrading 1.11.1, neither luck. nginx compiled just: ./configure --with-http_ssl_module --with-http_v2_module nginx -v output: nginx version: nginx/1.11.1 built gcc 5.3.1 20160413 (ubuntu 5.3.1-14ubuntu2.1) built openssl 1.0.2g-fips 1 mar 2016 tls sni support enabled configure arguments: --with-http_ssl_module --with-http_v2_module my config looks (my sites-available conf): upstream backend { server 127.0.0.1:8088 weight=100; } server { listen 443 ssl http2 deferred; server_

java - Fetching data from firebase taking more than one button click to display -

i want display data fetched firebase whenever user clicks button. code using currently todaypoem = (textview) findviewbyid(r.id.todpoem); /*firebase related code*/ myfirebaseref = new firebase("https://firebase url"); myfirebaseref.child("poem").addvalueeventlistener(new valueeventlistener() { @override public void ondatachange(datasnapshot snapshot) { system.out.println(snapshot.getvalue()); s1 = (string) snapshot.getvalue(); } @override public void oncancelled(firebaseerror error) { } }); } public void onclickpoem(view v) { todaypoem.settextsize(20); todaypoem.settext(s1); } and xml file contains textview , button fetch data firebase. problem whenever click button data not displayed instantly, takes 5-6 button clicks data displayed. doing wrong here? i had problem before... advice doi

Angularjs google maps API drawing polyline -

following code snippet gives me output (basically on each click new marker added , fetching it's lat , long values): 0: latitude: 40.207196906764054 longitude: -99.68994140625 1: latitude: 40.202477129519124 longitude: -99.60823059082031 code snippet: $scope.map.markers.push(marker); // console.log($scope.map.markers); (var item in $scope.map.markers) { console.log(item +': '+ "latitude: " + $scope.map.markers[item].coords.latitude + " " + "longitude: " + $scope.map.markers[item].coords.longitude); } to draw polyline need array in such format: var flightplancoordinates = [ {lat: 37.772, lng: -122.214}, {lat: 21.291, lng: -157.821}, {lat: -18.142, lng: 178.431}, {lat: -27.467, lng: 153.027} ]; i want draw lines along these markers. how can construct such structure inside loop add these lat , long values can feed 'path' variable polilines? you should able loop trough markers , add coordinates empty array (pr

html - How to set the value property in AngularJS -

html code <select class="form-control" id="txtcity" data-ng-model="register.city" ng-options="item item in dtcmbcity"> <option value="">please select</option> </select> <button type="button" ng-click="btnset();">set item</button> js code $scope.register = {city: ''}; $scope.dtcmbcity = ['delhi','bombay','chennai']; $scope.btnset= function () { $scope.register.city = "delhi" } my problem when load form data (delhi,bombay,chennai) displayed in select box. , click set button want set delhi selection box. thanks please help if looking setting value attribute in options fields same text value can you. your current code . ng-options="item item in dtcmbcity" result html. <select class="form-co

javascript - What RegEx would clean up this set of inputs? -

i'm trying figure out regex match following: .../string-with-no-spaces -> string-with-no-spaces or string-with-no-spaces:... -> string-with-no-spaces or .../string-with-no-spaces:... -> string-with-no-spaces where ... can in these example strings: example.com:8080/string-with-no-spaces:latest string-with-no-spaces:latest example.com:8080/string-with-no-spaces string-with-no-spaces and bonus be http://example.com:8080/string-with-no-spaces:latest and match string-with-no-spaces . is possible single regex cover cases? so far i've gotten far /\/.+(?=:)/ not includes slash, works case 3. ideas? edit: should mention i'm using node.js, ideally solution should pass of these: https://jsfiddle.net/ys0znlef/ how about: (?:.*/)?([^/:\s]+)(?::.*|$)

python - Invalid syntax error when applying lambda for multiple columns processing -

i have following code should put either 0 or 1 column indicator depending on if-then rules (values of columns t , s ): rawdata_base['indicator'] = rawdata_base.apply(lambda row: '1' if row['t']=='2' , str(row['s']).isdigit() , int(row['s'])<15 else '0' if row['t']=='2' , str(row['s']).isdigit() , int(row['s'])>=15 else '1' if row['t']=='1' , str(row['s']).isdigit() , int(row['s'])<35 else '0' if row['t']=='1' , str(row['s']).isdigit() , int(row['s'])>=35 else '0' if 'a' in row['s'] else '0', axis 1) i cannot figure out why error invalid syntax pops @ line el

javascript - How to attach data to fetch() request and get it back with response? -

is possible fetch() api attach arbitrary client-only data request , access response? i need attach sequence number each request particular endpoint , need somehow available through corresponding response (in order know when silently drop response "superseded" request), neither need nor want send seq number server , require server return it. just store in closure: var seq = 0; function makerequest() { var cur = ++seq; return fetch(…).then(function(response) { if (cur < seq) throw new error("has been superseded"); else return response.json(); }); }

java - Round double value to 2 decimal digits -

this question has answer here: format double value in scientific notation 5 answers how round number n decimal places in java 28 answers i have been working big numbers (with more 20 digits) , reason use double . form numbers 8.653762536765e28 . want display first 2 decimal digits. want 8.65e28 . i tried find formatting double values wan't able it. result getting 86537...12312.00 . what thing approach case? how can manage digits in front of e (the base) , not whole number? i think want achieve: double d = 8.653762536765e28; decimalformat df = new decimalformat("0.00e0"); system.out.print(df.format(d));

ios - Realm database file size -

my current realm file weights 700mb. many simple ios application. how can compressed copy of it? tried using realm.writecopytourl(url) official documentation , didn't me. problem can be? if realm database 700 mb , app simple, there's wrong db. try using realm browser inspect database , see if there's wrong. also, if added images database, suggest saving them directly filesystem instead , save path of image in database.

javascript - AngularJS $http.post 404 Error -

i new user angular.js, spa essence of it. however, when tried use $http.post , 404 error. here code file has 404: (function(){ angular.module('jerri') .controller('signupcontroller', ['$scope', '$state', '$http', function($scope, $state, $http){ $scope.createuser = function(){ console.log($scope.newuser); $http.post('api/users/signup', $scope.newuser).success(function(response){ }); } }]); }()); and error: angular.js:11821 post http://localhost:3000/api/users/signup 404 (not found) now, despite ignorance, referred google several hours. got many posts here on stack overflow angularjs website, have found nothing has worked @ moment. would mind helping me out rookie mistake? thank in advance. tavin

HTML form file upload to Google Drive and save URL to google sheet -

i'm new world of google scripting, , have found great tutorials on how either: upload file google drive html form ii append new rows google sheet. essentially trying to write basic html form collects few text fields , file attachment, file attachment uploaded google drive , url along other form text fields appended google sheet. here html form working (based on tutorial found): <!-- include google css package --> <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css"> <!-- can include own css styles --> <style> form { margin: 40px auto; } input { display:inline-block; margin: 20px; } </style> <script> // function called after form submitted function uploadfile() { document.getelementbyid('uploadfile').value = "uploading file.."; google.script.run .withsuccesshandler(fileuploaded) .uploadfiles(document.getelementbyid("labnol"));

php - mkdir permissions mess up -

i have simple code mkdir('users', 0775); but when go directory see drwxr-xr-x 4 www-data www-data 1m jun 11 16:30 users i expect see drwxrwxr-x 4 www-data www-data 1m jun 11 16:30 users what messing permissions? umask might affecting script. can try temporarily modify via php: http://php.net/manual/en/function.umask.php $old = umask(0); mkdir('users', 0775); umask($old); you try change permissions after directory created: mkdir('users'); chmod('users', 0775); … recommended on multithreaded web servers.

How to set border for a highcharts pie? -

Image
i want set border pie,but when there no data pie become this how realize it? you can catch load event, check series.data length , if empty, use renderer add empty circle. chart: { plotbackgroundcolor: null, plotborderwidth: null, plotshadow: false, type: 'pie', events:{ load: function() { var chart = this, series = chart.series[0], center = series.center; if(series.data.length === 0) { chart.renderer.circle(center[0],center[1],100) .attr({ fill:'rgba(0,0,0,0)', stroke: 'red', 'stroke-width': 1 }) .add(); } } } }, example: http://jsfiddle.net/u6tax8x4/

angular - Adding npm libraries to Angular2 (v2.0.0-rc.1) app -

i'm struggling bring npm libraries angular2 app (in particular, https://github.com/manfredsteyer/angular2-oauth2 ). when attempt import library app, 404. if add library systemjs.config.js map , packages sections, 404s library's dependencies. once add dependencies, 404s each dependency's dependencies (and on). i've added typings map github repo well: "dependencies": { "angular2-oauth2": "github:manfredsteyer/angular2-oauth2/oauth-service.d.ts#0a0d321" } what missing here? you need configure library , dependencies within systemjs configuration: var map = { 'app': 'app', // 'dist', '@angular': 'node_modules/@angular', 'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api', 'rxjs': 'node_modules/rxjs', 'angular2-oauth2': 'node_modules/angular2-oauth2', 'base64-js': 'node_modules/base64-js/

c++ - SIGSEGV in CUDA allocation -

i've host array of uint64_t of size spectrum_size , need allocate , copy on gpu. when i'm trying allocate in gpu memory, continue receive sigsegv... ideas? uint64_t * gpu_hashed_spectrum; uint64_t * gpu_hashed_spectrum_h = new uint64_t [spectrum_size]; handle_error(cudamalloc((void **)&gpu_hashed_spectrum, sizeof(uint64_t *) * spectrum_size)); for(i=0; i<spectrum_size; i++) { handle_error(cudamalloc((void **)&gpu_hashed_spectrum_h[i], sizeof(uint64_t))); } printf("\t\t...copying\n"); for(i=0; i<spectrum_size; i++) { handle_error(cudamemcpy((void *)gpu_hashed_spectrum_h[i], (const void *)hashed_spectrum[i], sizeof(uint64_t), cudamemcpyhosttodevice)); } handle_error(cudamemcpy(gpu_hashed_spectrum, gpu_hashed_spectrum_h, spectrum_size * sizeof(uint64_t *), cudamemcpyhosttodevice)); full code available here update: i tried in way, noy i've got sigsegv on other parts of code (in kernel, when using array

javascript - How would I go about separating numbers in a string and making them their own values? -

i'm making program user enters fraction, javascript code figure out percentage of given fraction. for example, figure enter 2/4, program return 50%. i'm wondering if there's function in javascript separate numerator , denominator given value , make them own separate values. here's code far: html: <!doctype html> <html> <head> <title>percentage finder javascript</title> <link rel="stylesheet" href="styles/index.css" /> </head> <body> <h1 id="head">enter fraction:</h1> <form> <input id="fraction" autofocus="on" placeholder="i.e: 1/4"></input> <input type="submit" id="sbmt"></input> </form> </body> <script src="scripts/js/index.js" type="text/javascript"></script> </html> jav

python - Darken or lighten a color in matplotlib -

Image
say have color in matplotlib. maybe it's string ( 'k' ) or rgb tuple ( (0.5, 0.1, 0.8) ) or hex ( #05fa2b ). there command / convenience function in matplotlib allow me darken (or lighten) color. i.e. there matplotlib.pyplot.darken(c, 0.1) or that? guess i'm hoping that, behind scenes, take color, convert hsl, either multiply l value given factor (flooring @ 0 , capping @ 1) or explicitly set l value given value , return modified color. a few months ago had solve problem. idea user choose color (any color) , software automatically generated colormap (this part of package scientific purposes). in case here code used achieve it. won't need of object give ask: import math class color(): def __init__(self, color, fmt='rgb'): self.__initialize__(color, fmt) def __initialize__(self, color, fmt='rgb'): if fmt == 'rgb': self.rgb = (int(color[0]), int(color[1]), int(color[2])) s