Posts

Showing posts from May, 2012

Node.js v8-profiler module won't install on Node v8.1.0 on OSX -

i ran yarn add v8-profiler command in osx terminal. error. says file node-v57-darwin-x64.tar.gz not available tries build node-gyp. there problem node-gyp in local machine. (i can't download xcode because internal wireless adapter on macbook doesn't work). can solve problem? output: node-pre-gyp info worked if ends ok node-pre-gyp info using node-pre-gyp@0.6.34 node-pre-gyp info using node@8.1.0 | darwin | x64 node-pre-gyp info check checked "/node_projects/project/node_modules/v8-profiler/build/profiler/v5.7.0/node-v57-darwin-x64/profiler.node" (not found) node-pre-gyp http https://node-inspector.s3.amazonaws.com/profiler/v5.7.0/node-v57-darwin-x64.tar.gz node-pre-gyp http 404 https://node-inspector.s3.amazonaws.com/profiler/v5.7.0/node-v57-darwin-x64.tar.gz node-pre-gyp err! tried download(404): https://node-inspector.s3.amazonaws.com/profiler/v5.7.0/node-v57-darwin-x64.tar.gz node-pre-gyp err! pre-built binaries not found v8-profiler@5.7.0 , node@8.1.0 (nod

When do we use setExperimentalOptions in selenium chrome options? -

can please explain me last 2 lines of code.i have searched many sites answer there no clear explanation. chromeoptions options = new chromeoptions(); hashmap<string, object> chromeprefs = new hashmap<string, object>(); chromeprefs.put("profile.default_content_settings.popups", 0); options.setexperimentaloptions("prefs", chromeprefs); sets experimental option. useful new chromedriver options not yet exposed through chromeoptions api. it allows test particular feature before gets released chrome developers. also check- example given in link

c# - Comparison of unspecified generic properties -

consider following code: public interface iidentifiable<t> { t id { get; set; } } public interface iviewmodel { } public class myviewmodel1 : iviewmodel, iidentifiable<int> { public string myproperty { get; set; } public int id { get; set; } } public class myviewmodel2 : iviewmodel, iidentifiable<string> { public string myproperty { get; set; } public string id { get; set; } } i have class operates viewmodels: public class loader<t> t: iviewmodel { public void loaddata() { /*some important stuff here*/ if (typeof(iidentifiable<??>).isassignablefrom(typeof(t))) { // ^- here's first problem data = data.where(d => _datasource.all(ds => ((iidentifiable<??>) ds).id != ((iidentifiable<??>) d).id)).tolist(); } // ^---- , there second ----^ /*some important stuff here

Ansible multiple condition not working -

ansible version: 2.2.1.0 hostfile: [master] 54.65.104.4 [slaves] 52.69.71.248 tasks/main.yaml - name: checking if node having spark master installed (master) stat: path: /etc/init.d/spark-master register: spark-master when: inventory_hostname in groups['master'] - name: checking if node having spark worker installed stat: path: /etc/init.d/spark-slave register: spark-slave when: inventory_hostname in groups['slaves'] # downloading master - include: download.yaml when: (inventory_hostname in groups['master']) , ( spark-master.stat.exists == false) # downloading slaves - include: download.yaml when: (inventory_hostname in groups['slaves']) , ( spark-slave.stat.exists == false ) but when execute script receiving following errors: fatal: [52.69.71.248]: failed! => {"failed": true, "msg": "the conditional check '(inventory_hostname in groups['s

javascript - How to use border radius with image on html2canvas? -

Image
i have faced issue border-radius on img tag in html2canvas . if has solution please share. original html view after converting image using html2canvas thanks in advance.

Scala Spark - task not serializable -

i have following code, fault @ sc.parallelize() val pairs = ret.cartesian(ret) .map { case ((k1, v1), (k2, v2)) => ((k1, k2), (v1.tolist, v2.tolist)) } (pair <- pairs) { val test = sc.parallelize(pair._2._1.map(_._1 )) } where k1, k2 strings v1, v2 lists of doubles i getting following error whenever try access sc. doing wrong here? exception in thread "main" org.apache.spark.sparkexception: task not serializable @ org.apache.spark.util.closurecleaner$.ensureserializable(closurecleaner.scala:315) @ org.apache.spark.util.closurecleaner$.org$apache$spark$util$closurecleaner$$clean(closurecleaner.scala:305) @ org.apache.spark.util.closurecleaner$.clean(closurecleaner.scala:132) @ org.apache.spark.sparkcontext.clean(sparkcontext.scala:1893) @ org.apache.spark.rdd.rdd$$anonfun$foreach$1.apply(rdd.scala:869) @ org.apache.spark.rdd.rdd$$anonfun$foreach$1.apply(rdd.scala:868)

SignalR with Angular 4 -

i want connect sinalr hub , retrieve data using angular 4 app. appreciate if provide me sample achieve this. thanks. thanks jota.toledo, c-sharpcorner.com/article works me. in addition have modify owinstartup below. app.usecors(microsoft.owin.cors.corsoptions.allowall); app.mapsignalr();

collation - SQL Server collate error between 2 databases -

i have had take existing stored procedure , amend 1 of tables comes different database. databases have been set different collate sequences. here's code far: alter procedure [dbo].[usp_getcontactdetails] @smid varchar(100) = '' begin set nocount on; select distinct a.staffid staffid, a.firstname firstname, a.surname surname, a.firstname + ' ' + a.surname staffname, a.jobtitle [job title], d.dept [dept], a.location [location], a.locationid [locationid], isnull(b.mobile, '') [mobile], isnull(b.directfaxno, '') directfaxno, cast(isnull(sp.[profile_description], '') varchar(8000)) [profile], directtel = isnull((select top 1 sitetelephone [directory].dbo.location o o.siteid = sit.siteid), ''), officefax = i

uiviewcontroller - popToViewController with UITabBarViewController not working or not Calling -

nested pop animation can result in corrupted navigation bar finishing navigation transition in unexpected state. navigation bar sub view tree might corrupted. uitabbarcontroller(root) --> uinavigationviewcontroller --> uiviewcontroller(1) --> uiviewcontroller(2) --> uiviewcontroller(3) i'm not connected viewcontrollers segue i'm pushing via code above flow structure. when tab back-button on uiviewcontroller(3) need poptoviewcontroller uiviewcontroller(1) override func willmove(toparentviewcontroller parent: uiviewcontroller?) { super.willmove(toparentviewcontroller: parent) if parent == nil { let controllers = self.navigationcontroller?.viewcontrollers vc in controllers! { if vc .iskind(of: uiviewcontroller(1).self) { self.navigationcontroller?.poptoviewcontroller(vc, animated: true) break } } } }

php - xampp does not run fatal error -

i got following warning , error working on laravel project using xampp: warning: unknown: failed open stream: no such file or directory in unknown on line 0 fatal error: unknown: failed opening required 'server.php' (include_path='c:\xampp\php\pear') in unknown on line 0 solved antivirus deleted of files. turned off , working.

java - Random Element as input and get the Value -

i don't know if it's duplicated question cause i've found nothing , didn't know keywords should i've been searching. i want have class gets element input , shows value of element. for example: public void showvalue(object obj){ system.out.println("output: " + obj.getvalue()); } and then: nativeselect ns=new nativeselect(); textfield tf=new textfield(); ns.addvalue("name"); ns.select("name"); tf.setvalue("lastname"); showvalue(ns); showvalue(tf); and have output: output: name output: lastname could maybe me or give me idea how should that! i'm new java , started programming after long time. thanks alot! you want function can print value of every field. this: public static void showvalue(field f) { system.out.println("output: "f.getvalue()); //will print via console new notification("output: "+f.getvalue()).show(page.getcurrent()); //will show text box in

css - Different font-weight for special characters -

i have problem font-weight, "en" languages working fine, when same thing with lang (sk) characters have different font weight. font 'open sans'. when try these chars in font.google viewer there no problem. actual font-weight 300, on 400 there no problem want thin. problem occurs on chrome(mobile),edge, ie. ideas? open sans on fonts.google open sans on website link page: thomaskovo.github.io/hotel-it/it_bussiness_solutions/hosted_exchange_office_365.html body{ font-family: 'open sans', sans-serif; font-weight:300; } <html> <head> <link href="https://fonts.googleapis.com/css?family=open+sans:300" rel="stylesheet"> </head> <body> testing text. mačka žena ťava šošovica <hr> open in edge or ie </body> </html> the font used doesn't contain glyphs. due font fallback, missing glyphs fall other font. you load latin glyphs. need load subsets contain ne

node.js - Howto patch/shim crypto.getRandomValues for React Native -

i porting packages created nodejs react native using reactnativify rewrite node api object dependencies browserify equivalents. one of them crypto . in transformer.js (or .babelrc ) have: // following plugin rewrite imports. reimplementations of node // libraries such `assert`, `buffer`, etc. picked // automatically react native packager. other built-in node // libraries rewritten browserify counterpart. [require('babel-plugin-rewrite-require'), { aliases: { crypto: 'crypto-browserify', // ... }, throwfornonstringliteral: true, }], in reactnativify global.js there code (which excluded, because not meant production): // don't in production. you're going want patch in // https://github.com/mvayngrib/react-native-randombytes or similar. global.crypto = { getrandomvalues(bytearray) { (let = 0; < bytearray.length; i++) { bytearray[i] = math.floor(256 * math.random()); } }, }; . my first question : how getrand

asp.net mvc - How to convert EF List objects to an arrayList of type dateTime -

i'm working on leave application. need excluded dates , convert datetime array. i used following approach partially achieve this. created helper folder added following class folder: namespace eleave.helpers { public class businessdayscalculator { public int calculate(datetime startdate, datetime enddate, datetime[] holidays) { startdate = fixstartdate(startdate); enddate = fixenddate(enddate.date); if (startdate > enddate) return 0; else return calculatedifference(startdate, enddate, holidays); } private int calculatedifference(datetime startdate, datetime enddate, datetime[] holidays) { int difference = (int)(enddate - startdate).totaldays; int weeks = difference / 7; if (enddate.dayofweek < startdate.dayofweek) weeks++; difference -= weeks * 2; difference -= holidaycount(start

python - Expected type 'int', got 'IntegerField' instead Django -

i trying object of class guide value of calculation of other objects in class. how far have got in code got error expected type 'int', got 'integerfield' instead. how work? here code: class guide(models.model): guide_title = models.charfield(max_length=200) guide_category = models.charfield(max_length=70) guide_why = models.textfield() guide_how = models.textfield() user_current_conversion_rate = models.integerfield(default=0) user_optimal_conversion_rate = models.integerfield(default=0) user_monthly_visitors = models.integerfield(default=0) user_average_order_value = models.integerfield(default=0) user_increase_conversion_rate = models.integerfield(default=0) @property def user_increase_conversion_rate(self): return int( (self.user_monthly_visitors*(self.user_optimal_conversion_rate/100))* self.user_average_order_value) - ((self.user_monthly_visitors*(self.user_c

database - Rails: How to get all of the records that have the maximum count of a relation with a where clause -

rails 5.1.2 these 2 models in question. class person < applicationrecord has_many :awards end class award < application record belongs_to :person end the award model has column called rank can 1 , 2 , or 3 , , column called category (also integers, let's use letters now). i'm trying rank people based on awards of rank. many people can have same amount of rank. example, 40 people might have 30 rank 1 awards of category x. for example: most awards category a people granted award rank 1 8 times person 1 person 2 people granted award rank 2 30 times person 1 person 7 person 19 people granted award rank 3 60 times person 2 person 19 person 44 i want build query returns collection of people . logically, query should (in pseudo code): get `people` have maximum `count` of awards `awards.category` `a` , `awards.rank` `1`. ...and repeat rank 2 , rank 3 . a counter_cache not work because of implication of catego

jquery - Datatables not displaying first column -

Image
i have json object trying display in table using jquery datatables first column not showing. know data in json object data not displaying. can see problem code please? thanks! <script src="jquery-3.2.1.min.js"></script> <script src="xlsx.full.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.15/datatables.min.css" /> <script type="text/javascript" src="https://cdn.datatables.net/r/bs-3.3.5/jqc-1.11.3,dt-1.10.8/datatables.min.js"></script> <meta charset="utf-8"> <a href="index.html"> <img border="0" src="home.png" width="

php - Remove the stock quantity from WooCommerce cart error messages -

iin woocommerce, i've set woocommerce->settings->products->inventory->stock display format "never show quantity remaining in stock" . however if customer ads product cart, continues cart or checkout page , enter value higher have in stock error message: sorry, not have enough " {product_name} " in stock fulfill order ( {available_stock_amount} in stock). please edit cart , try again. apologize inconvenience caused. what filter can use edit output? don't want show (absolutely anywhere on front end shop) actual available stock amount. i've found handled in function (check_cart_item_stock) in, [root]->wp-content->plugins->woocommerce->includes->class-wc-cart.php on line 491: if ( ! $product->has_enough_stock( $product_qty_in_cart[ $product->get_stock_managed_by_id() ] ) ) { /* translators: 1: product name 2: quantity in stock */ $error->add( 'out-of-stock', sprintf( __( 'sorry, not

how to add days to date variable on every ng-repeat loop in angularjs -

i have set date variable in "ng-init" directive , want add days date variable on every ng-repeat loop below: <table> <tr ng-repeat="n in myarr" ng-init="mydate=('07/25/2017'|date:adddays($index))"> <td ng-bind="mydate"></td> </tr> </table you can instantiate first date in controler : $scope.firstdate = new date('07/25/2017'); and add days in ngrepeat : <tr ng-repeat="n in myarr" ng-init="mydate=(firstdate.setdate(firstdate.getdate() + 1)|date)"> and if want date format mm/dd/yyyy , need add @ end of nginit :'m/d/yyyy' , (you can take @ the doc more information date format) : <tr ng-repeat="n in myarr" ng-init="mydate=(firstdate.setdate(firstdate.getdate() + 1)|date:'m/d/yyyy')"> but if have other things dates think idea take @ moment.js var app = angular.module('plunker

deep learning - How to reshape my data for the convolution neural network model? -

i need let input in convolution neural network model reshaping data, problem line of code: model = sequential() input_traces = input(shape=(3253,)) model.add(convolution1d(nb_filter=32, filter_length=3, activation='relu',input_shape = input_traces)) this line gives me error: cnn_based_attack.py:139: userwarning: update `conv1d` call keras 2 api: `conv1d(activation="relu", input_shape=(none, /in..., padding="same", filters=32, kernel_size=3)` model.add(convolution1d(nb_filter=32, filter_length=3, border_mode='same', activation='relu',input_dim=input_traces)) traceback (most recent call last): file "cnn_based_attack.py", line 139, in <module> model.add(convolution1d(nb_filter=32, filter_length=3, border_mode='same', activation='relu',input_dim=input_traces)) file "/home/.local/lib/python2.7/site-packages/keras/models.py", line 430, in add layer(x) file "/home/.loca

javascript - MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFU SED 127.0.0.1:27017] -

my question mongo not connecting server? , why saying failed connect server [localhost:27017] on first connect [mongoerror: connect econnrefu sed 127.0.0.1:27017] here code: var express = require("express"), app = express(), bodyparser = require("body-parser"), mongoose = require("mongoose"); mongoose.connect("mongodb://localhost/blogapp"); app.set("views engine", "ejs"); app.use(express.static("public")); app.use(bodyparser.urlencoded({extended: true})); app.get('/', function (req, res) { res.send('hello world!') }); app.listen(3000, function () { console.log('example app listening on port 3000!') }); install mongodb on machine, (if you're on mac, run brew install mongodb ), open new terminal, , run mongod , relaunch app

Associative array formatting -

i having array array ( [0] => array ( [008847] => mi ) ) please suggest how make in php array ( [008847] => 'mi' )

trimming - find index of word from list of words in text file in python -

i have list of words in text file, , have list of text files reach text. the list of words in text file has words starting word, line containing below words considered . same text file has words starting word, lines containing above words considered. in short want trim text files using words. here code: # load text file textfile=[] lines=[] path="images summarization _# ctscan/" text in sorted(os.listdir(path+'text/'),key=lambda x: os.path.splitext(x)[0]): textfile.append(open(path+"text/"+text,'r').read().lower()) lines.append(open(path+"text/"+text,'r').read().lower().splitlines()) ## trimming part trimed_words_top=open(path+"words trimming above.txt",'r').read() trimed_words_below=open(path+"words trimming below.txt",'r').read() trimed_words_top=trimed_words_top.lower().splitlines() trimed_words_below=trimed_words_below.lower().splitlines() word_index_top=[] data=[] tri

node.js - Ubuntu 16.04 pre-commit instalation causing an error -

i have tried set pre-commit hook , have installed https://www.npmjs.com/package/git-pre-commit on ubuntu 16.04 , when commiting have error cannot fixed: .git/hooks/pre-commit: 9: [: %path%: unexpected operator /usr/bin/env: ‘node’: no such file or directory i have installed node package manager , tried fix error based on https://github.com/animetosho/nyuu/issues/14 without success. have tried uninstall git-pre-commit , remove error still here. just mention node , npm functioning prior this. would if narrow down causing this. thanks. it seems error in pre-commit.sample in https://www.npmjs.com/package/git-pre-commit have deleted , install https://www.npmjs.com/package/pre-commit . error gone. if has same experience.

javascript - how to set tooltip text color in flot chart? -

i using flot chart multi series data.i want change tooltip text color in flot chart. using code: $("#placeholder").bind("plothover", function (event, pos, item) { if (item) { $("#tooltip").remove(); var hoverseries = item.series; var x = item.datapoint[0], y = item.datapoint[1]; var strtip = x + " / " + y + " " + item.series.label; var allseries = plot.getdata(); $.each(allseries, function(i,s){ if (s == hoverseries) return; $.each(s.data, function(j,p){ if (p[0] == x){ strtip += "</br>" + p[0] + " / " + p[1] + " " + s.label; } }); }); showtooltip(item.pagex, item.pagey, strtip); } }); any 1 color taking in tooltip? flot chart supports html tags in tooltip you can use html tag: <span> flot chart tooltip support html tags. with <s

amazon web services - API Gateway custom domain with WAF -

is there 1 way make api gateway, waf work together? i tried these steps: created 1 api gateway - , deployed in dev stage - urlx/dev created 1 waf rules auto block ips created 1 cloud front distribution urlx , waf web acl - described in various forums updated alias of custom domain domain of cloud front assigned ip addresses in blocking sets tried call urlx/dev blocking ip address - able call - shouldn't allowed can't call cust-domain/dev - shows could not response postman how make work together? concrete tutorial?

c# - How to: Join 2 DataTables with same Row Count -

i've got these 2 datatables: table1: columns->"timestamp1,result1" row[0]->"sometime,someresult" table2: columns->"timestamp2,result2" row[0]->"someothertime", "someotherresult" now want result table or string[] or string this: table result: columns->"timestamp1,result1,timestamp2,result2" row[0]->"sometime,someresult,someothertime,someotherresult" is there simple way of doing this? if tables got more rows one? i've allready got solution joining columns string: stringbuilder sb = new stringbuilder(); foreach (datatable dt in data_set.tables) { sb.append(string.join(",", dt.columns.cast<datacolumn>().select(x => x.columnname).toarray())); sb.append(","); } output example tables string >> "timestamp1, result1,timestamp2,result2" so using linq possibl

cordova - Ionic 2 - Error : net::ERR_CONNECTION_TIMED_OUT when run on android device -

(sorry bad english) i have built application ionic 2 android. in application need information api , it's works when run in browser (ionic serve). the problem when run on device (android 6.0.1) issue : net::err_connection_timed_out then searched how resolve , tried many things. i have cordova-plugin-whitelist , config.xml looks : <content src="index.html" /> <allow-navigation href="*" /> <allow-intent href="*" /> <access origin="*" subdomains="true" /> and put in index.html : <meta http-equiv="content-security-policy" content="default-src *; style-src * 'unsafe-inline'; script-src * 'unsafe-inline' 'unsafe-eval'; img-src * data: 'unsafe-inline'; connect-src * 'unsafe-inline'; frame-src *; media-src *;"> i have read many documentation concerning issue didn't find helpful. can me please ? thanks an obviou

vsts - Ignore files within the 'Delete Files Task' -

Image
as part of install scripts visual studio online (vso / vsts) delete files in directory shortly after uninstalling services. we have configuration files , logs i'd preserve everytime try tell 'delete files task' ignore files deletes them anyway. what want files in bifrost directory deleted except for the logs folder app.connections.config app.queues.config can please? if files want delete located in agent folder or subfolder of agent machine, can use delete files task . because source folder of delete files task can specified agent machine. if files want delete located on remote machine, should use powershell task or remotedelete task delete files. for powershell task, there many powershell script on web delete files remote machine. for remotedelete task, can set below: input remote machine’s ip, username , password. path: directory bifrost folder, such d:\test\bitfrost include items: folders , files want delete , separate comma (

oracle11g - Oracle Partitioned Table - How to Count -

i have partitioned table (mytable) on oracle (11g). quite large table, partitioned insert_date column (without time). the problem that, count(*) gives incorrect result . the query below returns: 5,726,829,673 select count(*) mytable insert_date >= to_date('01/01/2015', 'dd/mm/yyyy') the query below returns: 13,076,228,720 select sum(1) mytable insert_date >= to_date('01/01/2015', 'dd/mm/yyyy') how can possible? reason difference?

javascript - How do I get page breaks when using the text function in jsPDF? -

i trying print content of textarea pdf file (i.e. text, not html). content may or may not greater 1 page in length when printed. currently, code looks this: var doc=new jspdf(); doc.text(10,10,inputtexthere); doc.save('file.pdf'); this overflows bottom of page when inputtexthere long. there way jspdf automatically page break when text reaches end of page? have tried use pagesplit: true option, not work argument in text function. edit: have managed achieve wanted using jspdf-autotable, using single titleless column single row containing data (i.e. 1 cell content in), , options theme: 'plain', pagebreak: 'always', styles: {overflow: 'linebreak'} . however, still know if have been achieved in jspdf alone.

node.js - why the nodejs spawn api dont call no event (onexit,onend,onerror) and sync dont wait command is completed? -

this function contains 2 bugs: 1) output not printed , no event executed. if pass option stdio=true output printed anyway no event (close,error,exit) executed 2) sync dont wait expected. if dont call onclose ... sync might wait indefinitelly ... istead process finished . didnt use spawnsync because output in case available when command completed. not solution when output long or interactive var shellexecute = function (path, cmd) { console.log('\t' + cmd) function asyncfunction(callback) { var proc = $.proc.spawn(cmd, {cwd: path, encoding: 'utf8'}); proc.stdin && proc.stdin.pipe(process.stdin); proc.stdout && proc.stdout.pipe(process.stdout); proc.stderr && proc.stderr.pipe(process.stderr); proc.on('close', function (code) { console.log('closing code: ' + code); callback(null); }); proc.on('exit', function (code) {

android - App crashes when insert new data with ContentProvider -

this code: for insert of contentprovider : public uri insert(uri uri, contentvalues contentvalues) { final int match = surimatcher.match(uri); switch (match) { case dog: insertdog(uri, contentvalues); default: throw new illegalargumentexception("insertion not supported " + uri); } } private uri insertdog(uri uri, contentvalues contentvalues) { sqlitedatabase db = mdbhelper.getwritabledatabase(); long id = db.insert(dogentry.table_name, null, contentvalues); if (id == -1) { log.e(log_tag, "failed insert row " + uri); return null; } return contenturis.withappendedid(uri, id); } this insert data: contentvalues values = new contentvalues(); values.put(dogentry.name, "doggy"); values.put(dogentry.breed, "dingo"); values.put(dogentry.gender, dogentry.gender_male); values.put(dogentry.weight, 15); uri newuri = getcontentresolv

angular2 template - Generate angular 2 form after http callback -

i want generate angular 2 form group after receive response service. used following approach not work.i tried making service call , after receive response i'm trying generate form group not know how correct syntactically. below app.component.ts import { component,input } '@angular/core'; import { formgroup,formbuilder } '@angular/forms'; import { dropdownquestion } './question-dropdown'; import { questionbase } './question-base'; import { textboxquestion } './question-textbox'; import { dynamicformcomponent } './dynamic-form.component'; import { questionservice } './question.service'; import { questioncontrolservice } './question-control.service'; @component({ selector: 'my-app', template: ` <form [formgroup]="form"> <div *ngfor="let question of questions"> <input formcontrolname="questi

python - How to set degrees to a maximum of 360? -

i'm making program , want let snake go in same direction heading, when try code: def move(self): if pressed_keys[self.ctrls[0]]and self.dire == 0: self.y -= 10 if pressed_keys[self.ctrls[0]]and self.dire == 90: self.x -= 10 if pressed_keys[self.ctrls[0]]and self.dire == 180: self.y += 10 if pressed_keys[self.ctrls[0]]and self.dire == -90: self.x += 10 def turn_left(self): self.dire += 90 def turn_right(self): self.dire -= 90 . . . while 1: clock.tick(60) event in pygame.event.get(): if event.type == quit: sys.exit() if event.type == keydown , event.key == k_left: snake.turn_left() if event.type == keydown , event.key == k_right: snake.turn_right() pressed_keys = pygame.key.get_pressed() there problem: can turn twice right arrow-key can't go in direction anymore. because did was: pressed arrow twice -> self.dire - 90 - 90. self.dire -180. c

sql server - Python-Microsoft SQL Insert Variables into Table -

there working request: msqslquferty1="""insert dbo.users values('namedd188','logindd188','passworddd',0)""" cursor.execute(msqslquferty1) but if pass parameters through variables, error occurs. name1="ur2241" login1="login2241" password1="password2241" voises1="0" cursor.execute("insert dbo.users(name,login,password,voited) values (%s,%s,%s,%s);"%(name1,login1,password1,voises1)) traceback (most recent call last): file "e:/dropbox/pyton/network/client-server/server/sqlconnect.py", line 33, in cursor.execute("insert dbo.users(name,login,password,voited) values (%s,%s,%s,%s);"%(name1,login1,password1,voises1)) file "e:\pyton\lib\site-packages\pypyodbc-1.3.4-py3.6.egg\pypyodbc.py", line 1626, in execute file "e:\pyton\lib\site-packages\pypyodbc-1.3.4-py3.6.egg\pypyodbc.py", line 1652, in execdirect file &

node.js - Steam authentication API, passing data back to Angular -

i have problem express(nodejs)/angular web app rely on steam's login authentication. when user clicks "login" he's redirected steam authentication(steam's website), once logged in user redirected specific route on backend called /verify. once user hits /verify there session variables containing necessary user data access. therefore use jwt generate token data send client(angular in case). the problem sending token frontend(the client) save in local storage. any highly appreciated! currently, pass token via query string redirect frontend, doesn't seem solution. maybe should stick server-side sessions , write http routes user data. problem approach once again client unaware when user authenticates himself on backend, since callback triggered on backend. edit: tried approach, once again unsure of it's right way go both code-wise , security-wise. redirect user steam authentication page. wait authentication callback on server side, in case hit

java - From libGDX through GitHub to another computer -

project created in libgdx on computer, chosen platforms: android , desktop. absolutely ordinary, trivial project created, nothing special. worked in intellij idea. here tree . i placed on github. on computer tried clone project continue. , mistakes began. here screenshot i added module, changed paths, seems correct. files classes not work , in manifest there error. apparently, manifest not in project folder, subfolder android , manifest work correctly. i'm tired of sorting out settings already. doesn't work, whatever put in android:name field. fatal exception: main java.lang.runtimeexception: unable instantiate activity componentinfo{by.randomen.attempt/by.randomen.attempt.androidlauncher}: java.lang.classnotfoundexception: didn't find class "by.randomen.attempt.androidlauncher" on path: dexpathlist[[zip file "/data/app/by.randomen.attempt-2.apk"],nativelibrarydirectories=[/data/app-lib/by.randomen.attempt-2, /system/lib]]

php - Setting up Google Reporting API to work in cronjob -

i've managed set php script grabs data our google analytics account , can run great in browser i'm struggling figure out how allow work inside of cronjob script instead. here's code: <?php // load google api php client library. require_once dirname(__file__) . '/analytics/google-api-php-client-2.2.0/vendor/autoload.php'; session_start(); $client = new google_client(); $client->setauthconfig(dirname(__file__) . '/analytics/client_secrets.json'); $client->setaccesstype("offline"); //offline access $client->addscope(google_service_analytics::analytics_readonly); if (isset($_session['access_token']) && $_session['access_token']) { print "<br />start: ".date("h:i:s")."<br />"; // set access token on client. $client->setaccesstoken($_session['access_token']); $sessionid = $_session['access_token']['access_token']; /

php - Doctrine flush absolutely too long -

i have following situation: use symfony command list xml documents of given folder. parse each document , build document entity. want "import" new entities in mysql database using doctrine2. php class looks this: class importservice implements flushinterface { private $entitymanager; private $documentcache; private $flushcounter; public function __construct() { $this->documentcache = []; $this->flushcounter = 0; } public function savedocument(documententity $doc) { $this->persistdocumententity($doc); ... $this->checkbulk(); return $this; } protected function persistdocumententity(documententity $doc) { $cachekey = hash('sha256', $doc->getsource() . ':' . $doc->getsourceid() . ':' . $doc->getclient()); $this->entitymanager->persist($doc); $this->documentcache[$cachekey] = $doc; return $this;

forms - PHP Institutional Email Validation -

i make user registration form accepts email addresses university. e.g me@gmail.com, me@yahoo.com, me@live.com = invalid me@university.ac.uk = valid what types of terms , queries should start researching achieve this? new php, homework, i've done far can find tutorials on how validate emails based on rejecting invalid inputs, rather accepting valid domain extensions such @university.ac.uk hope makes sense, not trying code written me (although visual explanations helpful), asking few pointers in right direction. i suggest regex email requirements. /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@\buniversity.ac.uk/ please visits here https://regex101.com/r/kkjeho/9

search - Talend (Data Integration) - List all jobs which use a specific table -

Image
i have update in talend's project, , wondering if can list jobs use specific table (for example want list jobs use tables "employees") . finally, found solution. go folder install talend, "workspace > myproject > process" , research "employees" advanced options > file contents. this methods not perfect, allow me list jobs using table employees id doesn't allow me replace words employees example.

security - Constant-time string comparison function -

to compare 2 strings, use strcmp or 1 of variants. however, because strcmp take longer if more characters match, vulnerable timing attacks. there constant-time string comparison function in standard library on windows? i don't think windows nor visual studio has such functions. at least simple strcmp can whip yourself. if care equality: int strctcmp(const char*a, const char*b) { int r = 0; (; *a && *b; ++a, ++b) { r |= *a != *b; } return r; } if need sortable results and need process of longest string: int strctcmp(const char*a, const char*b) { int r = 0, c; (;;) { c = *a - *b; if (!r) r = c; if (!*a && !*b) break; if (*a) ++a; if (*b) ++b; } return r; } these not perfect timing wise should more enough network based.

c++ - Split string into string and int -

i trying use sscanf(inputcmd, "%s%d", cmd, value); convert string inputcmd string cmd , , int value in arduino sketch. isn't working, apparently variables wrong type (string, instead of char*) inputcmd in format foo90, , neither length of number or string can assumed constant. best way separate 2 parts of inputcmd , store them in 2 variables? cmd should foo, , value should 90. thanks. besides problem string versus char* , scanf format "%s" reads space-delimited string. if there's no space between string , number can't use sscanf . as possible solution can attempt substring of each part of input string, , number-part convert int . to find out length of first substring (which should put cmd ) , starting position of number, need iterate on characters of string until find non-alphabetic character.

dart - Drawer Avoid Infinite Activity Creation -

i use drawer each activity: final mydrawer _drawer = new mydrawer(); class mydrawer extends statefulwidget { @override _mydrawerstate createstate() => new _mydrawerstate(); } class _mydrawerstate extends state<mydrawer> { @override widget build(buildcontext context) { return new drawer( child: new listview( children: <widget> [ new drawerheader( child: new text("header"), ), new listtile( leading: new icon(icons.home), title: new text("home"), ontap: () { navigator.popandpushnamed(context, "/"); }, ), new listtile( leading: new icon(icons.android), title: new text("another page"), ontap: () { navigator.popandpushnamed(context, anotherpage.routename); }, ),new

product - Prestashop Display both prices with and without tax -

i found how display both price , without tax on product list. when there specific price, old price same , without tax. displays old price tax incl price tax exc. example : 549,0 € ht (733.20€) - 659.88 € ttc (733.20€) {if (!$ps_catalog_mode , ((isset($product.show_price) && $product.show_price) || (isset($product.available_for_order) && $product.available_for_order)))} <div class="content_price"> <p style="font-size: 20px;"> {l s='from'}</p> {if isset($product.show_price) && $product.show_price && !isset($restricted_country_mode)} {hook h="displayproductpriceblock" product=$product type='before_price'} <div id="prix_ht"> <span class="price product-price"> {if !$pricedisplay}{convertprice price=$product.pri

java - Best practice of designing JPARepository(ies) for ORM Domain graph -

i have been designing spring rest apis using standard mvc architecture domain layer pojos , repositories fetch domain data db tables. far these entities isolated design acted separate restcontroller, service, , repository flow each entity. have been looking understand best practice when comes association in domain objects i.e., orm. example, lets take following pseudocode illustrate domain classes (only purpose express design in question. have not provided complete classes): public class customer { @column private int id; @column; private string name; @onetomany private list<order> orders; //...getters setters } public class order { @column private int id; @column; private string ordernumber; @onetomany private list<product> products; @manytoone private customer customer; //...getters setters } public class product { @column private int id; @column; private string productname;

Spark SQL : Handling schema evolution -

i want read 2 avro files of same data set schema evolution first avro file schema : {string, string, int} second avro file schema evolution : {string, string, long} (int field undergone evolution long) want read these 2 avro file store in dataframe using sparksql. to read avro files using 'spark-avro' of databicks https://github.com/databricks/spark-avro how efficiently. spark version : 2.0.1 scala. 2.11.8 ps. here in example have mentioned 2 files in actual scenario file generated daily there more 1000 such file. thank in advance:) use union like {string,string, [int, long]} is valid solution your? should allow read both new , old files.

javascript - JS file upload validation, but instant in windows window -

i have form , did validation in js, form not send when user sends sth different .doc/.docx. (cv uploading). want faster. error instantly when file selected, not when button submitted. (in windows window). how it? it's standard form: <div class="form-group"> <label>your cv</label> <input required type="file" accept="application/msword" class="form-control" name="cv" id="cv" aria-describedby="name" placeholder="select cv file"/> </div> i've got answer. here's code (isdoc own function): function onchange(event) { var file = $('#file_cv')[0].files[0]; if ( !isdoc(file.name) ) { alert("please, choose .doc or .docx type."); document.getelementbyid("file_cv").value=&q

c# - GetPostBackClientHyperlink stops when navigating a second grid on the page -

i have 2 grids on page. on pageload both grids have data expected the first grid has event on rowdatabound protected void onrowdatabound(object sender, system.web.ui.webcontrols.gridviewroweventargs e) { if (e.row.rowtype == datacontrolrowtype.datarow) { e.row.attributes["onclick"] = page.clientscript.getpostbackclienthyperlink(gridview1, "select$" + e.row.rowindex); e.row.tooltip = "click select row."; } } the first grid's row click works expected. when start navigating through second grid using 'next' button, rowclick on first grid stops working. next button click on second grid below protected void lbtnnext_click(object sender, eventargs e) { try { int pageindex = (int)viewstate["current"] + 1; if (pageindex < grdimages.pagecount) { grdimages.pageindex = pageindex; bindsecondgrid();

c# - Executing a PowerShell script and leaving it running -

i have powershell script that, once executed listens on port. want execute script , leave running while c# program continues run. here have right when gets line waits until script finished (which never does). process proc = process.start("powershell.exe", @"/k tcdrvrcunit.exe automation.txt"); proc.waitforexit(); console.writeline(proc.processname);

Expectation failure not triggered if file ends with Boost Spirit Qi parser -

when file ends in middle of rule remaining expectations, doesn't trigger expectation error (it does, of course, fail parse). a simplified example triggers behavior this: data_var_decls_r %= (lit("data") > lit('{')) > lit('}'); if input data { then expectation error final expected } isn't triggered. is there way deal expectation errors extend past end of file? making self-contained example: see live on wandbox #include <boost/spirit/include/qi.hpp> namespace test { using namespace boost::spirit::qi; rule<std::string::const_iterator> rule = lit("data") > '{' > '}'; } int main() { std::string const input("data{"); bool ok = parse(input.begin(), input.end(), test::rule); } does throw expectation failure. even when using space skipper, still throws: see live on wandbox too #include <boost/spirit/include/qi.hpp> namespace t