Posts

Showing posts from July, 2013

Function for constructing relative paths in R? -

is there similar make.path.relative(base.path, target.path) ? i want convert full paths relative paths given base path (like project's directory). similar, shorter: make.path.relative = function(base, target) { common = sub('^([^|]*)[^|]*(?:\\|\\1[^|]*)$', '^\\1/?', paste0(base, '|', target)) paste0(gsub('[^/]+/?', '../', sub(common, '', base)), sub(common, '', target)) } make.path.relative('c:/home/adam', 'c:/home/adam/tmp/r') #[1] "tmp/r" make.path.relative('/home/adam/tmp', '/home/adam/documents/r') #[1] "../documents/r" make.path.relative('/home/adam/documents/r/project', '/home/adam/minetest') #[1] "../../../minetest" voodoo regex comes from here .

solrj - what happens when multiple processes send solr commits to single solr instance? -

we have multiple processes adding adding documents same collection in single instance of solr. happen if apps send commit @ same once, or close each other? cause data corruption, or kind of lock? you not going data corruption or locks, performance issues solr repeatedly heavy commit work (flush , reopen of readers). if on latest solr (4.3+), soft/hard commits based on timeout or document count . way don't need manage commits explicitly @ all.

ruby on rails - Unable to read file from within rake task -

i have rake task reads file. desc "dump images." task :dump_with_images => :environment yaml_path = rails.root + 'db/data.yml' # output: "" -- empty string puts file.open(yaml_path).read.inspect [...] end end if read , inspect file outside of task, yaml_path = rails.root + 'db/data.yml' puts file.open(yaml_path).read.inspect desc "dump images." task :dump_with_images => :environment it gives me data: zeromodulus@kosuna:~/projects/recipes$ rake dump_with_images "\n---\nphotos:\n columns:\n - id\n - created_at\n - updated_at\n - recipe_id\n - image_file_name\ i don't understand why can read exact same file outside of task, not in task. when inspect yaml_path, they're both same, , file has data in it. it looks opening file stream , not closing it, , later on in code attempting open same file stream again. i've wrapped file reading code in block, file.read(file_path, "r...

javascript - Uncaught TypeError: $(...).jflatTimeline is not a function -

i getting above below error after running code. question has been asked many times none of answers solved problem. uncaught typeerror: $(...).jflattimeline not function code <script type= "text/javascript"> $(document).ready(function(){ $('div.jflattimeline').jflattimeline({ scroll : '2', //max dates scrolling per arrow click width : '60%', //width; can done css. - .jflattimeline{width : x%;} scrollingtime : '300' // scrolling time }); }); </script> you did not include jquery flat timeline script. here can find it: http://codecanyon.net/item/jquery-flat-event-calendar-responsive-timeline/6039142

android - Defining resources for a given region -

i want create resources given regions created batch of value-rde directory germany or value-rus usa. seems directories won't work. documentation providing resources , points out work languages should e.g. values-de-rde or values-en-rus . combinations value-en-rde saw in wild. explode count of directories. now came idea use mobile country code (mmc) , seems option. reliable? there better way store region specific information resources? why want this? just take example iata code of capital city's airport, not need been localizated.

python - I have this function that is supposed to count points but it doesn't add them -

i have function supposed count points doesn't add them: def correct(totalpoints): print "correct" totalpoints = totalpoints+1 print "you have", totalpoints,"points" here example of use in: elif answer == 'nba': nbaques = random.randint(0,len(nba1)-1) nbavar = nba1[nbaques] print nbavar nbaanswer = raw_input() nbaanswer = nbaanswer.lower() if nbaanswer == nba2[nbaques]: print correct(totalpoints) elif nbaanswer != nba2[nbaques]: print "false. correct answer was", nba2[nbaques] nba1.remove(nbavar) nba2.remove(nba2[nbaques]) print "choose another." i think mix local , global namespaces. if change correct(totalpoints) this: def correct(totalpoints): return totalpoints + 1 and in "main code": print correct(totalpoints) to totalpoints = correct(totalpoints) print "you have", totalpoints, ...

ruby - Using random key/value from YAML file -

i'm trying use random key, value pair yaml file looks this: 'user_agents': 'mozilla': '5.0 (compatible; googlebot/2.1; +http://www.google.com/bot.html)' 'mozilla': '5.0 (compatible; yahoo! slurp; http://help.yahoo.com/help/us/ysearch/slurp)' 'mozilla': '5.0 (iphone; u; cpu iphone os 3_0 mac os x; en-us) applewebkit/528.18 (khtml, gecko) version/4.0 mobile/7a341 safari/528.16' 'mozilla': '4.0 (compatible; msie 6.0; windows nt 5.1)' using script: require 'mechanize' require 'yaml' info = yaml.load_file('test-rand.yml') @user_agent = info['user_agents'][info.keys.sample] agent = mechanize.new agent.user_agent = @user_agent if @user_agent.nil? puts "the user agent nil" else puts "using: #{@user_agent}" end however while running script keep getting the user agent nil , how pull random key/value yaml file? i've tried @user_agent = inf...

javascript - How to use Angular Js with Google Maps To render a people list when clicking on a marker? -

i using angular js v1 , need render list of people when click on marker on map , need marker have number on , number indicator number of people country , when click marker on map , list same number marker appears below similar website http://www.travelgirls.com/trips/ here example hope helps you. if not improve answer later on (i have not time now) <ui-gmap-google-map center='map.center' zoom='map.zoom'> <ui-gmap-markers models="markers" coords="'self'" options="markeroptions" events="markerevents" icon="'icon'"></ui-gmap-markers> <ui-gmap-window coords="model.selectedmarker" show="model.selectedmarker.show" templateurl="'/app/controls/gmapscontrol/mapinfowindow.html'" templateparameter="model.selectedmarker" closeclick="model.closeinfowindow(model)" isiconvisibleonclick="false"></ui-gma...

javascript - Set hover area to close subnav -

Image
how can set mouseout area of screen either between main (red) links @ top, or outside of subnav (green), when user moves mouse outside of main nav, subnav close? document.addeventlistener('domcontentloaded', function(){ var d = document; var navsub = d.queryselector('.nav-sub'); var navheader = d.queryselector('.nav-header'); function toggledrawer(state){ navheader.dataset.drawerdisplay = state; } //adding toggle state allows user close subnav clicking it, disables hover (now requires clicking) of main nav open subnav. messing mobile navigation. $(".nav-header").on('click',function(){ $(".nav-sub").slidetoggle("hide"); }); // header nav drawer function togglenav(){ var opener = d.queryselectorall('.opener'); [].foreach.call(opener, function(el, index) { el.addeventlistener('mouseenter', function(){ toggledrawer('show'); navheader.dataset.drawernum = inde...

How can I create an OSX-like list object with Java FX in Windows? -

Image
i can't find object same , feel 1 here: it isn't awt list, nor swing combobox, it? use choicebox. choicebox cb = new choicebox(fxcollections.observablearraylist( "first", "second", "third") ); choicebox tutorial . choicebox javadoc .

android UI react weird in gyroscope event -

i have app used gyroscope control value of padding. doesn't update ui unless i'm touching or moving device screen. private void gyrofunction(sensorevent event) { sensormanager .getrotationmatrixfromvector(mrotationmatrix, event.values); sensormanager.remapcoordinatesystem(mrotationmatrix, sensormanager.axis_x, sensormanager.axis_z, mrotationmatrix); sensormanager.getorientation(mrotationmatrix, orientationvals); // must put line of code make ui thread update every time temptxtview.settext(string.valueof(orientationvals[2])); imgv.setpadding((int) math.round(orientationvals[0]), (int) math.round(orientationvals[1]), (int) math.round(orientationvals[0]), (int) math.round(orientationvals[1])); } however when added temporary textview update value according gyro event, works. don't think it's solution block screen. there other solution? does calling imgv.invalidate() after...

input - Why Python does not see all the rows in a file? -

i count number of rows (lines) in file using python in following method: n = 0 line in file('input.txt'): n += 1 print n i run script under windows. then count number of rows in same file using unix command: wc -l input.txt counting unix command gives larger number of rows. so, question is: why python not see rows in file? or question of definition? you have file 1 or more dos eof (ctrl-z) characters in it, ascii codepoint 0x1a. when windows opens file in text mode, it'll still honour old dos semantics , end file whenever reads character. see line reading chokes on 0x1a . only opening file in binary mode can bypass behaviour. , still count lines, have 2 options: read in chunks, count number of line separators in each chunk: def bufcount(filename, linesep=os.linesep, buf_size=2 ** 15): lines = 0 open(filename, 'rb') f: last = '' buf in iter(f.read, ''): lines += buf.count(linesep)...

html - How to preserve whitespace but ignore line breaks in CSS? -

the white-space property in css-3 has pre-wrap value, preserve whitespace , line breaks, , wrap when necessary, , pre-line value, collapses whitespace, preserves line breaks, , wraps when necessary. what not have, though, value preserves whitespace , collapses line breaks, while still wrapping otherwise. is there combination of other css properties can use effect? for example: this example code should render on 1 line spaces intact. should like: this example code should render on 1 line spaces intact.

ldap - authentication failed using ldapsearch -

Image
i created local ldap server apache directory studio. user entry created uid "djiao1" , password "123456" (sha hashed password). i able search user following ldapsearch command: ldapsearch -h ldap://localhost:10389 -x uid=djiao1 # extended ldif # # ldapv3 # base <> (default) scope subtree # filter: uid=djiao1 # requesting: # # djiao, users, example.com dn: cn=djiao,ou=users,dc=example,dc=com sn: jiao cn: djiao objectclass: top objectclass: inetorgperson objectclass: person objectclass: organizationalperson userpassword:: e3noyx1mrxfoq2nvm1lxowg1wlvnbeqzq1pkvdrsqnm9 uid: djiao1 # search result search: 2 result: 0 success # numresponses: 2 # numentries: 1 however if run -w prompt password , type in "123456" "invalid credentials" error: ldapsearch -h ldap://localhost:10389 -w -x uid=djiao1 enter ldap password: ldap_bind: invalid credentials (49) additional info: invalid_credentials: bind failed: invalid authentication i tried ...

php soap - send request for multidimensional array -

first up, i'm trying send soap request using php soap , xml service accepts shown below. <u_memberreservedtransaction xmlns="http://tempuri.org/"> <userid>string</userid> <password>string</password> <memberreservedtransactionrequest> <memberreservedtransactions> <reservedtype>string</reservedtype> <firstname>string</firstname> <surname>string</surname> <icnew>string</icnew> </memberreservedtransactions> <memberreservedtransactions> <reservedtype>string</reservedtype> <firstname>string</firstname> <surname>string</surname> <icnew>string</icnew> </memberreservedtransactions> </memberreservedtransactionrequest> </u_memberreservedtransaction> just summarize service expecting, service receive array of memberreservedtransactions. soap...

sql - Query 2 different items within the same field and the same table -

i'm new sql , don't know how query 2 different items within same field , same table. i'm writing in excel vba using sql via oledb attach postgresql datasource basically have 2 queries need combine 1 query. first query primary group. need first find people code c10%. of c10 have code r110% the codes in srch table , people names in person table, these joined master_id=p.entity_id here 2 queries need combine: dim diag string diag = "select distinct master_id, eventdate, code, term, surname, forename " _ & "from srch inner join person p on master_id=p.entity_id " _ & "where code 'c10..%' " _ & "order master_id " dim diag string diag = "select distinct master_id, eventdate, code, term, surname, forename " _ & "from srch inner join person p on master_id=p.entity_id " _ & "where code 'r110%' " _ & "order master_id " ...

win universal app - How can I send WOL (UDP)? -

i can't figure out how send wol (wakeonlan) using iot. it seams should se datagramsocket, samples can find online, uses udpclient. how can send wol (udp) in iot? thanks. to send magic packet in winrt app indeed need use datagramsocket windows.networking.sockets api. basic solution i'd written while back: public async void sendmagicpacket(string macaddress, string ipaddress, string port) { datagramsocket socket = new datagramsocket(); await socket.connectasync(new hostname(ipaddress), port); datawriter writer = new datawriter(socket.outputstream); byte[] datagram = new byte[102]; (int = 0; <= 5; i++) { datagram[i] = 0xff; } string[] macdigits = null; if (macaddress.contains("-")) { macdigits = macaddress.split('-'); } else if (macaddress.contains(":")) { macdigits = macaddress.split(':'); } if (macdigits.length != 6) { th...

javascript - react - accessing DOM without breaking encapsulation -

is there cannonical way of going doing following without breaking encapsulation? import react, { component, proptypes } 'react'; class dashboard extends component { constructor(props, context) { super(props, context); this.setref = ::this.setref; } componentdidmount() { const node = reactdom.finddomnode(this.someref); const newheight = window.innerheight - node.offsettop - 30; node.style.maxheight = `${newheight}px`; } render() { return ( <div id="some-element-id" ref={this.setref}> </div> ); } setref(ref) { this.someref= ref; } } reactdom.finddomnode seems suggested way of going this, still breaks encapsulation , documentation has big red flag extent. you should use component "state" set style property of react element, access "real" dom node calculate height , update state, re-rendering compone...

php - Incorrect AVG Session Duration? -

i setting google analytics api functions, average session duration doesn't seem correct. typical average session duration 4:10 getting numbers such 1144 (seconds) or 24.06 minutes. way off know happening here? read incorrect date reference. using. users, sessions, , pageviews much less should well. $from = date('y-m-d', time() - 1 24 60 60); // "yesterday" "today" -- ' - d h m s ' change (d) day go further (1) day $to = date('y-m-d'); // today $metrics = 'ga:users,ga:pageviews,ga:bounces,ga:sessions,ga:sessionduration,ga:totalevents,ga:transactions,ga:transactionrevenue,ga:avgsessionduration'; $dimensions = 'ga:date,ga:eventcategory,ga:eventaction,ga:eventlabel,ga:devicecategory'; $sort = "-ga:sessions"; $data = $analytics->data_ga->get('ga:' . $ga_profile_id, $from, $to, $metrics, array('dimensions' => $dimensions, 'sort' => $sort, 'samplinglevel' => ...

docusignapi - docusign resend envelope issue with Demo account -

trying resend envelope recipients haven't signed document. the url = baseurl + "/envelopes/{envelopeid}/recipients?resend_envelope=true" not working demo https://demo.docusign.net/restapi/v2/ api. when prod https://na2.docusign.net/restapi/v2/ used working expected. please demo environment. looks turned out temporary server-side issue docusign's demo environment, has been subsequently fixed.

javascript - How to find the index of a css rule -

i trying find index number of css rule (.widget-area) in stylesheet. how i'm doing it, returns undefined. function findstyle(){ var mystylesheet=document.stylesheets[8].cssrules[".widget-area"]; console.log(mystylesheet); }; if leave out .cssrules[".widget-area"] returns rules of stylesheet, there thousands of them. knows how this? thanks. i think using .cssrules function object. if want custom rule should use this: var targetrule; var rules = document.stylesheets[8].cssrules; (i=0; i<rules.length; i++){ if (rules[i].selectortext.tolowercase() == ".widget-area"){ targetrule = rules[i]; break; } }

How to perform a Switch statement with Apache Spark Dataframes (Python) -

i'm trying perform operation on data value mapped list of pre-determined values if matches 1 of criteria, or fall-through value otherwise. this equivalent sql: case when user_agent \'%canvasapi%\' \'api\' when user_agent \'%candroid%\' \'mobile_app_android\' when user_agent \'%icanvas%\' \'mobile_app_ios\' when user_agent \'%canvaskit%\' \'mobile_app_ios\' when user_agent \'%windows nt%\' \'desktop\' when user_agent \'%macbook%\' \'desktop\' when user_agent \'%iphone%\' \'mobile\' when user_agent \'%ipod touch%\' \'mobile\' when user_agent \'%ipad%\' \'mobile\' when user_agent \'%ios%\' \'mobile\' when user_agent \'%cros%\' \'desktop\' when user_agent \'%...

greasemonkey - Change a variable in a javascript function with userscript -

i'm trying ikea kitchen planner work on firefox in linux. os/browser detection function uses bunch of if/else statements determine platform user on, , believe can make work changing value of variable "true" or removing lines set "false". i've learned lot userscripts , greasemonkey since started , here's i've tried far: beforescriptexecute event handler hijacking scripts guide (this seemed promising) other stuff became irrelevant when learned more js changing user agent (which how worked out platform detection clever) it doesn't work in virtual machine because hardware acceleration doesn't seem work well. when that's turned off works, software 3d implementation slow unusable, hence trying work on linux natively. for try google "ikea kitchen planner" , follow links (i can't post more). the function determines whether application or "use different os/browser" page in file called ui_all.js (there n...

mongodb - Changing from .group() to Aggregation -

i'm doing query in mongodb. want query iusing aggregation , not group. query using: var query_part = { "shipdate" : { "$gte" : 19940101, "$lt" : 19950101 }, "partsupp.supplier.nation.name" : { $regex : '^canada'}, "partsupp.part.name" : { $regex : '^forest', $options : 'i' } }; var red = function(doc, out) { out.sum += doc.quantity; }; var half_total_quantity = db.lineitems.group( { key : "sum_quantity", cond : query_part, initial : { sum : 0 }, reduce : red })[0].sum / 2; i'm trying change half_total_quantity calculation this: db.lineitems.aggregate( { $match : {$and : [{"shipdate" : { "$gte" : 19940101, "$lt" : 19950101 }}, {"partsupp.supplier.nation.name" : { $regex : '^canada'}}, {"partsupp.part.name" : { $regex : '^forest', $options : 'i...

c - Convert double to uint8_t* -

i have function accepts uint8_t* supposed string. want send double function. have tried code below doesn't work. double = 10.98 uint8_t* p = (uint8_t*) &a; printf("p: %u \n", p); send_data(p); but code below works, want replace string "90" double variable above. static const char *data[6]; data[0] = "90"; static uint8_t *test; test = ( unsigned char *) data[datacounter] ; send_data(test); so mean doesn't work function send_data supposed send string on bluetooth android phone. if first sample code, string passed correctly. note: i think possibly because of difference in data types being passed second argument. function expecting 3 arguments. static uint32_t send_data(uint8_t data[]){ return ble_nus_string_send(&m_nus, data, 5); } this function defintion: uint32_t ble_nus_string_send (ble_nus_t * p_nus,uint8_t * p_string, uint16_t length ) there 2 different things might mean "sending ...

How to use jQuery and Ajax to refresh div content? -

i should refresh content of div element clicking on div. tried using load() method of jquery, didn't work. code: <script> $(document).ready(function(){ $("#click").click(function(){ $("#torefresh").load("articoli.html"); }); }); </script> and html: <div class="col-md-8 main-div" id="torefresh"> <h3 class="lato-font" style="color: white;">elenco eventi</h3> <div class="conf-div"> <div class="conf-div-content lato-font text-left"> <div class="conference-div" id="click"> <div class="conference-content"> <img class="role" src="images/roles-icons/chair-active.png"> <img class="role" src="images/roles-icons/author-active.png"> ...

backbone.js - How to print Count, Sum of backbone collections items using underscore.js and -

i have following var cart= [{ item: "a", price: 2 }, { item: "b", price: 3 }, { item: "a", price: 2 }, { item: "c", price: 5 }, { item: "c", price: 5 }, { item: "a", price: 2 }]; now wanted output like. item price qty total 2 3 6 b 3 1 3 c 5 2 10 for given item : var sub = mycollection.where({item: item}), length = sub.length, total = _.reduce(sub, function(memo, num){ return memo + num; }, 0); if want items can take unlimited number of values, recommend sort collection first, loop on found values.

c# - EPPlus - How to rename a named range and maintain correct formulas? -

i have excel file named range (just 1 cell). there other cells who's formulas use name. trying programatically rename cell using epplus. first attempt removed old name , added new: workbook.names.remove("oldname"); workbook.names.add("newname", mysheet.cells["b2"]); this worked rename range, formulas still use "oldname" come #name? instead of corresponding cell's value. if reference name using linq var namereference = workbook.names.first(x => x.name == "oldname") notice trying set name property namereference.name == "newname" read-only property. is there method haven't seen renaming these named ranges? if not, alternatives there situation? if reference cells who's formulas call named range change each formula. think need scan every used cells' formulas reference, think take while, considering may have dozens of excel workbooks scan through.

d - What is the difference between immutable and const member functions? -

the d programming language reference shows 2 examples in declarations , type qualifiers section, these both possible: struct s { int method() const { //const stuff } } struct s { int method() immutable { //immutable stuff } } from docs: const member functions functions not allowed change part of object through member function's reference. and: immutable member functions guaranteed object , referred reference immutable. i've found this question , answers talking data types, not storage classes. same goes d const faq , though it's interesting read. so difference between 2 definitions above? there expressions can replace //const stuff , legal not //immutable stuff ? immutable methods may called on immutable objects. can work guarantee* object ( this ) not change, ever. const methods may called on const , immutable , or mutable objects. guarantee not change object, other references may change ob...

c# - Unable to access AWS using a Facebook AssumeRoleWithWebIdentity credentials -

short version logged in facebook user, use oauth token assume iam role on aws . returns looks valid credentials, e.g. there accesskeyid, secretaccesskey similar length our master keys. when try use these credentials access dynamodb table, 1 of 2 exceptions: "the remote server returned error: (400) bad request." ; or "the security token included in request invalid." . i'm using aws c# sdk version 1.5.25.0 long version as said above, i'm trying access dynamodb table on aws using credentials supplied amazonsecuritytokenserviceclient authorized facebook identity described in this aws guide . the policy iam role i've created is: { "version": "2012-10-17", "statement": [ { "action": [ "dynamodb:batchgetitem", "dynamodb:putitem", "dynamodb:query", "dynamodb:scan", "dynamodb:updateitem" ], ...

javascript - How do you merge two objects with functions into a new one using ES6? -

i want join 2 objects functions merged object using es6, not sure how this. for example, i'd merge these 2 objects: const first = { first: function() { return { type: first }; } }; const second = { second: function() { return { type: second }; } }; into new object: const new = { first: function() { return { type: first }; }, second: function() { return { type: second }; } } what best way this? tried object.assign({}, first, second); returned {} . any appreciated! you should able use object.assign this: note mentioned in chris' answer below, mutate first object. jsbin example var joined = object.assign(first, second); // joined: { first: function first() { return { type: first }; }, second: function second() { return { type: second }; } }

asp.net - Fail to create db with entity framework 7 on ubuntu 14.04 -

i'm following following tutorial: http://ef.readthedocs.org/en/latest/platforms/coreclr/getting-started-linux.html#create-your-database and came across problem using entity framework create new database app. running command dnx ef migrations add myfirstmigration throws me error: system.io.fileloadexception: not load file or assembly 'keepitsolved, culture=neutral, publickeytoken=null' or 1 of dependencies. general exception (exception hresult: 0x80131500) file name: 'keepitsolved, culture=neutral, publickeytoken=null' ---> microsoft.dnx.compilation.csharp.roslyncompilationexception: /home/demo/kistest/src/keepitsolved/migrations/20160414215220_initialmigration.cs(17,74): dnxcore,version=v5.0 error cs0103: name 'sqlservervaluegenerationstrategy' not exist in current context /home/demo/kistest/src/keepitsolved/migrations/20160414215220_initialmigration.cs(69,74): dnxcore,version=v5.0 error cs0103: name 'sqlserverv...

arrays - java objects changing without setting them -

this question has answer here: why arraylist contain n copies of last item added list? 4 answers i trying understand how below code working: public class sample { public static void main(string[] args) { name defaultname = new name(); defaultname.setfirstname("defaultfirst"); defaultname.setlastname("defaultlast"); name name1 = new name(); name1.setfirstname("name1first"); name1.setlastname("name1last"); name name2 = new name(); name2.setfirstname("name2first"); name2.setlastname("name2last"); list<name> namesnew = new arraylist<name>(); namesnew.add(name1); namesnew.add(name2); list<name> names = new arraylist<name>(); for(int i=0;i<2;i++){ name na...

javascript - Drag and Drop HTML5 not working? -

i trying understand drag , drop html5, can drag , have element suppose take dragged element accept it. cant ondrag or ondragenter, or @ least functions events call work i'm not sure i'm doing wrong. <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>week 3 drag , drop</title> <link rel="stylesheet" type="text/css" href="week3draganddropcss.css"> <script src="week3draganddropjs.js"></script> </head> <body> <header> <h1>week 3 drag , drop</h1> </header> <div style="height:200px;width:200px;background: red" id="obj1"draggable="true"></div> <div style="height:200px;width:200px;background: green"id="obj2"draggable="true"></div> <div style="height:200px;width:200px;background: orange" id="o...

ios - Selector is not fired from scheduledTimerWithTimeInterval -

i checked existing posts on topic , googled it, not able identify mistake or make work me. have function iterativedeepening() inside class chessplayer. after 15 seconds want stop further iterations within function. in code below, function "flagsetter" never invoked. if use nstimer.fire() function invoked , not after 15 seconds. tried placing flagsetter function before or after iterativedeepening(). either case not work. have done incorrectly? class chessplayer { var timeoutflag = false //code func iterativedeepening() { ***//variables , constants*** let timer = nstimer.scheduledtimerwithtimeinterval(15.0, target: self, selector: #selector(self.flagsetter), userinfo: nil, repeats: false) ***while mindepth <= maxdepth { // loop iteration code if timeoutflag { break out of loop } }*** } @objc func flagsetter(timer: nstimer) { print("flag changed true") sel...

Connecting a lua state to another one -

i using lua extend c++ application. application have parts(ex: timer event , ui events ) can extended lua, each part, make new state , load files , functions related part in it, making change part , reloading wont affect other parts. now in situation need general files shared among other parts. like example : making function timer events part, , there object defined in general files want change info in function. in ui event part , need when access object in general file want contain changes made ui part. so thought creating state , make __index global table in other state search state if don't find stuff in it:)) apparently don't know how make that . i hope mean , tell me how make that?! lua states created lua_newstate or lua_newstate separated , cannot directly talk each other: need copy data manually 1 state other. you can set __index metamethod global table in 1 state data in other one, you'll have in c or export function lua that.

dependency injection - Is it necessary to inject $scope to a controller in angularjs? -

this question has answer here: reason using array notation when defining angularjs controller 3 answers is there difference between following 2 code snippet? both work. 1. myapp.controller("myappcontroller", ["$scope", function($scope) { // function body }]); 2. myapp.controller("myappcontroller", function($scope) { // function body }); well, difference create during minfication. if don't follow step1 , minification break code. uglify version of 1st code myapp.controller("myappcontroller",["$scope",function(o){}]) uglify version of 2nd code myapp.controller("myappcontroller",function(o){}) if follow step 1 , angular find definition of o injection. but if follow step 2 , angular won't find definition of o source.

Android Double NumberPicker with increment and accuracy -

i trying create modified numberpicker double/float values increment , precision setting can increment values other 1. use cases, have calculator app want use 2-3 of these numberpickers input/select double value. inputs might on order of 10,000,000 , others might small 0.0001 need able adjust increment step , precision each picker. since there large range of values don't want use setdisplayedvalues. want allow user input numbers directly through edittext on numberpicker. this have far numberpickerdouble class: import android.annotation.targetapi; import android.content.context; import android.os.build; import android.text.inputfilter; import android.util.attributeset; import android.view.view; import android.view.viewgroup; import android.widget.edittext; import android.widget.numberpicker; import java.math.bigdecimal; public class numberpickerdouble extends numberpicker { private double mprecision = 1; private double mincrement = 1; private edittext numberedit...

objective c - iOS: How can I make this game reset button work properly? -

i have game fireball uiimage falls screen, , user moves player object touch screen avoid them. after 8 points, playagainbutton pops up. however, playagainbutton button isn't working. doesn't execute of code in resetgame method, , resets position of character object "dustin", don't want happen. have referencing outlet attached button. how can code in resetgame work? viewcontroller code below. int thescore; - (void)viewdidload { [super viewdidload]; // additional setup after loading view, typically nib. [self initializetimer]; } - (ibaction)resetgame:(id)sender { //only thing happens right dustin resets reason. thescore = 0; [self updatescore]; _fireball.center = cgpointmake(64, 64); _endlabel.hidden = true; _playagainbutton.hidden = true; [self gamelogic:thetimer]; } - (void)updatescore { _score.text = [[nsstring alloc] initwithformat:@"%d",thescore]; } - (void) initializetimer { if(thetime...

php - Laravel: JSON to post many to many relations Error: SQLSTATE[23000]: Integrity constraint violation -

i'm trying post data json , alright except when try send data many many relationship. (i'm using uuid ) this error: sqlstate[23000]: integrity constraint violation: 1048 column 'idresource' cannot null (sql: insert ctl_resource_has_tags ( idresource , idtag ) values (, 0119a3b2-04da-11e6-9079-6971fda2300c)) this json i'm trying post tags , quicktags , relatedto many many relations, don't know how send or if i'm okey json or way i'm trying store data. { "idresourcetype": "0122b128-04da-11e6-9079-6971fda2300c", "idcreatoruser": "011d5c46-04da-11e6-9079-6971fda2300c", "idmodifieruser": "011d5c46-04da-11e6-9079-6971fda2300c", "idcreationcountry": "011f14b4-04da-11e6-9079-6971fda2300c", "title": "234234324", "description": "asfjñwlejñlr howoowowowowoowowow", "thumbnail": null, "minimum...

javascript - Unity: Trump won't die on my cactus. Why? -

Image
so, wan't game go level 2 when trump collides cactus. why wont work? code attached cacti. function ontriggerenter2d(collider : collider2d) { application.loadlevel(2); } try ontriggerenter2d , , put function inside cactus .

python 2.7 - How can I convert a string representation of binary notation to actual binary notation -

so i've been playing around 20x4 character lcd display raspberry pi , python 2.7. i've been driving using rplcd library found here https://github.com/dbrgn/rplcd . in test_20x4.py source create custom characters using series of appears binary notations. example, create happy face character: happy = (0b00000, 0b01010, 0b01010, 0b00000, 0b10001, 0b10001, 0b01110, 0b00000) this represents 8 rows, 5 column character. now, wrote gui son using tkinter , 1 of things want have user create own custom characters. have string representation of each 1 of series, example: '0b00000' can convert binary notation? >>> int('0b10101', 2) 21

java - How to setEnabledCipherSuites when using Apache HTTP Client? -

since need work legacy server, , since rc4 removed java 8, need re-enable rc4 based ciphers. described in release note have use sslsocket/sslengine.setenabledciphersuites() . since i'm using apache http client not able find way this. in advance! (i found quite semitrailer problem out answer thought of posting new one) i facing same problem , able figure out. secureprotocolsocketfactoryimpl protfactory = new secureprotocolsocketfactoryimpl(); httpsclient.gethostconfiguration().sethost(host, port, httpsprotocol); in "secureprotocolsocketfactoryimpl" class have override method public socket createsocket() secureprotocolsocketfactory class. in method socket this sslsocket soc = (sslsocket) getsslcontext().getsocketfactory().createsocket( socket, host, port, autoclose ); so there able below. cipherstobeenabled[0] = "tls_ecdhe_ecdsa_with_rc4_128_sha...

ruby on rails - What is difference between perform_in and perform_async in sidekiq? -

i want update old sidekiq jobs new time interval. how can ? possible through perform_in option. in addition want know clear difference between perform_in , perform_async . you have pass perform_in time. perform_async gets pushed queue right away. other they're same. you'd call perform_in(10.minutes)

java - Detecting stream data corruption -

i have server sending/receiving data multiple clients, each attached separate server thread. data being sent via datainputstreams , dataoutputstreams , consists entirely of strings. send int-based signals indicate client behavior should change, data sent in stringized format. from understand currently, tcp automatically resend dropped packets, want able handle data corruption. if call, say, dataoutputstream.writeutf() send message client server, if checksum detection done behind scenes make sure full message transmitted properly? , how detect problems? would, say, catching ioexception in server code datainputstream , manually asking client resend message (which should therefore id-stamped somehow) proper way of handling situation?

java - Are there any tools to create dummy objects to use for JUnit test cases? -

i writing junit test cases test crud operations in dao classes. pretty boilerplate code , bulk of create test object , assign dummy values instance variables. there tools in java create object , assign dummy values based on declared type? i don't want use jmock or mockito need interact database , test crud operations successful. i don't know tool create mock object , fill automatically fuzzy data. but maybe following approach close want achieve. pseudo code foo foo = new foo(); foo.setintvalue(generateint()); foo.setstringvalue(generatestring(20)); ... // store record in database // retrieve record database // check if retrieved values equal values in `foo` if want achieve might have quickcheck the goal of quickcheck replace manually picked values generated values. quickcheck-based test tries cover laws of domain whereas classical testing can test validity distinct values. basically, quickcheck generators of data. quickcheck runner method fancy lo...