Posts

Showing posts from January, 2015

How would one create an algorithm class like the algorithm used to choose a random number in java? -

i'm not asking code random number algorithm is, believe prng, psuedorandom number generator: how random number algorithm generator code, use same class structure concrete class in java instance variables, default constructors, overload constructors, getmethods, methods, tostring, or code these algorithms different way? in addition, wondering if there specific programs 1 use create algorithm class? note: if have question, fell free leave them in comments before downvoting question. thank can appreciated! note: also, know there lot of algorithms out there, when looking answer, if end needing answer. great if java algorithms or common type of algorithms in general, not random ones. again!

conv neural network - TensorFlow Inception Model Can't See Files In Folder -

i hope having great day. i'm attempting train convnet fun, tensorflow inception v3 model doesn't find files within folders though there. i error when trying train it: looking images in 'evening_star' no files found looking images in 'morning_star' no files found no valid folders of images found @ /tf_files/image_recognition does have ideas why occurring?

How to coordinate the task chain in the celery-rabbitMQ framework to reduce the memory usage? -

Image
1、 design tool hand traffic report of lte-network.i follow git-project : https://github.com/esperdyne/celery-message-processing . the code work, yet memory highly occupied , therefore hope coordinate task chain of celery-rabbitmq. 2、 use- case model in example have 2 use cases, let’s see use-case diagram below. figure 4-1 use case model form above diagram, can see wish have timer , 2 jobs: 1, fetch traffic report files ftp servers, parse file ,pick information field wish , , storage files in database. 2, fetch traffic report files ftp servers, parse file ,pick information field wish. calculate total traffic of each cell, filer cell traffic volume bigger 100 m, , copy records database. let’s have @ use-case description of 2 use case. 1.2.1 storage traffic report 1、 timer visit ftp server every week , find out new arriving files. 2、it pick file, convert file intermediate stream in memory. 3, pick information necessary traffic dimension , ready

android - Is it possible to get speed limit data using OSMBonusPack? -

i've been trying develop speed limit application & have tried many different approaches done . i have used overpass apis & did did not have speed limit information few of locations around europe & installed velociraptor uses osm map & here maps apis still failed data . here screenshot of velociraptor app : screenshot image . yesterday came across osmbonuspack & looks promising allows choose 3 best routing services available . , before proceed implementation thought might useful suggestions on if can speed limit project. any suggestions appreciated. unfortunately, 3 routing services not returning speed limit information. options: contact them directly convince them add speed limit per segment fork open source 1 (osrm?), , implement yourself back overpassapi or velociraptor

sockets - Java Soket cannot send multicast packet on Raspberry Pi -

i try run code in raspberry pi. socket can receive data multicast group, however, shows following error when tries send data: pi@raspberrypi:~ $ java protocol java.net.multicastsocket@647e05 java.io.ioexception: cannot assign requested address @ java.net.plaindatagramsocketimpl.send(native method) @ java.net.datagramsocket.send(datagramsocket.java:693) @ protocol.getsensordata(protocol.java:201) @ protocol.main(protocol.java:305) here code: import java.net.*; import java.util.*; public class protocol { private multicastsocket socket = null; private multicastsocket socket_switchpanel = null; string multicast_address = ""; int port = -1; public protocol(string nic, boolean isbyip, string multcastaddress, int port) { this.multicast_address = multcastaddress; this.port = port; try { inetaddress dstaddr = inetaddress.getbyname(multicast_address); socket = new multicastsocket(port);

dynamic programming - For 0/1 classic kanpsack with 1 bag ( capacity: 2V) or 2 bags (each capacity: V), which choice is better? -

i think variant of classic 0/1 knapsack problem. say, assume plan steal treasure given capacity limit(say 2v). given capacity limit, have 2 choices: 1 bag capacity 2v, or 2 bags capacity v sepetately. there mathmatical formula can use pre-compute solution better(give better optimal value)? or have compute optimal value seperately via different recurrence regulation , choose better one? more over, can generalize problem one: given capacity limit(v), can take 1 bag capcity v or take k bags capcity v/k conduct stealing. , eonchoose best 1 solve problem one bag better. content of n bags solution can fit 1 bag, not vice versa.

javascript - Vue - Passing same data from one component to many component -

i have following code. main.js new vue({ el: '#app', template: '<app/>', components: { app } }) app.vue <template> <div id="app"> // not pass data component <basics :resume="resume"></basics> <education :resume="resume"></education> // gets value json file {{resumedata.name}} {{resumedata.education}} </div> </template> <script> import basics './components/basics.vue' import education './components/education.vue' import resume '../resume.json' export default { name: 'app', data() { return { resumedata: resume } }, components: { basics, education } } </script> /components/basics.vue <template> <div> <p>basics</p> // not value json file {{resumedata.name}} </div> </template> /components/educatio

java - Adding Header or Footer on every page using ITextRenderer from HTML -

i'm creating html report usgin freemarker, , produce pdf html using itextrenderer. itextrenderer renderer = new itextrenderer(); renderer.setdocumentfromstring(html); renderer.layout(); renderer.createpdf(baospdf); i have table in html, header shows on every page using css classes: thead { display:table-header-group } is possible same trick arbitrary section of document? (let say, div ) i'ld keep html vanilla, , identify "header" , "footer" want see on every page using css. is possible, css? perhaps should have at http://developers.itextpdf.com/content/itext-7-examples/converting-html-pdf it gives few examples of converting html pdf. including loading external stylesheet.

How to get the updated location with an interval of 1 minute ANDROID -

i want updated location interval of 1 minute me put marker on map , @ same other application can see current location whenever move. so here's code sad won't update location if code inside onlocationchanged method. i'm not sure though if code's right. @override public void onlocationchanged(location location) { mlastlocation = location; if (mcurrlocationmarker != null) { mcurrlocationmarker.remove(); } latlng = new latlng(location.getlatitude(), location.getlongitude()); lat = string.valueof(location.getlatitude()); llong = string.valueof(location.getlongitude()); driverid = pref.getstring("driverid", ""); final query username = ref.orderbychild("username").equalto(username); username.addvalueeventlistener(new valueeventlistener() { @override public void ondatachange(datasnapshot datasnapshot) { (datasnapshot snapshot : datasnapshot.getchildren()) {

web component - Does IOS Safari support Shadow DOM? -

Image
my application able render shadow dom, inspector cannot display shadow root. can me out on this? it depends on shadow dom mean—shadow dom v0 or shadow dom v1. see http://caniuse.com/#feat=shadowdomv1 , http://caniuse.com/#feat=shadowdom no version of safari supports shadow dom v0. far ios safari, version 10.2+ support shadow dom v1 following limitation: certain css selectors not work ( :host > .local-child ) , styling slotted content ( ::slotted ) buggy. as far differences between shadow dom v0 , v1, see https://hayato.io/2016/shadowdomv1/ about how see shadow root in webkit/safari inspector, there’s button need click show shadow roots; looks this: and in inspector ui, it’s in toolbar on right below tabs. turns blue when activated:

windows - Scheduling console apps -

does have better ways of managing / scheduling console apps, without use of windows scheduler? eg. console app pickup records in database requires set of actions. *** experience in past, when number of tasks increase on time, get's bit messy , difficult maintain when moving servers. there third party apps at, of suggested in cron-like system windows? . however, if windows scheduler provide functionality need, not ideal management, @ using cli schtasks.exe you can define tasks in xml schema meaning more port across machines.

r - Looping linear models for multiple files in directory -

i have folder 26 .csv files in it. each file has 2 columns headers do2 , time_min , have @ least 300+ rows. i want make scatterplot x=time_min , y=do2 , make linear model of each, take coefficient , r^2 each of 26 models , put in table. this i've written far code goes. know can copy , paste know there has smarter way. setwd("~/documents/masters/data/r/35789/35789_ucrit") #the file want coefficients , r^2 go ue_slope <- read.csv("~/documents/masters/data/r/35789/35789_ue_slope.csv") temp = list.files(pattern="*.csv") (i in 1:length(temp))(assign(temp[i], read.csv(temp[i]))) #seal# names files directory, 1-26 plot(do2 ~ time_min, data = seal1) model1 <- lm(do2 ~ time_min, data = seal1.csv) ue_slope <- rbind(ue_slope, data.frame("slope"=coef(model1)[[2]], "r.2"=summary(model1)$r.squared)) we first define function, reads "csv" file, fits linear model , obtains summary statistics. f <- f

javascript - is it possible to render part of a ractive template on click event? -

for crud-interface have json in datatable rendered ractive. 2 of columns need multiselect dropdown (with bootstrap-multiselect ), values predefined out of list of computed values. simplified looks this: const datatpl = '{{#persondata:i}}' + '<td><select multiple id="persons{{i}}" value="{{hasskill}}">' + '{{#skills}}' + '<option value="{{_id}}">{{skill}}</option>' + '{{/skills}}' + '</select></td>' + '<td><button on-click="@this.edit(i)"></button></td>'; let ractive = new ractive({ el: '#table', template: datatpl, data: { alldata: docs }, computed: { skills() { // --> computes list of possible skills out of given data }, persondata() { // --> computes list of persons } } }); the script works great

excel - How do I specify a path in the worksheet.add command? -

i'm relatively new programming in vba. want insert template worksheets. have code right works first step: private sub workbook_sheetchange(byval sh object, byval target range) if target.column = 2 or 3 or 4 or 5 worksheets.add after:=worksheets(worksheets.count) worksheets(worksheets.count).name = target end if end sub i know if want insert template these steps: expression: .add(before, after, count, type) type specifies sheet type. can 1 of following xlsheettype constants: xlworksheet, xlchart, xlexcel4macrosheet, or xlexcel4intlmacrosheet. if inserting sheet based on existing template, specify path template. default value xlworksheet. i need link type projectonderdelen.xltm, located in c:\users\stage\documents\aangepaste office-sjablonen can me agony please? greetings, brendon if target.column = 2 or 3 or 4 or 5 then not correct syntx. either use: if target.column = 2 or target.column = 3 or target.column = 4 or target.column = 5 or,

javascript - reactJS how to change between many application states -

new reactjs , trying have 1 of components alternate through many crud states (creating object, listing objects, updating objects, deleting objects), each 1 display appropriate forms... i thinking cannot see if thinking flawed. constructor() { super(props); this.state = { list: true, edit: false, create: false, // , on crud operations } then later there method... handlecrudviewchange(newview) { // flip false... // turn correct 1 true } then in render this... switch (true) { case this.state.list: <listcomponent /> case this.state.edit: <editcomponent /> // , on... } is thinking sound? "react" way things? yes, on right track. may want simplify bit - const modes = {list: 0, edit: 1, create: 2}, crud_components = [listcomponent, editcomponent, createcomponent]; constructor(){ this.state = {"mode" : modes.list}; }, handlecrudviewchange(newview) { // decide relevantmode

javascript - How to dynamically add links to canonical urls -

i working on project in angular need add dynamic links canonical urls. page changes url in canonical href should change/update.there conditions have added because of parent urls should added. below code: var url = window.location.href, urlsegments = url.split("/").length - 1 - (url.indexof("http://")==-1?0:2); if(urlsegments <= 7) { var link = document.createelement('link'); link.setattribute('rel', 'canonical'); link.setattribute('href', url); document.head.appendchild(link); } but not working.what wrong doing here , can best solution this. in advance!! you tagged angulajs tag think should angular way - directive. haven't specified not working hard give details, here have example on how manipulate <head> elements directive.

tensorflow - Finetuning VGG-16 Slow training in Keras -

i'm trying finetune 2 last layers of vgg model lfw dataset , i've changed softmax layer dimensions removing original 1 , adding softmax layer 19 outputs in case since there 19 classes i'm trying train. want finetune last connected layer in order make "custom feature extractor" i'm setting layers want non-trainable this: for layer in model.layers: layer.trainable = false using gpu takes me 1 hour per epoch train 19 classes , minimum of 40 images per each class. since don't have lot of samples, it's kind of strange training performance. anyone knows why happening? here log: image shape: (224, 224, 3) number of classes: 19 k.image_dim_ordering: th ____________________________________________________________________________________________________ layer (type) output shape param # connected ========================================================================================

ios - Black effect when screen popping controller with custom animation? -

i popping view controller navigation controller.when popping controller want give animation pushing view controller.for purpose using below code catransition* transition = [catransition animation]; transition.duration = 0.3f; transition.type = kcatransitionpush; transition.subtype = kcatransitionfromright; [self.navigationcontroller.view.layer addanimation:transition forkey:kcatransition]; [self.appdelegate setupforlvc]; [self.navigationcontroller popviewcontrolleranimated:no]; when animation starts black effect here.please tell me issue code ? add code in didfinishlaunchingwithoptions self.window.backgroundcolor = [uicolor whitecolor]; self.window.tintcolor = [uicolor whitecolor]; **or** 2)set animation duration 0

database - Normalizing transitive / partial dependencies -

Image
consider table named books table books has attributes: isbn booktitle author_num lastname publisher royalty edition the primary keys bolded there partial dependencies isbn can determine booktitle isbn can determine edition author_num can determine last name there transitive dependency: - booktitle can determine publisher what best way , systematic way normalise table? for me, is: identify non-primary key holds partial dependency , no transitive dependency (i.e. isbn can determine booktitle , edition using rule , author_num can determine lastname) , put them in separate table each instance of rule applies partial dependencies allow transitive dependency occur grouped in own table (i.e. booktitle & publisher) final table have values associated 2 initial determiners of partial dependency (isbn, author_num values hold no dependency i.e. royalty) diagram:

How to redirect get methods with Liberator in Clojure? -

i have endpoint called /account provides user info(returns html). when unauthorised user tries access endpoint need able redirect login page in liberator found post-redirect far , post methods . i need redirect get methods well, how can achieve this? i found workaround following code trick: (defn account [] (resource :allowed-methods [:get] :available-media-types ["text/html"] :exists? (fn [_] false) :existed? (fn [_] true) :moved-temporarily? (fn [ctx] {:location "/redirected-path-or-url"}) :handle-ok (fn [ctx] [:html ...]) :handle-exception (fn [_] "something went wrong"))) or can check :authorized? , return login html :handle-unauthorized doubt it's practice or not.

firebase - Ionic2 authentication: auth0 vs ionic cloud service -

i need implement login functionality in ionic2 app. goal allow various social login providers (google, fb, twitter). i've done earlier (ionic1) in custom way, prefer framework handles calls me. seems there more 1 option: ionic (cloud) auth service auth0 firebase it's quite unclear me how hey differ , 1 should preferred choice. can't find existing articles pointing out (except this one). although see of these can combined makes more mysterious. rather learning 3 first make fact-based decision, i'd love hear experienced opinions. don't want start discussion, facts features, performance, errorproofness etc.

java - Why I am not able to Pop Element from stack using Linked List Implementation? -

problem: i not able pop element second time. example have 4,3,2,1 4 on top of stack.i not able delete 3,2 can guide me why? below stack implementation : public static void push(int data){ if(head==null){ node newnode=new node(data); head=newnode; }else{ node newnode1=new node(data); newnode1.next=head; head=newnode1; } } public static int pop(){ if(head==null){ return 0; } else{ node temp=head; int a=temp.data; temp=null; return a; } } public static void traverse(){ node temp=head; while(temp!=null){ system.out.println(temp.data); temp=temp.next; } } you have problem in pop method public static int pop(){ if(head==null){ return 0; } else{ node temp=head; head = head.next; int

elixir - Testing Phoenix.Controller.redirect -

i'm new phoenix , i'm testing custom plug should redirect /404.html page if condition not met. code works correctly when try success/failure paths i'm having difficult time understanding why testing approach blowing up. the test failure boils down following: %plug.conn{} |> phoenix.controller.redirect(to: "/404.html") my expectation should return conn object can run assertions on. however, when try run above code following error: ** (undefinedfunctionerror) function plug.conn.send_resp/4 undefined or private. did mean 1 of: this bit weird since phoenix.controller module implements send_resp/4 function , imports plug.conn @ top of definition. why ignoring function , trying hit plug.conn directly? i'm not calling private function, public function delegating it, should kosher unless i've missed obvious. there easy solution problem or should take approach? edit here full stack trace iex: %plug.conn{} |> phoenix.controller.redire

javascript - Simplify function for removing duplicate array -

i want find div element contain custom attribute mod append div list item. first have remove divs contain duplicate mod value. here's have done <div class="list"></div> <div class="container"> <div mod="dog"></div> <div mod="man"></div> <div mod="woman"></div> <div mod="dog"></div> <div mod="bird"></div> <div mod="insects"></div> <div mod="dog"></div> </div> this script modarr($('.container').find('[mod]')) function modarr(el){ var filterarray = [] // store mod , modnames = [] // store mod value , arrindex = [] // store non duplicate index , li = [] // store modarray = el // store mod value for(var i=0; < modarray.length; i++){ modnames.push($(modarray[i

javascript - Is it possible to set an element's margin-top as 60% of another element's height with SCSS? -

question says all. possible set element's margin-top 60% of element's height scss? i'm developing ionic 2 app, targeting browsers, android, ios , windows phone. here elements: <div class='logobox'> <img src="assets/img/-.png" class="corner-logo" alt="-" /> <img src="assets/img/icon.png" class="logo" id="logo" alt="-" /> </div> <div class='headerbox' id="headerbox">...</div> this how i'm setting positioning right now: ionviewdidenter(){ document.getelementbyid('headerbox').style.margintop = math.round(number(document.getelementbyid('logo')['height']) * 0.6) + 'px'; window.addeventlistener('orientationchange', () => { document.getelementbyid('headerbox').style.margintop = math.round(number(document.getelementbyid('logo')['height']) * 0

tensorflow error:Unimplemented: Cast string to uint8 is not supported -

sorry poor english.first. i'm reading mnist tutorials,and try code functions encode images tfrecord , read data tfrecord files. , there errors. tf version 0.11 enter image description here i'm not sure whether there wrong in encoding or decoding process. compared codes tutorials code, no mistake can find. suspect no record read reader.read(), how can exam assumption? img=image.open(img_path) img=img.resize((rows,cols)) img_raw=img.tobytes() example=tf.train.example(features=tf.train.features(feature={ 'image_raw':_byte_feature(img_raw), 'label':_int64_feature(int(i))})) decoding process reader=tf.tfrecordreader() _,example=reader.read(filequeue) features=tf.parse_single_example(example,features={'image_raw': tf.fixedlenfeature([],tf.string), 'label':tf.fixedlenfeature([],tf.int64)}) image=tf.decode_raw(features['image_raw'],tf.uint8) image.set_shape(rows*cols) image=tf.

javascript - rentlinx featured property remove duplicate -

i have displayed featured property listing using rentlinx. <script type="text/javascript" src="http://www.[tagname].rentlinx.com/featuredpropertyjs.aspx?template=http://www.rentlinx.com/external/calvofeatured.xsl&ref=1"></script> i want featured property scroll via owl carousel. <div class="owl-item"><div class="each-properties"> <script type="text/javascript" src="http://www.[tagname].rentlinx.com/featuredpropertyjs.aspx?template=http://www.rentlinx.com/external/calvofeatured.xsl&amp;ref=1"></script> </div> <div class="owl-item"><div class="each-properties"> <script type="text/javascript" src="http://www.[tagname].rentlinx.com/featuredpropertyjs.aspx?template=http://www.rentlinx.com/external/calvofeatured.xsl&amp;ref=2"></script> </div> scroll working now. properties repeated display. how ca

Find points within polygon with multiple self intersections with Matlab -

Image
i have polygon intersects multiple times. try create mask polygon, i.e., find points/pixels location within polygon. use matlab function poly2mask this. however, due multiple self-intersections results obtain: resulting mask poly2mask multi-self-intersecting polygon so, areas remain unmasked, because of intersections. think matlab sees sort of inclusions. matlab poly2mask doesn't mention this. have idea how include these regions in mask? i obtain results combining small erosion/dilation step , imfill follows: data = load('polygon_edge.mat'); x = data.polygon_edge(:, 1); y = data.polygon_edge(:, 2); bw1 = poly2mask(x,y,ceil(max(y)),ceil(max(x))); se = strel('sphere',1); bw2 = imerode(imdilate(bw1,se), se); bw3 = imfill(bw2, 'holes'); figure imshow(bw3) hold on plot(x(:, 1),y(:, 1),'g','linewidth',2) the small erosion , dilation step needed sure regions connected @ places polygon connected through single point, otherwise

javascript - VueJS v-for access both parameters and event object on event -

suppose have nested elements repeated v-for this: <div id="container"> <div v-for="i in 3"> <div v-for="j in 3" v-on:click="clicked(i,j)"> {{i+','+j}} </div> </div> </div> and corresponding javascript: var vm = new vue({ methods:{ clicked:function(i, j){ //how access click event here? } }, el:'#container' }) if use v-on:click="clicked" can access event (and corresponding element) in clicked function. want supply parameters , j, how can both access them , click event? want able regardless of event (keyup, keydown, blur, focus etc). to access event object send $event parameter, vue assign event object if $event named parameter found in event handlers. <div v-for="j in 3" v-on:click="clicked(i, j, $event)"> {{i+','+j}} </div>

Troubles when reading csv in vb.net (using LumenWorks) -

i need make vb.net program using lumenworks reads each line of .csv file. first line of file contains names of fields, , next lines contain information, , fields delimited coma (,). most of lines okay, there few lines 1 of fields has comma in it, in cases quotes (") used, example of 4 fields (see "communication, management" 1 single field): united states, america,"communication, management",20/02/1997 this code @ moment. when csvreader gets line contains aforementioned quotes ("), error: primera excepción del tipo 'lumenworks.framework.io.csv.missingfieldcsvexception' en lumenworks.framework.io.dll i hope can me! public sub readfile() dim csv csvreader = new csvreader(new streamreader(path, system.text.encoding.default), true) dim fieldcount integer = csv.fieldcount dim headers string() = csv.getfieldheaders() while csv.readnextrecord() integer = 0 fieldcount - 1 con

Docker setup - facing issues while running chaincode locally -

i've installed docker , hyperledge-fabric v0.6 on local system. unfortunately while trying run sample chaincode, i'm facing below mentioned error. please guide me run chaincode successfully. addrconn.resettransport failed create client transport: connection error: desc = "transport: dial tcp [::1]:30303: connectex: no connection made because target machine actively refused it."; reconnecting {"localhost:30303" } 10:05:25.048 [shim] erro : error trying connect local peer: grpc: timed out when dialing error starting simple chaincode: error trying connect local peer: grpc: timed out when dialing c:\users\arunh\goworkspace\src\github.com\testapp\learn-chaincode\start>docker-compose op 'docker-compose' not recognized internal or external command, operable program or batch file. hyperledger fabric has evolved quite bit since v0.6 release. recommend if still on v0.6 upgrade v1.0.x. http://hyperledger-fabric.readthedoc

c++ - Optimizing subroutine with memcmp, memcpy -

i wonder if there optimizations (something more efficient memcmp/memcpy maybe using loop or breaking down fast assembly instructions) can done subroutine. num_bytes constant value (always = 18): void ledsmoothwrite(uint8_t ledtarget[]) { // if new target different, set new target if(memcmp(target_arr, ledtarget, num_bytes)) memcpy(target_arr, ledtarget, num_bytes); // obtain equality for(uint8_t = 0; < num_bytes; i++) { if(rgb_arr[i] < target_arr[i]) rgb_arr[i]++; else if(rgb_arr[i] > target_arr[i]) rgb_arr[i]--; } render(); } this subroutine smoothly setting led colors might called several hundred times per second. loop() function increases in run time takes more time each led desired values. any appreciated. thank in advance! check documentation on many compilers memcmp() , memcpy() implemented efficient machine code instructions. may (for practical purposes) fast gets. try not doing comparison. dependi

php - Laravel: how to access a file in the local disk? - File does not exist -

i'm trying edit excel file after uploading in laravel. file uploaded local disk, no 1 can access public. filesystems.php 'local' => [ 'driver' => 'local', 'root' => storage_path('app') routes.php route::get('test',function() { // create new phpexcel object $objphpexcel = new phpexcel(); $objphpexcel = phpexcel_iofactory::load(storage::disk('local')->url('margin/analyser/0igkqqgmgxkhrv9isnbtrgyzfupfjz3cwjblgbdn.xlsx')); $objphpexcel->setactivesheetindex(0); echo $objphpexcel->getactivesheet()->gethighestrow(); })->middleware('admin'); i keep getting error: could not open /storage/margin/analyser/0igkqqgmgxkhrv9isnbtrgyzfupfjz3cwjblgbdn.xlsx reading! file not exist. this works $objphpexcel = phpexcel_iofactory::load('..'.storage::disk('local')->url('app/margin/analyser/0igkqqgmgxkhrv9isnbtrgyzfupfjz3cwjblg

c# 4.0 - How to manage state between android app and ASP.net Web API? -

we have android app through retailer can recharge customers mobile. need authorize every recharge request. to send recharge request retailer needs hit api recharge related information , userid , userkey. below [acceptverbs("get")] public ihttpactionresult prepaid(int puserid = -1, string pkey = "", string pcustomerno = "", decimal pamount = 1, int pserviceproviderid = -1, int pdevicetypeid = -1) we authenticate user every api hit comparing userkey(encrypeted password) password stored in db this makes many db calls , our server gets slow its b2b app , retailer perform different kind action transaction history, credit request, book complaint other recharge how maintain state after user login android app if userkey unique identification every user, or every 1 unique mobile number, think better verify mobile number user using make recharge sending otp. user can send otp authentication. @ time of login, , store unique user key have

elasticsearch - Space issue with query_string -

i using query_string standard analyzer i have data :- { "foo":"john smith" } { "foo":"smith john" } { "foo":"john smith hi how u" } { "foo":"beacon" } { "foo":"demo hei device" } but when using query query_string :- { "query": { "query_string": { "query": "foo:john a" } } } expected result should :- { "foo":"john smith" } { "foo":"smith john" } { "foo":"john smith hi how u" } actual responce :- { "foo":"john smith" } { "foo":"smith john" } { "foo":"john smith hi how u" } { "foo":"beacon" } { "foo":"demo hei device" } could tell , result data ("foo":"beacon") , { "foo":"demo hei device" } coming ? i th

sql server - Hardcode a specific day in data time while pulling the data - SQL -

actually have different date in sql table when pull via sql query, day of datetime field should have fixed day. example: (dd-mm-yyyy) day should "7" > (7-mm-yyyy) 10 -08-2007 > 07 -08-2007 27 -12-2013 > 07 -12-2013 01 -03-2017 > 07 -03-2017 can me on this. in advance. find difference between 7 , day of original date , add original date: select dateadd(day, 7 - day(originaldate), originaldate)

Jquery multiple ID selector doesn't work -

i tried script didn't work second given id; both element inside iframe <script> jquery(document).ready(function(){ $("#subscribe_newsletter, #close_bar").each(function(){ $(this).click(function(){ alert("with each"); $.cookie( "nl_cookie" , 1 , { path: "/" } ); $("#footer_accept_newsletter").hide("slow"); }); }); cookievalue = $.cookie("nl_cookie" , { path: "/" }); if(!cookievalue){ $("#footer_accept_newsletter").removeclass("hidden"); } }); </script> i tried following code no success; $("#subscribe_newsletter, #close_bar").click(function(){ $.cookie( "nl_cookie" , 1 , { path: "/" } ); $("#footer_accept_newsletter").hide("slow"); }); it work me $(docum

javascript - HTML 5 drag events: 'dragleave' fired after 'dragenter' -

i'm using html5 dragevents in single page application. currently, i'm listening dragleave , dragenter events set proper classes on elements. but, when 2 valid target elements(a , b) next each other, , drag elment through b, events fired in following sequance. +--------------+-------------+ | | | +-------+ | | b | | | | | | | elem +------------------------------------> | | | | | | +-------+ | | | +--------------+-------------+ dragenter of a dragenter of b dragleave of a the expected order of events be, dragenter of a dragleave of a dragenter of b i assumed order since item has leave a before entering b . missing here? there rationale dragenter being fired before dragleave ? there way change behaviour

Getting Mac address from Docker Container -

is possible mac address of host machine docker container , write in text file? docker inspect <container name or id> |grep macaddress|tr -d ' ,"'|sort -u or inside container: ifconfig -a ifconfig part of 'net-tools' linux pkg , way enter running container: nsenter -t $(docker inspect --format '{{ .state.pid }}' <container name or id> ) -m -u -i -n -p -w

devise gem Ruby on Rails in ubuntu -

i have problem. want install devise gem.my ruby version:2.4.0 in terminal: installing devise 4.2.1 errno::eacces: permission denied @ rb_sysopen - /home/fatih/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/devise-4.2.1/.gitignore error occurred while installing devise (4.2.1), , bundler cannot continue. make sure gem install devise -v '4.2.1' succeeds before bundling.

android - Schedule Executor's Schedule Method is Executing Only Once -

i trying implement sample schedule want toast displayed every 10 seconds.but schedule method running once.is there solution. here code public class mainactivity extends appcompatactivity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); scheduledexecutorservice scheduledexecutorservice= executors.newscheduledthreadpool(1); scheduledexecutorservice.schedule(new runnable() { @override public void run() { runonuithread(new runnable() { @override public void run() { toast.maketext(getapplicationcontext(), "hello schedule", toast.length_long).show(); } }); } }, 10, timeunit.seconds); } } read documentation on difference between scheduledexecutorservice#schedule() , scheduledexecutorservice#scheduleat*

qt - write and read data to terminal from serial port without connecting any hardware devices to serialport -

actually have qt code. need send data of packets serial port terminal , display data in terminal , terminal need read data , display in qt window page. main problem is, serial communication terminal, require serial port should connect hardware devices , also.. can write , read data terminal without connecting serial port hardware devices. the code transceiver layer serial port transceiver::transceiver(qobject *parent) : qobject(parent), mserial(new qserialport(this)) { mserial->setportname(qstring("com1")); qint32 baudrate = 9600; mserial->setbaudrate(baudrate); mserial->setdatabits(qserialport::data8); mserial->setparity(qserialport::noparity); mserial->setstopbits(qserialport::onestop); connect ( mserial, &qserialport::readyread, [ ]() { qbytearray data = mserial->readall(); ondatareceived( data ); qdebug()<<data; } ); }

jsf - Get ui:param from java managedBean -

i'm including .xhtml in other 1 follows: <ui:include src="/app/common/panels/task_list.xhtml"> <ui:param name="idobject" value="#{backingbeanref['workgroup']['id']}" /> <ui:param name="classname" value="#{backingbeanref['workgroup']['class']['name']}" /> <ui:param name="backingbeanref" value="#{ttaskquerybean}" /> </ui:include> in order bean follows: facescontext fc = facescontext.getcurrentinstance(); string classname = (string) fc.getapplication().evaluateexpressionget(fc, "#{classname}", string.class); but returns " " in despite of being showed in view when #{classname} does know how can solve this? thanks in advance edit : have tried this throws nullpointerexception

How to make a function delay 5 seconds in javascript -

how make function display after 5 or 6 seconds function a() { alert("after 5 seconds"); } a(); you can use js timers want. settimeout/setinterval, etc. var duration = 5000; #in ms, miliseconds. 5000 = 5s function delayedalert() { window.settimeout(slowalert, 5000); } function slowalert() { alert('that slow!'); } look more in https://developer.mozilla.org/en-us/add-ons/code_snippets/timers

Having issue with authentication in case of WCF wshttpbinding -

i trying communicate wcf creating serviceclient class. surprisingly m able communicate wcf if pass wrong domain. happen if pass domain admin user. normal iisuser throws proper validation exception in case of wrong domain. test env. in different domain wcf hosted , can able communicate passing wrong domain remote machine(exist in diff domain). in below code passing wrong domain name in "domainname" variable , domain admin user in "username" , works fine. how can make sure user has pass correct domain ? wshttpbinding httpbinding = new wshttpbinding(); httpbinding.name = "wshttpbinding_iservice"; httpbinding.closetimeout = timespan.maxvalue; httpbinding.opentimeout = timespan.maxvalue; httpbinding.receivetimeout = timespan.maxvalue; httpbinding.sendtimeout = timespan.maxvalue; httpbinding.bypassproxyonlocal = false; httpbinding.transactionflow = false; httpbinding.hostnamecomparisonmode

synchronization - Android : How to restrict disable sync -

in android application using sync adapter sync data server in every 1 hour.i need make happen every time, in android setting --> accounts --> app there option user turning off sync functionality, there way restrict user turning off sync method. you can restrict disable sync. in syncadapter.xml set android:uservisible false . this: <sync-adapter xmlns:android="http://schemas.android.com/apk/res/android" android:contentauthority="com.example.android.basicsyncadapter" android:accounttype="com.example.android.basicsyncadapter.account" android:uservisible="false" android:supportsuploading="false" android:allowparallelsyncs="false" android:isalwayssyncable="true" /> if make uservisible false then, users won't able disable sync settings manually.

Android Twitter fabric users/search.json -

i working on fabric twitter in android can able login twitter twitterloginbutton below twitterloginbutton = (twitterloginbutton) view.findviewbyid(r.id.login_button); twitterloginbutton.setcallback(new callback<twittersession>() { @override public void success(result<twittersession> result) { // result, provides twittersession making api calls l.m(result.data.getauthtoken().tostring()); l.l("twittter auth : " + result.data.getauthtoken().tostring()); } @override public void failure(twitterexception exception) { // on failure } }); now need search users using below twitter api endpoint https://api.twitter.com/1.1/users/search.json?q=%@&page=1&count=20 in ios can able twtrapiclient.urlrequest(withmethod: "get", url: url!, parameters: nil, error: &clienterror) method but comming android can't see requesturl method in twitt

c# - Automapper not mapping different property names -

i have dto class called cardatadto 2 properties named below: public decimal fueltanksize { get; set; } public decimal carengineoutput { get; set; } i using dapper , can see data getting returned , mapped properties in dto expected. i using webapi return data ui - properties on ui named differently below in class called cardata public decimal size { get; set; } public decimal engineoutput { get; set; } so attempting use automapper map these properties below - have automapper config class initialize method called in application_start in global.asax.cs config.createmap<cardata, cardatadto>() .formember(dest => dest.fueltanksize, opt => opt.mapfrom(src => src.size)) .formember(dest => dest.carengineoutput, opt => opt.mapfrom(src => src.engineoutput)) .reversemap(); i getting data in webapi method db list of data , returning below: var cardata = _myservice.getallcardata().tolist(); //error checking etc removed brevity ret

javascript - Webpack error : output filename not configured -

// webpack.config.js const webpack = require('webpack'); const path = require('path'); module.exports = { entry: path.join(__dirname, 'src', 'app-client.js'), output: { path: path.join(__dirname, 'src', 'static', 'js'), filename: 'bundle.js' }, module: { loaders: [{ test: path.join(__dirname, 'src'), loader: ['babel-loader'], query: { cachedirectory: 'babel_cache', presets: ['react', 'es2015'] } }] }, plugins: [ new webpack.defineplugin({ 'process.env.node_env': json.stringify(process.env.node_env) }), new webpack.optimize.dedupeplugin(), new webpack.optimize.occurenceorderplugin(), new webpack.optimize.uglifyjsplugin({ compress: { warnings: false }, mangle: true, sourcemap: false, beautify: false, dead_code: true }) ] }; i have checked file

ruby - Implement a basic datatype in BinData -

i trying implement binary16 encoding half-precision floating point type. the code working except 1 detail: returns object 3 properties (sign, exponent, fraction), return float. right now, have call to_f float. work way integrated int , float classes work. here's code: require 'bindata' class binary16be < bindata::record # naming based on https://en.wikipedia.org/wiki/half-precision_floating-point_format bit1 :sign_bit bit5 :exponent bit10 :fraction def sign sign_bit.zero? ? 1 : -1 end def to_f if exponent == 31 # special value in binary16 - exponent bits 1 return fraction.zero? ? (sign * float::infinity) : float::nan end sign * 2**(exponent - 15) * (1.0 + fraction.to_f / 1024) end end what like: binary16be.read("\x3c\x00") => 1.0 what happens right now: binary16be.read("\x3c\x00") {:sign_bit=>0, :exponent=>15, :fraction=>0} (this not own answer, received gem's author.

java - log4j2 does not read spring boot property from correct configuration -

in log4j2.xml have following 2 properties: <properties> <property name="log-path">logs</property> <property name="bootstrap.servers" value="${bundle:application:app.kafkabrokers}"></property> <property name="filename" value="${bundle:application:app.correctname}"></property> and following 2 appenders: <kafka name="kafka" topic="logaggregation" > <jsonlayout complete="false" compact="false" /> <patternlayout pattern="%date %message" /> <property name="bootstrap.servers">${bootstrap.servers}</property> </kafka> <rollingfile name="rollingfile" filename="${filename}" filepattern="logs/$${date:yyyy-mm}/app-%d{mm-dd-yyyy}-%i.log.gz"> <patternlayout> <pattern>%d %p %c{1.} [%t] %m%n</pattern> </patternlayout> <policies

LARAVEL - Order by on relationship propriety -

Image
i try sort topics date of creation of last post in each subject. have idea how this? recover want, not in right order. one topic has many poste , 1 poste belongsto 1 topic. *: topic = sujet in code. topics = lessujets. $lessujets = sujet::where('jeu_id', $idjeu)->paginate(20); @foreach ($lessujets $sujet) <tr> <td><a href="{{route('sujet.show', $sujet->id)}}">{{$sujet->titre}}</a></td> ... </tr> screenshot: i topics sorted last reply. order should be: "your best card", "test 1", "aaaaa ..!", "[firm] zzzz .."; can know last answer of topic $sujet->postes->last()->created_at (in view of screenshot). you can use eager loading use orderby() relationship. i'm not entirely sure of database schema, being french speaking myself, i'll try , give example match , make sense gave ;-) $sujets = sujet

matlab - how to traverse on white pixels on image and add nodes after every two pixel and connect that nodes using edges -

Image
every 1 doing project on novel graph database handwritten word images in doing on {graph extraction – keypoint (node extraction)} alogithm input: skeleton image s, distance threshold d output: graph g = (v, e) nodes v , edges e 1: function keypoint(s,d) 2: each connected component cc ∈ s 3: v = v ∪ {(x, y) ∈ cc | (x, y) end- or junction points} 4: remove junction points cc 5: each connected subcomponent ccsub ∈ cc 6: v = v ∪ {(x, y) ∈ ccsub | (x, y) points in equidistant intervals d} 7: each pair of nodes (u, v) ∈ v × v 8: e = e ∪ (u, v) if corresponding points connected in s 9: return g i finding branch points , end points , mid points in between branch points , end points using bwmorph function code. clc; clear all; % read in sample image -- see letters.png, bagel.png j=im2double(imread('i2.jpg')); % normalize , binarization b = imresize(j,[100,100]); th = graythresh(b); bw1 = im2bw(b, th); figure; imshowpair(b, bw1, 'montage'); % standard skeletonizat