Posts

Showing posts from September, 2012

Windows Batch file - taskkill if window title contains text -

i want write simple batch file kill process contains text in window title. right have: taskkill /fi "windowtitle eq xxxx*" /im cmd.exe and works, except want use wildcard both @ beginning , end of title. like: taskkill /fi "windowtitle eq \*x*" /im cmd.exe but tried , not work. there i'm missing or not possible? no, wildcards not allowed @ start of filter. for /f "tokens=2 delims=," %%a in (' tasklist /fi "imagename eq cmd.exe" /v /fo:csv /nh ^| findstr /r /c:".*x[^,]*$" ') taskkill /pid %%a this retrieve list of tasks, in csv , verbose format (that include window title last field in output). the list filtered findstr regular expression search indicated text (the x ) in last field. if line matches filter, for tokenize it, retrieving second field (the pid) used in taskkill end process.

javascript - Get data from a reactive container -

from docs , need use reactive data container around component retrieve logged in user (if 1 exists), how data container? import { meteor } 'meteor/meteor'; import react, { component } 'react'; import { createcontainer } 'meteor/react-meteor-data'; export default foocontainer = createcontainer(() => { return { user: meteor.user() }; }, class foocomponent extends component { render() { return (<div>{ /* this.data.user ??? */ }</div>); } }); how data returned container function inside render method? i see returned user key in container, therefore data accessible via this.props.user prop in component. just make sure add container: export default foocontainer = createcontainer(() => { const subscription = meteor.subscribe("userdata"); subscription.ready() ? session.set("dataready", true) : session.set("dataready", false); return { user: meteor.user() }; } and in rende

jquery - How to create only one li element per call to d3.append? -

Image
i'm passing in name of checkbox option in jquery d3 in order render new tab li element same name. but tried passing in option name eg, "option1" creates new tab each letter in string using .data(val) option. so in example below val = "option1" , create tab this: d3.select("ul#charttabs") .selectall("li") .data(val) .enter() .append('li') .insert("a", ":first-child") .attr("data-toggle", "tab") .attr("id", function(val, i){ var result = val + i; return result; }) .text(function(d){ return d; }) question: how can create 1 tab per call d3.append? this current output when passing in val "option1" . not expected creates new tab each letter. instead of single button value option1. d3 coercing string array, use .data([val]) ,

Reading hex to double-precision float python -

i trying unpack hex string double in python. when try unpack following: unpack('d', "4081637ef7d0424a"); i following error: struct.error: unpack requires string argument of length 8 this doesn't make sense me because double 8 bytes long, and 2 character = 1 hex value = 1 byte so in essence, double of 8 bytes long 16 character hex string. any pointers of unpacking hex double super appreciated. you need convert hex digits binary string first: struct.unpack('d', "4081637ef7d0424a".decode("hex")) or struct.unpack('d', binascii.unhexlify("4081637ef7d0424a")) the latter version works in both python 2 , 3, former in python 2

javascript - How to test if a template has rendered for a iron:router route in a mocha test? -

in meteor app, want able test if template has rendered specific route/path. current setup includes following: iron:router, practicalmeteor:mocha, , using blaze rendering. there 2 issues in particular cannot work: waiting route finish without using settimeout (i prefer callback of sort) figuring out whether or not blaze template has rendered on page. how can test if template has rendered after calling router.go() ? import { router } 'meteor/iron:router'; import { template } 'meteor/templating'; import { chai } 'meteor/practicalmeteor:chai'; router.route('/example', { name: 'exampletemp' }); describe('example route', function() { it('renders template exampletemp', function() { router.go('/example'); // not sure put here wait route finish // don't know how achieve function below chai.assert.istrue(template.exampletemp.isrendered()); }); }); this isn't

javascript - React/Meteor init function when data is fully rendered -

Image
i have following react component, subscribes mongodb loads images , returns page. export default class portfolio extends trackerreact(react.component) { constructor(props) { super(props); this.state = { subscription: { albumbs: meteor.subscribe('albums') } } } componentwillunmount() { this.state.subscription.albums.stop(); } albums() { return albums.find().fetch(); } render() { function init () { $('.carousel').flickity({ // options "lazyload": true }); }; return ( <reactcsstransitiongroup component='div' classname='carousel' transitionname='postload' transitionleavetimeout={2000} transitionentertimeout={2000}> {this.albums().map( (album) => { return <div classname='carousel-cell' key={album._id}><albumcover albums={album} /></div> })} {init()} </reac

swift - List all mounted Volumes in a Menu Bar Submenu (programmatically only) -

i'm working on "menu bar only" project , need list mounted volumes in submenu in menubar app. figured out how print() mounted volumes need submenu (without .xib or .storyboard work) "listvolumes func" func listvolumes(sender: nsmenuitem) { let keys = [nsurlvolumenamekey, nsurlvolumeisremovablekey, nsurlvolumeisejectablekey] let paths = nsfilemanager().mountedvolumeurlsincludingresourcevaluesforkeys(keys, options: []) if let urls = paths { url in urls { if let components = url.pathcomponents components.count > 1 && components[1] == "volumes" { print(url) } } } } an below code "menu bar app" let statusitem = nsstatusbar.systemstatusbar().statusitemwithlength(-2) func applicationdidfinishlaunching(anotification: nsnotification) { if let button = statusitem.button { button.image = nsimage(named: &q

Arabic characters doesn't show properly in JavaScript -

when add arabic characters in javascript, not showed properly. guess ascii problem. suggestions? javascript document.getelementbyid('div-msg').innertext = "اسم المستخدم لا يمكن أن تترك فارغة"; html <html> <head> </head> <body> <div id="div-msg" style="width:100%; height:200px; background:yellow"> </div> <script type="text/javascript"> document.getelementbyid('div-msg').innertext = "اسم المستخدم لا يمكن أن تترك فارغة"; </script> </body> </html> i have met issue when tried write turkish characters. solution simple. first, move javascript code external script file. second, add script html charset attribute below <script src="external_script.js" charset="utf-8" type="text/javascript"></script>

Embedded NoSQL DB for .NET Core -

what best choice embedded nosql db used .net core application (could built run in linux)? so in summary, requirements: can used in .net core application (asp.net 5 mvc), , compiled run in linux. nosql, document-based. embedded, not require server installation, can deployed application.

plone - Installation of collective.autopublishing -

i want use collective.autopublish set outdated plone pages private. goal set plone pages private after expiration date automatically. (similar problem described here ) i installed collective.autopublish , can configure in web interface. should use collective.timedevents extension triggered. added , tried install using readme file. told me add zope clock-server triggering events, did according code snippet on page. [instance] ... zope-conf-additional = <clock-server> method /mysite/@@tick period 90 user clockserver-user password password host localhost </clock-server> i changed mysite plone url. clock-server seems work, got http calls /mysite/@@tick page every 90 seconds, resulting in 404 errors, nothing triggered collective.timedevents. did miss or wrong documentation? should work? btw: registered handler collective.autopublish itickevent. i'm unable answer question directly can provide more simpler solution problem. as see,

variables - Where is a list of all of python's `__builtin__` datatypes? -

i'm using comparisons like: if type( self.__dict__[ key ] ) str \ or type( self.__dict__[ key ] ) set \ or type( self.__dict__[ key ] ) dict \ or type( self.__dict__[ key ] ) list \ or type( self.__dict__[ key ] ) tuple \ or type( self.__dict__[ key ] ) int \ or type( self.__dict__[ key ] ) float: i've once discovered, i've missed bool type: or type( self.__dict__[ key ] ) bool \ , okay - wondered other types missed? docs.python.org - there no table types... i've started googling: diveintopython3 : python has many native datatypes. here important ones: booleans either true or false. numbers can integers (1 , 2), floats (1.1 , 1.2), fractions (1/2 , 2/3), or complex numbers. strings sequences of unicode characters, e.g. html document. bytes , byte arrays, e.g. jpeg image file. lists ordered sequences of values. tuples ordered, immutable sequences of values. sets unordered bags of values. dictionaries unordered

java - Liquibase: How to identify change set only basis ID? -

as per liquibase documentation: each changeset tag uniquely identified combination of “id” tag, “author” tag, , changelog file classpath name. this seems poor design choice. identity of changeset shouldn't linked location. if changelog run via automatic application deployment changeset come classpath location within jar file. if want run same changesets commandline manually, location might current directory. in case instead of recognizing changeset same based on id liquibase try apply twice. is there way change behavior , have identify changesets basis specified id? i suggest using logicalfilepath attribute of databasechangelog tag. this gives more freedom change directory structure of project. prevents file name being stored absolute path (which might happen in circumstances).

elasticsearch - How to define seperated indexes for different logs in Filebeat/ELK? -

i wondering how create separated indexes different logs fetched logstash (which later passed onto elasticsearch ), in kibana , can define 2 indexes them , discover them. in case, have few client servers (each of installed filebeat ) , centralized log server ( elk ). each client server has different kinds of logs, e.g. redis.log , python logs, mongodb logs, sort them different indexes , stored in elasticsearch . each client server serves different purposes, e.g. databases, uis, applications. hence give them different index names (by changing output index in filebeat.yml ?). in filebeat configuration can use document_type identify different logs have. inside of logstash can set value of type field control destination index. however before separate logs different indices should consider leaving them in single index , using either type or custom field distinguish between log types. see index vs type . example filebeat prospector config: filebeat: prospectors

gwt - Workaround for known timestamp bug of *.nocache.js files (for Windows / without Maven) -

in gwt 2.7 there known bug *.nocache.js files, not getting actual timestamp while compiling timestamp of module file (see this ). for gwt-maven-plugin there workaround commited ( see compilemojo.java ). for projects not built maven wanted ask, if knows "maven-free" , automated solution workaround?! what i'm doing right know touching file on linux server find /my/path/ -name '*.nocache.js' -exec touch {} \; && which working fine right now. can use copy /b filename.ext +,, on windows, wanted know if knows automated workaround compilation issue in gwt 2.7 (with eclipse) you can install "touch" command on windows , keep using current script. you can find number of implementations of touch windows, here open source one: https://sourceforge.net/projects/touchforwindows/

java - Classcast Exception while running Projection count query in hibernate -

i using hibernate 4.3.1 final version of hibernate. in hibernate mapping file have defined property integer. eg: <property name= "jobno" type="integer"> database used db2. in jobno column defined integer . when trying retrive count of jobno using projection api as: criteria.setprojection(projections.count(jobno)); criteria.uniqueresult(); it returning long . ideally, should returned integer . i new can me on? it returning long. ideally, should returned integer. you have not hand on it. it's handled jpa implementation (hibernate here). if know value returned count cannot exceed integer max value (2147483647), should not problem. can convert long integer. if have doubt, can check long value doesn't exceed integer max value. anyway, advise cast number rather long , may avoid surprise if change jpa implementation. int jobno = ((number)criteria.uniqueresult()).intvalue();

php - How to get last inserted value for each sender? -

i know can last inserted id using $insertedid = $user->id; i'm trying last inserted value in view each sender sends data. inbox shown last message sent sender. how can show in view? this post messaging happens. public function postmessage(request $request) { $this->validate($request, [ 'recipient' => 'required', 'message' => 'required|max: 2000', ]); $message = new message(); $message->message_content = $request->message; $message->save(); $user = auth::user(); foreach($request->recipient $recipientid) { $message->users()->sync([ $recipientid => ['sender_id' => $user->id]],false ); } return redirect()->back(); } retrieving values. i'm done here far retrieve user's message. still don't have idea how last inserted. how can achieve this? public function getmessage() { $recipientlists = db::table('u

python - Groupby and any() | all() -

i have following pd.dataframe in [155]: df1 out[155]: order_id acq date uid 2 3 false 2014-01-03 1 3 4 true 2014-01-04 2 4 5 false 2014-01-05 3 6 7 true 2014-01-08 5 7 8 false 2014-01-08 5 9 10 false 2014-01-10 6 0 11 false 2014-01-11 6 where each entry order, values order_id , date , uid , acq (indicates whether first order associated uid in dataset). i trying filter , keep orders placed users have made first order inside time period covered in dataset (i.e. @ least 1 of orders of such users satisfy acq == true ). so, desired output be: order_id acq date uid 3 4 true 2014-01-04 2 6 7 true 2014-01-08 5 7 8 false 2014-01-08 5 and have managed reach by: in [156]: df1.groupby('uid').filter(lambda x: x.acq.any() == true) out[156]: order_id acq date uid 3 4 true 2014-01-04 2 6 7 true 2014-01-0

java - Issue with UNSIGNED BIGINT of MySQL while fetching using JDBC client -

as per mysql docs , maximum value unsinged bigint = 18446744073709551615 i inserted value 9223372036854776900 ( far lower max limit ) in unsinged bigint column. no error shown. when tried access programmatically via jdbc client, got exception: com.mysql.jdbc.exceptions.jdbc4.mysqldataexception: '9223372036854776900' in column '10' outside valid range datatype bigint. @ sun.reflect.nativeconstructoraccessorimpl.newinstance0(native method) @ sun.reflect.nativeconstructoraccessorimpl.newinstance(nativeconstructoraccessorimpl.java:62) @ sun.reflect.delegatingconstructoraccessorimpl.newinstance(delegatingconstructoraccessorimpl.java:45) @ java.lang.reflect.constructor.newinstance(constructor.java:422) @ com.mysql.jdbc.util.handlenewinstance(util.java:411) @ com.mysql.jdbc.util.getinstance(util.java:386) @ com.mysql.jdbc.sqlerror.createsqlexception(sqlerror.java:1026) @ com.mysql.jdbc.sqlerror.createsqlexceptio

python - sympy.geometry Point class is working slow -

i have code reads unstructured mesh. wrote wrappers around geometric entities of sympy.geometry such as: class point: def __init__(self, x, y, parent_mesh): self.shape = sympy.geometry.point(x,y) self.parent_mesh = parent_mesh self.parent_cell = list() everything works fine initialization of sympy.geometry.point takes lot of time each point . actually, code did not finish execution thousands of points. similar code written in c++ finished in few seconds. without code fast enough (i removed , timed). read possible reason sympy.geometry converts floating point numbers rationals precision. there way (flag) speed sympy.geometry not need exact precision? take @ point class documentation , specifically, in 1 of first examples: floats automatically converted rational unless evaluate flag false . so, pass flag named evaluate during initialization of point classes: self.shape = sympy.geometry.point(x,y, evaluate=false) which appare

php - Use a class static variable as part of a closure use list -

i "use" static class variable part use list statement of closure ? following snippets fail unexpected 'self' parse errors. array_walk($_categories, function($c, $i) use (&self::$tree) { or array_walk($_categories, function($c, $i) use (self::&$tree) { parse error: syntax error, unexpected 'self' (t_string), expecting variable (t_variable) is there special syntax use in special case ? why on earth want that? given use of self , closure defined within class somewhere, you're able access static member anyway: class foo { protected static $bar = 123; public function test() { return function($x) { static::$bar += $x; // or self::$bar return static::$bar; }; } } $x = new foo; $y = $x->test(); var_dump($y(1));//int(124) var_dump($y(2));//int(126) no need muck references @ all... if you're on eol'ed version of php (5.3 example), work around problem a

json - Golang interface{} type misunderstanding -

i got bug in go when using interface{} function parameter type, when given non-pointer type, , using json.unmarshal it. because piece of code worth thousand words, here example: package main import ( "encoding/json" "fmt" ) func test(i interface{}) { j := []byte(`{ "foo": "bar" }`) fmt.printf("%t\n", i) fmt.printf("%t\n", &i) json.unmarshal(j, &i) fmt.printf("%t\n", i) } type test struct { foo string } func main() { test(test{}) } which outputs: main.test *interface {} map[string]interface {} json.unmarshal turns struct map[string]interface{} oo... little readings later explains of it, interface{} type in itself, not sort of typeless container, explains *interface{} , , fact json.unmarshal not initial type, , returned map[string]interface{} .. from unmarshal docs: to unmarshal json interface value, unmarshal stores 1 of these in interface

ios - AVCaptureStillImageOutput Image orientation is wrong -

i'm running avcapturesession still images on user action (button press). i've problem orientation rotated 90 degree although set values : - (void)setupavcapture { //capture session _session = nil; _session = [[avcapturesession alloc] init]; [_session setsessionpreset:avcapturesessionpreset1280x720]; //preview view self.previewlayer = nil; self.previewlayer = [[avcapturevideopreviewlayer alloc] initwithsession:_session]; [self.previewlayer setvideogravity:avlayervideogravityresizeaspectfill]; calayer *rootlayer = [_previewview layer]; [rootlayer setmaskstobounds:yes]; [[_previewlayer connection]setvideoorientation:avcapturevideoorientationportrait]; } and - (ibaction)captureimage:(id)sender { avcaptureconnection *stillimageconnection = [stillimageoutput connectionwithmediatype:avmediatypevideo]; [stillimageconnection setvideoorientation:avcapturevideoorientationportrait]; [stillimageoutput capturestillimageasynchro

visual c++ - Adding references of Casablanca Libraries -

i unable find references of casablanca libraries visual studio , online source, need references of these 2 libraries, http_client.h , filestream.h i using visual studio 2013 , can please tell me can download references of these libraries? i grateful problem resolved when installed vs 2015 enterprise, , in here don't need add references, install casablanca packages in project.

python - How to handle > (&gt;) symbol in Django forms -

in mysql table row (utf-8) have both &gt; , < . < used html , &gt; text within html. the problem is, keep getting error: djangounicodedecodeerror: 'utf8' codec can't decode byte 0xa3 what should do?

php - pgsql string escape when inserting -

i new postgresql, trying insert html code data base text cant inserted such single quotes example. looking code me "trim" or allow allow characters inserted. have tried following code didnt work. $title= $_post['title']; $intro= $_post['intro']; $content= $_post['content']; $category= $_post['category']; $sort_footer = 24; //insert code $stmt = $dbh->prepare("insert content(title, intro, content, category, sort_footer ) values ( :title, :intro , :content , :category ,:sort_footer ) "); $stmt->bindparam(':title', $title); $stmt->bindparam(':intro', $intro); $stmt->bindparam(':content', $content); $stmt->bindparam(':category', $category); $stmt->bindparam(':sort_footer', $sort_footer); $stmt->execute();

arrays - Filter SwiftyJson Data -

i have json data. array of dictionaries swiftyjson array called jsonobj["customer"] , looks like: [{ "kode_customer": 1, "nama_customer": "logam jaya, ud", "alamat_customer": "rajawali no 95", "kodepos": 60176, "kode_provinsi": 11, "gps_lat": -7.233834999999999, "gps_long": 112.72964666666667 }, { "kode_customer": 2, "nama_customer": "terang, tk", "alamat_customer": "raya dukuh kupang 100", "kodepos": 60225, "kode_provinsi": 11, "gps_lat": -7.285430000000001, "gps_long": 112.71538333333335 }, { "kode_customer": 3, "nama_customer": "sinar family", "alamat_customer": "by pass jomin no 295", "kodepos": 41374, "kode_provinsi": 9, "gps_lat":

unicode - How to remove strange characters using gsub in R? -

i'm trying clean text loaded memory using readlines(..., encoding='utf-8'). if don't specify encoding, see kinds of strange characters like: "the way talk family......i ass beat death....but kno cray cray & leave @ 😜ðŸ˜â˜º'" this looks after readlines(..., encoding='utf-8'): "the way talk family......i ass beat death....but kno cray cray & leave @ \xf0\u009f\u0098\u009c\xf0\u009f\u0098\u009d☺" you can see unicode literals @ end: \u009f, \u0098, etc. i can't find right command , regular expression rid of these. i've tried: gsub('[^[:punct:][:alnum:][\s]]', '', text) i tried specifying unicode characters, believe they're getting interpreted text: gsub('\u009', '', text) # unchanged the easiest way rid of these characters convert utf-8 ascii: combined_doc <- iconv(combined_doc, 'utf-8', 'ascii', sub='')

angularjs - ReactiveX JS and TypeScript - How to unsubscribe? -

i've been attempting implement new rxjs observable in angular 2 component using typescript. have created service, myservice returns observable in 1 of methods, e.g., export class myservice { getmyobs(){ return new observable(observer => { observer.next(42); }); } } then in angular 2 component subscribe observable in oninit, e.g., export class mycomponent implements oninit { obs: any; constructor(private myservice: myservice){}; ngoninit { this.obs = myservice.getmyobs().subscribe(data => { // stuff here... }); } } the rxjs documentation talks unsubscribing observable such observable knows no longer emit messages observer. therefore, figured should unsubscribing observable when component gets destroyed, like export class mycomponent implements oninit, ondestroy { obs: any; constructor(private myservice: myservice){}; ngoninit { this.obs = myservice.getmyobs().s

iText Java - Can't get the image show on pdf on html header -

i following example htmlheaderfooter.java creating pdf file has same header , footers on each page reason can't image display on pdf. it's blank needs show image. i tried moving image on every single folder in case it's path issue no luck on either. here example of code below. package amt.view.pdf.section0; import amt.methods; import com.itextpdf.text.*; import com.itextpdf.text.pdf.*; import com.itextpdf.tool.xml.*; import java.io.file; import java.io.fileoutputstream; import java.io.ioexception; import java.sql.connection; import java.sql.resultset; import java.sql.sqlexception; public class section0 { static string customer; static string customertitle; static string refno; static string revision; static string refnotitle; public static string dest; public static final string userdesktop = system.getproperty("user.home") + "/desktop"; static string selectedid = "1"; p

php - Laravel's Model Factory throwing syntax error -

i have tried using factory create number of users through use of stock migration/model/factory definition , following command ran within php artisan tinker: $user = factory(app\user::class)->make(); i have made no changes function can see below; $factory->define(app\user::class, function (faker\generator $faker) { return [ 'name' => $faker->name, 'email' => $faker->safeemail, 'password' => bcrypt(str_random(10)), 'remember_token' => str_random(10), ]; }); yet following error: [symfony\component\debug\exception\fatalthrowableerror] parse error: syntax error, unexpected '->' (t_object_operator), expecting']' update i must have deleted somewhere along line caused error, have no idea started fresh project , no longer have error. thankyou trying help! what happens if wrap factory call in parentheses, object operator after? though, expecting closing ] ma

fgetcsv - CSV File Not uploading data in codeigniter -

i can't upload data in csv starting letter 'c' , space c r mohan,3102,ii,d,,cin45l@yahoo.com,1234567890, s r alex,3102,ii,d,,xuy566@yahoo.com,1234567880, charmila,3102,ii,d,xu5566@yahoo.com,1234567880, the second , third line got inserted in db,but whenever line stating 'c' , space not inserting in db.pls help use below function passing values in it function escape_string($data) { $result = array(); if(is_array($data)){ foreach($data $row){ $utf_data = mb_convert_encoding(str_replace('"', '',trim($row)), 'utf-8', 'utf-8'); $result[] = str_ireplace('?', '', $utf_data); } }else{ //return utf8_encode(str_replace('"', '',trim($data))); $utf_data = mb_convert_encoding(str_replace('"', '',trim($data)), 'utf-8', 'utf-8'); return str_ireplace('

java - Vaadin - ListSelect - set focus on selected item? -

i'm using listselect component of vaadin (version 7.x) , highlight option i've set default selection using setvalue() method - similar happens onclick() event when background colour changes blue , text colour white. does know how this? listselect itemlist = new listselect("please select item:"); itemlist.add(initialitem) for(item item: items) { if(!item.equals(initialitem.getname())) { //add item } itemlist.setvalue(initialitem.getname()); //set focus on intial item make stand out other items thanks use itemlist.select(initialitem)

c - Problems with creating HMAC signature -

i need work azure blob storage in programs written on c. didn't found c library work it, decide write own code using azure blob storage rest api, curl , openssl libraries. i found bash script making simple request azure storage work , start rewriting c. for have problems creating hmac signature request. i'm newbie in cryptography , after searching found this . well, here code make simple request list of blobs in storage: #include <errno.h> #include <string.h> #include <unistd.h> #include <time.h> #include <stdlib.h> #include <stdio.h> #include <limits.h> #include <openssl/evp.h> #include <curl/curl.h> #include <stdint.h> #include <assert.h> #include "crypto.h" #define verb_get "get" #define verb_post "post" #define verb_put "put" #define azure_api_version

html - Text align not working under div using javascript print button -

i have placed div on html page , text under center align. custom java script button placed printing under div content. when press button previews text left align. please guide how set or apply css or style div center align. complete html code following written in asp.net. in advance <%@ page language="c#" autoeventwireup="true" codebehind="webform1.aspx.cs" inherits="margin_issue.webform1" %> <!doctype html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1"> <div id="divforprint" class="mydivtoprint" style="border: 1px dotted black; text-align: right; padding-left: 250px; width: 600px"> <span style="font-size: 10pt; font-weight: bold; font-family: arial">hello, <br /> <span

Uploading files using multipart/form-data through REST API -

i'm trying upload 4 files used request body in rest api call through robot framework. i'm using requests library achieve this. i think i'm facing problem setting correct mime type/boundary error thrown if run file using pybot: {u'errormessage': u"couldn't find mime boundary: ------bound0901"} is correct way set mime boundary? can set custom mime boundaries, have in code sample given below? or required set boundaries defined web app? here's code i'm using done: library | requestslibrary *** testcases *** 1. login create session | host | http://10.10.20.20 &{headers}= | create dictionary | user=scott | password=tiger ${response}= | requestslibrary.get request | host | /api/login | ${headers} &{headers} create dictionary | contenttype=multipart/form-data;boundary=----bound0901 ${file1}= | binary file | file1.au ${file2}= | binary file | file2.crs ${file3}= |

delphi - Return the library path of a specific platform using OTA -

i want library path specific platform (win32, win64, osx). but, when ask library path for, ota return me osx library path. the code is: environmentoptions := (borlandideservices iotaservices).getenvironmentoptions; paths.text := environmentoptions.values['librarypath']; i noticed strange thing. when ask key values 3 librarypath. when do: environmentoptions.getoptionnames i get: ... lot of values 'classcompletionbooleanaddinterface', tkenumeration 'librarypath', tklstring --> 1 'packagedploutput', tklstring ... lot of values 'librarypath', tklstring --> 2 'packagedploutput', tklstring ... lot of values 'hppoutputdirectory', tklstring 'librarypath', tklstring --> 3 'packagedploutput', tklstring ... lot of values i think each key must represent 1 of possible targets have (win32, win64, osx). can call value of key it's name, return me

jquery - Copying content of a div to a new window adds extra unwanted new line -

i use code copy contents of div show in new window var w = window.open(); var text = $("#my-div").html(); $(w.document.body).html(text); but along content, adds new lines, around 200px before content. what might reason ? for empty body: <body> </body> $(document.body).html() --> `"↵↵↵"` so, if need avoid empty lines use trim(): var w = window.open(); var text = $("#my-div").html().trim(); $(w.document.body).html(text); trim() : removes whitespace both ends of string. whitespace in context whitespace characters (space, tab, no-break space, etc.) , line terminator characters (lf, cr, etc.).

python - How to access request parameters from SET value of on_delete in django model -

i have 10 models each of use user foreign key. when user deleted, want set values in each of these tables 1 deletes user. users being deleted through django admin area authorized staff. so, guess have call function , use set of on_delete method set value. code per documentation. from django.db import models django.contrib.auth.models import user def get_sentinel_user(): return user.objects.get_or_create(username='deleted')[0] class mymodel(models.model): user = models.foreignkey(user, on_delete=models.set(get_sentinel_user)) in case, want user deletes user. can obtained request parameters. how can access request parameters in get_sentinel_user function? since staff member deleting other users , taking ownership of objects belongs deleted user effective solution override delete_model method in admin . def delete_model(self, request, obj) : ''' deletes single item. changes ownership ''' mymodel.objects.fi

google spreadsheet - Javascript look-up function optimization -

i'm writing custom function google sheet using javascript, should return value based upon table. i've got works, feels extremely ugly lots of nested if statements. how improved readability? function price(msrp, order_quantity) { var percentage; if(order_quantity >= 200 && order_quantity <= 400) { if(msrp >=49 && msrp <= 99) { percentage = 0.07; } else if (msrp >=100 && msrp <= 249) { percentage = 0.06; } else if (msrp >=250 && msrp <= 499) { percentage = 0.05; } else if (msrp >=500) { percentage = 0.04; } else { return null; } } else if (order_quantity >= 500 && order_quantity <= 900) { if(msrp >=49 && msrp <= 99) { percentage = 0.06; } else if (msrp >=100 && msrp <= 249) { percentage = 0.05; } else if (msrp >=250 && msrp <= 499) { percentage = 0.04; } else if (m

angularjs - Two Step authentication in IONIC -

authentication flow chart firstly no pro, started ionic framework. i trying accomplish authentication shown in image above. what trying do? firstly, on loading app, checks if user logged in or not. if user logged in, he/she redirected dashboard. if user not logged in , system check if user waiting verification code . if user waiting verification code , input verification form displayed. else, user directed input username form. what have done far? have created 3 controllers username input, verification code , dashboard. service handles back-end communication server , stores authentication key , necessary user credentials on local storage. using php slimframework rest api. my question how check if user logged in or waiting verification code, when ionic app loads. how check if user logged-in you can check if user logged-in checking if token key exists in local storage so: angular.module('starter') .service('authservice', func

select - Using select_ and starts_with R -

why doesn't code work? mtcars %>% select_("starts_with('d')") error in eval(expr, envir, enclos) : not find function "starts_with" this simplified example. trying pass select_ command function. the difference between select() , select_() non-stadard / standard evaluation of argument. if function starts_with() used argument of select_() should quoted tilde: library(dplyr) mtcars %>% select_(~starts_with('d')) this yields same output normal use of select : identical(mtcars %>% select_(~starts_with('d')), mtcars %>% select(starts_with('d'))) #[1] true for more information see vignette on non-standard evaluation: vignette("nse") .

Webpack require.context Pre-load Dynamic Assets -

i'm using webpack create collection of games. pre-load assets (.svg files) based on run time configuration. i'm trying this: let requestgameassets = require["context"]('../../../resources/html5images/gameassets', true, /.+\/.*/); i'm not 100% clear on weather creates bundle includes assets? or wrapper allows resolving each of included assets. e.g. once call first asset loaded?: requestgameassets(requestgameassets.keys()[0]); secondly second call doesn't seem result in being loaded! still required use full path asset not key in context otherwise gives me 404. if use full path asset seems load asset @ time. in other words context doesn't give me anything.. if there way include assets context in css helpful. this seems reasonably common used case if point me example of great. webpack documentation focuses more on loading code modules assets. cheers rod

android - TextInputEditText view not rendering as expected -

my problem textinputedittext view not expand take entire width of parent expect using android:layout_width="match_parent" . code below snippet application: <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.constraintlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/constraintlayout"> <android.support.design.widget.textinputlayout android:layout_width="0dp" android:layout_height="wrap_content" android:id="@+id/textinputlayout1" android:layout_margintop="16dp" app:layout_constrainttop_totopof="@+id/constraintlayout" android:layout_marg