Posts

Showing posts from February, 2014

ios - Selecting a row in table view with image and label gives only label text when get selected -

i have made program can select 2 things image , label table view , printed in console. when run program table view appears , cell contains image , label when select specific cell, text selected , image disappears. while when run program continuously gives memory warnings well. func tableview(_ tableview: uitableview, didselectrowat indexpath: indexpath) { let selecteddatag = countryl[indexpath.row] countrybutton.settitle(selecteddatag, for: .normal) self.countrytable.ishidden = true self.flag = 1 let indexpath = countryt.indexpathforselectedrow let currentcell = countryt.cellforrow(at: indexpath!)! as! flagtableviewcell let finalresult = currentcell.countrylabel.text! let finalflag = currentcell.flagimage.image! print("\(finalflag)" + "\(finalresult)") } } it's quirk of uitableviewcell, can use: cell.selectionstyle = .none to prevent happening , stop

reactjs - Webpack - Uncaught SyntaxError: Unexpected token import with Redux -

i have been trying out react webpack , redux , stumbled upon uncaught syntaxerror: unexpected token import. i know there lot of questions these, have find none involves redux. here webpack config: var app_root = 'src'; // app root folder: src, src_users, etc var path = require('path'); var cleanwebpackplugin = require('clean-webpack-plugin'); module.exports = { app_root: app_root, // app root folder, needed other webpack configs entry: [ // http://gaearon.github.io/react-hot-loader/getstarted/ 'webpack-dev-server/client?http://localhost:8080', 'webpack/hot/only-dev-server', 'babel-polyfill', __dirname + '/' + app_root + '/index.js', ], output: { path: __dirname + '/public/js', publicpath: 'js/', filename: 'bundle.js', }, module: { loaders: [ { test: /\.js$/, loaders: ['react-hot', 'babel'], exclude: /node_modules/, }, { // https://github.com/jtangel

How to hide gallery folder and show only the document using ACTION_GET_CONTENT in android? -

i want pick xls , xlsx files device. have used action_get_content, showing photos inside gallery. intent intent = new intent(intent.action_get_content); intent.settype("*/*"); intent.addcategory(intent.category_openable); string[] mimetypes = {"text/plain","application/pdf", "application/txt","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document"}; intent.putextra(intent.extra_mime_types, mimetypes); i don`t want gallery files shown. how achieve this...? in advance replace (intent.action_get_content); (intent.action_open_document);

node.js - How can I run a JavaScript automatically on a command-line? -

i have simple javascript myscript.js code below; var printer = function(somestring){ console.log(somestring); } printer("this printed on console."); i'm on windows 10 , need able call myscript.js on command prompt , have code executed without doing node myscript.js . there way set things command prompt or powershell can automatically call nodejs or other javascript engine? if windows can run normal shell scripts on command line can add shebang line node script shell scripts. example: #!/usr/bin/env node // node code here also can try configure node invoked files .js extension can security hazard because may execute arbitrary code clocking on javascript files may have downloaded on system wouldn't recommend that. another alternative make bat script node app: example.bat: node example.js example.js: // node script that able run just: example on command line.

android Place Autocomplete how to get list of searched place on top by default -

Image
i implement place autocomplete in application , write search keyword in edittext result according search place keyword. here code start placeautocomplete activity search place int place_autocomplete_request_code = 1; try { intent intent = new placeautocomplete.intentbuilder(placeautocomplete.mode_fullscreen) .build(this); startactivityforresult(intent, place_autocomplete_request_code); } catch (googleplayservicesrepairableexception e) { } catch (googleplayservicesnotavailableexception e) { } when activity launch list showing blank. what want- searched place should show when activity launch uber app you have persistent autocomplete results within internal app storage (shared preferences, database..) or somewhere want. basically, need implement ui yourself. don't think can customise placeautocomplete.intentbuilder needs. implement api-call autocompletegoogleplaces (we using retrofit this) @get("/maps/api/place/autocomplete

react native encoding conversion -

i'm trying convert fetch response iso-8859-1 utf-8 in react native. found answer : encoding conversion of fetch response in react native i'm having troubles... i didn't manage use iconv, tryed : npm install --save iconv-lite // success then do var iconv = require('iconv-lite') // error 500 react native i didn't manage use buffer, unknown react native and require('buffer').buffer // error 500 react native so here questions : what best way make encoding conversion in react native ? in case encoding conversion of fetch response good: how use iconv ? how use buffer ?

Python - in place list partition -

is there way partition list predicate in place using standard python 2.7( c++ stl std::partition style) ? group_by itertools without crating additional arrays ? need recursively partition array 2 groups, based on variadic conditions , limited amount of ram. what looking function like: partitioncppstyle(data, startindex, endindex, condition) which result in data[startindex:endindex] list having elements satisfying condition @ beginning , returning index of first element doesn't fullfil condition. no copies, little memory used possible. i've ended writing own implementation: def partitioninplace(data, startindex, endindex, predicate): swapindex = endindex index = startindex while(index < swapindex): if not predicate(data[index]): temp = data[swapindex] data[swapindex] = data[index] data[index] = temp swapindex = swapindex-1 else: index = index+1 return index is there

mysql - Count groups in table but if any record in 2 group is same then consider it as one group only -

i woking on production database in organisation. have come across 1 scenario. here sample data generated. actual data similar only, changed field names. table structure similar this, tableai - unsigned bigint(20) - auto increment index logindetails - varchar(200) logintype - tinyint(4) (2- gmail, 3 facebook) studentid - unsigned bigint(20) tableai | logindetails | logintype | studentid 1 | abc@gmail.com | 2 | 333 2 | abc@facebook.com | 3 | 333 3 | xyz@facebook.com | 3 | 444 4 | xxx@gmail.com | 2 | 444 5 | test@gmail.com | 2 | 555 6 | abc@facebook.com | 3 | 555 7 | ac@facebook.com | 3 | 666 8 | ac@gmail.com | 2 | 777 9 | abc@facebook.com | 3 | 777 i want count total number of students (that simple). here requirement if logindetail same 2 students consider them 1 student. so, above example studentid 333, 555 , 777 have same facebook email id. so, when count number of students, have consider these 2 student ids 1 though gmail account different. so, if 1 login detai

New to php programming, simple syntax error which I can't seem to resolve -

this question has answer here: php parse/syntax errors; , how solve them? 11 answers i'm having go @ php programming , bumped troubles syntax. don't seem understand php enough resolve syntax error, though should pretty obvious trained eye. i'm hoping can find solution error here. i have login page written in html/php called login.php: <?php session_start(); ?> <html> <body> <?php if (isset($_session["user"])) { echo "<p>welcome back, " . $_session["user"] . "!<br>"; echo '<a href="process.php?action=logout">logout</a></p>'; } else { ?> <form action="process.php?action=login" method="post"> <p>the username is: admin</p> <input type="text" name="user" size="20&q

java - Output of Elasticsearch query results -

there query elasticsearch database 6 aggregations. required every first aggregation namely ip address deduce data database. is, source ip address ip address, icmp-request, icmp.response, bytes_in, bytes_out. assume array of ip addresses , array of elements of separate class (with necessary data). how bypass aggregations create these arrays 6 nested cycles not want to. maybe knows how elasticsearch. or how crawl data on parameters without elasticsearch. searchresponse response = client.preparesearch("packetbeat-*").settypes("dns") .setquery(querybuilders.boolquery() .must(querybuilders.rangequery("@timestamp").gte("now-18d").lt("now-3d")) .addaggregation(aggregationbuilders .terms("client_ip") .field("client_ip")

java - ExecutorService with multiple threads not working normally but works fine in debug mode -

basically have process large csv file 1 million records using multi threading. i created class ingestioncallerthread public class ingestioncallerthread { public static void main(string[] args) { try { int count = 0; inputstream ios = ingestioncallerthread.class.getclassloader().getresourceasstream("aa10.csv"); byte[] buff = new byte[8000]; int bytesread = 0; bytearrayoutputstream bao = new bytearrayoutputstream(); while ((bytesread = ios.read(buff)) != -1) { bao.write(buff, 0, bytesread); } byte[] data = bao.tobytearray(); bytearrayinputstream bin = new bytearrayinputstream(data); bufferedreader fileinputstreambufferedreader = new bufferedreader(new inputstreamreader(bin)); while ((fileinputstreambufferedreader.readline()) != null) { count++; } bin.reset(); int numberofthreads = 12; int rowsforeachthread = count /

java - Can't seem to split String by new line regex -

i have method, , not correctly add split string list. public static list<string> formatconfigmessages(fileconfiguration config, string key, boolean colour, object... regex) { list<string> messages = new arraylist<>(); if (config.islist(key)) { config.getstringlist(key).foreach(message -> { if (message.contains("\\n")) { collections.addall(messages, message.split("\\r\\n|\\n|\\r")); } else { messages.add(message); } }); } else { string message = config.getstring(key); if (message.contains("\\n")) { collections.addall(messages, message.split("\\r\\n|\\n|\\r")); } else { messages.add(message); } } return messages.stream().map(message -> formatmessage(message, colour, regex)).collect(collectors.tolist()); } for bit of context, method used format configurable mes

class - What is causing the "Exception in thread "main" java.lang.NullPointerException" Error? -

this question has answer here: what nullpointerexception, , how fix it? 12 answers so in middle of project , supposedly code fine part keep getting errors anyway. i'm not sure original problem i'm sure it's changed @ point during changes. despite pointing the line problem, can't figure out problem(s) is/are. causing error? exception in thread "main" java.lang.nullpointerexception @ cafe.setname(cafe.java:14) @ cubancafe.main(cubancafe.java:16) import java.util.scanner; public class cubancafe { public static void main(string[] args) { string statename; scanner scan = new scanner(system.in); system.out.print(" enter state: "); statename = scan.nextline(); cafe cafestate = new cafe(statename); cafestate.setname(); cafestate.settaxrate(); system.out.println(cafestate);; system.ou

html - Align list items with variable height to bottom ul -

Image
i'd align series of li items bottom of parent, ul . 1 of tricky parts is: li items require float: left items being variable in height , width. there way achieve without using "hacky" method? here's current code: ul { width: 1000px; height: 400px; float: left; vertical-align: bottom; /* doesn't influence list items because of float: left. thought i'd put here anyways */ } ul li { float: left; display: inline-block; } ul li figure { /* determines width & height of list item */ margin: 0; padding: 0; width: 150px; height: 150px; background: red; } ul li:nth-child(2n) figure { width: 300px; height: 300px; } <ul> <li> <figure> <img /> </figure> </li> <li> <figure> <img /> </figure> </li> <li> <figure> <img /> </figure> </li> <

Google python Geolocator : SSL CERTIFICATE_VERIFY_FAILED -

i got ssl error when try use google geolocator. strange because same project works fine on other computers. here code : from geopy.geocodersimport googlev3 geolocator = googlev3(my_key) location = geolocator.geocode("1 rue martel, 75010 paris") here issue : traceback (most recent call last): file "/library/frameworks/python.framework/versions/3.6/lib/python3.6/urllib/request.py", line 1318, in do_open encode_chunked=req.has_header('transfer-encoding')) file "/library/frameworks/python.framework/versions/3.6/lib/python3.6/http/client.py", line 1239, in request self._send_request(method, url, body, headers, encode_chunked) file "/library/frameworks/python.framework/versions/3.6/lib/python3.6/http/client.py", line 1285, in _send_request self.endheaders(body, encode_chunked=encode_chunked) file "/library/frameworks/python.framework/versions/3.6/lib/python3.6/http/client.py", line 1234, in endheaders

angularjs - How to forbideen updating model in Angular JS? -

i have nested controller like: <div ng-controller="maincontroller"> <div ng-controller="childcontroller"></div> </div> inside child controller there function: $scope.isstatus = function() { return function(item) { }}; this function used in ng-repeat . so, problem when modify model of controller maincontroller reload model of childcontroller , means function isstatus() works again , reload model. how fix it? you can use controlleras syntax avoid this <div ng-controller="maincontroller main"> <div ng-controller="childcontroller child"> <ul ng-repeat ="item in child.item"> </div> </div> and in js function childcontroller (){ var vm = this; vm.isstatus = function() { return function(item) { }}; } you can see more infomation in here https://github.com/johnpapa/angular-styleguide/tree/master/a1#controllers

java - Error Building Android APK - duplicate v4 widget -

when "build apk," getting "duplicate entry" error. it's fine when build , run in emulator, or on actual device. when go build apk upload, fails. there ton of similar questions on stackoverflow, point out support-v4 culprit...and error spells out well. i've tried eliminating of them no avail. appreciated. here error: error:execution failed task ':app:transformclasseswithjarmergingfordebug'. > com.android.build.api.transform.transformexception: java.util.zip.zipexception: duplicate entry: android/support/v4/widget/compoundbuttoncompatlollipop.class and here app's gradle.build. put in gist make more readable. https://gist.github.com/crowell256aa/eb38857b76bee88c8d66782d8fcf83b8

What is props in ReactJS, Is it the same $scope of angular? -

what props in reactjs? same $scope of angularjs? can't seem understand props in react, since im new it. thank in advance. they not equivalent: react props input values passed components describe output. angular $scope object refers contextual execution (the scope) expression. [check out answer 'what $scope in angular?'] angular $scope object defines context of variables/properties/functions of controller object. react props actual arbitrary values consumed component function/class. react docs : " conceptually, components javascript functions. accept arbitrary inputs (called "props") , return react elements describing should appear on screen. " angular docs : " scope object refers application model. execution context expressions. "

C#: delete an element from xml -

i writing , reading xml file c# winfroms level. additionally want have function delete element given content. xml format: <libraryimages> <imagelink>*link1*</imagelink> <imagelink>*link2*</imagelink> </libraryimages> function body: system.xml.linq.xdocument xdoc = system.xml.linq.xdocument.load("xmldata.xml"); xdoc.root.elements("imagelink").select(el => el).where(el => el.value == pathtoremove).tolist().foreach(el => el.remove()); as 'pathtoremove' parameter pass link1 example. thing - doesn't remove element xml - after restart application content of library previously, if hadn't removed item. why doesn't work? i've browsed through many of stackoverflow questions, though i've found nothing. you should update xml file after in-memory manipulations: // read file disc , build in-memory representation of xml var xdoc = xdocument.load("xmldata.xml&qu

java - Change field value using cglib -

suppose have object field of class java.lang.reflect.field . possible change value of field of object o1 value of o2 `s field field.set(o1, o2) . wondering whether can done faster of library, example cglib? no, jvm implements jit compiler makes byte code generation obsolete performance in 99.9% of cases. in case of reflection, people sometime use code generation avoid security checks reflection api implies. rather that, should methodhandle s moves security check handle creation such not triggered on each call.

android - Is it possible to show google drive shared folder data into recyclerview or listview? -

what want have shared link this contain pdf , images want display in recyclerview or list cant find cant solution i have tried using google drive api can not find driveid. driveid can once create folder , in scenario there no need of it. can open google drive using intent can not access of data. any suggestion appreciated. in advance.

java - using JScrollPane with JFrame, JPanel and GridLayout -

this question has answer here: java: can't apply gridlayout jscrollpane. get java.lang.classcastexception 1 answer scrollpane adding grid layout 3 answers i have gridlayout (of jtextfields : 57*57) in jpanel in jframe (resolution 800*800) , result small , that's why have jscrollpane (that have 800*800 resolution , gridlayout resolution 3000*3000 example). i've tried many things not working. can please me ? here concerned part of code : thanks. gridlayout grid = new gridlayout(thumbnail.getheight(), thumbnail.getwidth(),0,0); final_frame = new jframe(); final_frame.setpreferredsize(new dimension(800, 800)); jpanel mypanel = new jpanel(); mypanel.setlayout(grid); //fill grid colors , denomination

sql server - Split Microsoft SQL Row -

assume have data so: +------+------+------+------+ | col1 | col2 | col3 | col4 | +------+------+------+------+ | | b | x | y | +------+------+------+------+ i wish split after column achieve this: +------+------+ | col1 | col2 | +------+------+ | | b | | x | y | +------+------+ what easiest way achieve this? forced in old ms access database connection sql server. thoughts? use union all : select col1, col2 t union select col3, col4 t; both databases support union all . both take column names first subquery.

react native - occurred configuring project ':app'. > Failed to notify project evaluation listener -

i start first application react-native when write in command line "react-native run-android" : what went wrong: problem occurred configuring project ':app'. failed notify project evaluation listener. javax/xml/bind/annotation/xmlschema does know problem?

c# - WPF Bind to derived object property -

i have abstract class vehicle, , 3 concrete class inherited i.e.boat, car , aeroplane. now have collection of object has id, quantity , vehicle class data { public int id {get; set} public int quantity {get; set;} public vehicle vehicle {get; set;} } now have collection of data i.e. ienumerable<data> in viewmodel and binding datagrid. now properties car object might have aeroplane , boat object might not have , vice versa. how can identify concrete object there in collection , accordingly show in description column. for car want show data property review. aeroplane want show data property notes , boat. all above property data should come in "description" column of datagrid can please help? add abstract description property vehicle class, , make sure classes inherit class put proper information in that. ui have consistent bind to. abstract class vehicle { public abstract string description { get; } } class aeroplane : ve

java selenium null pointer -

i not sure how solve null pointer exception. thought page properties not found page gets loaded causing this. if 1 kindly point out helpful. in advance. code: import org.openqa.selenium.by; import org.openqa.selenium.webdriver; import org.openqa.selenium.webelement; import org.openqa.selenium.chrome.chromedriver; public class flight { public static webdriver driver; //this following section browser , getting url public static webdriver browser(){ system.setproperty("webdriver.chrome.driver", "c:\\users\\chq-sheikhr\\downloads\\eclipse\\chromedriver.exe"); webdriver driver= new chromedriver(); driver.get("https://www.orbitz.com/flights"); return driver; } //this following section getting properties of page public static void getpageproperties(string ff,string ft, string fd, string rd){ //flight f= new flight(); -- thought getting null pointer because properties not found

Are Swift conditional breakpoints broken in Xcode 8.2? -

i tried create conditional breakpoint in xcode gui clicking add breakpoint, editing , entering expression in condition field. however, breakpoint triggers. i distilled down entering true or false condition field, , doesn't work. curiously, setting conditional breakpoint on line of objective-c in same (mixed swift/objective-c) project does work. it looks me breakpoint conditions ignored when breakpoint in swift source code. are other developers seeing same problem? there "secret sauce" getting swift breakpoints work missing?

Why this java regex returning false? -

my intention locate "tokens" , quoted strings string::split() method: (("[\w\s]*")|(\w*))* input text: this "a test" abd "and more" it returns false. also, how "quote" can use in source code? string.split splits using matches separators, i.e. returns doesn't match. if want return you're matching, should use matcher.find . also, \\w* matches length 0 string, want avoid. use + match 1-or-more. you have unnecessary brackets , outer * should not there - rest of regex matches characters in single token , multiple tokens should presumably matched across multiple invocations of regex matching (so saying "any number of these" doesn't make sense). matcher m = pattern.compile("\"[\\w\\s]*\"|\\w+").matcher("this \"a test\" abd \"and more\""); while (m.find()) system.out.println(m.group()); the above prints: this "a test" ab

java - Can't implement getIntent(); method in Fragment -

i try implement getintent(); in fragment , display text cannot resolve method 'getintent()' here part of fragment3.java public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { // inflate layout fragment return inflater.inflate(r.layout.fragment_3, container, false); textview textviewdisplayresult = (textview) getview().findviewbyid(r.id.text_view_display_result); textviewdisplayresult.settext(getintent().getbooleanextra("key_answer", false)?r.string.good_answer:r.string.wrong_answer); here xml textview displaying text <textview android:id="@+id/text_view_display_result" android:layout_width="match_parent" android:layout_height="wrap_content" android:textappearance="?android:attr/textappearancelarge"/> and part of mainactivity regarding matter final intent intent = new intent(mainactivity.this, fragment3.cla

python - How to sort a list containing objects? -

i have following code: lst = [] class data: def __init__(self): s = ['',''] def filllst(): d1 = data() d1.s[0] = 'zebra' d1.s[1] = 23 d2 = data() d2.s[0] = 'airplane' d2.s[1] = 435 d1 = data() d1.s[0] = 'aira' d1.s[1] = 211 lst.append(d1) lst.append(d2) lst.append(d3) when print list following: zebra - 23 aira - 211 airplane - 435 now want sort list output: aira - 211 airplane - 435 zebra - 23 so how can sort list data objects in it? you this: sorted(lst, key=lambda data: data.s[0]) if want sort elements in lst s[0] . sorted function has parameter key can specify function returns key sort. sorted function in python document : sorted(iterable[, key][, reverse]) ... key specifies function of 1 argument used extract comparison key each list element: key=str.lower . default value none (compare elements directly).

c# - Is there a modern version of "Deep Zoom Composer" for Silverlight that allows for stitching together panoramic images? -

silverlight used offer "deep zoom" , technology respected bandwidth user zoomed in , out. finally, after many years found use it; using images hot air ballon students see effects of climate change on micro, , macro level. q how can make panoramic photos "zoomable", similar deep zoom in silverlight? http://openseadragon.github.io/ javascript cousin of deep zoom (both came same team within microsoft, though openseadragon independent now). client side viewing, , uses same dzi format deep zoom used. for dzi creation, can continue using whatever tool you're using , view openseadragon. here's list of additional conversion tools: http://openseadragon.github.io/examples/creating-zooming-images/

node.js - Express: limit request size -

to limit request size 123 bytes, use following works fine: app.use(bodyparser.urlencoded({ extended: true, limit: 123 })); to parse requests except for "/specialrequest", use following works fine well: app.use(/^(?!\/specialrequest)/,bodyparser.urlencoded({ extended: true })); but fail limit request size of all requests 123 , parse requests except for "/specialrequest". here current code: app.use(/^(?!\/specialrequest)/,bodyparser.urlencoded({ extended: true, limit: 123 })); however, limits requests size requests different "/specialrequest". how can limit request size of all requests 123 , parse requests except for "/specialrequest"? if want request body /specialrequest limited in size not parsed, can use bodyparser.raw() . in case, req.body buffer instance contains request body as-is (unparsed, although inflated if presented gzipped or deflated data; behaviour can disabled through options).

javascript - KnockoutJS data-bind optionsCaption -

var vm = { weatherid: ko.observable(), weatherconditions: [{ id: '1', name: 'sunny' }, { id: '2', name: 'rainy' }, { id: '3', name: 'cloudy' }, { id: '4', name: 'snowy' }] }; ko.applybindings(vm); <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js"></script> <select data-bind="options: weatherconditions, value: weatherid, optionstext:'name', optionscaption: 'select today weather'"> </select> i have ko data bind snippet want set optionscaption read "select today's weather". wasn't able inset apostrophe in middle - need help. escape apostrophe backslash \ optionscaption: 'select today\'s weather'"> var vm = { weatherid: ko.observable(), weatherconditions: [{ id: '1',

Spark Window Function top N items performance issues -

i trying top n items in dataset . initially did this. var df = seq( (1 , "row1") , (2,"row2"), (1,"row11") , (1 , null) ).todf() df=df.select($"_1".alias("p_int"), $"_2".alias("p_string")) val resultdf =df.where($"p_string".isnotnull).select( $"p_int" ,$"p_int" +1 , upper($"p_string") , rank().over(window.partitionby($"p_int").orderby( $"p_string" )) "rankindex", row_number().over(window.partitionby($"p_int").orderby( $"p_string" )) "rownumber" ).where($"rownumber" <= 2 ) but want avoid performance cost of operation "where($"rownumber" <= 10 )" so decided following var df = seq( (1 , "row1") , (2,"row2"), (1,"row11") , (1 , null) ).todf() df=df.select($"_1".alias("p_int"), $"_2".alias("p_strin

css - Transfer block in table-cell on a new line -

i’m writing template marking on flex/box. , faced problem of emulation of properties. @ moment, decide them on js. complicates code. so decided try use property of table-cell child elements parent has property display: block . yes, it’s not right, works! when i’m trying break table-cell elements strings, ran problem. , that’s how tried solve them: if child blocks table-cell overflow parent horizontally, following blocks not transferred new line. , logical. example: nowrap in link. if use cancel flow, lose equal width of columns element wrapped next line. so, method works ie9+. i’m willing drop ie7, not ready abandon ie8. example: wrap nth-of-type in link. if use blocks separate table-cell on line, becomes fine! complicates css , js code. example: wrap break elements in link. example: http://codepen.io/anon/pen/gmgxmo what ways break table-cell can applied, besides above described options? an example of 12 column layout, fix problem of calculation of width p

mongodb - pushing object to array attribute when updating a document -

i'm using mongoose schema & persistence layer. when adding item array-attribute in existing document, fail: err equal null , raw equal { n: 0, nmodified: 0, ok: 1 } . any idea why happens? update code let concreteanswer = { questionid: 1, answer: { rating: 34 } }; participation.update( { _id: 'some-unique-id', 'answers.$.instrumentname': 'some-instrument-name' // instrumentname unique within answers array }, { $push: {"answers.$.concreteanswers" : concreteanswer} }, (err, raw) => { console.log(`error occured! raw: ${raw}, error: ${err}`); } ); schema definition var participationschema = new schema({ answers: [{ instrumentname: { type: string, enum: validinstruments }, concreteanswers: [{ questionid: number, answer: {} }] }] // further attributes omitted readability }, { timestamps: true }); var participation = mongoose.model('partici

Docker read file from local system when container is running -

my dockerfile runs python script requires reading in text file local machine. dockerfile from fedeg/python-vim:2 add . /code workdir /code run pip install -r requirements.txt copy file.txt /data/file.txt cmd ["python", "run.py"] in run.py there function reads in text file: def read_file(filename): lines = [line.rstrip('\n') line in open(filename)] return lines i wondering if pass image else , run it, file.txt saved inside image or docker able file.txt in person's local machine when image started? what want docker name file.txt on machines image running on can work on contents of other file.txt instead of file.txt provided local machine. yes saved inside image. an image contains change describe in dockerfile. happens in there part of image , usable give image to. anything happens on container create docker run or docker service not effect image. if wanted docker commit container turn new image.

python - normalizing a matrix in numpy -

what np.linalg.norm(x, axis = 1, keepdims=true) return? i have matrix np.array([[3.0,4.0],[1, 2]]) . trying normalize each row of matrix . answer should np.array([[0.6,0.8],[0.4472136,0.89442719]]) not able understand code answer. here code: x = np.array([[3.0,4.0],[1, 2]]) norms = np.linalg.norm(x, axis = 1, keepdims = true) x /= norms this code should give normalized x don't understand np.linalg.norm() returning here. np.linalg.norm(x, axis = 1, keepdims=true) doing in every row (for x): np.sqrt(3**2 + 4**2) row 1 of x gives 5 np.sqrt(1**2 + 2**2) row 2 of x gives 2.23 this vector [5, 2.23] norms variable all values in x divided norms variable should give np.array([[0.6,0.8],[0.4472136,0.89442719]]) . hope helps please see http://mathworld.wolfram.com/frobeniusnorm.html

c# - UserControl renders with no width in designer -

i have uwp usercontrol contains path element, data property of path bound string property of usercontrol called icon . when add control page , set it's icon property resource item, control doesn't render icon , has 0 width in designer. when deploy application device control renders expected. there way fix this? for reference, i'm trying build simple toolbar has bunch of clickable icons. i'm sure there other ways of achieving i'm using learning xaml skills pretty lacking. code can found below. mainpage.xaml <stackpanel grid.column="1" orientation="horizontal" horizontalalignment="center" verticalalignment="stretch"> <local:actionicon icondata="{staticresource test}" ></local:actionicon> </stackpanel> actionicon.xaml <usercontrol x:name="usercontrol" x:class="uwptest.actionicon" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/present

MongoDB can not be installed in Ubuntu 16.04 -

zguindouos@zguindouos:~$ sudo apt-get install mongodb-org [sudo] password zguindouos: reading package lists... done building dependency tree reading state information... done mongodb-org newest version (3.2.12). 0 upgrade, 0 newly install, 0 remove , 4 not upgrade. 6 not installed or removed. after operation, 0 b of additional disk space used. want continue? [y/n] y setting initramfs-tools (0.122ubuntu8.8) ... update-initramfs: deferring update (trigger activated) setting linux-image-extra-4.4.0-66-generic (4.4.0-66.87) ... run-parts: executing /etc/kernel/postinst.d/apt-auto-removal 4.4.0-66-generic /boot/vmlinuz-4.4.0-66-generic run-parts: executing /etc/kernel/postinst.d/dkms 4.4.0-66-generic /boot/vmlinuz-4.4.0-66-generic run-parts: executing /etc/kernel/postinst.d/initramfs-tools 4.4.0-66-generic /boot/vmlinuz-4.4.0-66-generic update-initramfs: generating /boot/initrd.img-4.4.0-66-generic gzip: stdout: no space left on device e: mkinitramfs failure cpio 141 gzip 1 upd

javascript - How do you loop over an array of objects and get a key from each? (Angular 2) -

i have array of objects. need loop on array, access same key in each object, , compare string properties array, see if string shares words it. if does: something. i can compare array have hardcoded string, using lodash _.difference method. i'm confused how string key of each object using loop. tried foreach, can't seem keys of each element. what best way go achieving this? thanks much. component import { component, oninit, ngzone, viewchild } '@angular/core'; import { routermodule, router } "@angular/router"; import { newsapiservice } '../service/news-api.service'; import { http, response } '@angular/http'; import { mapcomponent } '../map/map.component'; import * _ "lodash"; @component({ selector: 'app-main', templateurl: './main.component.html', styleurls: ['./main.component.css'] }) export class maincomponent implements oninit { private bbcjson: any; private aljazeerajs

html - Angular2 - Radio button value binding -

i have problem bind data group of radio buttons. want bind visible value whenever check 1 of radio button. can me this? thanks lot! <div class="col-lg-8 inputs-group"> <div class="btn-group" data-toggle="buttons"> <label class="btn btn-primary active"> <input type="radio" name="visible" [(ngmodel)]="visible" autocomplete="off" value="true">yes </label> <label class="btn btn-primary"> <input type="radio" name="visible" [(ngmodel)]="visible" autocomplete="off" value="false">no </label> </div> </div>

c++ - how to increment or decrement from variable until get char -

i wanted create snake program in console application. in 1 confused. problem this: #include <iostream> #include <cstdlib> #include <ctime> #include <conio.h> using namespace std; int main() { int a=2000; while (1) { cout << time(0)<<endl; -= 100; _sleep(a); **if (getch())break; else continue; } } my problem in **, want ,to while loop until pressed 1 key. example want run this: print time(). = 1900. wait 1.9s. print time(). a=1800. wait 1.8 s. // pressed key. break.//end program so found answer used kbhit() in conio.h library. you may try this. of course need in parent process have getchar() return key press without waiting, such using _getchar(). #include <iostream> #include <cstdlib> #include <ctime> #include <signal.h> #include <conio.h> using namespace std; int main() { pid_t id; id = fork(); if(id) { getchar(); kill(id

Java: Method chaining in derived class -

i writing derivedclass (extends superclass) method chaining. example, public class superclass { protected int responsecode; protected string responsemessage; public void setresponsecode(int code) { this.responsecode = code; } public int getresponsecode() { return responsecode; } public superclass withresponsecode(int code) { setresponsecode(code); return this; } public void setresponsemessage(string message) { this.responsemessage = message; } public string getresponsemessage() { return responsemessage; } public superclass withresponsemessage(string message) { setresponsemessage(message); return this; } } and public class derivedclass extends superclass { protected string credentialtype; protected string credentialid; public void setcredentialtype(string type) { this.credentialtype = type;

Groovy missing constructor (in Jenkins post-hook) -

i'm trying modify jenkins authentication setting post-init.groovy.d hook , change jenkins authentication reverseproxy plugin. by reading others' java code understood, should create reverseproxysecurityrealm instance , call jenkins.instance.setsecurityrealm set realm. tried debug code script console i've got unexpected expection. i stopped @ creating reverseproxysecurityrealm object groovy, exception groovy.lang.groovyruntimeexception: not find matching constructor for: org.jenkinsci.plugins.reverse_proxy_auth.reverseproxysecurityrealm(string, string, string, string, string, string, string, boolean, string, string, string, string, string, string, string, string, integer, boolean, string, string) i tried compare declared , used parameters don't see difference. my code: import org.jenkinsci.plugins.reverse_proxy_auth.reverseproxysecurityrealm; def realm=new reverseproxysecurityrealm( forwardeduser"x-forwarded-user", headergroups="x-f

c# - Brand new Xamarin.Forms project: The file "obj\Debug\android\bin\packaged_resources" does not exist -

Image
i installed visual studio 2017 , i'm trying work on xamarin.forms project. cloned existing repo , build , deploy ios app fine, when try build android app throws following error: severity code description project file line suppression state error file "obj\debug\android\bin\packaged_resources" not exist. [solution name].android c:\program files (x86)\microsoft visual studio\2017\community\msbuild\xamarin\android\xamarin.android.common.targets 1794 everything works great in xamarin studio on mac. i created clean xamarin.forms project in vs 2017 isolate particular solution issues , getting exact same error. how can fix this? this issue occurs when correct build tools aren't correctly installed. open android sdk tools. here if using visual studio. make sure have latest sdk tools, platform toosl , build tools. delete preview or old build tools. use rev. 25 ones. rev 24. had few issues, make sure uninstalled. then make sure ha

ios - Google Places API with HDAugmentedReality framework -

i using google places api hdaugmented reality framework based off of tutorial jean-pierre. my question can limit search results (annotations) specific places fall under criteria. ex: on university campus limiting annotations university buildings. google places offers option called autocomplete not sure how incorporate code? simply change url match parameters intend display. visit https://developers.google.com/places/web-service/autocomplete examples , lists of parameters.

java - Expandable listview with indicator image -

i have customized expandable listview. want arrow on left side of every group. tried (note section " getgroupview "): package com.aaron.waller.mrpolitik.tabs; import android.os.bundle; import android.support.annotation.nullable; import android.support.v4.app.fragment; import android.view.layoutinflater; import android.view.view; import android.view.viewgroup; import android.widget.baseexpandablelistadapter; import android.widget.expandablelistview; import android.widget.imageview; import android.widget.textview; import android.widget.toast; import com.aaron.waller.mrpolitik.r; /** * created oclemmy on 5/10/2016 programmingwizards channel , http://www.camposha.com. */ public class fragenfragment extends fragment { view rootview; expandablelistview lv; private string[] groups; private string[][] children; public imageview groupholder; public fragenfragm