Posts

Showing posts from June, 2014

python - BFS and UCS algorithms. My BFS implementation works but my UCS doesn't. Can't figure out why -

as long not mistaken, ucs same bfs difference instead of expanding shallowest node, expands node lowest path cost. (also using priorityqueue instead of queue that)so copied bfs code, created map keep track of each node's path cost , changed way items being pushed/popped in queue/priority queue. note: getsuccessors(state) returns list of triples (state, action, cost) these both of implementations: bfs: def breadthfirstsearch(problem): """search shallowest nodes in search tree first.""" queue=queue() objectqueue=queue() visited=set() actions=[] flag=0 objectmap={} actionmap={} start=problem.getstartstate() objectmap[start]=start queue.push(start) objectqueue.push(start) if problem.isgoalstate(start): return actions while queue: parent=queue.pop() object=objectqueue.pop() if parent in visited: continue visited.add(parent) if problem.isgoalst...

windows - Batch for adding suffix of several files except of batchfiles -

i found solution renaming files. did not work, added suffix after file ending like @echo off setlocal enabledelayedexpansion %%a in (*.*) ( ren "%%a" "%%a tenor 1" ) pause&exit my problem: have several filetypes in folder like: song1.mp3 song2.mp3 text1.txt text2.txt document1.pdf document2.pdf add_tenor_1.bat add_tenor_2.bat replaceblankwithunderline.bat and on. want add example files except batch files suffix "* tenor 1". song1 tenor 1.mp3 song2 tenor 1.mp3 text1 tenor 1.txt text2 tenor 1.txt document1 tenor 1.pdf document2 tenor 1.pdf add_tenor_1.bat add_tenor_2.bat replaceblankwithunderline.bat is possible use *.* in condition exception (for .bat) ? how code batch file like? another thing add suffix .txt , .pdf files example. work in 1 routine or need 1 .txt , 1 .pdf? song1.mp3 song2.mp3 text1 tenor 1.txt text2 tenor 1.txt document1 tenor 1.pdf document2 tenor 1.pdf add_tenor_1.bat add_tenor_2.bat replaceblankwithunderline.b...

Are preconditions necessary inside handler APIs that are supported by Frameworks? -

basically when spring io or other framework matter routes url handler method, injects path parameters user supplied values. public responseentity<list<datamodel>> doget(@pathvariable string param1, @pathvariable string param2) { preconditions.checknotnull(param1); preconditions.checknotnull(param2); } is practice or redundant make precondition checks on supplied params inside function shown above? the spring framework not allow injection of null values above parameters. still, handler method can invoked other parts of code (a bad practice, legit nevertheless). method can passed null values when under junit test. so having said this, there compelling case not have preconditions assertions @ top of handler api?

c++ - QT how to cross compile for Windows on linux -

good day all i need test , distibute software have written linux, windows. i using qt creator 4.0.2 (based on qt 5.7.0). i have found tutorial regarding this, found here , had issue building compilter. unfortunately while building compilter (mingw32), have run error - vtk package cannot built - , have not found solution since. for record: $ gcc --version gcc (ubuntu 6.2.0-5ubuntu12) 6.2.0 20161005 is there other methods avaiable build cross-platform applications in linux using qt-creator? thanks in advance

javascript - In es6 I need my promise to return true or false when done -

in es6 need promise return true or false when done this attempt returns promise , need true or false return this.isuserauthenticated() .then(() => this.checkifteacherprofileexists()); the return part needs true or false. this 1 of returns looks like: isuserauthenticated = (): promise<any> => { return new promise((resolve, reject) => { this.authservice.checkifloggedin().then((isauthuser: boolean) => { resolve(true); }); }); } your return promise holding true or false . have chain .then() hold boolean. return this.isuserauthenticated() .then(() => this.checkifteacherprofileexists()) .then(v => console.log(v)); // true or false regarding comment, see @felixkling's comment - can't that, that's not how promises work.

sql - Cannot find the Nvarchar to Int conversion in my code -

i making project school have make program can create orders in. when try create orders error returned me. error converting data type nvarchar int. in advance i'm sorry if basic question easely spotted. me , project members beginning programmers cannot spot goes wrong. the code execute in vba : set rs = dbconn.execute("exec sporderplaatsen '" & me.tbtijd & "', " & me.klantnr & ", '" & me.tbophaaldatum & "', '" & me.tbafleverdatum & "', '" & me.tbophaaladres & "', " & me.tbpalletnr & ", " & me.tbaantalpallets & "") this code execute's our stored procedure. stored procedure looks this. create procedure sporderplaatsen ( @tijd time(0), @klantnr integer, @ophaaldatum date, @afleverdatum date, @palletnr integer, @aantal integer, @adres varchar(255) ) ...

Python PLY parsing : definition scope -

i'm using ply parse files containing nested blocks. typically : a { b { } c { d { } } } i using simple grammar : def p_nodes(p): ''' nodes : node nodes | node ''' # ?? def p_node(p): ''' node : identifier open_curly_brace node_çontent close_curly_brace ''' p[0] = node(p[3])#fixme? def p_node_content(p): ''' node_content : nodes | ''' if len(p) > 1: p[0] = p[1] else p[0] = none i know able access 'parent' node in parser. in other terms how can build ast can retrieve in example d child of c child of a since have visibility parent rule in parser. what should put in p_nodes , p_node valid ast can built ? thanks. we have need node class, presume like: class node: def __init__(self, children): self.children = children self....

android - Ionic 2 camera not working on phone -

i relatively new ionic 2, cordova & mobile. followed sample app build simple camera app. similar code in couple of other questions. running on android phone, camera takes picture no image displayed. "takepicture fired" log entry displays no further log entries. there missing permission issue? can't understand why not seeing log entry. relevant code: mypage.html <button ion-button block color="primary" (click)="takepicture()">take picture</button> ... <img [src]="base64image" *ngif="base64image" /> mypage.ts export class mypage { public base64image: string; constructor(public navctrl: navcontroller) { } takepicture() { console.log("takepicture fired."); camera.getpicture({ destinationtype: camera.destinationtype.data_url, sourcetype: camera.picturesourcetype.camera, encodingtype: camera.encodingtype.jpeg, targetwidth: 1000, targetheigh...

Sqlite3 Python - Check if a field > integer -

i have code check if he/sheis admin or not, how check if number in database higher required? the field in table named adminlevel def login(): def loggedin(): if adminlevel > 0: print("hello there admin!") print("commands: bet, deposit, logout") print("admin commands: ban, give credits") else: print("hello there {}".format(username)) print("commands: bet, deposit, logout") adminlevel = 0 username = input("please enter username: ") password = getpass("please enter password: ") admin = c.execute("select 1 accounts adminlevel > 0") c.execute("select 1 accounts username = ? , password = ?", (username, password)) if c.fetchone(): print('hello there! {}'.format(username)) loggedin() else: print("username , password not found!") login() if c.fetchone(): c.execute("select 1 accounts admi...

metaprogramming - Groovy Meta Programming with getter method -

would me figure out why added "get" method works 1 class(string) not other class(node)? string.metaclass.getfoo = { "string foo" } s = "test" println s.foo // works: "string foo" node.metaclass.getfoo = { "node foo" } xml = "<test><body>test</body></test>" nodes = new xmlparser().parsetext(xml) println nodes.foo // not work: gets [] how make calling "foo" resulting same getfoo() class node? nodes.foo try find element in parsed tree of nodes. directly using getfoo() option afaik.

ffmpeg - Which pixel format for web mp4 video? -

i have create video in mp4 format, , seems can encode different pixel formats yuv420p , yuv422p , yuvj422p . 1 should use maximize compatibility browsers/players? yuv420p you can use -pix_fmt yuv420p or -vf format=yuv420p make sure output uses pixel format (assuming you're outputting h.264 video).

What is php composer and what does dependency manager means? -

hello guys i've been stuck around php composer read lot of articles still not clear 100% can please explain main reason why should use composer , dependency ? , mean composer dependency manager ? thanks in advance. can please explain main reason why should use composer , dependency you use install libraries made other people. example: you're dealing dates in php application. can use date function , datetime class comes php. however, need display human-readable date in format of "5 minutes ago" or "in 2 hours" etc. so developing , realize you're going spend time on feature. it's nice have, takes time it. a wise developer think " someone had same issue did, let's see how solved it " , stumble upon library: carbon now want use library because takes care of problem. option download github , add project manually, means placing in directory, including in app etc. or can use composer , can tell composer want...

java - VR-Like App / Issues doubling the output -

i'm doing app testing few images (do / or not) scientific project. isolate person tested he/she vr-glasses (cardboard) person can see images , keyboard klick "good" or "bad". due i'm a) @ stage 1 learning android developing , b) not using vr-sensors camera, acceration etc. goal create app show 2 images on 50/50 shared screen side side. for first approach, i've used 5 images in dravable directory, , animated them animationdrawable. i have few questions far: to show same image 2 times side side, had use 2 animationdrawable side side - not elegant , efficient. there better way double output of one-time-happening animation? public class gameactivity extends activity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.game); getwindow().addflags(windowmanager.layoutparams.flag_keep_screen_on); imageview myanimation = (imageview) findviewbyid(r.id.spin_ani...

c++ - opengl camera zoom to cursor, avoiding > 90deg fov -

i'm trying set google maps style zoom-to-cursor control opengl camera. i'm using similar method 1 suggested here . basically, position of cursor, , calculate width/height of perspective view @ depth using trigonometry. change field of view, , calculate how need translate in order keep point under cursor in same apparent position on screen. part works pretty well. the issue want limit fov less 90 degrees. when ends >90, cut in half , translate away camera resulting scene looks same larger fov. equation find necessary translation isn't working, strange because comes pretty simple algebra. can't find mistake. here's relevant code. void visual::scroll_callback(glfwwindow* window, double xoffset, double yoffset) { glm::mat4 modelview = view*model; glm::vec4 viewport = { 0.0, 0.0, width, height }; float winx = cursorprevx; float winy = viewport[3] - cursorprevy; float winz; glreadpixels(winx, winy, 1, 1, gl_depth_component, gl_float, ...

rust - Is `iter().map().sum()` as fast as `iter().fold()`? -

does compiler generate same code iter().map().sum() , iter().fold() ? in end achieve same goal, first code iterate 2 times, once map , once sum . here example. version faster in total ? pub fn square(s: u32) -> u64 { match s { s @ 1...64 => 2u64.pow(s - 1), _ => panic!("square must between 1 , 64") } } pub fn total() -> u64 { // fold (0..64).fold(0u64, |r, s| r + square(s + 1)) // or map (1..64).map(square).sum() } what tools @ assembly or benchmark this? for them generate same code, they'd first have do same thing . 2 examples not: fn total_fold() -> u64 { (0..64).fold(0u64, |r, s| r + square(s + 1)) } fn total_map() -> u64 { (1..64).map(square).sum() } fn main() { println!("{}", total_fold()); println!("{}", total_map()); } 18446744073709551615 9223372036854775807 let's assume meant fn total_fold() -> u64 { (1..64).fold(0u64, |r, s| ...

python - Linux Only 'ascii' codec can't encode character u'\u0161' in position 3: ordinal not in range(128) -

i encountered error, happens on linux server apache2 running wsgi on django. development in windows copy on linux server. i see problem in string: (bold part marked django) društvo t abornikov - rod srnjak logatec but error happens on 1 page. same string used on settings page displays properly. same error pops on admin page. in views.py file have set utf-8 encoding. error doesn't happen if start server without apache with: python3 manage.py runserver 0.0.0.0:8000 trace: environment: request method: request url: https://***.***.**/vodnik/eposta/?cid=17 django version: 1.10.3 python version: 2.7.12 installed applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'vodnik', 'schedule', 'djangobower'] installed middleware: ['django.middleware.security.securitym...

html - adjust image to fixed content -

Image
i'm dealing img tags have fixed width & height. the question have set of images each 1 has own dimensions, in resulting view, of them vary in height keeping width constant. this get: ... , want accomplish: is there way whatever image loaded in img tag keep proportions , same height? you can use css , set property of width , height ever want img { width : 150px; height : 150px; } <img src="https://static.pexels.com/photos/57825/pexels-photo-57825.jpeg" alt="no image available" /> <img src="https://static.pexels.com/photos/149941/pexels-photo-149941.jpeg" alt="no image available" /> <img src="https://static.pexels.com/photos/163145/laptop-computer-coffee-yellow-163145.jpeg" alt="no image available" /> <img src="https://static.pexels.com/photos/7107/notebook-hero-workspace-minimal.jpg" alt="no image available" />

php - Different result for same page on different ports : cakephp -

i new cakephp, , following 'bookmarkers tutorial'. know can access project using 2 kind of urls(i using apache , folder located @ /var/www/html/bookmarker): localhost:8765 and localhost/bookmarker now, when use first url, following warning message on top: warning(2) : file_put_contents(/var/www/html/bookmarker/logs/error.log): failed open stream: permission denied [core/src/log/engine/filelog.php, line 133] but not case second url ! why there such difference b/w these 2 urls? 1 should used? , how resolve message appearance? appreciated! it's 2 servers here. "localhost:8765" server built-in cakephp when run command: "bin/cake server" have apache web server @ "localhost", don't need it. and 2 servers being ran 2 users: localhost:8765 you localhost apache that's why don't have permission write log file (owned apache) stop server built-in (bin/cake server), , use apache server (2nd url) in c...

asp.net - RDLC report is getting timeout during export -

i have asp.net web app (.net framework 4.5) hosted in azure. used rdlc report there. report showing data (for year , no of records less 10000) in way (no time out issue) when go exporting pdf/excel showing time out. dont know why showing data in report getting time out during export. please me it.

jquery - JavaScript code runs once at the start than it stop -

i using jvectormap library display world-wide map. have followed tutorial official site getting started tutorial include map in html view file follows: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <link rel="shortcut icon" href="assets/ico/favicon.png"> <title>al andulas</title> <!-- bootstrap core css --> <link href="assets/css/bootstrap.css" rel="stylesheet"> <link href="assets/css/font-awesome.min.css" rel="stylesheet"> <!-- custom styles template --> <lin...

excel - Copy Range with VBA to clipboard -

so here i'm trying do. have sheet parse cisco router interface errors between snapshots create summary of how many packets , errors on each interface. have button tied macro executes copy summary itself. x1 = cells(2, 6).value y1 = cells(3, 6).value x2 = cells(4, 6).value y2 = cells(5, 6).value activesheet.range(cells(y1, x1), cells(y2, x2)).copy each of cells listed have value of row or column sections copied correctly. x2's cell set based on how many interfaces can change selected range. my problem lies wanting copy , latest snapshot (which in cell directly above summary section) together. want place snapshot under summary ideally when copied clipboard. i've imagine i'll need convert range string add both strings , put in clipboard. can't range convert can put in clipboard. code i'm using below found on here converting range string array , putting strings clipboard. can't figure out how string array clipboard errors out 'object required'...

arm - How to use "printf" in raspberry pi assembly language -

does printf has limit number of values can print? here code. .data .balign 4 string: .asciz "\n%d %d %d %d\n" .text .global main .extern printf main: push {ip, lr} @ push return address + dummy register @ alignment ldr r0, =string @ address of string r0 mov r1, #11 mov r2, #22 mov r3, #33 mov r4, #444 bl printf @ print string , pass params @ r1, r2, , r3 pop {ip, pc} @ pop return address pc when compile , execute code prints this: 11 22 33 1995276288 as can see, value in r4 not print right value. i don't know why? only first 4 arguments passed in registers (r0-r3) on arm -- additional args passed on stack. check out procedure call abi details.

netty - How do I set up a camel netty4 component for synchronous request-reply? -

i need write camel component send synchronous request-reply on tcp legacy system. have tried set netty4 component, there weird happening. here route: from("direct:foo") .dotry() .process(exchange -> { message message = (message) exchange.getin().getbody(); logger.info("sending message: {}", message); }) .tof("netty4:tcp://localhost:%d?sync=true&synchronous=true&requesttimeout=%d&encoders=stubencoder&decoders=stubencoder", port, timeout) .process(exchange -> { response response = (response) exchange.getin().getbody(); logger.info("[{}] received reply: {}", exchange, response); }) .enddotry() .docatch(readtimeoutexception.class) .process(exchange -> { // handle timeout... }) .end(); the remote port , timeout injected properties. input/output of route domain objects rest of application. have set codec translates ...

android studio - Computing device's angle -

i'd compute device's angle, when it's tilted @ bottom edges left , right, using accelerometer , magnetometer. save highest value i've received , show in textview. this how tried: public void onsensorchanged(sensorevent event) { if (event.sensor.gettype() == sensor.type_accelerometer) mgravity = event.values; if (event.sensor.gettype() == sensor.type_magnetic_field) mgeomagnetic = event.values; if (mgravity != null && mgeomagnetic != null) { float r[] = new float[9]; float i[] = new float[9]; boolean success = sensormanager.getrotationmatrix(r, i, mgravity, mgeomagnetic); if (success) { float orientation[] = new float[3]; sensormanager.getorientation(r, orientation); playerangle = (float) math.todegrees(orientation[3]); tv.settext(string.valueof(playerangle)); }

php - Android login can't proceed to another procedure -

i'm trying build basic android login via json parser. here code: package com.muzaffar.spycare.activity; import android.app.progressdialog; import android.content.intent; import android.os.asynctask; import android.os.bundle; import android.support.v7.app.appcompatactivity; import android.util.log; import android.view.view; import android.widget.button; import android.widget.edittext; import android.widget.toast; import com.muzaffar.spycare.app.jsonparser; import com.muzaffar.spycare.app.sessionmanager; import com.muzaffar.spycare.app.util; import com.muzaffar.spycare.r; import org.json.jsonexception; import org.json.jsonobject; import java.util.hashmap; import java.util.regex.pattern; import static com.muzaffar.spycare.app.constant.base_url_login; import static com.muzaffar.spycare.app.constant.login_success_message; /** * created oligococo on 11/2/2016. */ public class login_activity extends appcompatactivity { //declaration private edittext app_email,app_p...

android - Log.d is not working when filtering logcat -

Image
my verbose logcat not working log.d("b","hi stack."); because filtering logcat gc.uploaderimager(my package name). if don't filter logcat package name logcat being fast, excessive messages. 1 week ago, there no problem , remember did not filtering , no excessive messages. did happen 1 week ago? couldn't understand. now, can not see log messages if do filtering. my logcat fast , not readable if not filtering. then solution? package gc.uploaderimager; import android.support.v7.app.appcompatactivity; import android.os.bundle; import android.util.log; public class mainactivity extends appcompatactivity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); log.d("b","hi stack."); } } the android monitor view in android studio little flaky experience. app's package name should appear...

Why is my go lang string comparison not working as expected? -

i dipping toe go , have written code check if y or n input: reader := bufio.newreader(os.stdin) fmt.print("(y / n): ") text, _ := reader.readstring('\n') text = strings.tolower(text) if strings.compare(text, "y") == 0 { fmt.println("true") } else { fmt.println("else") } when run code & type y (and press enter) expect see true else - can see why? you want like: reader := bufio.newreader(os.stdin) fmt.print("(y / n): ") text, _ := reader.readstring('\n') text = strings.tolower(text[0:len(text)-1]) if strings.compare(text, "y") == 0 { fmt.println("true") } else { fmt.println("else") } as comment above says, readstring() returns delimiter part of string. you're getting "y\n" , comparing "y" - result false. (you might rather use trim() function remove whitespace either side of input,instead!) edit: trim() suggestion...

web - Is it possible to customize radius for a feature in Mapbox [html]? -

i trying have icons circles instead of squares using web-implementation of mapbox. there doesn't seem radius property? since you're using mapbox.js, can use l.circle add circle measured in meters or l.circlemarker add circle measured in pixels. assuming have map instantiated , assigned variable map , you'd call: l.circle([10, 0], 200).addto(map); // 10=latitude, 0=longitude, 200=meters or l.circlemarker([10, 0], 200).addto(map); // 10=latitude, 0=longitude, 200=pixels this documented on leaflet's , mapbox's sites.

django - Why does CMD never work in my Dockerfiles? -

i have few dockerfiles cmd doesn't seem run. here example (all way @ bottom). ########################################################## # set base image ansible ubuntu:16.10 # install ansible, python , related deps # run apt-get -y update && \ apt-get install -y python-yaml python-jinja2 python-httplib2 python-keyczar python-paramiko python-setuptools python-pkg-resources git python-pip run mkdir /etc/ansible/ run echo '[local]\nlocalhost\n' > /etc/ansible/hosts run mkdir /opt/ansible/ run git clone http://github.com/ansible/ansible.git /opt/ansible/ansible workdir /opt/ansible/ansible run git submodule update --init env path /opt/ansible/ansible/bin:/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin env pythonpath /opt/ansible/ansible/lib env ansible_library /opt/ansible/ansible/library run apt-get update -y run apt-get install python -y run apt-get install python-dev -y run apt-get install python-setuptools -y run apt-get install python-pip run mkdir /a...

Protect thumbnail and library images from media browser from being deleted in Drupal 7 -

i have drupal 7 site authenticated users can create webpage raise money charity. can add picture media library using media browser. however, if delete page, deletes thumbnail , library image db , site. i've tried file lock module, doesn't work. i've set user permissions images cannot deleted; doesn't work. images used in other places need keep them library future users. appreciated. assuming you're running on linux box, can make files read-only using crontab. as superuser, type crontab -e add line crontab * * * * * cd /var/www/mysite/sites/default/files/yourcustomimagesfoldername/ && find . -type f -exec chmod 444 {} + to explain, line changes directory images folder, makes every single file in images folder read-only, iterates through subdirectories well. may need tweak chmod based on distro. it not alter directory permissions. best,

apache spark - Difference in fromOffset/untilOffset/offset.count to total records in the RDD partition -

my spark-kakfa streaming logic looks this... when @ offsets , records, there different in offset.count() of partition , total number records printing when use foreach loop.(on rdd partition). those counts inconsistent logic. can guide me correct logic.??? javainputdstream<byte[]> directkafkastream = kafkautils.createdirectstream(jsc, string.class, byte[].class, stringdecoder.class, defaultdecoder.class, byte[].class, kafkaparams, topicmap, (function<messageandmetadata<string, byte[]>, byte[]>) messageandmetadata::message); directkafkastream.foreachrdd(rdd -> { rdd.foreachpartition(itr -> { integer partnid = taskcontext.get().partitionid(); arraylist <byte[]> recordbatch = new arraylist <byte[]>(); while (itr.hasnext()) { byte[] record = itr.next(); recordbatch.add(record); } offsetrange[] offsets = ((hasoffsetranges) rdd.rdd())....

ffi - How to Use Haskell's Stack Build Tool to Export a Library to Be Consumed by C/C++? -

suppose 1 using stack build tool make haskell library (importing packages hackage, , forth) to used c/c++ project in main located in c/c++ . supposing project named lib.hs (which uses external libraries hackage), there way use stack export lib.o , lib.hi , , lib_stub.h consumed c/c++ compiler gcc or g++ ? edit: related question might be: "how can 1 use stack build tool used haskell & c/c++ project in main located in c/c++? edit2: upon reflection, 1 way solve problem use stack usual, migrate c/c++ main function haskell. best way it? there huge performance costs or should aware of? stack can't on own. there's support generating called "foreign libraries" added cabal, it's not in released version, yet. see commit 382143 produce shared library dynamically links against dynamic versions of each haskell package used. you can build package stack , after fact can assemble single native library. in galua project custom setup.hs , s...

javascript - Why is mouseover function not working -

i have simplest of codes, i've never tried using onmouseover before, not sure why it's not working: <div class="play" id="buttonplay"> <img src="buttons/play/playrest.png" onmouseover="this.src='buttons/play/playclick.png'" width="100%"> </div> any ideas? , way go debugging it? try declaring function in script element , reference function instead of doing inline. @ least way can set breakpoint in developper console of browser , see happening. <div class="play" id="buttonplay"> <img src="buttons/play/playrest.png" onmouseover="myfunction(this)" width="100%"> </div> <script> function myfunction(element) { element.src='buttons/play/playclick.png'; } </script>

java - setOnClickListiner in FloatingActionMenu -

i wondering if there possibility of overriding setonclicklistiner in floatingactionmenu. lastly, found tutorial: http://www.viralandroid.com/2016/02/android-floating-action-menu-example.html what need create menu on top of other system icons. want allow user move floatingactionmenu without triggering menu itself. in detail, want move button id material_design_android_floating_action_menu (according tutorial) without triggering menu itself. far have menu on top of system icon, wanted, have no idea how move it. setontouchlistiner doesn't work. assume library (this not android standard lib) has setted kind of listiner material_design_android_floating_action_menu set own allow user move witout triggering whole menu. idea how that? thanks in advance. :) materialdesigndialogservice public class materialdesigndialogservice extends service { private windowmanager windowmanager; windowmanager.layoutparams params; int lastpositionx, lastpositiony; view dialoglayout; private...

excel - Subroutine returning all 0s -

i trying return values user defined function, returned 0s. feel values i'm assigning variables wk1 , wk2 aren't being used in function. the goal of subroutine calculate weekly returns of stocks, given prices provided in worksheet "prices". i'm not savvy vba appreciated thanks help! public sub wklyrtn() dim wk1, wk2 long dim row long, column long dim matrix1(2 261, 2 11) integer sheets("prices").select selection.activate row = 2 261 column = 2 11 wk2 = cells(row, column).value wk1 = cells(row + 1, column).value matrix1(row, column) = rtrn(wk1, wk2) next column next row sheets("returns").select selection.activate row = 2 261 column = 2 11 cells(row, column) = matrix1(row, column) next column next row end sub public function rtrn(wk1, wk2) dim delt long application.volatile true delt = wk2 - wk1 rtrn = delt / wk1 end function try this. not sure trying matrix . give val...

javascript - Build a balanced binary tree -

const tree = function(value){ this.value = value this.right = null this.left = null } tree.prototype.insert = function(number){ if(this.left === null){ this.left = new tree(number) } else if(this.right === null){ this.right = new tree(number) } else { this.left.insert(number) } } const arbre = new tree(10) arbre.insert(5) arbre.insert(2) arbre.insert(1) arbre.insert(20) arbre.insert(6) console.log(json.stringify(arbre,null,4)) i'm trying build balanced binary tree. means each time i'm inserting value fill left node first , right node, , on. that: 0 / \ 1 2 /\ / 34 5 my code keep building in left side doesn't go in right side maintain balance of tree. like: 0 / \ 1 2 /\ 34 / 5

Need explanation of Pseudocode and code - Python 3+ -

this question has answer here: explain slice notation 24 answers i have code acts recursive function prints out possible combinations of string: def permut(head, tail = ''): if len(head) == 0: print(tail) else: in range(len(head)): # need explaning part permut(head[0:i] + head[i+1:], tail + head[i]) # print string permut('xy') this print out: xy yx i need explaining going on, on part: permutations(head[0:i] + head[i+1:], tail + head[i]) print statements friend! head being 'xy', 2 characters long, expect function's loop 'loop' through twice (once each character). in first iteration, find possible combinations of characters, calling (what presume built-in function) permutations on 2 arguments, first being head[0:i] + head[i+1:]. if recall how list...

c - Collecting a list of function pointers and other ancillary data via distinct macro invocations -

i want declare number of functions same signature, possibly spread across different header files, , use preprocessor collect array pointers such functions, , create an array of corresponding function names. so, example, assuming common signature int func(int x) have following declarations: func(a) { return x + x; } func(b) { return x >> 1; } func(c) { return x ^ 123; } ... , through macro magic, end after preprocessing looks like: int a(int x) { return x + x; } int b(int x) { return x >> 1; } int c(int x) { return x ^ 123; } typedef int (*intfunc_t)(int) const intfunc_t func_ptrs[] = { &a, &b, &c }; const char *func_names[] = { "a", "b", "c" }; a worse version of possible using x-macros , requires list like: #define x_macro \ x(a) \ x(b) \ x(c) this duplicates information encoded in func(a) definitions , makes tough use approach unknown number of functions spread across many headers, sinc...

python - doing joins in filter criteria in pandas -

if have 2 dataframes like: df1: | | b | 0 | 0 | 0 | 1 | 0 | 1 | 2 | 1 | 1 | df2: | c | d | 0 | 0 | 1 | 1 | 1 | 1 | 2 | 2 | 1 | how select rows df2 df1[df2['c']]['b'] != 0 . in other words, rows df2 it's value in column c index used check value in df1 column b not equal 0. so 1 other way @ it. select columns df2 column c foreign key df1 , , don't want value in column b equal 0. i think should trick. let me know if need else. df1['index1'] = df1.index df = pandas.merge(df1, df2, how='left', left_on=['index1'], right_on=['c']) df = df[df.b != 0]

How to access the nth item in a Laravel collection? -

i guess breaking rules deliberately making duplicate question... the other question has accepted answer. solved askers problem, did not answer title question. let's start beginning - first() method implemented approximately this: foreach ($collection $item) return $item; it more robust taking $collection[0] or using other suggested methods. there might no item index 0 or index 15 if there 20 items in collection. illustrate problem, let's take collection out of docs: $collection = collect([ ['product_id' => 'prod-100', 'name' => 'desk'], ['product_id' => 'prod-200', 'name' => 'chair'], ]); $keyed = $collection->keyby('product_id'); now, have reliable (and preferably concise) way access nth item of $keyed ? my own suggestion do: $nth = $keyed->take($n)->last(); but give wrong item ( $keyed->last() ) whenever $n > $keyed->count() . how can...

What is the difference between single-quoted and double-quoted strings in PHP? -

i'm not expert in php programming, i'm little confused why see code in php string placed in single quotes , in double quotes. i know in .net, or c language, if in single quote, means character, not string. php strings can specified not in two ways, in four ways. single quoted strings display things "as is." variables , escape sequences not interpreted. exception display literal single quote, can escape slash \' , , display slash, can escape backslash \\ ( so yes, single quoted strings parsed ). double quote strings display host of escaped characters (including regexes), , variables in strings evaluated. important point here you can use curly braces isolate name of variable want evaluated . example let's have variable $type , echo "the $types are" variable $types . around use echo "the {$type}s are" can put left brace before or after dollar sign. take @ string parsing see how use array variables , such. heredoc ...

Is there a communication standard for IP cameras? -

i trying chose ip camera outdoor surveillance, not sure how able communicate it. afaik. these cameras have ip address on local network, can access video stream. controlling part, rotation, zoom, ir movement sensor, etc? there communication standard that, or should try find kind of developer documentation? i found onvif prevalent communication standard ip cameras. https://en.wikipedia.org/wiki/onvif

reactjs - React Router <redirect> not working -

i have configured react-router redirect unknown url "/": <router history={browserhistory}> <route path="/" component={shell}> <indexroute component={githubpage}/> <route path="clock" component={clockpage}/> <redirect from="*" to="/"/> </route> </router> the server has been correctly configured redirect unknown urls /index.html , looks this: <html> <head> <link href="main.css" rel="stylesheet"> </head> <body> <main></main> <script src="main.js" type="text/javascript"></script> </body> </html> react router 2.8.1 behavior /clock gets routed correctly clockpage /clock/est (which unknown route) not load app. server correctly sends /index.html , css , js files not loaded because browser asking /clock/main.css...

background color of console change with c++ -

i'm beginner @ c++ programming , have problem. how can change text colour , background colour of console(not background of text) ? example: want print coloured "hello world" in 10 rows , cmd background change each row , how can in loop?! thx.

javascript - return new Promise() not working in Node.js -

i'm new concept of promises, javascript in general. i'm trying write function in node.js can pass url promise of results. i have programmed 2 ways. first not work, in can pass url function. second work, in url statically defined. first 1 not work because compiler not think function reason can't figure out, why? this way doesn't work function getjson not interpreted node function: var options = { method: 'get', url: url, // dynamically filled argument function getjson headers: { authorization: 'oauth realtokenwouldbehere', accept: 'application/json' } }; var getjson = function(url){ return new promise(function(resolve, reject) { request(options, function (error, response, body) { if(error) reject(error); else { resolve(json.parse(body)); //the body has array in jason called items } }); }); // edited original post. had 2 curly braces }}; here accident, why funct...