Posts

Showing posts from January, 2014

spring cloud configuration client spamming our configuration server -

we have set of micro services obtain configuration configuration server have created. our configuration server uses mongo backing store configuration files , run in redundant configuration if of configuration servers fail can fail on another. now configuration each service uses discovery location of configuration server. can see each service obtains reference ants proper configuration data server , services start correctly data. now 1 thing noticed services regularly request configurations configuration server every 3 mins. being done @ configuration client level , not in our code base. this request every service @ rate causing quite bit of load on configuration service. expected , if how can lower rate of these pings? one additional issue if make health request service, triggers request services configuration remote configuration service. the combination of both of these elements driving our configuration server ground since 5 requests/sec on server.

github - Git errors for a repo on network drive -

i've created network drive locally hosted website, , i'm managing files directly on network drive. , i'm using network drive local git repo. so, if make changes file there, i'd want able push my remote git repo. when start that, gives me many errors. sometimes, fails check status, gives errors such as "fatal: index file smaller expected" "fatal: unable create 'y:/demo.dotcms.com/demos/tstgit/.git/index.lock': file exists." "error: update_ref failed ref 'head': cannot lock ref 'head': unable create 'y:/demo.dotcms.com/demos/tstgit/.git/refs/heads/master.lock': file exists." "error: update_ref failed ref 'refs/remotes/origin/master': cannot lock ref 'refs/remotes/origin/master': unable create y:/demo.dotcms.com/demos/tstgit/.git/refs/remotes/origin/master.lock': file exists." i've googled , followed every direction in: 1. http://codybonney.com/fixing-fatal-index-fi...

android - MapFragment and Camera seem to interfere with each other in the same Activity -

i'm trying use mapfragment google maps android api v2 in conjunction camera preview. need able switch between camera preview , mapfragment, can’t make work. for camera preview, i’ve copied camerapreview class example guide . when want see camera preview, add instance of camerapreview class activity using camerapreview mpreview = new camerapreview(this); addcontentview(mpreview, new layoutparams(layoutparams.match_parent,layoutparams.match_parent)); this works fine when when i’m not using mapfragment. for mapfragment, i’ve added activity’s layout via <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".mainactivity" > <fragment android:i...

Alignment against parent div with CSS/HTML -

i'm working on little project buddy's band , switched new navbar. how it's layed out logo in center, , page links left/right of it. far that's working fine, wanted add text or maybe image right , can't figure out how navbar set center everything. example shown in image here: http://i.imgur.com/3slwdux.png keep in mind navbar stays on top of screen. here's looks @ moment, had use span2 css: .fixed-nav-bar { position: fixed; top: 0; z-index: 9999; width: 100%; height: 100px; background-color: #000; display: table; } span2 { display: table-cell; vertical-align: middle; position: relative; } html: <nav class="fixed-nav-bar"> <style> ul { list-style-type: none; overflow: hidden; background-color:000; } li { display: inline-block; } li { display: inline-block; color: white; padding: 14px 16px; text-decoration: none; } li a:hover { ...

slice - url string, jquery/js get numbers that are between two slashes -

i'm working on forum has url's so: http://www.place.com/forum/d7/2/ http://www.place.com/forum/d7/22/ http://www.place.com/forum/d7/234/ http://www.place.com/forum/d7/9999/ http://www.place.com/forum/d7/98765/ /d7/ username /2/ user id the user id's go 1 to, let's unlimited. how 'get' user id? i figured out how if it's 1 number, e.g., 2. how tell @ every number between last 2 slashes? this answer seek. var url = "http://www.place.com/forum/d7/9999/".split("/"); var id = url[url.length - 2]; this work if there trailing / . if there not, -1 instead of -2 , if check last character, can use understanding. var url = "http://www.place.com/forum/d7/9999/"; var islastslash = (url[url.length -1]=="/")? true: false; var url= url.split("/"); var id = url[url.length - (islastslash? 2: 1)]; return id;

html - CSS overflow container with images isn't working? -

i javascript/php programmer brand new css , having trouble getting images display in container overflow. understanding below code should display images in rows of 3 15 pixels of space between them. instead, displays 1 single image in top left of div should be. if remove id div images display down vertical line, , if remove div entirely flow rightward across page normally. when gave div background color appeared proper size , in proper location. #items_container { position:absolute; overflow:auto; height:500px; width:500px; } .item_image { margin: 0 15px 15px 0; padding: 0 0 0 0; } <div id="items_container"> <img src="imagelocation" height="150" width="150" class="item_image" /> <img src="imagelocation" height="150" width="150" class="item_image" /> <img src="imagelocation" height="150" width="150" cla...

phpmyadmin - MySQL connection conflict with wildcard (any) user and host -

i have weird user conflict on mysql server. have 2 users. stuck first wildcard user (any user @ host) , had deny him access security : ╔══════╦══════════════╦══════════╦═══════════════════╦═══════╗ ║ user ║ host ║ password ║ global privileges ║ grant ║ ╠══════╬══════════════╬══════════╬═══════════════════╬═══════╣ ║ ║ % ║ no ║ usage ║ no ║ ║ root ║ 10.15.15.115 ║ no ║ privileges ║ yes ║ ╚══════╩══════════════╩══════════╩═══════════════════╩═══════╝ the second 1 one using (forget fact doesn't have password). when try connect 'root'@'10.15.15.115' , mysql says : access denied ''@'%' even though explicitly specifying connect 'root'@'10.15.15.115' why mysql confusing first wildcard user? the host field specifies host you're connecting from , perception of wrote makes sound 10.15.15.115 server you're connecting to . if mysql can't match username , hos...

Keeping all Python imports in one file -

i have file , has lot of imports: import x y import z , on .... is there way keep imports in file called 'allimports.py' , able as: import allimports im then able use: im.x im.z , on i want because file has 20 rows of imports, , it's going increase. why not practice? when this: file a.py : import x it imports in x ... including other imports. if x has defined @ top: import y then can in a : x.y therefore, if in a : import x z you can do: z.y the difficulty importing function @ point imported: adding degrees of indirection makes things such testing, , determining going on in file, harder. ides allow collapse import lists, means problem you're trying solve (not having see huge list of imports) more solved tool. i note, too, 1 of important things code can readable. forcing use im. namespace in front of everything, occluding code doing, , preventing writing code elegant , easy read , understand.

silverlight - SlideInEffect not working on WP7? -

thanks in advance help. trying use toolkit slide animation on text blocks within panoramaitem. believe required add toolkit:slideineffect.lineindex each textblock want slide. well, did that, , cannot life of me work. any ideas going wrong? many thanks <controls:panoramaitem header="payslips" foreground="black"> <listbox x:name="payslipslistbox" margin="0,0,-12,0" itemssource="{binding alluserpayslips, mode=oneway}" toolkit:tilteffect.istiltenabled="true"> <listbox.itemtemplate> <datatemplate> <stackpanel orientation="horizontal" margin="0,0,0,17"> <stackpanel width="400"> <textblock text="{binding name, converter={staticresource nameconverter}}" textwrapping="wrap" style="{staticresou...

objective c - NSMutableArray error, keep saying error out of bounds -

i cant see forest through trees say. first off, here code : -(nsmutablearray*)getwaranty:(nsstring*)string start:(nsstring*)start and:(nsstring*)end{ nsmutablearray *waranties = [[nsmutablearray alloc] init]; nsrange startrange = [string rangeofstring:start]; nsrange valuerange; valuerange.location = startrange.location + startrange.length; //beginpunt nsrange eindrange = [string rangeofstring:end]; valuerange.length = eindrange.location - valuerange.location; nsstring *result = [[nsstring alloc]init]; result = nil; if(valuerange.location != nsnotfound){ if(valuerange.length != nsnotfound){ result = [string substringwithrange:valuerange]; nsstring *testresult = [[nsstring alloc]init]; testresult = result; nsstring* begintrim = [[nsstring alloc]init]; nsstring* begintrim1 = [[nsstring alloc]init]; nsstring* begintrim2 = [[nsstring alloc]init]; nsstring* begintrim3 = [[nsstring alloc]init]; nsstring* begintrim4 =...

foreach causing out of bounds error in Java when used with array -

this question has answer here: enhanced loop exception [duplicate] 3 answers i want print elements in array using foreach loop int[] array={1,2,3,4,5}; for(int i:array) system.out.println(array[i]); and compilers gives me error/warning exception in thread "main" java.lang.arrayindexoutofboundsexception: 5 but when print else int[] array={1,2,3,4,5}; for(int i:array) system.out.println("print something"); it writes "print something" 5 times , gives no warning/error. i assume has first element in array has index 0, not sure. can explain why ? in first chunk of code, not printing elements in array. going through elements in array , each element printing entry in array corresponding element's value. what want this: int[] array={1,2,3,4,5}; for(int i:array) system.out.println(i...

javascript - ng-repeat gets commented out by Drop.js -

Image
i'm trying make dropdown menu using drop.js , angular.js . when try use ng-repeat directive inside content element defined drop.js, ng-repeat element commented out reason (see screenshot below). knows why happens , what's way solve problem? screenshot of dom: i error in console: typeerror: cannot read property 'insertbefore' of null here's html code: <div id="dropdownmenu"> dropdown menu <i class="fa fa-caret-down"></i> </div> <div id="dropdownmenu-content"> <div>line 1 works fine.</div> <div>line 2 works fine too.</div> <div>but lines in ng-repeat not showing up!</div> <div ng-repeat="l in ['line 1', 'line 2', 'line 3']"> {{l}} </div> </div> my javascript code: var drop = new drop({ target: document.queryselector('#dropdownmenu'), content: do...

javascript - Angularjs - ng-disabled with angular.isDefined doesn't work -

i trying enable/disable radio button based on value backend when open kendo window. used ng-disabled angular.isdefined , angular.isundefined in html not working. here code below. per below backend data progressive radio button should disabled. <div class="col-md-6 zero-left-padding ligther" style="margin-left:-107px;"> <label for="progressive"> <input type="radio" id="progressive" name="version" ng-model="adhoctranscode.version" ng-value="24" ng-disabled="{{angular.isundefined(jobdetails.aes_data.instance_type_urlmap.nonlinear-progressive) && angular.isdefined(jobdetails.aes_data.instance_type_urlmap.broadcast) }}"/> <span style="font-weight:lighter;">progressive &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span> </label> backend json...

c# - How do you convert a Razor view to a string? -

i use razor view kind of template sending emails, "save" template in view, read controller string, necessary replacements, , send it. i have solution works: template hosted somewhere html page, put application (i.e. in view). don't know how read view string in controller. i use following. put on base controller if have one, way can access in controllers. public static string renderpartialtostring(controller controller, string viewname, object model) { controller.viewdata.model = model; using (stringwriter sw = new stringwriter()) { viewengineresult viewresult = viewengines.engines.findpartialview(controller.controllercontext, viewname); viewcontext viewcontext = new viewcontext(controller.controllercontext, viewresult.view, controller.viewdata, controller.tempdata, sw); viewresult.view.render(viewcontext, sw); return sw.getstringbuilder().tostring(); } }

javascript - Parse.com + AngularJS ngRoute - route on log in -

i want spa redirect user /home after logging in. first click on log in logs in user. second click - redirects. should happen on first click. if rid of user.login() code , promise, redirection works first time. why that? myapp.controller('logincontroller', ['$scope', '$location', function($scope, $location) { $scope.message = 'login page!'; $scope.update = function(usr) { user.login(usr.name, usr.password) .then(function() { $location.path('/home'); }, function(err) { alert(err.message); })} }]); button code: <button ng-click="update(usr)">log in</button> i tried putting $location code in then -operation(just in case) didn't work. edit: kinda got working. not suggested gave me idea. still, i'm reading events in angularjs @ moment. , see if come closer idea - promise. $scope.gohome = function() { $location.path('/home...

ruby on rails - ActiveRecord::RecordNotFound in CoursesController#show -

all courses showing on index.html.erb , trying view individual course clicking view more. should link show path understand, display individual course. result need. however, rails throughs error on url http://ruby-on-rails-102039.nitrousapp.com:3000/courses/rails (within url rails title of course, title created each new course. activerecord::recordnotfound in coursescontroller#show couldn't find course 'id'=rails extracted source (around line #7): def show @course = course.find(params[:id]) end course controller class coursescontroller < applicationcontroller def index @courses = course.all end def show @course = course.find(params[:id]) end routes devise_for :users root 'signups#new' resources :signups, only: [:new, :create] resources :courses prefix verb uri pattern controller#action root / signups#new root / signups#new signups post /signups(.:format) signups#create new_...

c# - Getting data from another form into dataGridView -

Image
i working on account generator , need making accounts appear datagridview in form. code right now. don't know how can put accounts datagridview . this form have: private void button4_click(object sender, eventargs e) { string email = richtextbox2.text; string password = richtextbox1.text; (var currentaccount = 0; currentaccount < (int32.tryparse(out)).richtextbox4.text; currentaccount++) { } list<string> firstnames = new list<string>(); firstnames.add("james"); firstnames.add("jakob"); firstnames.add("jacob"); firstnames.add("jonathan"); firstnames.add("albert"); firstnames.add("calvin"); firstnames.add("kyle"); firstnames.add("christopher"); firstnames.add("jeremy"); firstnames.add("ari"); firstnames.add("maximus...

php - Parse error - syntax error, unexpected T_STRING -

i've tried diagnose myself i'm no programmer, hopeful guys can me out. functions.php file, i'm told issue in add_filter('excerpt_more', 'new_excerpt_more'); line, wanted include larger part of code at. appreciated! function new_excerpt_more($more) { global $post; return '...<br><a href="'.get_permalink($post->id).'">read more <img class="read-more" src="'.get_bloginfo('template_url').'/images/read-more-arrow.jpg" alt="read more" /></a>'; } add_filter('excerpt_more', 'new_excerpt_more'); // custom excerpt length show homepage small excerpts function custom_excerpt_length($length) { return 100; } add_filter('excerpt_length', 'custom_excerpt_length', 999); the problem in above line return statement. there's apostrophe missing @ end of line, before semicolon. line should this: return '...<br...

android - Using external source folders -

i have codenameone project configured linked external source folder. java sources in external folder not being included in android builds. how fix include external sources. it works fine in simulator environment. one way add additional src line build.xml <javac destdir="build/tmp" compiler="modern" source="1.5" target="1.5" bootclasspath="lib/cldc11.jar" classpath="lib/codenameone.jar:${build.classes.dir}:lib/impl/cls"> <src path="src"/> <src path="../whereever/src"/> </javac>

javascript - How to apply var height = $(window).height() - 20; to .followTo() function -

i have script. pretty simple. js skills shaky @ best. makes navigation (which positioned bottom of window) scroll content until reaches top of page remains fixed. or "sticky" the issue im having since banner 100% in height. .followto(830); works on screen resolution. how make followto() find windows current height , follow height , subtract 20px followto value? ideal. can accomplished simply? var windw = this; $.fn.followto = function ( pos ) { var $this = this, $window = $(windw); $window.scroll(function(e){ if ($window.scrolltop() > pos) { $this.css({ position: 'fixed', top: "20px" }); } else { $this.css({ position: 'absolute', bottom: '0', }); } }); }; $('#mainnav').followto(830); someone ...

jquery - addClass function doesn't work -

i want add effect class existing classes input type="submit" has, long action contains string special . i'm using following code: <body> <form action="/go/special" method="post" target="_blank"> <input type="submit" class="zzz" value="click me"></form> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script> jquery(function($) { // find forms have "special" in action, find input, , add class $('form[action*="special"] input[type="submit"]').addclass('effect'); }); </script> </body> if work output should be: <form action="/go/special" method="post" target="_blank"> <input type="submit" class="zzz effect" value="click me"></form> but remains: <form action=...

oracle - Converting mysql procedure to pl-sql procedure -

Image
i trying convert mysql project pl/sql implement apex application. have problem converting stored procedure. working when using in mysql, gives error in pl/sql. have read pl/sql syntax, think have done necessary changes convert stored procedure pl/sql format. my code following: create or replace procedure findsuitableroom ( varbuilding_id in number, varlecture_block_id in number, varweek_of_the_day in number ) begin select a.room_id ( select room_id, room_number, r.building_id building inner join (select room.room_id, room_number, ruilding_id room inner join room_building_location on room.room_id=room_building_location.room_id) r on building.building_id=r.building_id r.building_id=varbuilding_id ) left join ( select room_id timetable timetable.lecture_block_id=varlecture_block_id , timetable.week_of_the_day=varweek_of_the_day ) b on a.room_id=b.room_id b.room_id null; end; i think apex being oracle product sh...

c# - Unit Test that involves some UI element -

should writing unit tests following? code: public observablecollection<dxtabitem> tabs { get; private set; } public icommand customerscommand { get; private set; } customerscommand = new delegatecommand(opencustomers); private void opencustomers() { var projectservice = new projectservice(project.filepath); var vm = new customersviewmodel(projectservice); addtab("customers", new customersview(vm)); } public void addtab(string tabname, object content, bool allowhide = true) { tabs.add(new dxtabitem { header = tabname, content = content }); } test: [testmethod] public void customercommandaddstab() { _vm.customerscommand.execute(null); assert.areequal("customers", _vm.tabs[1].header); } xaml: <dx:dxtabcontrol itemssource="{binding tabs}" /> i using tdd approach, working code, , passes tests locally, on server ci build fails test because view ( customersview ) has inside doesn't work. realized test, tho...

Output shell command in python -

def run_command(command): p = subprocess.popen(command, stdout=subprocess.pipe, stderr=subprocess.stdout) return p.communicate() on running : command = ("git clone " + repo).split() run_command(commmnd) everything working.but when try run multiple commands got error. command = ("git clone www.myrepo.com/etc:etc && cd etc && git stash && git pull).split() run_command(command) use subprocess.check_output() shell=true option, heed security warning re untrusted inputs if applies you. import subprocess command = 'git clone www.myrepo.com/etc:etc && cd etc && git stash && git pull' try: output = subprocess.check_output(command, shell=true) except subprocess.calledprocesserror exc: print("subprocess failed return code {}".format(exc.returncode)) print("message: {}".format(exc.message)) after output ...

DAPL errors on Azure RDMA-enabled SLES cluster -

i set 2 azure a8 vms in availability set running sles-hpc 12 (following tutorial here: https://azure.microsoft.com/en-us/documentation/articles/virtual-machines-linux-cluster-rdma/ ). when run intel mpi pingpong test, getting dapl errors: azureuser@sshvm0:~> /opt/intel/impi/5.0.3.048/bin64/mpirun -hosts 10.0.0.4,10.0.0.5 -ppn 1 -n 2 -env i_mpi_fabrics=shm:dapl -env i_mpi_dynamic_connection=0 -env i_mpi_dapl_provider=ofa-v2-ib0 /opt/intel/impi/5.0.3.048/bin64/imb-mpi1 pingpong sshvm1:d28:bef0eb40: 12930 us(12930 us): dapl_rdma_accept: err -1 input/output error sshvm1:d28:bef0eb40: 12946 us(16 us): dapl err accept input/output error [1:10.0.0.5][../../src/mpid/ch3/channels/nemesis/netmod/dapl/dapl_conn_rc.c:622] error(0x40000): ofa-v2-ib0: not accept dapl connection request: dat_internal_error() assertion failed in file ../../src/mpid/ch3/channels/nemesis/netmod/dapl/dapl_conn_rc.c @ line 622: 0 internal abort - process 0 similar errors when running 1 of osu mpi microbench...

php - Twitch API Live Callback Service -

i integrating twitch user account api platform , had through api see if there callback section of sort send update server when user starts streaming, can't seem find reference one. is there services offer sort of thing? if not, best way of running regular checks on of users in database see when streaming, of course doing alone kill server database queries, i'm stuck go now. what looking receive callback , create post in social feed user has started streaming. based on discussions @ links below, api doesn't support webhooks , won't anytime soon. instead, expect use polling. set worker process makes requests periodically, such every 5 minutes, creates appropriate social feed posts, etc. can batch them if have bunch of channels check (exaple from github issue): https://api.twitch.tv/kraken/streams?channel=riotgames,dota2ti,machinima,esltv_hearthstone https://github.com/justintv/twitch-api/issues/211 https://discuss.dev.twitch.tv/t/notifications-using...

Superimposing Multiple HTML Canvases with unique CSS Styles on top of Eachother -

i'm new stackoverflow , programming. i'm designing website right , wondering if me figure out how stack multiple html canvases on top of eachother, each own css style attached. right have square in middle of page css style attached establishes it's size, animates growth, etc. want top layer of several, larger squares have same effect (i.e. series of concentric squares expand when moused over.) here's html code: <html> <head> <meta charset="utf-8"/> <link href="hvr-grow.css" rel="stylesheet" type="text/css"> <link href="hvr-grow2.css" rel="stylesheet" type="text/css"> </head> <body onload="draw();"> <div> <canvas class="hvr-grow" id="magazine 1"></canvas> </div> <div> <canvas class="hvr-grow2" id="magazine 2"></canvas...

java - Debugging a Unity Android "Unable to convert classes into dex format" error on build -

i've been having trouble doing unity android build because of these dex format errors. i've looked @ similar errors people have had involving duplicate .jar files in unity project, i've removed culprits can find , still happening. updated unity facebook plugin , there several other plugins in project well, know prone have duplicate files. i can see there lot of "illegal argument exception" added translations errors, i'm assuming getting referenced twice, can't figure out these "accessibility service" files are. i'll admit rest of error i'm still trying figure out. i'm not super experienced java/android developer yet. does know might wrong? or have ideas of how might go debugging error further? error building player: commandinvokationfailure: unable convert classes dex format. see console details. /library/java/javavirtualmachines/jdk1.7.0_45.jdk/contents/home/bin/java -xmx2048m -dcom.android.sdkmanager.toolsdir=...

Is it possible to create a Windows exe on Linux using C++ with CMake? -

i'm working home windows pc on code, compile on linux pc on ssh connection. since resulting program creates gui, can't test it. possible create, besides linux program, windows exe can run on home computer? here cmakelists (using qt5): cmake_minimum_required(version 2.8.11) project(p3) set(cmake_prefix_path $env{qt5_qmake_dir}) message(status "qt5_qmake_dir: " ${cmake_prefix_path}) set(executable_output_path ${project_source_dir}/bin) set(library_output_path ${project_source_dir}/lib) set(cmake_include_current_dir on) set(cmake_verbose_makefile on) set(cmake_automoc on) # possibly set debug testing set(cmake_build_type release) include_directories(${cmake_current_binary_dir}) #project source directories find_package(qt5widgets required) find_package(qt5core required) find_package(qt5gui required) find_package(openmp) if (openmp_found) message("openmp found") set(cmake_c_flags "${cmake_c_flags} ${openmp_c_flags}") set(cmake_cxx_f...

c++ - Can i check if a chunk of memory (e.g., allocated using malloc) stays in the cache? -

assume allocate space using malloc. can check whether continuous memory remains within cpu's cache (or better within cache levels l1, l2, l3 etc.) in run-time ? determining content of cpu cache low level , beyond c can do. in fact, caching transparent code may writing cpu pretty decides cache , cannot afford waste timein convoluted logic on how so. quick googling on specific tools effect came intel tuning guide , performance analysis papers: https://software.intel.com/en-us/articles/processor-specific-performance-analysis-papers . obviously, vendor specific. amd have specific tools.

clojurescript - Checking if a Clojure(Script) Channel is Full -

suppose c channel of size n . trying write function in clojure(script) checks see if c full and, if so, closes channel. but how 1 check see whether channel full? core.async offers pair of functions this: offer ! put on channel if space available, , let know if full. poll ! gets if it's available , lets know if channel has nothing offer @ moment. so write like: (if-not (offer! my-chan 42) (close! my-chan)) which accomplish when putting on channel. safer trying have process watch moment get's full , close it. if want check if it's full can extract buffer , ask it: user> (->> (async/chan (async/buffer 1)) (.buf) (.full?)) false though think 1 through first.

json - What am I doing wrong with this Service Stack Web Service or jQuery call? -

i able service stack's hello world example working, i'm trying expand little return custom site object. made simple test html file uses jquery pull result back, i'm not getting site object returned (i think). here's web service: using funq; using servicestack.serviceinterface; using servicestack.webhost.endpoints; using system; namespace my.webservice { public class siterepository { } public class site { public string name { get; set; } public string uri { get; set; } //switch real uri class if find useful } public class siteservice : service //: restservicebase<site> { public siterepository repository { get; set; } //injected ioc public object get(site request) { //return new site { name = "google", uri = "http://www.google.com" }; return new siteresponse {result = new site {name = "google", uri = "http://www.google.c...

Unique array of random numbers using functional programming -

i'm trying write code in functional paradigm practice. there 1 case i'm having problems wrapping head around. trying create array of 5 unique integers 1, 100. have been able solve without using functional programming: let uniquearray = []; while (uniquearray.length< 5) { const newnumber = getrandom1to100(); if (uniquearray.indexof(newnumber) < 0) { uniquearray.push(newnumber) } } i have access lodash can use that. thinking along lines of: const uniquearray = [ getrandom1to100(), getrandom1to100(), getrandom1to100(), getrandom1to100(), getrandom1to100() ].map((currentval, index, array) => { return array.indexof(currentval) > -1 ? getrandom1to100 : currentval; }); but wouldn't work because return true because index going in array (with more work remove defect) more importantly doesn't check second time values unique. however, i'm not quite sure how functionaly mimic while loop. how's this: cons...

How to merge two arrays of objects, and sum the values of duplicate object keys in JavaScript? -

so, have indeterminate amount of arrays in object, , need merge objects in them. arrays guaranteed same length, , objects guaranteed have same keys. i've tried iterating through it, though reason, sums objects in every key in array. example: var demo = { "key1": [{"a": 4, "b": 3, "c": 2, "d": 1}, {"a": 2, "b": 3, "c": 4, "d": 5}, {"a": 1, "b": 4, "c": 2, "d": 9}] "key2": [{"a": 3, "b": 5, "c": 3, "d": 4}, {"a": 2, "b": 9, "c": 1, "d": 3}, {"a": 2, "b": 2, "c": 2, "d": 3}] }; mergearrays(demo); /* returns: { "arbitraryname": [{"a": 7, "b": 8, "c": 5, "d": 5}, {"a": 4, "b": 12, "c": 5, "d": 8}, {"a": 3, ...

javascript - Implementing brush thickness variation in HTML5 canvas (example want to emulate inside) -

Image
i pointed in right direction in terms of algorithm in demo below here http://sta.sh/muro /. canvas tools using - i.e. drawing lines or drawing many arcs, etc specifically want emulate brush turning cause entire "brush stroke" thicker. see image brush settings want emulate. ultimately, create paint brush vary in thickness when turned, behaviour below. to need record mouse points when button down. need check each line segment find direction, length of line , normalised vector of line segment can on sample mouse samples. so if have set of points taken mouse following required details. for(var = 0; < len-1; i++){ var p1 = line[i]; var p2 = line[i+1]; var nx = p2.x - p1.x; var ny = p2.y - p1.y; p1.dir = ((math.atan2(ny,nx)%pi2)+pi2)%pi2; // direction p1.len = math.hypot(nx,ny); // length p1.nx = nx/p1.len; // normalised vector p1.ny = ny/p1.len; } once have details of each line ...