Posts

Showing posts from July, 2015

javascript - How do I return the response from an asynchronous call? -

i have function foo makes ajax request. how can return response foo ? i tried return value success callback assigning response local variable inside function , return one, none of ways return response. function foo() { var result; $.ajax({ url: '...', success: function(response) { result = response; // return response; // <- tried 1 } }); return result; } var result = foo(); // ends being `undefined`. -> more general explanation of async behavior different examples, please see why variable unaltered after modify inside of function? - asynchronous code reference -> if understand problem, skip possible solutions below. the problem the a in ajax stands asynchronous . means sending request (or rather receiving response) taken out of normal execution flow. in example, $.ajax returns , next statement, return result; , executed before function passed success callback ...

javascript - jquery plugin add event listener -

i have jquery plugin have created, shows content , hides content in tab interface. wanting trigger event when content shown can listen in source code, , fire event based on possible? here plugin, $.fn.appstabs = function(options){ // these defaults. var settings = $.extend({ // these defaults. selected: "home" }, options ); // set active $(this).find('.pops-tabs-navigation li[data-route="'+settings.selected+'"]').addclass('active'); // hide boxes , show first 1 $(this).find('.apps-tabs-content .pops-tab-content').addclass('cloak'); $(this).find('.pops-tabs-content .pops-tab-content#content-'+settings.selected).removeclass('cloak'); // clicks on li in navigation $(this).find('.apps-tabs-navigation li').click(function(){ if($(this).hasclass('active') == false) { // id of tab id = $(this).attr('id'); tabid = 'content-'+id;...

ember.js - Chunk Ember Model Array -

i trying split model array of controller make easier display approach came not right. how access model array of controller can manipulated , still maintain computed properties of model? controller: export default ember.controller.extend({ queryparams: ['page'], page: "", playlists: ember.computed("model", function(){ var playlistcontent = this.get("model.content"); return _.chunk(playlistcontent, 3); }), actions: { setpage(page){ this.set("page", page); } }); template: {{#each playlists |playlistgroup|}} <div class="row"> {{#each playlistgroup |playlist|}} <div class="col-md-4"> <div class="card playlist-card"> <img class="card-img-top" src={{playlist._data.thumbnail}} alt="card image cap"> <div class="card-block"> <h4 class=...

How to update Chrome Extension without alerting the users -

how update chrome extension without alerting users? example have extension , must change everyday info in , don't want update app version or upload again when need change info in it.. how can make change info in chrome extension mean modify .html file without updating version? can use external web page show in extension , update info website everytime need updates? option too.. don't know if guys google extensions accept this. please me.

eclipse - Domino Designer 9.0.1FP3 Groovy Plugin -

we using domino designer 9.0.1fp3 , use groovy alternative java. as far know domino designer 9.0.1fp3 corresponds eclipse 3.4.2. unfortunately found no working download link update site or archive zip. we unsure, if getting eclipse 3.4.2 groovy plugin suffice groovy support in domino designer 9 running. pointers on how proceed appreciated... :-)

python - django- Use prefetch_related inside of another prefetch_related -

closest thing asking can found here say have following models: class division(models.model): name = models.textfield() state = models.integerfield() class team(models.model): name2 = models.textfield() division = models.foreignkey(division, ...) class player(models.model): name = models.textfield() hometown = models.integerfield() team = models.foreignkey(team, ...) now can following 1 table: players = player.objects.prefetch_related('team') how go adding state queryset? endgoal able player.team.division.state inside of template. other alternative use nested loops avoid that. you don't need prefetch_related here. can follow foreign keys player team division using select_related() . players = player.objects.select_related('team__division') a use-case prefetch_related if started division queryset, , wanted fetch related teams @ same time.

python - How to deliberately build bad URL with url_for() in unit tests? -

im writing unit tests api written in python flask. specifically, want test error handling routes work want deliberately build urls missing parameters. want avoid hard-coding using url_for() doesn't allow have missing parameters, how build bad urls ? when comes url_for generates 2 kinds of urls. if there named routes, like @app.route('/favorite/color/<color>') def favorite_color(color): return color[::-1] then url parameters required : url_for('favorite_color') builderror: not build url endpoint 'favorite_color'. did forget specify values ['color']? however, parameter not present in route converted querystring parameter: print(url_for('favorite_color', color='blue', no='yellooooowwww!')) /favorite/color/blue?no=yellooooowwww%21 so when ask url missing parameter, you're asking url has no route . can't build url that, because flask trying build parameters endpoints exist. the best can...

subprocess - Mapping Window Drives Python: How to handle when the Win cmd Line needs input -

good afternoon, i used version of method map dozen drive letters: # drive letter: m # shared drive path: \\shared\folder # username: user123 # password: password import subprocess # disconnect on m subprocess.call(r'net use * /del', shell=true) # connect shared drive, use drive letter m subprocess.call(r'net use m: \\shared\folder /user:user123 password', shell=true) the above code works great long not have folder file in use program. if run same command in cmd window , file in use when try disconnect drive returns are sure? y/n . how can pass question user via py script (or if nothing else, force disconnect code can continue run? to force disconnecting try /yes so subprocess.call(r'net use * /del /yes', shell=true) in order 'redirect' question user have (at least) 2 possible approaches: read , write standard input / output stream of sub process work exit codes , start sub process second time if necessary the f...

GNUradio: How to stream data in companion? -

this question exact duplicate of: gnuradio streaming between 2 computers? 3 answers i'd set gnuradio can remotely control system , stream data control computer. on 1 system there gnuradio program controlling radio dongle of kind, , on other side there gnuradio wx gui , control widgets. computer controller sends data radio computer, receives data dongle, streams control computer, displays on wx scope. i've been told zmq blocks kind of thing, unable receive data way, , person recommended found same problems, think block might broken @ moment. there other way using standard gnuradio blocks? in browser, open https://github.com/gnuradio/gnuradio/tree/master/gr-zeromq/examples select 1 of grc files clicking on it, save "raw" , open in gnuradio-companion. all examples should work correctly since sockets being opened on local computer. th...

image - PHP-GD Transparency of watermark PNG not correctly merged with JPEG -

Image
i trying install watermark in middle of image, every time shows weird square not transparent. result of code: this code: <?php header("content-type: image/png"); $image = imagecreatefromjpeg('http://www.sideshowtoy.com/wp-content/uploads/2016/03/dc-comics-batman-v-superman-woner-woman-sixth-scale-hot-toys-feature-902687.jpg'); $watermark = imagecreatefrompng('https://d5odq6jbm6umf.cloudfront.net/assets/img/video-play-button-transparent.png'); imagesavealpha($watermark,true); $watermark_width = imagesx($watermark); $watermark_height = imagesy($watermark); $dest_x = (imagesx($image) - $watermark_width)/2; $dest_y = (imagesy($image) - $watermark_height)/2; imagecopymerge($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height, 100); imagejpeg($image); imagedestroy($image); imagedestroy($watermark); ?> i create new true colour resource , copy it. ensures gd doesn't too quirky. it's little bit more resourc...

php - Ajax Not Executed -

i beginner ajax world , trying call contents php page using $.ajax() function , code couldn't executed. html page used: <!doctype html> <html> <head> <title>ajax</title> </head> <body> <div > <input type="text" name="search" id="search"> <br> <br> <h2 id="result"></h2> </div> <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-bbhdlvqf/xty9gja0dq3hiwqf8lacrtxxzkrutelt44=" crossorigin="anonymous"></script> <script src="js/script.js"></script> </body> </html> the jquery code used in script.js: $(document).ready(function() { $('#search').keyup(function () { var search = $('#search').val(); $.ajax({ url:'search.php', //the page request go ...

c# - Unity2D: How to lock my game for a certain amount of time sort of like candy crush -

hi have 2d topdown rpg game, , wanted know if there way of locking game amount of time (countdown) when player loses of hearts (lives). , no matter user can not access game until countdown has complete. candy crush when lose of lives. far i've got panel slides down, saying gameover, when player dies (when of hearts gone). i'm not sure how put lock on game amount of time, want user sill go main menu if game still lock. said before want similar candy crush saga if player loses live have wait amount of time play game. this script health script of player, can see game on panel linked ui manager: public int curhealth; public int maxhealth = 3; vector3 startposition; public playerhealth playerhealthref; float counter; public animator anima; // drag panel in here again private ui_managerscripts uim; private playerscript ps; void start () { curhealth = maxhealth; startposition = transform.position; ps = gameobject.findgameobjectwithtag("playerscript").ge...

javascript - Angular - how to set up click event on the start -

i want append click event li (list) elements (i have ordered list - ul). using angular controller. strange thing doesnt work. here's part of code setting event (inside angular controller): $document.ready(function () { $scope.getallnotes(); $scope.addsortable(); $scope.setevents(); //function call function click event li loader.hide(); $window.focus(); }) function click event: $scope.setevents = function () { jquery("#ulnotes li").click(function () { alert("you've clicked li!"); }); } i guess if doesn't work can still use iife, believe there must angular way this. don't use jquery angular tushar stated. html: <div ng-controller="samplecontroller"> <ul ng-repeat="item in items"> <!-- assuming you're looping through list' --> <li ng-click="clickfunction($index)">click me!</li> </ul> ...

ios - swift - Popover is not displayed correctly in landscape mode -

Image
popover takes complete screen when displayed in landscape mode, works correctly in portrait mode though. also, not disappear when click outside popover in landscape mode. i connected popover through storyboard. inside popoverviewcontroller placed view contains buttons. code viewdidload() of popoverviewcontroller is: override func viewdidload() { super.viewdidload() self.preferredcontentsize = popoverview.frame.size } override func didreceivememorywarning() { super.didreceivememorywarning() // dispose of resources can recreated. } portrait: landscape: you have add uipopoverpresentationcontrollerdelegate to class this: swift 3 import uikit class viewcontroller: uiviewcontroller, uipopoverpresentationcontrollerdelegate { ... as second step, add following function: func adaptivepresentationstyle(for controller: uipresentationcontroller, traitcollection: uitraitcollection) -> uimodalpresentationstyle { return uimodalpres...

amazon web services - PDF uploading to AWS S3 corrupted -

i managed generated pdf uploaded s3 node js server. pdf looks okay on local folder when tried access aws console, indicates "failed load pdf document". i have tried uploading via s3.upload , s3.putobject apis, (for putobject used .on finish checker ensure file has been loaded before sending request). file in s3 bucket still same (small) size, 26 bytes , cannot loaded. appreciated!!! var pdfdoc = printer.createpdfkitdocument(inspectionreport); var writestream = fs.createwritestream('pdfs/inspectionreport.pdf'); pdfdoc.pipe(writestream); pdfdoc.end(); writestream.on('finish', function(){ const s3 = new aws.s3(); aws.config.loadfrompath('./modules/awsconfig.json'); var s3params = { bucket: s3_bucket, key: 'insp_report_test.pdf', body: '/pdf/inspectionreport.pdf', expires: 60, contenttype: 'application/pdf' }; s3.putobject(s3params, func...

React-native error when running on android -

i'm new react-native, , i'm trying test app , running on phone. @ first, getting error couldn't find support library v4 (23.2.1), followed advice on stackoverflow post ( this one ) , copied android-support-v4.jar on extras/android/support/v4/ extras/android/m2repository/com/android/support/support-v4/23.2.1/ , renamed support-v4-23.2.1.jar . i'm getting error: what went wrong: problem occurred configuring project ':app'. could not find support-v4.aar (com.android.support:support-v4:23.2.1). searched in following locations: file:/c:/users/ritvik/appdata/local/android/sdk/extras/android/m2repository/com/android/support/support-v4/23.2.1/support-v4-23.2.1.aar any appreciated. thanks. there's typo when renamed file. renamed file support-v4-23.2.1.aar . look @ extension, should jar not aar .

android - Gradle is not compiling using ndkBuild -

i have android project configured in eclipse works ant , ndk-build customized android.mk , application.mk files. need move them android studio , don't want use cmake comes it, want keep old .mk files. started simple hello world example following code: here native-lib.cpp: #include <jni.h> #include <string> extern "c" { jstring java_com_comscore_android_app_mainactivity_stringfromjni( jnienv* env, jobject /* */) { std::string hello = "hello c++ lalalaaaaaa"; return env->newstringutf(hello.c_str()); } } and here gradle file: android { compilesdkversion 23 buildtoolsversion "24.0.1" defaultconfig { applicationid "com.comscore" minsdkversion 10 targetsdkversion 23 versioncode 1 versionname "1.0" testinstrumentationrunner "android.support.test.runner.androidjunitrunner" externalnativebuild { ndkbu...

groovy - Strange error highlighting 'instance method cannot override the static method' in Eclipse -

assume have such code in groovy: class base { static string name = 'base'; } class child extends base { string name = 'child'; static main(args){ def ch = new child(); println ch.name; } } eclipse mars 4.5.2 highlights there error: this instance method cannot override static method base i don't override static methods , executes expect, eclipse think wrong? the error message improved because you're doing here isn't related method (unless eclipse considering methods in generated java), it's related variable. also, groovy doesn't care code works, java wouldn't it. eclipse letting know defining instance variable in child has same name static variable in base . you should have static modifier in both classes. class child extends base { static string name = 'child' //... }

Issues calling Oracle stored procedure from C# -

this first time have ever had call oracle stored procedure c# , don't know why code not working. trying return datatable. stored procedure compiles fine - here pseudocode describing it: create or replace procedure sproc_online ( year in number default null , name in varchar2 default null , id in varchar2 default null , refcursor out sys_refcursor ) begin open refcursor select * table field_year = year , field_name = name , field_id = id; end sproc_online; here pseudocode describing c#: public static datatable search(int? year, string name, string id) { try { oracleconnection conn = getconnectionstring(); oraclecommand cmd = new oraclecommand(); cmd.connection = conn; cmd.commandtext = "sproc_online"; cmd.commandtype = commandtype.storedprocedure; cmd.parameters.add("year", oracledbtype.int32).value = year; cmd.parame...

python 2.7 - Can't get counter to compare first letter of word against A-Z alphabet -

what i'm trying compare first letter of each word against lower case a-z alphabet , print (similar word_frequency) how many times word starts each letter of alphabet (such this) a = 0 b = 2, c = 0, d = 2 ------------ y = 1, z = 0 but unable find way through counter of yet or found worked me (beginner). idea had along lines of w in word_count: l_freq = [] l_freq.append(w[0]) and comparing counter against it? not sure how compare against whole alphabet rather letters in string? also, there way print frequency cleaner? without counter , brackets showing up? from collections import counter def function(): string = "this string written in python." word_count = string.split() char_count = 0 char in string: if char != " " , char != ".": char_count += 1 word_freq = counter(word_count) print "word count: " + str(len(word_count)) print "average length of wor...

javascript - JQuery Selector not working, where looping does. Why? -

i have 2 jquery selectors used did not find desired option third "brute force" method did. @ complete loss why. each looked should of , validated document loaded when selector ran. tried each value , text in selector , got same result in page. html dynamically loaded using jquery load method below (where thetype value coming html select control) associated javascript: var thetype = $('#tickettype option:selected').val(); var theid = $("#id").val(); var url = '/systembuildsiteconfigs/' + thetype + '/' + theid; $('#ticketdiv').html(""); $("#ticketdiv").load(url, function (response, status, xhr) { if (status == "error") { alert("there error loading " + thetype + " form"); } else { $.getscript("/scripts/siteconfig" + thetype + ".js", function () { }); } }); the html select in question: <select name="suppor...

OOP techniques with Python GUI (PySide) elements -

objective: create line item object contains textbox label, value, , value units in pyside. background: creating control panel device run off of raspberry pi using python pyside (qtpython) handle gui. using grid layout, , have common motif trying encapsulate in class avoid repeating myself. need building class. typically, code looks this: class form(qdialog): def __init__(self, parent=none): super(form, self).__init__(parent) self.pressure_label = qlabel('pressure:') self.pressure_value = qlabel() self.pressure_units = qlabel('psi') self.temperature_label = qlabel('temperature:') self.temperature_value = qlabel() self.temperature_units = qlabel('oc') ... grid = qgridlayout() grid.addwidget(pressure_label, 0, 0) grid.addwidget(pressure_value, 0, 1) grid.addwidget(pressure_units, 0, 1) grid.addwidget(temperature_label, 1, 0) g...

asp.net - How to save a null datetime to SqlServer DB? not working -

Image
vs-studio 2012 web express, asp.net, webforms , vb , sqlserver , website application having trouble saving null value datetime typed row: dim orowvehicles main_tbladap.tvehiclesrow = odtvehicles.rows(0) ' (0) first row. orowvehicles.[welectrical] = if(welectrical.year < 10, dbnull.value, welectrical) ...etc... currently detailsview template field textbox < blank> or empty or "" , bll function shows date like: #01/01/0001#. test year value of passed in variable if less 10 save dbnull.value orowvehicles.[welectrical] fails since datatype=date , cannot convert dbnull date. the db-field type date , allows nulls. the tableadapter.xsd view shows default value < dbnull>. so, why orowvehicles not date nullable? how make welectrical column nullable date? i must overlooking something, because cannot 1 save optional date value sql-db. your comments , solutions welcome. thanks...john edit aspx code 1 date field in detailsview (oth...

javascript - Adobe Analytics DTM custom script prop not setting -

i trying show last time made published change , current library version i created data element global - example: return "dtm:" + _satellite.publishdate.split(" ")[0] + "|" + "adobe:" + s.version; then set prop %global - example%. it doesn't work. tried debug in console. when console.log("dtm:" + _satellite.publishdate.split(" ")[0] + "|" + "adobe:" + s.version); works in console , the last publish date , current version of library. however, won't work reason in dtm. using data element in case have impact on timing. if add code adobe analytics custom code section of rule or aa global code should able set prop fine. s.prop1 = _satellite.publishdate.split(" ")[0] + "|" + "adobe:" + s.version); hope helps.

php - How do I modify this tree node insertion logic to result into a balanced binary tree? -

Image
i new coding trees. given following input array - array(10,7,13,5,6,8,11,15,14,4,3,16) i prepare balanced binary tree inserting these values 1 one, starting first element (left child of node should inserted, right child, next node should checked insert it's left , right children. insertions should happen level first, before inserting higher level). result should appear - here code have (modified bit bst code found here ) <?php class node { public $left; public $right; public $data; public function __construct($data) { $this->data = $data; $this->right = null; $this->left = null; } } //end class node class btree { public $root; public function __construct() { $this->root = null; } /* insert first node bst*/ public function insert($data) { $node = new node($data); if($this->root === null) $this->root = $node; else ...

c# - How to add new table in context ASP.NET MVC -

please, me. had file imagecontext: using system; using system.collections.generic; using system.linq; using system.web; using system.data.entity; namespace usergallery.models { public class imagecontext : dbcontext { public dbset<image> images { get; set; } } } i create new model slide , add string connect in imagecontext. result ... public class imagecontext : dbcontext { public dbset<image> images { get; set; } public dbset<slide> slides { get; set; } } ... how update database create table slides? screenshoot database table: enter image description here if have automatic migrations set should pretty straight forward. if haven't, need run enable-migrations –enableautomaticmigrations perhaps further reading here first though: http://msdn.microsoft.com/en-gb/data/jj554735.aspx create new migration addition of slides add-migration "slidemigration" now update... , should work. ...

C++ 11 to C# code Conversion issue -

i trying convert following c++11 code c# using visual studio 2012: typedef enum { _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n,_o,_1,_2,_3 } tkeyidentity; typedef std::vector<tkeyidentity const> tkeypath; typedef std::vector<tkeypath const> tkeymap; const tkeymap keypad = { { _h, _l }, // { _i, _k, _m }, // b { _f, _j, _l, _n }, // c { _g, _m, _o }, // d { _h, _n } // e } const tkeypath keypadroot = { _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _1, _2, _3 }; traversekeypaths( tkeypath const &keypath, int pressesremaining, int vowelsallowed ) { ( auto pressedkey: keypath ) { int value = traversekeypaths(keypad[ pressedkey ],pressesremaining, vowelsallowed - isvowel[pressedkey] ); } } the complete c++ code available : http://lucid-motif.blogspot.com/2013/11/coding-puzzle-knight-sequences.html c# code: enum tkeyidentity { _a, _b, _c, _d, _e, _f, _g, _h, _i,...

git - Is it possible to include a file in your .gitconfig -

i'd include file in .gitconfig has github settings - possible? can this: [core] include = /path/to/file git (1.7.10+) supports syntax in .gitconfig : [include] path = /path/to/file see here detailed description of git change , edge cases. by way, couple of subtleties worth pointing out: environment-variable expansion, e.g. $home , not supported. (expansion of ~ appeared in git 1.7.10.2.) if relative path specified, relative .gitconfig file has [include] statement. works correctly across chained includes -- e.g. ~/.gitconfig can have: [include] path = subdir/gitconfig and subdir/gitconfig can have: [include] path = nested_subdir/gitconfig ... cause subdir/nested_subdir/gitconfig loaded. if git can't find target file, silently ignores error. appears design.

Android SDK Custom Keyboard, setting background and text colors: of a single key -

here code: public class customkeyboardview extends keyboardview { public customkeyboardview(context context, attributeset attrs) { super(context, attrs); } @override public void ondraw(canvas canvas) { super.ondraw(canvas); paint paintbackground = new paint(); paintbackground.settextalign(paint.align.center); paintbackground.settextsize(48); paintbackground.setcolor(color.yellow); list<key> keys = getkeyboard().getkeys(); for(key key: keys) { if(key.label != null && key.codes[0] == 110) canvas.drawrect(key.x, key.y, key.x+key.width, key.y+key.height, paintbackground); paintbackground.setcolor(color.white); canvas.drawtext(key.label.tostring(), key.x + (key.width / 2), key.y + (key.height / 2), paintbackground); } } } the strange thing if comment out canvas drawrect or canvas drawt...

c++ - Variable class/struct structure? (Not template & not union?) -

i have tried union... struct foo { union { struct // 2 bytes { char var0_1; }; struct // 5 bytes { char var1_1; int var1_2; }; }; }; problem: unions want, except take size of biggest datatype. in case need struct foo have initialization allows me tell structure chose of 2 (if legal) shown below. so after that, tried class template overloading... template <bool b> class foo { } template <> class foo<true> { char var1; } template <> class foo<false> { char var0; int var1; } problem: happy templates , fact use same variable name on char , int, problem syntax. because classes created on compile-time, template boolean variable needed hardcoded constant, in case boolean needs user-defined on runtime. so need of 2 "worlds." how can achieve i'm trying do? !!note: foo class/struct later inherited, therefore mentioned, size of...

clearcase - windows process waiting for lsass -

my company using clearcase on linux server , development environment under linux , windows 7. windows 7 machines snapshot only. problem have windows only. for each clearcase command under windows, there lot of latency. noticed process lsass.exe when ressource monitor/analyze wait chain of cleartool process. wait of cleartool on lsass cuase latency going 50 sec 1 minute the problem not occur users , not time. when problem not occur cleartool process has no process on analyze wait chain. have clearcase 8 set on server , clients version 7 or 8 . we pretty sure not clearcase problem. i information lsass , see cause wait on lsass.exe lsass local security authority subsystem service , process in microsoft windows operating systems responsible enforcing security policy on system. i have seen issues in pass when anti-virus analyzing clearcase views. try , deactivate many process/service possible in order see if cleartool commands still experience kind of latency....

sql - Attaching file for a SAS program -

i new sas , tried performing simple query on sas enterprise guide. program follows: libname iss meta library="sql - iss" metaout=data; proc sql; select * market_option_day contract_market_code = '023a61' , report_date between '1/1/13' , '6/30/15'; quit; the error im getting following : file work.market_option_day.data not exist. i dont understand whats wrong because can view file in "sql-iss" library if file located in library, need prefix library name. proc sql; select * iss.market_option_day /* other stuff here ...*/ ; quit; for example.

php - Custom post format for custom post type : Wordpress -

i have custom post type floors , need make dropdown several templates (2templates) standard floors , garage floors. in posts can make several .php files code in head /* template name posts: # article post */ , dropdown automatically creating in backend. in custom post type add in head /* single post template: floors */ this code , no dropdown creating, no reaction. how can same custom post types, , in format must .php file. have 1 single-floors.php , need garage-singlefloors.php. happy every answer! you can use built-in post formats custom post types using add_post_type_support( $post_type, $supports ) . see related documentation in codex.

python - how to automatically update pyserial to latesT? -

i have following code raise exception when pyserial version less 2.7,how programatically run pip install pyserial --upgrade automatically update latest version , ensure installed correctly? if py_ser_ver < 2.7: raise standarderror("pyserial version 2.7 or greater required. version is: " + serial.version) use os.system('python -m pip install pyserial --upgrade') or use subprocess then once installation complete, check using python -m pip list command. work if pip not in path. import os import subprocess = os.system('python -m pip install pyserial --upgrade') if == 0: d = subprocess.popen('python -m pip list', stdout = subprocess.pipe).communicate() if 'pyserial' in d[0]: print 'success'

pdf - Rails app with Prawn and PDFKit, Prawn no longer working -

i have rails app generates pdfs using prawnto_2 . somewhere else in app wish generate pdfs using pdfkit . after installing pdfkit (and wkhtmltopdf-binary ), prawn generated pdf no longer renders. it issue using pdfkit middleware. (which renders file pdf writing .pdf after url is possible have app both installed? suggestions. first solution: disabled pdfkit middleware second solution: uninstalled pdfkit , installed wicked_pdf.

ruby - Asterisk Outgoing call file unresponsive -

i've made basic ruby program makes call files , sends them on outgoing file asterisk. outbound = [<phone numbers>] number in outbound call_file = file.new("#{number}.call", "w") call_file.puts("channel: sip/ext-sip-account/#{number}", "context: test", "extension: 100") call_file.close file.rename "#{number}.call", "/var/spool/asterisk/outgoing/#{number}.call" end running file creates file , moves destination asterisk doesn't read file or delete it.

refactoring - Refactor code to remove duplicate code -

i have several classes share common logic. example, class addemployee responsible adding employee api. addlocation responsible adding location of person. classes following : class addemployee { public function add() { $apiurl = "https://api.abc.com/employees";; $authparameters = array( 'oauth_consumer_key' => $this->consumer_key, ); $xml .= <<<eom <superfund> <abn>$obj->abn</abn> <type>regulated</type> </superfund> eom; $queryparameters = array( 'xml' => $xml ); $response = $this->processsrequestandgetresponse('post',$apiurl,$authparameters,$queryparameters,$oauth_secret); return $response; } } class addlocation { public function add() { $apiurl = "https://api.abc.com/locations";; ...

javascript - Loading image not displaying on Safari 7/8/9 on form submission -

i representing common issue here weird behavior. hoping mistake cleared out or solution. trying show loading image upon submission of form clicking button. using simple htmls , javascript on jsp page. below code reference - <input type="button" onclick="submitform('myaction','mycontext')" /> <div id="progressbar" style="display:none;"> <img id="gifimg" src="../images/load.gif"> </div> function submitform(action, originalcontext){ document.getelementbyid('progressbar').style.display='block'; document.forms[0].action = document.forms[0].action + "?method=" + action + "&originalcontext=" + originalcontext; document.forms[0].submit(); return; } issue - above code works fine in universe except safari 7, 8, 9 on mac 10.9, 10.10, 10.11 respectively. appreciate if can , suggest. thank :) are browsers angry onclick attr...

winapi - Detect SetWindowsHookExA WH_MOUSE_LL detachment / unhooking -

i have little python script collects statistics keyboard , mouse usage on windows machine. i set via windll.user32.setwindowshookexa(win32con.wh_mouse_ll, mouse_pointer, win32api.getmodulehandle(none), 0) . write can see api i'm using. have been c++ programm. it works fine, 1 exception: when use android studio compile app, core i7 4 cores maxes out @ 100% on cores, mouse , os in general becomes unresponsive, known issue android studio. usually when such high cpu load occurs couple of seconds (4+) wh_mouse_ll hook gets detached os, if it's saying "nope, don't have time you, we're unregistering you" i don't blame on python, because have sound volume manager called powermixer apparently registers mouse hook can track mouse scroll wheel actions on lower taskbar (explorer.exe shell_traywnd) , application looses it's ability use mouse hook after compiling. also, when compiling , scroll scroll wheel (just fun) computer starts beep, in low level...

javascript - Why is index.html being treated as JSON? Unexpected token < at position 0 -

i trying use qunit make unit tests html. error i'm getting uncaught syntaxerror: unexpected token < in json @ position 0 . it's pointing "<" in <!doctype html> isn't json, thinks is, i'm not sure why. <!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>pinpoint test</title> <link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.0.0.css"> <script type="text/javascript" src="https://code.jquery.com/qunit/qunit-2.0.0.js"></script> <script type="text/javascript" src="lib/jquery-3.0.0.min.js"></script> <script type="text/javascript" src="jshamcrest.js"></script> <script type="text...

rust - What ways exist to create containers of several types? -

this question has answer here: what best way create heterogeneous collection of objects? 1 answer i know ways have container containing several types. know that: a tuple can contain several types if create enumeration e , can create vec<e> . in c++, can create vec<a*> containing both b* , c* elements if b , c inherit a . can similar in rust? instance, if several types implement same trait? 1) can store references or pointers trait objects. 2) can create enum on things want store.

Swift Protocol Arrays Adding vs. Instantiating -

in swift 3.0 xcode beta 3, defined simple protocol , 2 structs implement it, if initialize array when creating objects, works, if try add elements error: cannot convert value of type '[h]' expected argument type 'inout _' shouldn't work? protocol h { var v : int { set } func hello() } struct j : h { var v : int func hello() { print("j") } } struct k : h { var v : int func hello() { print("k") } } let ag:[h] = [k(v:3), j(v:4)] // works ag[0].hello() ag[1].hello() var af:[h] = [] af += [k(v:3)] // not work af += [j(v:4)] // not work af[0].hello() af[1].hello() it's type issue. need things add af same type af , namely [h] : var af:[h] = [] let arr1:[h] = [k(v:3)] let arr2:[h] = [j(v:4)] af += arr1 af += arr2

Postgresql: Set variable equal to a specific entry in an array -

i have table newb looks this: tablename | columnname ----------------------- walls | id floors | rowid first create array: create table finalsb ( tabnam newb array ); then put data table array: insert finalsb values(array(select newb newb)); the following statement displays 'id' table newb: select tabnam[1].columnname finalsb; i want like: declare colvar varchar,tabvar varchar colvar = select tabnam[1].columnname finalsb; tabvar = select tabnam[1].tablename finalsb; my main goal use: select * tabvar colvar = "somevalue"; can tell me how can declare select statement variable? you have use select ... variable construct: do $$ declare colvar varchar; tabvar varchar; begin select tabnam[1].columnname colvar finalsb; select tabnam[1].tablename tabvar finalsb; raise notice 'tabvar: %, colvar: %', tabvar, colvar; end $$; to run dynamic sql plpgsql's execute needed: execute format(...