Posts

Showing posts from February, 2014

It seems like my java code is stuck in a loop somewhere -

import java.util.random; import java.lang.math; import java.lang.string; public class gameofnim { private int min,max; private int turn; private int firstturn; private int stupid; private int smart; private int computer; private int user; private int first; private int pile; public gameofnim(int min, int max ){ pile=(int)(math.random()*max+min); smart=(int)(math.random()*100); stupid=(int)(math.random()*100); system.out.println("pile size "+pile); firstturn=(int)(math.random()*100 + 1); computer=0; user=1; if(firstturn>50) { firstturn=user; } else { firstturn=computer; } firstturn=turn; } public void play() { if(smart>50) { system.out.println("computer playing smart"); } else { system.out.println("computer playing stupid"); } if(firstturn==user) {

javascript - How to dynamically add questions to Vue Webpack template's meta.js file? -

i've forked standard vue webpack template , editing meta.js file. i'm trying find way add property prompts this: "pages": { "type": "input", "required": true, "message": "how many pages template have?" }, and thereafter use pages variable add more questions, this: "page1": { "type": "string", "required": true, "message": "what name page1?" }, i imagine loop defined outside of object adds properties object. loaded @ same time object , variables undefined. ideas? the meta.json content evaluated vue-cli, have fork , change there. are questions runtime-dependent, or need contitionals? because works, can find examples of in template's questions right now, example sub-questions linting.

c++ How to check if there is a file in a directory quick way? -

what trying when directory has no write permission , if directory contains @ least 1 file trying print out "permission denied" dir *dir; dir = opendir (argv[i]); if (!(sb.st_mode & s_iwusr) && (readdir(dir) != null)) { printf("rm: cannot remove "); printf(argv[i]); printf(": permission denied\n"); } this trying do, prints out messages when there no files... suggestions?

add custom font to a cordova project -

i have custom fonts use in app. the font name myfont , files extension (myfont.eot,.myfont.svg,myfont.ttf,myfont.woff,myfont.woff2) , copied ios , android asset folder when cordova build. however, when open app on device don't see new font display. i see new fond display when run app safari browser on mac. here snippet css file html, body { overflow-x: hidden; -webkit-tap-highlight-color: rgba(0,0,0,0); font-family: 'myfont'; font-size: 16px; } is there else need in order see new font on android , ios device thanks use @font-face in css. @font-face { font-family: "my-font"; src: url("../assets/myfonts.ttf"); // give relative path css file. } add code css file @ top. , can use font-family my-font need it. example: css .class-myfont { font-family: my-font; } html <span class="class-myfont">hello there</span>

c - Porting Unix to Windows, disks, partitions, EFI labels -

a unix program listing /dev/ , picking out diskx , diskxsy entries open , attempt read own "label" from. these disks/partitions not recognised windows, , not mounted. console app, pass paths kernel open (eventually). so have setup test 5g disk use vm. gpt protected efi labelled disk. on osx see disk1 , disk1s1 , disk1s9 . program needs go through disks , partitions find label, in test case, jackpot disk1s1 . i can use setupdienumdeviceinterfaces() , list of \\?\physicaldrivex . can open ( createfile() ) , readfile() those. on test machine, 2 of these. first 1 boot, second test disk. i can iterate findfirstvolume() , , open/read them (although, if delete trailing "\" ?), here 3 "volumes". 2 on first physicaldrive0 , 1 on physicaldrive1 . not seem able call functions read partitions method/path name. if call ioctl_disk_get_drive_layout_ex on \\.\physicaldrive1 see 4 partitions, , first partition of type 0xee . (protected gpt). what ca

random - R: can 'mu' or 'Sigma' be vectorized in MASS::mvrnorm() when generating bivariate normal samples? -

consider data below, n <- 3 phi0 <- 1 phi1 <- 0.1 phi2 <- 0.2 w2 <- runif(n,0,1) w3 <- runif(n,0,1) w <- cbind(w2,w3) phi <- rbind(phi0,phi1,phi2) rho <- 0.4 sigma1 <- exp(as.numeric(model.matrix(~w) %*% phi)) sigma2<- 1 library(mass) #sigma <- ??? mu <- rep(0,2) v <- mvrnorm(n, mu, sigma) sigma1 vector of variance. i want generate bivariate vector v=(v1,v2) of length n normal bivariate distribution. in such way i-th line of v has bivariate normal distribution of mean mu=(0,0) , correlation rho=0.4 , marginal variance sigma=(sigma1, 1) sigma1 receives value of i-th line sigma1 . how can proceed? editor's clarification in 1d case, rnorm accepts vectorized mu , sigma , that rnorm(3, 0, sqrt(sigma1)) gives samples n(0, sqrt(sigma1[i])) . op asking same capability mvrnorm . basic solution no, can't vectorized. write for loop. v <- matrix(0, n, 2) (i in 1:n) { sig11 <- sigma1[i] sig21 <

Is it possible to filter out counties (not countries) from Google Autocomplete? -

i return state, cities, , zipcodes within us. restricting results regions within us. bring state, cities , zipcodes adds in others such counties. how can restrict results find state, cities , zipcodes? this have: var autocomplete = new google.maps.places.autocomplete(input, { types: ['(regions)'], componentrestrictions: { country: 'us' } });

asp.net mvc - How to bind Linq Multiple models data in a View using ViewBag MVC? -

i using linq join multiple model classes , pass linq object view using viewbag . i facing problem while repeating data or binding data model properties: public class salesmodel { public string customername { get; set; } public int ssn { get; set; } public int licenseid { get; set; } public int age { get; set; } public string city { get; set; } //vehicle sales public datetime? saledate { get; set; } public int customerid { get; set; } public int selectemodle { get; set; } } public actionresult createvehiclesalesview() { var make = objvehiclecontext.vehiclemakes; salesmodel objsalesmodle = new salesmodel() { makeslist = new selectlist(make, "makeid", "make") }; vehicledatacontext objdatacontext = new vehicledatacontext(); var vehcilesalesdetails = vs in objdatacontext.vehiclesales join vmodel in objdatacontext.vehiclemodels on vs.modelid equals vmodel.mode

Can someone tell me what's wrong with this javascript? -

i trying experimental here, please answer, what's wrong in code? function run(){ for(var i=0;i<arguments.length;i++){ var type=arguments[i].split(" ")[0]; if(type=="(write)"){ var arr=arguments[i].split(" "); var str=[]; for(var i=1;i<arr.length;i++){ str.push(arr[i]); } var fin="\n"+str.join(" "); document.getelementbyid("console").textcontent+=fin; } } } run( "(write) wonder if works.", "(write) think does!" ); somehow puts "i wonder if works." in div no "i think does!". can tell me what's wrong , return corrected script? javascript not have block scope.. change other var else

wpf - isEnabled binded to other button click -

Image
i can't figure out resource missing work, getting messages ei namespace not found. <button name="btnenter" click="btnenter_click" style="{staticresource signbuttons}" fontfamily="comic" fontsize="24" fontweight="demibold" grid.column="3" height="51.562" width="75" margin="30,23.624,0,0" grid.row="3" template="{dynamicresource enterbutton}"> <i:interaction.triggers> <i:eventtrigger eventname="click"> <ei:changepropertyaction targetobject="{binding elementname=btnmultiplication}" propertyname="isenabled" value="false"/> </i:eventtrigger> </i:interaction.triggers>

Equivalent of Matlab filter2(filter, image, 'valid') in python -

i want know equivalent of matlab's filter2(filter, image, 'valid') function in python opencv or scikit-image library. concerned valid argument allows calculate convolution of filter , image without 0 padding image. aware of fact similar question posted on forum equivalent of filter2 function valid argument has not been described properly. the documentation filter2 says filter2(h, x, shape) equivalent conv2(x,rot90(h,2),shape) ; a python equivalent conv2 signal.convolve2d . equivalent you're looking is: signal.convolve2d(x, np.rot90(h), mode='valid')

datetime - SAS Given a start & end date I need to know the dates of each 30 day period AFTER the first 35 days -

i am given 2 dates, start date , end date. i know date of first 35 day period, each subsequent 30 day period. i have; start end 22-jun-15 22-oct-15 9-jan-15 15-may-15 i want; start end tik1 tik2 tik3 tik4 22-jun-15 22-oct-15 27-jul-15 26-aug-15 25-sep-15 9-jan-15 15-may-15 13-feb-15 15-mar-15 14-apr-15 14-may-15 i fine dates calculations real issue creating variable , incrementing name. decided include whole problem because thought might easier explain in context. you can solve problem via following logic: 1) determining number of columns added. 2) calculating values columns basis requirement data test; input start end; informat start date9. end date9.; format start date9. end date9.; datalines; 22-jun-15 22-oct-15 09-jan-15 15-may-15 ; run; /*******determining number of columns*******/ data noc_cal; set test; no_of_col = floor((end-start)/30); run; proc sql; select max(no_of_col) into:

ruby - Dynamic Class Definition WITH a Class Name -

how dynamically define class in ruby name? i know how create class dynamically without name using like: dynamic_class = class.new def method1 end end but can't specify class name. want create class dynamically with name. here's example of want of course doesn't work. (note not creating instance of class class definition) class testeval def method1 puts "name: #{self.name}" end end class_name = "testeval" dummy = eval("#{class_name}") puts "dummy: #{dummy}" dynamic_name = "testeval2" class_string = """ class #{dynamic_name} def method1 end end """ dummy2 = eval(class_string) puts "dummy2: #{dummy2}" # doesn't work actual output: dummy: testeval dummy2: desired output: dummy: testeval dummy2: testeval2 ====================================================== answer: totally dynamic solution using sepp2k's method dynamic_name = &qu

javascript - Adding image to table given link -

i have following code goes through rows , columns (var j=0; j < cols; j++) { (var k=0; k < cols; k++) { alert(data[j][i]) if(data[j][i].endswith(".jpg")) { var img = document.createelement('img'); img.src = data[j][i]; img.onload = function() { //check make sure tabledata += '<td>' + img + '</td>'; }; } else { tabledata += '<td>'+data[j][i]+'</td>'; } break; } } i trying create images nothing pops in spot. idea might doing wrong? tried without .onload , pops [object htmlimageelement] variable img hold object, not html string. use <img> tag string instead! also note onload event async, callback invoke later! for (var j =

php - Laravel 5.3 : hidden fields are returned in JSON response -

first of i've searched web answer , not find quite astonished me. maybe did not search right terms, please excuse me in advance if case. so defined in model fields hidden : protected $hidden = [ 'hasexpired', 'hasbeentreated', 'reporterid' ]; and how output results : return response()->json([ 'latestreports' => $latestreports ]); and $latestreports variable defined somewhere else : $query = db::table('reports') ->where('catid', 0) ; $latestreports = $query->where('hasexpired', 0) ->orderby('created_at', 'desc') ->get(); how on earth possible these fields still appear in response on client server, , above should correct prevent them appearing. in other word how can make hidden array enforced ? please note: other models (e.g. users) hidden array enforced, hidden fields not appear in response. any appreciated.

c# - Repeating pattern matching with Regex -

i trying validate input regular expression. until tests fail , experience regex limited thought might able me out. pattern: digit ( possibly "," digit ) ( possibly ; ) a string may not begin ; , not end ;. digits allowed stand alone or my regex (not working): ((\d)(,\d)?)(;?) problem not seem check until end of string. optional parts giving me headaches. update: ^[0-9]+(,[0-9])?(;[0-9]+(,[0-9])?)+$ this seems work better not match single digit. ok: 2,3;4,4;3,2 2,3 2 2,3;3;4,3 nok: 2,3,,,, 2,3asfafafa ;2,3 2,3;;3,4 2,3;3,4; your ^[0-9]+(,[0-9])?(;[0-9]+(,[0-9])?)+$ regex matches 1 or more digits, optional sequence of , , 1 digit, followed one or more similar sequences. you need match zero or more comma-separated numbers: ^\d+(?:,\d+)?(?:;\d+(?:,\d+)?)*$ ^ see regex demo now, tweaking part: if single-digit numbers should matched, use ^\d(?:,\d)?(?:;\d(?:,\d)?)*$ if comma-separated numb

C++ deque iterate to second last element -

i trying iterate through deque excluding last entry. ideally avoid counting , comparing length, tried auto it_end = dq.rbegin(); it_end++; ( auto = dq.begin(); !=it_end; ) { if ( cond() ) { = dq.erase( ); } else { it++; } } but compiler complains there no match operand seems understandable since have reverse iterator , regular iterator. there elegant way stop before last element avoids counting? like, offset? tried usign back, turned out reference not iterator, != not happy either. you can use dq.end() - 1 1 before end. you can use std::remove or std::remove_if remove items want instead of doing job on own. note kind of partitioning operation--it returns iterator, , want keep beginning of range iterator. want delete after iterator, end of range provided input. in case, might on general order: std::deque<int> vals { 1, 2, 3, 4, 5, 6, 7, 8}; // iterator 1 before end of `vals` auto end = vals.end(

ios - How to install Eureka version 3 -

how install version 3, not in cocoapods. pod file source 'https://github.com/cocoapods/specs.git' platform :ios, '9.0' target 'project' use_frameworks! pod 'eureka', '~> 3.0' end the result of command pod install analyzing dependencies [!] unable satisfy following requirements: eureka (~> 3.0) required podfile none of spec sources contain spec satisfying dependency: eureka (~> 3.0) . you have either: * out-of-date source repos can update pod repo update . * mistyped name or version. * not added source repo hosts podspec podfile. note: of cocoapods 1.0, pod repo update not happen on pod install default. i understand repository not updated in cocoa pods? do?

computer science - You are not allowed to access this area in cs cart -

i using cs cart cs-cart 4.3.3. getting error: you not allowed access area. i have changed app\addons\access_restrictions folder name , disable status of access_restrictions add on table cscart_addons , empty 3 more table cscart_access_restriction , cscart_access_restriction_block , cscart_access_restriction_reason_descriptions . now can login unable administrator menus (like general settings, products, manage addons, etc.) please us.

node.js - Node js - Cluster delay before delegating request -

i'm using cluster module node.js benefit multiple cpu cores (4 in case). problem is, if worker busy, next request delegated available worker after 10 seconds, unacceptable. i'm using infinite loop test cluster follows: var cluster = require ('cluster'); if (cluster.ismaster) { var cpucount = require('os').cpus().length; (var = 0; < cpucount-1; ++i) { cluster.fork(); } } else { var express = require('express'); var app = express(); app.get('/', function (req, res) { console.log('served worker %d!', cluster.worker.id); while(true) {} console.log("done"); res.status(200).send(); }); app.listen(8080, function () { console.log('worker %d running!', cluster.worker.id); }); } cluster.on('exit', function (worker) { console.log('worker %d died :(', worker.id); cluster.fork(); }); at first open localhost:80

python - Change color of parasite axis in matplotlib -

Image
i want change color of parasitic axis. base code example http://matplotlib.org/examples/axes_grid/demo_parasite_axes2.html i add par1.spines['right'].set_color("red") to change color (according https://stackoverflow.com/a/12059429/716469 ). doesn't work. the full code: from mpl_toolkits.axes_grid1 import host_subplot import mpl_toolkits.axisartist aa import matplotlib.pyplot plt host = host_subplot(111, axes_class=aa.axes) plt.subplots_adjust(right=0.75) par1 = host.twinx() par2 = host.twinx() offset = 60 new_fixed_axis = par2.get_grid_helper().new_fixed_axis par2.axis["right"] = new_fixed_axis(loc="right", axes=par2, offset=(offset, 0)) par2.axis["right"].toggle(all=true) host.set_xlim(0, 2) host.set_ylim(0, 2) host.set_xlabel("distance") host.set_ylabel("density") par1.set_ylabel("temperature") par2.set_ylabel(

javascript - How to auto call System or AMD modules? -

this question has answer here: how set typescript in symfony? 2 answers question: how auto call system or amd modules without manually adding script call registered/defined module ? description: when i'm generating es5 file using system module defined in tsconfig , expected output system.register(/* ... */) of course doesn't run when added page. is there way avoid adding script tag html file manually call modules? <!-- module script added above --> <script> system.get('module_name_here'); </script> extra: if i'd forego system / amd module's completely. however, it's required moment decide create 1 outfile while using import/export in typescript . if has solution this, save me big headache. thanks. since mention amd modules... if produce series of amd modules, use requirejs , make use of suppo

frontend - editing SEO metadata in virtocommerce -

i'm trying use seo store , set page titles store pages customer profile, sign in, cart, .... last seo entry in store seo's applies pages (except category, product), example have 3 seo entry , addresses applies pages, home! it possible set seo title , description shopping cart, personal cabinet , similar pages checking liquid-template name on theme layout before using liquid-variables page_title , page_description . so: ... {% if template == 'cart' %} {% assign page_title = 'cart.general.title' | t %} {% assign page_description = 'cart.general.title' | t | append: ' - ' | append: shop.name %} {% endif %} ... <title>... {{ page_title }} ...</title> <meta name="description" content="{{ page_description | escape }}" />

java - downloading a input stream using servlets -

i using following code content object in s3 bucket. able copy data file locally, file needs 'downloaded' , has shown in browser's downloads list. searched bit , cam know has response.setheader( "content-disposition", "attachment;filename=\"" + filename + "\"" ); tried add somehow couldn't work. understanding source has file on server converted stream. s3 contents in form of input stream. how download file in browser? below code have tried far amazons3 s3 = new amazons3client(new profilecredentialsprovider()); s3object fetchfile = s3.getobject(new getobjectrequest(bucketname, fileloc)); final bufferedinputstream = new bufferedinputstream(fetchfile.getobjectcontent()); response.setcontenttype("application/json"); response.setheader( "content-disposition", "attachment;filename=\"" + filename + "\"" ); servletoutputstream sos = r

Android - Disable parent view click events when popup window is viewable -

i've spent large amount of time trying solve issue both myself , searching through here find solution, none of have worked me. my current scenario when popup window appears want disable clickable events on foreground view underneath popup window. if (shared.inspectiondata.jobviewmodel.rams_id == null || shared.inspectiondata.jobviewmodel.rams_id.equals("")) { // disable foreground view here loadramspopup(); } private void loadramspopup() { mainlayout.getforeground().setalpha(150); layoutinflater layoutinflater = (layoutinflater) getbasecontext().getsystemservice(layout_inflater_service); final view ramsview = layoutinflater.inflate(r.layout.popup_rams, null); final popupwindow popuprams = new popupwindow( ramsview, viewgroup.layoutparams.wrap_content, viewgroup.layoutparams.wrap_content ); if (build.version.sdk_int >= 21) { popuprams.setelevation(5.0f); } findview

xcode - Output of data with Firebase . Swift -

there gallery, in photo added, works through firebase. write data @ibaction func savdata(_ sender: any) { let date1 = nsdate() let rootref = firdatabase.database().reference() rootref.child("/gellery/\(date1.description)/photo").setvalue(base64.convertimagetobase64(photoimage.image!)) rootref.child("/gellery/\(date1.description)/name").setvalue(addname?.text) let storyboard = uistoryboard(name: "main", bundle:nil) let vc = storyboard.instantiateviewcontroller(withidentifier: "nextview") as! navigationcontroller self.present(vc, animated: true, completion: nil) } output of data let rootref = firdatabase.database().reference() let imageref = rootref.child(constans.firebase.url.object) imageref.observe(.value, with: {(snapshot) in if let snapshots = snapshot.value as? [string: anyobject] { // let date = nsdate() snapshot in snapshots {

swift - How can we pass type, page_token,sorting etc… in google place IOS API? -

with web api can pass type like "&type=restaurant|cafe|bar”&pagetoken=“mynextpagetoken” but mobile api(gmsplacesclient class) don’t find way this, have gone place api framework. , find places people says mobile api has more limitations web apis can suggest how mobile api? right i’m using mobile api add place , fetch places i’m using web-api. to mimic behaviour described in question there's separate class in ios api: gmsplacepicker documentation can found here . edit looking through documentation mobile api, there's no indication such functionality exists. clicking on 'search' in docs redirects web api search docs. you'll have use web api fetching places.

amazon web services - Cloud-init on aws ec2 not working properly -

i'm running amazon-linux 2016.09 in /etc/cloud/cloud.cfg got following parameters set: repo_upgrade: security which means @ next reboot, i'm expected important , critical security installed. unfortunately, after reboot, running yum list-security --security i got following: alas-2017-798 important/sec. bind-libs-32:9.8.2-0.47.rc1.52.amzn1.x86_64 alas-2017-798 important/sec. bind-utils-32:9.8.2-0.47.rc1.52.amzn1.x86_64 alas-2017-805 important/sec. kernel-4.4.51-40.58.amzn1.x86_64 alas-2017-811 important/sec. kernel-4.4.51-40.60.amzn1.x86_64 alas-2017-805 important/sec. kernel-devel-4.4.51-40.58.amzn1.x86_64 alas-2017-811 important/sec. kernel-devel-4.4.51-40.60.amzn1.x86_64 alas-2017-805 important/sec. kernel-headers-4.4.51-40.58.amzn1.x86_64 alas-2017-811 important/sec. kernel-headers-4.4.51-40.60.amzn1.x86_64 alas-2017-805 important/sec. kernel-tools-4.4.51-40.58.amzn1.x86_64 alas-2017-811 important/sec. kernel-tools-4.4.51-40.60.amzn1.x86_64 alas-2017-805 impo

active directory - know when access was granted to RD -

i wasn't able remote desktop windows server last week. now admin said have access in past. and indeed, able access now… delay caused issues; want able retrieve @ time access granted me… or maybe if find failed login/auth last week, way can prove it. is there log can information from?

javascript - React: Event-triggered Ajax call in componentDidUpdate or render creates infinite loop -

i have ajax call triggered event(click). works it's supposed to(it populate table), keeps doing ajax call time, eating out memory unsustainable, of course. what's issue here? have tried putting ajax call inside componentdidmount , result same, if it's triggered ajax call explode(5-10 calls per second). i hack , make count , stop @ 1, that's not right way solve it(i need find root cause :) ) sample code: let sample = react.createclass({ getinitialstate : function () { return{ data: [], }; }, ajaxcall : function(somevalue) { // ajax call sets data $.ajax({ // ... }); }, rendertable(value, index) { // populates table // .. }, render : function () { let tabledata = this.state.data; if (tabledata) { this.ajaxcall(this.props.somevalue); // goes infinite loop return ( <popover id="popover-positioned-scrolling-left&

ubuntu - Linux - User expiration date in hours -

i setting expiration date of linux users account using command below: chage -e '2017-04-07' username however can block user using dates, , when day occurs user blocked. would have account expire in 24hrs? tks! you cannot use 'chage' since require specifying date. if want inactivate user after few minutes, use following adduser username_here && sleep 600 && usermod --lock username_here or adduser username_here echo usermod --lock username_here | @ + 10 minutes

jquery - Transition for a Collapse -

i'm working on custom collapser don't know how can make transition when hiding. searching online found "display: none;", doesn't support transition. i've tried height: auto; , height: 0px; doesn't support transition too. here's code: html <a class="clp" href="#clp-1"><div>button</div></a> <div class="clp-body clp-show" id="clp-1">lorem ipsum</div> css .clp > div { border: 1px solid black; border-radius: 3px; width: 150px; padding: 5px; } .clp { text-decoration: none; font-family: verdana; color: black; } .clp-body { border: 1px solid black; border-radius: 3px; width: 150px; padding: 5px; margin-top: 5px; transition: 0.5s ease; } .clp-show { opacity: 1; } .clp-show { opacity: 0; display: none; /* example */ } js (jquery) $('a.clp').click(function(){ var value = $(this).attr("href"); if ($('div

android - PowerMockito doThrow when call static method return UnfinishedStubbingException -

latest use cache lib disklrucache developed jakewharton https://github.com/jakewharton/disklrucache , writing test piece of code public void initdisklrucache() { try { disklrucache = disklrucache.open(context.getfilesdir(), 1, 1, max_cache_size); } catch (ioexception e) { e.printstacktrace(); } } and wanna test when open file failed , throw exception, used powermockito according doc : https://github.com/powermock/powermock/wiki/mockitousage#how-to-stub-void-static-method-to-throw-exception @test(expected = ioexception.class) public void testinitdisklrucachefailed() throws ioexception { powermockito.mockstatic(disklrucache.class); powermockito.dothrow(new ioexception("error")).when(disklrucache.open(any(file.class), anyint(), anyint(), anylong())); service.initdisklrucache(); } i add @preparefortest(disklrucache.class) and @runwith(powermockrunner.class) , failed error java.la

elasticsearch - Elastic Search compound queries -

i make compound query in elastic search? query: co la and search results return: coca cola 350ml diet coca cola 2l latin condom ultra soft cornstarch lard assuming have index "food" , type "allproducts", how structure search? thanks complementing requests mapping index used this: curl -xput 'localhost: 9200 / food / _settings' -d' {              "index.analysis.analyzer.default.filter.0 ": "standard ",              "index.analysis.analyzer.default.tokenizer ": "standard ",              "index.analysis.analyzer.default.filter.1 ": "lowercase ",              "index.analysis.analyzer.default.filter.2 ": "stop ",              "index.analysis.analyzer.default.filter.3 ": "asciifolding " } ' example of current search using match_phrase_prefix, allows compound words have last sentence snippet. this.clientelastic.search ({       i

c# - Unit testing many simple method that call internal methods/other tested methods, resulting in complex (yet similar) output -

i've got data access layer has 2 types of method getlatestx , getx . getlatestx looks this: public ielementtype getlatestelementtype(guid id) { ielementtype record = null; using (databasesession session = createsession()) { record = session.connection.get<elementtyperecord>(id); } return record; } that's reasonably easy unit test. however, getx wraps getlatest in refcount observable , emits new values in response messaging system. testing method lot more complex. want check following, rather complex behavior: you can subscribe , retrieves value database it starts listening messages subscribing again doesn't result in repeated database call when mock message system simulates message new database access called , subscriptions new versions. 1 additional database call used. unsubscribing second subscription doesn't result in system stopping listening messages. unsubscribing first sub

android - How to make textview in expandable listview MATCH_PARENT -

Image
i working on 3 level expandable list view. works expect width of textview of second , third level of expandable listview wrapping content , not matching parent i've specified in layout. here code parent level adapter: public class parentleveladapter extends baseexpandablelistadapter { private final context mcontext; private final list<string> mlistdataheader; private final map<string, list<string>> mlistdata_secondlevel_map; private final map<string, list<string>> mlistdata_thirdlevel_map; private list<string> stringlist = new arraylist<>(); activity activity; public parentleveladapter(context mcontext, list<string> mlistdataheader) { activity = (activity) mcontext; this.mcontext = mcontext; this.mlistdataheader = new arraylist<>(); this.mlistdataheader.addall(mlistdataheader); // second level string[] mitemheaders = new string[0]; mlis

cordova - Ionic 2 custom config -

i'm building ionic 2 app multiple companies. therefore, need able set multiple custom config values. these values located in config.xml(for example: name/description), in variables.scss(for example: primary/secondary color), , have custom configuration file holding server/database values. what want achieve, every time build app new company, have edit values in 1 single config file, instead of 3 config files in current situation. i have been trying find way access config.xml values, without success. have tried setting values of config.xml & variables.scss own custom config file, without success. does know how tackle problem? i think best way achieve using hooks. don't think it's possible change scss via hooks and, it, need create config files por every action want , change before every build. so maybe easier if develop architecture of app that's easy mantain , change needed variables every client.

python - x has type function but calling x gives a type error Python3 -

i have following python statement x = lambda :8() checking type of x returns following <class 'function'> but doing this x() typeerror: 'int' object not callable i can solve putting parenthesis around lambda so x = (lambda :8)() but wondering going on. the problem not lie calling x , trying call 8 8() . calling integer raises error because instances of int not callable. i can solve putting parenthesis around lambda so what doing x = (lambda :8)() construct anonymous function returns number 8, call it, , assign name x return value. >>> x = (lambda :8)() >>> x 8 however, x() still raise error because again it's trying call integer. >>> x() traceback (most recent call last): file "<stdin>", line 1, in <module> typeerror: 'int' object not callable

java - Apply wordnet on string to words vector filter output -

i've applied string word vector filter on 100 message follows try{ stwv.setoutputwordcounts(true); stwv.settftransform(true); stwv.getattributeindices(); stwv.setstopwords(value); stwv.setattributeindices("2"); stwv.setmintermfreq(1); stwv.setwordstokeep(10000); stwv.settftransform(true); stwv.setinputformat(data); stwv.settokenizer(wt); instances output = weka.filters.filter.usefilter(data, stwv); reorder.setattributeindices("2-last,1"); reorder.setinputformat(output); instances outputorder=weka.filters.filter.usefilter(output,reorder); then applied reorder filter make class attribute last attribute. i want apply wordnet on outputorder . how can perform this?

r - Data Table Column Reference -

i have data table column names strings of characters. while datatable[rownumber, `column name`] is working fine, datatable[rownumber,datatable2[rownumber,,columnname]] is not working. datatable2[rownumber,,columnname2]= column name2 how fix this? you might running problem needing set "with = false" if referencing column name text string , not is. example library(data.table) head(iris) > head(iris) sepal.length sepal.width petal.length petal.width species 1 5.1 3.5 1.4 0.2 setosa 2 4.9 3.0 1.4 0.2 setosa # data.frame convert data.table dt <- as.data.table(iris) dt[1, sepal.length] # 5.1 dt[1, "sepal.length"] # gives error, need with! dt[1, "sepal.length", = false] # 5.1 # done when code columns programmatically my.col <- "sepal.length" dt[1, my.col, = false] # 5.1

scala - Guice , unable to create injector -

im trying create in injector testing api. the test binding follows class apitestmodule extends abstractmodule { def configure(): unit = { bind(classof[client]).in(classof[singleton]) bind(classof[apigetcontroller]).in(classof[singleton]) bind(classof[apipostcontroller]).in(classof[singleton]) bind(classof[indexservice]).in(classof[singleton]) bind(classof[panelservice]).in(classof[singleton]) bind(classof[entitiesservice]).in(classof[singleton]) bind(classof[authenticatedpublicapiaction]).in(classof[singleton]) bind(classof[ratelimitedapiaction]).in(classof[singleton]) bind(classof[apikeyvalidatorupdaterthread]).in(classof[singleton]) bind(classof[apikeyvalidatorservice]).in(classof[singleton]) bind(classof[articlefrontservice]).in(classof[singleton]) } i've created te injector in code val testmodule = new abstractmodule() { def configure() = { new apitestmodule().configure(binder())

java - Capture big movement with Android Smartphone -

i able capture big movement on android phone game. example stroke arm right, left or other direction , able differentiate them. is there exist ? what sensor should use purpose , why ? thx you should use accelerometer. direction in difference in acceleration helps detect movement of arm. don't pay attention values of accelerometer, rather differences: can't detect arm is, neither if moved, can detect if accelerated , decelerated move.

Android Toolbar menu text color -

Image
i'm trying change toolbar's menu item text color here, doesn't work. here's style: <style name="apptheme" parent="theme.appcompat.light.noactionbar"> <item name="colorprimary">@color/colorprimary</item> <item name="colorprimarydark">@color/colorprimarydark</item> <item name="coloraccent">@color/coloraccent</item> <item name="toolbarstyle">@style/apptheme.toolbarstyle</item> <item name="buttonstyle">@style/apptheme.buttonstyle</item> <item name="colorcontrolhighlight">@color/colorprimary</item> </style> <style name="apptheme.toolbarstyle" parent="base.theme.appcompat.light.darkactionbar"> <item name="android:background">@color/colorprimary</item> <item name="titletextcolor">@android:color/white</item>

javascript - Problems with offline.js -

i'm using offline.js offline.js when reconnects lost internet connection makes previous ajax call again. doesn't go through success function. went through thread ( https://github.com/hubspot/offline/issues/120 ) didn't seem of help. here have idea how can fix this?

Convert matlab statement to python -

this question has answer here: numpy: find first index of value fast 14 answers i should convert following matlab statement in python: lam = find(abs(b)>tol,1,'first')-1; thanks in advance numpy doesn't have capability first matching one, not yet anyway . so, need matching ones np.where replace find , numpy.abs replacement abs . thus, - import numpy np lam = np.where(np.abs(a)>tol)[0][0]-1 thus, getting matching indices np.where(np.abs(a)>tol)[0] , getting first index indexing first element np.where(np.abs(a)>tol)[0][0] , subtracting 1 it, did on matlab. sample run - on matlab : >> b = [-4,6,-7,-2,8]; >> tol = 6; >> find(abs(b)>tol,1,'first')-1 ans = 2 on numpy : in [23]: = np.array([-4,6,-7,-2,8]) in [24]: tol = 6 in [25]: np.where(np.abs(a)>tol)[0][0]-1 out[25]: 1 # 1

javascript - angular one-time binding syntax gives blank output -

trying use one-time binding syntax angular output not work when put :: vm.doctors. $interpolateprovider.startsymbol('{['); $interpolateprovider.endsymbol(']}'); <li ng-repeat="item in ::vm.doctors"> {[ ::item.name ]} </li> what doing wrong ? can set vm.doctors = []; , one-time binding gets final value? explain not updating values when $http.get finishes, in totally different digest cycle after variable stabilized. setting variable in get callback first time should solve issue. if allow further updates of collection (like loading more items on scroll), don't set one-time binding on collection, on items.

swift - How to get exact time since iOS device booted? -

this question has answer here: getting ios system uptime, doesn't pause when asleep 6 answers i've encountered problem. need exact timeinterval since device booted. in coremotion framework cmlogitem class have timestamp property, returns exact time since device booted. ( link ) necessary in order measure exact time event occurred. i tried following code: let timestamp = processinfo.processinfo.systemuptime but returns different time need. appreciated, in advance! after investigation of data provide. possible conclude cmlog​item : the cmlog​item class base class core motion classes handle specific types of motion events. objects of class represent piece of time-tagged data can logged file. cmlog​item defines read-only timestamp property records time motion-event measurement taken . not exact time since device booted. by processin

java - add external jar to classpath -

i have added external jar file classpath , application don't use class in ,any idea , code: code : string java = system.getproperty("java.home") + "/bin/java"; string classpath=system.getproperty("java.class.path"); string mainclasspath=system.getproperty("sun.java.command"); string file = "c:\path file \file.jar"; final stringbuffer command = new stringbuffer("\"" + java + "\" "); command.append("-cp \""+""+classpath+";"+file+"\" "+ mainclasspath); runtime.getruntime().addshutdownhook(new thread() { @override public void run() { try { runtime.getruntime().exec(command.tostring()); } catch (ioexception e) { e.printstacktrace(); } } }); system.exit(0);

php - Check WordPress login outside currrent domain -

in php website (no wordpress) want check if current visitor , logged in wordpress blog (different folder or domain). i use code: define('wp_use_themes', false); require('../wp-blog-header.php'); if(!is_user_logged_in()) { exit('you not have access'); } it works correctly if php site in path example.com/site/index.php but error 500 if use in subdomain.example.com/index.php define('wp_use_themes', false); require('https://www.example.com/wp-blog-header.php'); if(!is_user_logged_in()) { exit('you not have access'); } is possible cross-domain check? i having similar issue when creating sub-domain display page off site. wasn't getting 500 error page load , user not logged in. reason because wordpress sees sub-domain it's own domain , not try load/access same cookies. ran across post: https://github.com/dellis23/django-wordpress-auth/issues/6#issuecomment-130070419 you have add cookie_domain

c++11 - Is it possible for a garbage value to be negative in an array in C++? -

consider: int a[100]; is possible uninitialized value in a[i] (where 0 < < 100) negative? yes, why wouldn't ? theses bits can , sign of integer msb (most significant bit). if bit 1 , int considered negative. i see little point of knowing though. can't rely on garbage data it's undefined behavior.

c# - Objects in list seem to share dictionary keys and vaules -

im coding small program tries calculate how many robots can escape hole within 5, 10 , 20 seconds, robots travel speed of 10 m/s. the robots , holes have 2 floating point numbers coordinates , figure out distance between holes , robots use pythagoras theorem. to keep track of robot closest hole equiped each hole dictionary robots id key , distance hole value. there can different scenarios, maxium 10, different numbers , holes. input looks this, first number n number of robots in field followed n lines of x/y coordinates. second number m number of holes followed m lines of x/y coordinates. the input ends 0. 3 0.0 0.0 10.0 0.0 0.0 10.0 3 99.0 0.0 0.0 1000.0 1000.0 1000.0 3 0.0 0.0 100.0 0.0 200.0 0.0 2 95.0 50.0 105.0 50.0 0 theese classes class robot { public int id { get; private set; } public double posx { get; private set; } public double posy { get; private set; } public bool ishiding { get; set; } public robot(double posx, double posy, i