Posts

Showing posts from September, 2015

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

i'm trying implement crud operation using datatableseditor using datatables.but i'm getting error messages: 1)uncaught exception: datatables editor - remote hosting of code not allowed. please see http://editor.datatables.net details on how purchase editor license 2)typeerror: a.editor undefined 3) $.fn.datatable.editor not constructor" what reason? here configuration: <%@ page language="java" contenttype="text/html; charset=iso-8859-1" pageencoding="iso-8859-1"%> <!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> <title>insert title here</title> <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.12/css/jquery.datatables.min.css"> <link re...

Regex Matching Words in XML Between Two Other Words (Matlab regexp) -

i'm trying parse xml file using matlab regexp. retrieve array of incidences of word "curvepoint" occuring between "deposits" , "/deposits". xml below should [6x1] array like " <curvepoint> <curvepoint> <curvepoint> <curvepoint> <curvepoint> <curvepoint> " my attempt below doesn't work there lots of other text interspersed between each "curvepoint" word-incidence , look-aheads/backs, don't know how handle this. regexp(xmltext,'(?<=<deposits>)(<curvepoint>)(?=</deposits>)','match')' xmltext is <?xml version="1.0" encoding="utf-8"?> <interestratecurve> <effectiveasof>2016-11-07</effectiveasof> <currency>eur</currency> <baddayconvention>m</baddayconvention> <deposits> <daycountconvention>act/360</daycountconvention> <snapti...

distributed computing - How to run Tensorflow on SLURM cluster with properly configured parameter server? -

i in fortunate position of having access university's slurm powered gpu cluster. have been trying tensorflow run in cluster node, far have failed find documentation. (everyone have spoken @ university has run using cpu nodes before or using single gpu node. i found excellent bit of documentation previous question here . unfortunately, it's rather incomplete. of other distributed examples have found such such this 1 rely on explicitly specifying parameter server. when try run using code question, appears work until either fails connect nonexistent parameter server or hangs when server.join called , no print outs provided sbatch outfile (which understand should happen). so in short, question how 1 go starting tensorflow on slurm cluster? sbatch stage onwards. first time dealing distributed computing framework besides spark on aws , love learn more how configure tensorflow. how specify 1 of items in tf_hostlist example server parameter server? alternatively can use sbat...

python - multiprocessing pool with map -

i try multiprocess code this: param_seq = [] pool = pool(multiprocessing.cpu_count()-1) def work(param_set): (_, v) = experiment_sim(param_set[0], param_set[1]) v_dev = np.subtract(exp_v, v) return - np.sum(np.square(v_dev)) / (2 * noise_sigma ** 2) x in ra.values: y in gpas.values: param_seq.append((x, y)) likelihood = pool.map(work, param_seq) and looks working fine, work, in , stops , nothing , have stop program. following message occurs: process poolworker-8: process poolworker-10: process poolworker-13: process poolworker-14: process poolworker-11: process poolworker-12: traceback (most recent call last): traceback (most recent call last): traceback (most recent call last): traceback (most recent call last): traceback (most recent call last): traceback (most recent call last): file "/usr/local/cellar/python/2.7.11/frameworks/python.framework/versions/2.7/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap file ...

python - Poor performance of db. inserts using django-mssql -

i designed data warehousing application, struggle poor performance when fetching data source , saving them db. - approximately 150 kb/s. because of limitations imposed customer, forced use django on 64bit win machine , save data ms sql express (exact versions below). using django-mssql (1.7) backend. original data stored in .dbf file (visual foxpro), dbfread returns each row file python dict (this not issue, tested running reader discarding data). dictionary checked data quality (function sanitize_value_for_db() below), data copied django data model (attributes of object populated; tables wide, hence each table/object has 100 columns/attributes) , objects saved db. using django objects.bulk_create() (in batches of 50-100). i run code through profiler using cprofile , pstats modules. results below. see of time spent in pywin. have no clue if there can do. hints or opinions appreciated. thanks. configuration: xeon e5-2403 v2 @ 1,8 ghz, 30 gb ram windows server 2012...

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -

i trying convert json java object use of gson in maven, following youtube video guidance - https://www.youtube.com/watch?v=vqgghm9pwe0 , theres error occurs when in main class error - package com.squareup.okhttp3 doesn't exist. code below: java package com.codebeasty.json; import com.squareup.okhttp3.okhttpclient; public class main { private static okhttpclient client = new okhttpclient(); public static void main (string [] args) { } } i put in dependency in pom.xml: <dependencies> <dependency> <groupid>com.squareup.okhttp3</groupid> <artifactid>okhttp</artifactid> <version>3.4.2</version> </dependency> <dependency> <groupid>com.google.code.gson</groupid> <artifactid>gson</artifactid> <version>2.8.0</version> </dependency> </dependencies> i dont understand why doesn't recognize com.squareup. there may need download? have downl...

Generate uuid based on some value and retrive c# -

i need generate uuid based on (userid+time+ip) @ client side, , retrive details uuid (which user passes me through phone). what need in detail user,time , ip should encoded in uuid such way uuid self not reveal details after processing should able details. how encode values in uuid , retrive them ? suggested answer:(by vivek nuna) this code works fine generating uuid , how retrive userid,time , ip uuid ? string input = "userid"+"time"+"ip"; using (md5 sha256 = md5.create()) { byte[] hash = sha256.computehash(encoding.default.getbytes(input)); guid result = new guid(hash); }

Return maximum list of list in Entity Framework C# -

i have these 2 classes : public class result { public string plate { get; set; } public double confidence { get; set; } public int matches_template { get; set; } public int plate_index { get; set; } public string region { get; set; } public int region_confidence { get; set; } public long processing_time_ms { get; set; } public int requested_topn { get; set; } public list<coordinate> coordinates { get; set; } public list<candidate> candidates { get; set; } } public class candidate { public string plate { get; set; } public double confidence { get; set; } public int matches_template { get; set; } } i have query : list<list<candidate>> lstcandidates = deserializedproduct.results.select(i=>i.candidates).tolist(); as can see have list of list<candidate> . every candidate has plate , confidence . need plate number maximum confidence in lstcandidates . how can value? ...

javascript - What does obfuscated code mean? -

this question has answer here: what comma in javascript expressions? 4 answers so on site , peeking source code, , javascript code obfuscated(as usual). don't know obfuscated code normally, think this: var1 > 10 / 2, var1 = 0 is same as if(var1 > 10 / 2){ var1 = 0; } is how is? if not, please tell. you can see happen, when place code inside of parenthesis inside of console.log. need parenthesis, because console.log reads comma separator parameter. comma operator : the comma operator evaluates each of operands (from left right) and returns value of last operand. var var1; console.log(var1); // undefined console.log((var1 > 10 / 2, var1 = 0)); // 0 console.log(var1); // 0

mongodb - Configuring Parseserver hosted on Heroku to use AWS S3 Bucket -

i have app hosted on parse wanted migrate parseserver. so, did following : 1 - migrated data(without files) mongodb on mlab. 2 - deployed app directly on heroku using "connect github" button on heroku site connect parseserver repository wich have forked. 3 - have correctly configured app justed deployed on heroku use, mongodb database , parse app keys. 4 - downloaded latest parse android sdk , updated client use , went fine : new client connects correctly app hosted on heroku , can data mongodb database through app. 5 - created aws account , s3 bucket on , migrated files bucket parse. my problem : how use files s3 bucket in heroku app ? what did : followed tutorial on https://github.com/parseplatform/parse-server/wiki/configuring-file-adapters#configuring-s3adapter configure app use s3-adapter. tutorials devided in 2 parts : set bucket , permissions , configuration options . did first 1 no problem. in second 1 configuration options , configure s3 ada...

reactjs - Children to children components communication -

i have 1 parent component name [parent-1] , 1 child component name [child-1]. now, have few more other components name [other-1] , [other-2]. now passing [other-1] , [other-2] component [child-1] component. jsx rendering correct. how can access [other-1/2] component functions [child-1] ? or how can pass props [child-1] [other-1/2] ? by using refs able call [other-1/2] functions [parent-1] want access [child-1]. tried passing refs [child-1] <child abc={() => this.refs.other1.hello()}/> or <child abc={this.refs.other1.hello()}/> not working. by using global event emitter way able achieve solution above problem. not sure if that's appropriate way in react.js i think you're not using refs properly. when try give arrow function refs sometime causes error due ref returning null . see my question find out why. the example should understand refs hope helps! class others1 extends react.component { log(){ console.log('hello o...

android - Get activity `ViewDataBinding` field inside `Robolectric` unit test after being assigned -

i writing robolectric unit test requires me make use of activity under test view data binding class( viewdatabinding ), unfortunately no luck stuck being null inside of unit test inside of mainactiviy class: ... activitymainbinding binding; // <-- field returns null inside unit test ... @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); binding = databindingutil.setcontentview(this, r.layout.activity_main); } ... if has written test similar requirement please demonstrate example of how got viewdatabinding classed assigned before test completed. thanks! note: using android studio 2.2 i found out testing robolectric version 3.1 issue , after upgrading using robolectric version 3.1.4 activities viewdatabinding field no longer returning null see pr: https://github.com/emartynov/android-architecture/pull/1 thanks @eugenmartynov contribution towards issue. note: used gradle version 3.1 b...

Mixing javascript with jquery -

on click assign class element (svg path) using pure javascript: this.getelement().classlist.add('active'); the new class part of series of other classes has. once new class added clicked element, should give class .active other elements in html have matching classes clicked element itself. html: <button class="1600 1500"></button> <button class="1600 1300 1200"></button> <button class="1300 1200 1700 1800"></button> <button class="1300 1200 1100 1900"></button> <div class="1600 1700 item leaflet"></div> i don't know button has matching class since classes dynamic too. know div have class matching button's class. the thing specific reasons using pure javascript assign new class name on click on div ( works ): this.getelement().classlist.add('active'); so following won't work: this.click(function() { var classes = this.at...

html - "Span" Selector not working -

i trying build border around h1 reason can't select exact "span" in css? have written incorrectly? html h1 span { display: inline-block; padding: 0.5em border: white solid 10px; } <header> <div class="logo"> <img src="octopus.png"> </div> <nav> <a href="">one</a> <a href="">one</a> <a href="">one</a> <a href="">one</a> </nav> <h1><span>elias</span></h1> <p class="kicker">stuff // other stuff // more</p> </header> you missing ; after padding , won't let border work h1 span { display: inline-block; padding: 0.5em; border: white solid 10px; } /*demo*/ body { background: lightblue } <nav> <a href="">one</a> ...

tensorflow - Saving and Restoring a trained LSTM in Tensor Flow -

i trained lstm classifier, using basiclstmcell. how can save model , restore use in later classifications? i wondering myself. other pointed out, usual way save model in tensorflow use tf.train.saver() , believe saves values of tf.variables . i'm not sure if there tf.variables inside basiclstmcell implementation saved automatically when this, or if there perhaps step need taken, if else fails, basiclstmcell can saved , loaded in pickle file.

java - Memory Consumption is always increasing in Humble-Video -

i have been using humble-video in live streaming project convert flv mp4. i've realized java process's(in humble-video codes running) memory usage increasing when looking top command. after changed demo source code of humble-video , put segmentfile function in infinite loop , memory usage of process again increasing when looking top command. on 2.5gib , has been running 30 mins. i expect process's memory consumption stay stable somewhere between 40-50mb not keep increasing always. do have idea that? i've resolved problem. the problem garbage collector not clear weakreferences jnimemorymanager not delete native objects. calling system.gc() after every iteration helping not exact solution. the solution calling delete() @ end of each iteration. objects created may not expect during execution please @ objects created jnimemorymanager.getmgr().dumpmemorylog(); , @ how many objects alive jnimemorymanager.getmgr().getnumpinnedobjects(); the last s...

JSF wrong display of elements when iterating a Map -

i have simplify problem as possible. basically, map not been printed correctly after make modifications on it. i have following xhtml code: <c:foreach items="#{personcontroller.groupedpersons}" var="persong"> <p> <h:commandbutton action="#{personcontroller.removepersongroup(persong.key)}" type="submit" value="remove"> <f:ajax render="@form" /> </h:commandbutton> </p> <p>#{persong.key}</p> <p>#{persong.value.size()}</p> </c:foreach> this iterates on map , prints information. each key, there button allows removing map. with code in personcontroller bean (which @viewscoped , implements serializable ): private hashmap<integer, list<person>> groupedpersons; public void removepersongroup(integer age) { groupedpersons.remove(age); } my testing data has key=20 , 3 values (person) , key=30 ,...

How to display properties of a nested query in semantic media wiki? -

i have category called actors , called film. category film has property 'hasbudget' , 'hasactor'. each actor has property 'hasnationality'. i need display list of australian actors have features in films budget above 40 million. i use following query list actors , corresponding films , budget. {{#ask:[[category:actor]] [[hasnationality::australia]] [[-hasactor::<q> [[category:film]] [[hasbudget::>40000000]]</q>]] |?# |?-hasactor |?hasbudget |format=broadtable |link=all |headers=show |searchlabel=... further results |class=sortable wikitable smwtable }} however not able pick budget subquery. how can extract budget property? any appreciated..thanks that's right - you're querying category:actor result you're receiving actor pages , not film pages. there no "joins" in smw query syntax, way achieve use sub-queries along template result format. the idea encapsulate sub-queries templates, way able quer...

wordpress - Calling manually wp-load.php in conjunction with qtranslate-x I get file not found -

i have custom php code outside of wp-content of wordpress, ie www.xyz.com/test calling code below works fine, if enable qtranslate-x add language literal ie www.xyz.com/fr/test result "404 file not found." require_once($_server['document_root'].'/wp-load.php'); what can resolve problem ? do need plugins when loading wordpress core? core load minimum configuration (without plugins , themes): define('shortinit', true); require_once($_server['document_root'].'/wp-load.php'); if need theme support can trick: define('wp_plugin_dir', ''); require_once($_server['document_root'].'/wp-load.php'); /* start theme */ get_header(); the_content(); get_footer(); all code in functions.php should loaded fine

python - Referencing Tabs in Notebook Tkinter Widget -

i'm fresh python beginner (v3.5) trying work tkinter. i'm having trouble referencing tabs i've created within init class . error issue i'm receiving attributeerror: 'gui' object has no attribute 'tab1' . have feeling answer obvious , haven't been able figure out. i've tried hack away of irrelevant code efficiency. relevant code is: from tkinter import * tkinter.ttk import * class gui: def __init__(self): self.root = tk() self.root.title("title") self.notebook() self.player_selection_and_score() self.process_button() def notebook(self): nb = notebook(self.root) # creates notebook tab1 = frame(nb) # creates tab1 nb.add(tab1, text="score entry") # adds tab1 nb.pack(expand=1, fill="both") # pack tab make visible def player_selection_and_score(self): top = labelframe(self.tab1) ...

r - changing aesthetic ggplot2 layer object inside function -

Image
i trying change aesthetic of geom wasnt defined in original plot call. for example shape , size p=iris%>%ggplot(aes(x=sepal.length,y=sepal.width,colour=species))+geom_point()+theme_bw() change_shape=function(a){ a$layers[[1]]$aes_params[['shape']]=5 a$layers[[1]]$aes_params[['size']]=10 return(a) } pnew=change_shape(p) p clone layer (l) existing plot object , have not connect original plot clonelayer=function(l){ layer.names=c('mapping','data','geom','position', 'stat','show.legend','inherit.aes', 'aes_params','geom_params','stat_params') x=sapply(layer.names,function(y){ b=l[[y]] if('waiver'%in%class(b)) b=null if(y=='geom') b=eval(parse(text=class(b)[1])) if(y%in%c('position','stat')) { b=gsub(y, "", tolower(class(b)[1])) } b }) x$params=append(x$...

javascript - Why is ng-repeat being commented out my MEAN stack app? -

i trying simple tracer bullet mean stack application. stuck on trying app.js file in server communicate app.js in views. here index.html <!doctype html> <html ng-app="allinone"> <head> <link rel="stylesheet" type="text/css" href="/stylesheets/bootstrap.min.css" /> <link rel="stylesheet" type="text/css" href="/stylesheets/normalize.css" /> <link rel="stylesheet" type="text/css" href="/stylesheets/xxx.css" /> <script type="text/javascript" src="/src/angular.min.js"></script> <script type="text/javascript" src="/src/app.js"></script> </head> <body> <!-- header --> <header> <h1 class="text-center">xxx</h1> <h4 class="text-center">all in one</h4> </header> <!-- containers / content --> <...

c++ - How to reset or update KCF tracker ROI when it lose the target -

i using kcf tracking algorithm, problem when target exit window, tracker won't reset , show it's rectangle on edge of window wrongly. in ideal state tracker should delete rectangle when lose target. these codes: int main(int argc, char** argv) { rect2d roi; mat frame; // create tracker object ptr<tracker> tracker = tracker::create("kcf"); videocapture cap("c2_0002.mp4"); cap >> frame; resize(frame, frame, size(frame.cols / 2, frame.rows / 2)); roi = selectroi("tracker", frame); //quit if roi not selected if (roi.width == 0 || roi.height == 0) return 0; // initialize tracker tracker->init(frame, roi); // perform tracking process printf("start tracking process, press esc quit.\n"); (;; ) { // frame video cap >> frame; resize(frame, frame, ...

css3 - CSS all that start with chaining - CSS select all IDs that start with "u" and are in :hover and control other id that start with u -

i hope i'll able explain. i've got automatically generated code wish override css. here example of code wish override: #u1150:hover #u1153-4 p {color: red} important: "u" in code generated, other numbers randomly generated , added u (e.g. #u3726 or #u3427-12). since can count on u being generated, want grab control on ids via u letter , change color tried this: [id^u]:hover [id^u] p {color: green !important} in plain language tried to: 1. select ids start u , in :hover 2. further select ids start u 3. further select p tag , give different color (in case green) can achieved because code isn't achieving desired result. you're missing = symbol after ^ . [id^="u"]:hover [id^="u"] p { ... } [id^="u"]:hover [id^="u"] p { color: green; } <div id="u123"> <span id="u124"> <p>hover here make green</p> </span> </div> ...

forms - Multi-select Button grid angular2 -

i'm trying create small grid of buttons can clicked add values array part of object creation form in angular2. specifically, buttons display time signatures, of 0 or more can selected apply new song in music database. i've been referencing following article far: https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2 . currently when running in chrome, receive following error: core.umd.js:3004 exception: uncaught (in promise): error: error in http://localhost:3000/app/meter.component.html:1:23 caused by: cannot find control unspecified name attribute , , i'm having difficulty diagnosing element being considered unnamed in meter component. current code these components can found @ https://plnkr.co/edit/wyhzbnl8yoetvnkt6dvx?p=info .

C# .NET XML Search layout -

i want have query results come out vertical , element name next each result example "name: result". how can accomplish that? sending them rich text box. private void xpathbutton_click(object sender, eventargs e) { var doc = xdocument.load(ofd.filename); var = doc.xpathselectelements(xpathquery.text).elements(); var result = get.select(x => x.value); var stringlist = string.join(",", result.toarray()); queryresults.text = stringlist; }

javascript - Better Grouping for Mongoose Aggregate Queries -

a bit of background information on structure of collection. i've got various types of financial transactions, saved 1 collection using discriminatorkey. here example: "_id" : objectid("5816346ef201a84e17a84899"), "accountupdatedby" : -9.95, "transactionamount" : 9.95, "paidto" : "vimeo", "expensecategory" : "advertising", "accountname" : "bank name", "transactiondate" : isodate("2016-08-31t00:00:00z"), "transactionid" : "", "transactioncomment" : "", "transactioncategory" : "selfemploymentexpense", "transactionfee" : 0, "entrydate" : isodate("2016-10-30t17:57:02.144z"), "__v" : 0 what need gather of totals transaction types, grouped year , month. after taking @ similar questions here, best query i've come ...

Weights by name in Keras -

after training model using keras, can list of weight arrays using: mymodel.get_weights() or mylayer.get_weights() i'd know names corresponding each weight array. know how indirectly saving model , parsing hdf5 file surely there must direct way accomplish this? function get_weights returns list of numpy arrays no name information in them. as model.get_weights() , it's concatenation of layer.get_weights() each 1 of [flattened] layers. however, layer.weights gives direct access backend variables, , these, yes, may have name. solution iterate through each weight of each layer, retrieving name attribute. an example vgg16: from keras.applications.vgg16 import vgg16 model = vgg16() names = [weight.name layer in model.layers weight in layer.weights] weights = model.get_weights() name, weight in zip(names, weights): print(name, weight.shape) which outputs: block1_conv1_w_6:0 (3, 3, 3, 64) block1_conv1_b_6:0 (64,) block1_conv2_w_6:0 (3, 3, 6...

tensorflow - questions on defining and calling train.momentumoptimizer -

i have questions regarding following code segment def _optimizer(self,training_iters, global_step, opt_kwargs={}): learning_rate = self.opt_kwargs.pop("learning_rate", 0.2) decay_rate = self.opt_kwargs.pop("decay_rate", 0.95) self.learning_rate_node = tf.train.exponential_decay(learning_rate=learning_rate, global_step=global_step, decay_steps=training_iters, decay_rate=decay_rate, staircase=true) optimizer = tf.train.momentumoptimizer(learning_rate=self.learning_rate_node, **self.opt_kwargs).minimize(self.net.cost, global_step=global_step) the input pararameter of opt_kwargs setup opt_kwargs=dict(momentum=0.2...

ios - Ambiguous use of 'dismiss()' on UIButton when converting to swift 3.0 -

i have programmatically created uibutton in swift 2.0 named nobtn , signifies dismissal of uiviewcontroller . when user clicks button, view controller containing button dismisses. when converted swift 3.0 kept getting error: ambiguous use of 'dismiss()' i tried adding arguments dismiss() didn't work. here original code without arguments. nobtn.addtarget(self, action: #selector(setupnameviewcontroller.dismiss), for: uicontrolevents.touchupinside) rewrite this. first, give same class dismiss method: func dismiss() { self.dismiss(animated:true) } second, change selector #selector(dismiss) . now selector call dismiss function call dismiss(animated:completion:) trying do.

android studio - Trying to change the color of a dialog's button after closing it once -

so created dialog in android studio. wanted button switch colors after clicked red blue , blue red. if (btnsoundon.gettext().tostring().equals("on")) { bluebtn=false; btnsoundon.startanimation(scale1); btnsoundon.startanimation(scale2); btnsoundon.setbackgroundcolor(color.red); mp.pause(); btnsoundon.settext("off"); } else if(btnsoundon.gettext().tostring().equals("off")) { bluebtn=true; mp.start(); btnsoundon.startanimation(scale1); btnsoundon.startanimation(scale2); btnsoundon.setbackgroundcolor(color.blue); btnsoundon.settext("on"); } after close dialog wanted remember color of button. put in creating dialog function created: if (bluebtn) { btnsoundon.setbackgroundcolor(color.blue); } else if (!bluebtn) { btnsoundon....

How to arrange return order in an idiomatic way using pattern matching in Scala -

def arrange(str1: string, str2: string): (string, string) = { if (str1 == "yellow") { return (str1, str2) } else { return (str2, str1) } } i imagine write using pattern matching in more idiomatic way def arrange(str1: string, str2: string) = str1 match { case "yellow" => str1 -> str2 case _ => str2 -> str1 }

xml - stax parsing using java if element value blank then assign parsing element to upper element -

i parsing big xml input data using stax parser. my input xml part below <user> <loginname>abcd</loginname> <firstname>abcd</firstname> <lastname>kkk</lastname> <companyname>infosys</companyname> <emailaddress>mmm@gmail.com</emailaddress> <corporateemailaddress></corporateemailaddress> </user> my stax code below private static message parsemessage(xmlstreamreader xr) throws xmlstreamexception { string username = null; string content = null; string email = null; string comp = null; while (xr.hasnext()) { int event = xr.next(); switch (event) { case xmlstreamconstants.start_element: { string elname = xr.getlocalname(); if (login_name.equals(elname)) { username = xr.getelementtext(); } else if (content.equals(elname)) { ...

python - Merging tuples with same head in list -

this question has answer here: python list grouping , sum 5 answers i have list composed tuples. each tuple in following tuple format: (string, integer). i want merge tuples have same head (string) follows: [("foo", 2), ("bar", 4), ("foo", 2), ("bar", 4), ("foo", 2)] should become: [("foo", 6), ("bar",8)]. what python algorithm this? how collecting sums in defaultdict ? from collections import defaultdict d = defaultdict(int) (key, value) in items: d[key] += value and turn them list of tuples: list(d.items()) the defaultdict in example uses int function fill in unknown values 0 . first time particular d[key] added to, assumes initial value of 0 , gets summed there.

javascript - Running gulp gives "path.js:7 throw new TypeError('Path must be a string. Received ' + inspect(path));" -

Image
in wordpress project i'm using laravel elixir deal assets. working till today. now every time run gulp i'm getting: $ gulp path.js:7 throw new typeerror('path must string. received ' + inspect(path)); ^ typeerror: path must string. received { includepaths: [ 'bower_components/foundation-sites/scss/', 'bower_components/slick-carousel/slick' ] } @ assertpath (path.js:7:11) @ object.join (path.js:1211:7) @ prefixone (/users/slick/code/komarnicki2/wp-content/themes/komarnicki/node_modules/laravel-elixir/dist/tasks/gulppaths.js:143:43) @ gulppaths.prefix (/users/slick/code/komarnicki2/wp-content/themes/komarnicki/node_modules/laravel-elixir/dist/tasks/gulppaths.js:153:20) @ gulppaths.src (/users/slick/code/komarnicki2/wp-content/themes/komarnicki/node_modules/laravel-elixir/dist/tasks/gulppaths.js:44:25) @ getpaths (/users/slick/code/komarnicki2/wp-content/themes/komarnicki/node_modules/laravel-elixir/dist/ta...

algorithm - How do I map the position of a hamming-encoded bit to the position of the decoded bit using a closed function or map? -

this in reference simple sec hamming code of arbitrary length. have working decoder, requires 2 loops, , seems there should more efficient way of calculating position of changed bit in destination (decoded) bit-array. here current algorithm: decode(input_str) each symbol in input string if symbol == 1 xor position of symbol accumulator //binary addition if position not power of 2 append symbol output array //accumulator holds position of flipped bit in input string //need map position in output_string after reducing input bit array shorter, decoded bit array, need correct error has resulted flipped bit. position or index of flipped bit stored in accumulator. however, position of bit in input array. need way map position in output array efficient , doesn't loop. the issue more general this. i'm looking closed formula maps dst_bit src_bit in following tables show relationships between position of destination...

c++ - error in your SQL syntax; [...] near '%+var+%' at line 1 Consulta LIKE MYSQL -

` unicodestring user=usuario->text; unicodestring vidnom="select id_nombre nombre nombre % "+user+" %"; unicodestring contrasena; contrasena=log1->fieldvalues["id_nombre"];` i'm doing school project in embarcadero rad studio 10.1 berlin want make query wildcard "like" compiler throws me error '%+a variable-code+%' suggestions if understand code (formatted , corrected me) unicodestring user=usuario->text; unicodestring vidnom="select id_nombre nombre nombre '%"+user+"%'"; unicodestring contrasena; contrasena=log1->fieldvalues["id_nombre"];` then such concatenating sql query can lead sql injection, or dependency on special characters in data.

sql server - Log-in condition in Visual Basic -

so have code , i'm having hard time giving admin privileges. in database have boolean value is user admin . want write sql statement checks if person admin , use different form if person user. i'm new @ stuff - how go doing (with have checks if information i'm trying log-on user , take me new form) try con.connectionstring = "***" con.open() cmd.connection = con cmd.commandtext = "select username, pword users" _ & " (username = '" & txtusername.text _ & "') , (pword = '" & txtpassword.text & "')" dim lrd sqldatareader = cmd.executereader() if lrd.hasrows lrd.read() password = lrd("pword").tostring() username = lrd("username").tostring() password2 = txtpassword.text() ' if passowrd = passowrd2 , username = txtusername.text then' messagebox.show("logg...