Posts

Showing posts from February, 2014

actionmailer - receive emails in rails app -

i know can receive emails rails app using actionmailer configuration or using griddler/mailman gems. possible receive unique emails? ex: when user signed app create him unique email address. when user sends email unique email address rails app should receive email. i used google find solution couldn't answer. please me(reference links appreciated). no complete solution, idea: set catch email address on mail server receives mail sent domain. then, in rails use mailman/mail gem receive mails sent catch-all address , process depending on to header.

Structuring xml returned by select statement in Sql Server -

lets say, have 2 tables itemgoods, servicegoods have name , price among other columns. representing different kinds of goods sold. i want select single xml structure. right using select declare @goods_prices varchar(8000) set @goods_prices = (select * (select [name] item_name, [cost] price itemgoods union select [name] service_name, [cost] price servicegoods) goods xml auto); output : <goods> <itemname>item1</itemname> <price>299.0</price> </goods> <goods> <itemname>service1</itemname> <price>4,99</price> </goods> the output seek like <goods> <itemgoods> <item> <itemname>item1</itemname> <price>299.0</price&

angularjs - Accessing parameters in custom data -

i'm using custom data add human readable name states, this: .state('data', { parent: 'week', url: '/data', displayname: 'data overview', i can use in template this: <h1>showing {{$state.current.displayname}}</h1> which nice. want create route parameter, , use parameter in displayname: .state('upload', { parent: 'week', url: '/upload/:level', displayname: 'data upload ' + level, ... but can't figure out correct syntax use access value of level inside displayname . the static data (suggested placed inside of data : {} - not directly on root state settings) - static data. so: there no way how set these data dynamically. e.g. based on $stateparams . these settings expected defined in .config() phase, not evaluated in .run() (in compariosn others resolve, templateurl...) see doc: attach custom data state objects you can attach custom data state ob

c++ - Last Build number in OSVERSIONINFOEX -

i wanted os product version 6.3.9600.17415 when using osversioninfoex 6.3.9600 how last build number 17415 if need exact build number, use getfileversioninfo on kernel32.dll. post explains using getfileversioninfo: https://stackoverflow.com/a/17286050/2501336 this documented means of getting true os build number , immune virtualization: getting system version to obtain full version number operating system, call getfileversioninfo function on 1 of system dlls, such kernel32.dll , call verqueryvalue obtain \\stringfileinfo\\<lang><codepage>\\productversion subblock of file version information.

Age, gender, & country not showing in Facebook Insights data -

nearly other metrics available view in facebook insights, except user demographics. when try view them, empty array: "data": [ { "name": "page_impressions_by_age_gender_unique", "period": "day", "values": [ { "value": { }, "end_time": "2015-10-08t07:00:00+0000" } ], "title": "daily reach demographics", "description": "daily: total page reach age , gender.", "id": "x/insights/page_impressions_by_age_gender_unique/day" } ], i have permissions set: read_insights, manage_pages, publish_actions. for me it's working page. if don't have daily means search in weekly or 28 days report. may todays report not updated yet. "daily reach demographics" have "weekl

Unicode Printing in Java- abstract characters -

Image
i'm making program prints unicode characters. looks this: public class test { public static void main(string[] args) { system.out.println('\u00a5'); system.out.println((char) 0x00a5); system.out.println((char) (integer.parseint("00a5", 16))); system.out.println('\u261e'); system.out.println((char) 0x261e); system.out.println((char) (integer.parseint("261e", 16))); } } the output looks like: ¥ ¥ ¥ ? ? ? why latter half print question marks? i can understand program printing japanese character, when change \u261e , can't recognize it. help? if want apply changes specific project then: go project properties -> change text file encoding utf-8 or if want apply projects globally then: got window -> preferences -> general -> workspace : text file encoding note: if using other ide, should have similar option there too.

php - Nested sets for Yii2 Invalid argument supplied for foreach() -

Image
i using https://github.com/creocoder/yii2-nested-sets extension yii2 ! so, first version yii1 in version have problem. all done strictly according manual! when created models earn error: this error appear @ query category table. if delete behavior entire work ;( categories model : <?php namespace backend\models; use creocoder\nestedsets\nestedsetsbehavior; use yii\db\activerecord; class categories extends activerecord { public function behaviors() { return [ 'tree' => [ 'class' => nestedsetsbehavior::classname(), 'treeattribute' => 'tree', ], ]; } public function transactions() { return [ self::scenario_default => self::op_all, ]; } public static function find() { return new categoryquery(get_called_class()); } } categoryquery model : <?php namespace backend\models; use creocoder\nestedsets\nestedsetsquerybehavior; use yii\db\activere

select - Jquery .prop("selected", "selected") doesnt work on ipad chrome/safari -

i have problem code : $('#activity_filter_type_activity option').eq(1).prop("selected", true); it works on classic desktop not in safari/chrome on ipad. can me ? try using ".attr" checked $('#activity_filter_type_activity option').eq(1).attr('checked',true); i found solution in other thread, same problem .prop() vs .attr()

Python 2.7 Invalid syntax when running script from .csv file using pandas -

i running script python 2.7 using pandas read 2 csv files. keep getting "invalid syntax" error messages, particularly on line 6 , 8. can't figure out problem, since line 6 identical line 5 , there don't error. ! import numpy np import csv csv import pandas pd da = pd.read_csv('snp_rs.csv', index_col=(0,1), usecols=(0, 1), header=none, converters = dict.fromkeys([0,1]) db = pd.read_csv('chl.map.csv', index_col=(0,1), usecols=(0,1), header=none, converters = dict.fromkeys([0,1]) result = da.join(db, how='inner') x = result.to_csv('snp_rs_out.csv', header=none) # write csv print x as commented need close parentheses around read_csv call: da = pd.read_csv('snp_rs.csv', index_col=(0,1), usecols=(0, 1), header=none, converters = dict.fromkeys([0,1]) it's missing closing paren. i find lot easier write/read these if split lines: da = pd.read_csv('snp_rs.csv', index_col=(0,1

material design - Android float button and background overlay -

Image
i have searched not found tutorial or library on how float button background 1 below used in skype. i followed tutorials using these tutorials making floatbutton. https://github.com/codepath/android_guides/wiki/floating-action-buttons , https://www.bignerdranch.com/blog/floating-action-buttons-in-android-l/ , https://github.com/codepath/android_guides/wiki/design-support-library edited please read ! according @simon, able use https://github.com/futuresimple/android-floating-action-button library achieve float button layout. stuck making background dim because cannot set relative layout background color inside library functions. see working java code below floatbutton, have stripped out other buttons leaving skype alike. public class floatbuttonactivity extends activity { relativelayout brl; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_float_button);

pointers - Why can't I swap memory address of two variables using a function? C -

static void swapaddr(int *numone, int *numtwo) { int *tmp; tmp = numone; numone = numtwo; numtwo = tmp; } int main(void) { int = 15; int b = 10; printf("a is: %d\n", a); printf("address of a: %p\n", &a); printf("b is: %d\n", b); printf("address of b: %p\n", &b); swapaddr(&a, &b); printf("\n"); printf("a is: %d\n", a); printf("address of a: %p\n", &a); printf("b is: %d\n", b); printf("address of b: %p\n", &b); return 0; } when compile , run piece of code, output a is: 15 address of a: 0x7fff57f39b98 b is: 10 address of b: 0x7fff57f39b94 is: 15 address of a: 0x7fff57f39b98 b is: 10 address of b: 0x7fff57f39b94 clearly result not intended, since address not seem have been swapped @ all. you can't change address of variable. your 'swapaddr' function changes parameter valu

javascript - JqueryFileUpload form url issue -

i try use jqueryfileupload plugin make ajax upload while form filling. have hard issue because need have different url in form params. i use url param in jqueryfileupload object doesnt works if file input field located in form. uses form action url 'index.php?option=com_xxx&layout=edit&id=0' in .fileupload function instead of url 'index.php?option=com_xxx&task=item.uploadimage'. how use ulr param in fileupload function , have file field inside form different action url? possible? jquery code: jquery('#jform_file').fileupload({ url: 'index.php?option=com_xxx&task=item.uploadimage', // element accept file drag/drop uploading dropzone: jquery('#drop'), // function called when file added queue; // either via browse button, or via drag/drop: add: function (e, data) { var tpl = jquery('<li class="working"><input type="text" value="0" data-width=&q

php - session_start() is not success when use multi byte into the session in cakephp3 -

recently started use cakephp3.1 , error bellow. warning (2): session_start(): trying destroy uninitialized session [core/src/network/session.php, line 324] warning (2): session_start() [function.session-start]: failed decode session object. session has been destroyed [core/src/network/session.php, line 324] warning (2): session_start() [function.session-start]: cannot send session cache limiter - headers sent (output started @ /home/www/service/vendor/cakephp/cakephp/src/error/debugger.php:742) [core/src/network/session.php, line 324] when set multi byte word session such login user's name japanese or multi byte word set flash, it's happen. so assumed did't installed mbstring extension. there's installed. this happens due session storage not being able handle multibyte characters. if storage mysql database setting character set utf8 collation utf8_general_ci for table , the field holding session data solves these problems.

Remove last word from string in SAS? -

i have list of counties in dataset (calhoun county, el paso county, etc.) , return dataset has word 'county' stripped (calhoun, el paso, etc.) there easy way in sas? thank you! call scan report position of nth word, can use substr. count=-1 end rather beginning. data _null_; starting_word='el paso county'; count=-1; call scan(starting_word, count, pos, length); end_word=substr(starting_word,1,pos-2); *pos 'c' two; put end_word=; run;

javascript - Difference between simple ajax and :remote => true In Ruby on Rails -

actually have two, 3 questions heart of 3 question same written in title . make points clear here in description following specification of question javascript file path => assets/javascript/ js.erb file path => views/customers/index.js.erb view file name => views/customers/html.erb controller name => customers action name => index point # 1 if make ajax call customers/index through javascript file (with mentioned path) hit index.js.erb file ? point # 2 can use js , js.erb file same action . mean 'is possible send ajax js file in assets folder , after controller action index method handle response in index.js.erb file in view folder ?' point # 3 say can handle response in index.js.erb file how can / or if can stop sending response / data in js file if have missed more related points kindly edit question , place , maximum people can enjoy knowledge also have @ this question , answer if can update i made small e

.net - XUnit.net: run Theories in parallel -

xunit.net supports parallel test execution. my tests parameterized (theories). every test run against different storage. here's example: public class testcase1 { [theory] [inlinedata("mssql")] [inlinedata("oracle")] [inlinedata("pgsql")] [inlinedata("sqlite")] public void dotests(string storage) {} } public class testcase2 { [theory] [inlinedata("mssql")] [inlinedata("oracle")] [inlinedata("pgsql")] [inlinedata("sqlite")] public void dotests(string storage) {} } by default tests executed in parallel . can grouped in collections (with of collection attribute). i can't run tests in parallel every test case has own db schema. put tests single collection assembly-level attribute: [assembly: collectionbehavior(collectionbehavior.collectionperassembly)] but means tests differnt storages run serially. what want run tests different storages

python - How to uninstall jupyter -

i have been trying uninstall jupyter i have tried following commands pip uninstall jupyter pip3 uninstall jupyter and rm -rf /users/$user/library/jupyter/* even after running these commands when type jupyter in terminal following message usage: jupyter [-h] [--version] [--config-dir] [--data-dir] [--runtime-dir] [--paths] [--json] [subcommand] jupyter: error: 1 of arguments --version subcommand --config-dir --data-dir --runtime-dir --paths required what going wrong , why still able use command? when $ pip install jupyter several dependencies installed. best way uninstall running: $ pip install pip-autoremove $ pip-autoremove jupyter -y kindly refer related question . pip-autoremove removes package , unused dependencies. here docs .

java - Why is there no @DoubleRange annotation in Android Studio Support Annotations like @IntRange and @FloatRange -

i read article on android studio support annotations today , started using these annotations in code, here example: public final static class googlemapszoomlevel { public static final int min_zoom_level = 0; public static final int max_zoom_level = 21; .. public googlemapszoomlevel(@intrange(from=min_zoom_level, to=max_zoom_level) int zoomlevel) { if (zoomlevel < min_zoom_level || zoomlevel > max_zoom_level) { throw new illegalargumentexception(error_zoom_level_out_of_bounds); } this.zoomlevel = zoomlevel; } .. } further down in code have class accepts double values in it's constructor, there no @doublerange annotation. use @floatrange or nothing @ all? same question long values actually, @floatrange 's documentation states: denotes annotated element should float or double in given range and similar situation @intrange denotes annotated element should int or long in given range

java - Combine tables and sql from 2 reports without the use of subreports -

is there way can take 2 reports, each seperate sql , queries, , combine them onto single report without tampering sql or queries? i trying 'make report' using information 2 ready established , made reports. 2 reports inventoryallocationworkorder report , inventoryallocationsalesorder report. i've started making copy , editing workorder report (which ive done , looks nice) im @ teh part need information other report (salesorder). i new sql , ireport dont believe trying hard im making it. know subreports asking if there way combine 2 on 1 report without master report. thank helping me learn! i did attempt add photos post unable without 10 reputation. best answer questions though! fast solution...see sub report feature of crystal, active reports or ssrs. they have "sub report" type features let embed existing report "parent" report. crystal subreports better solution, create new report , re-work queries. depending on complexity

java - Constructor of Reflections not running correctly -

i using reflections library ( see info ) classes within package. using following code: public static void build() { system.out.println("start reflection"); reflections reflections = new reflections("org.octocash.client.support.cache"); system.out.println("done constructor"); set<class<?>> dataclasses = reflections.getsubtypesof(object.class) .stream().filter(c -> !c.getclass().equals(data.class)) .collect(collectors.toset()); data.addall(dataclasses); } the problem prints "start reflection" in console, unable run constructor. if surround code try-catch block, not printing exception either. i using uberjar reflections (not using maven), maybe has this. what happening here? totally in dark on how debug this.. any appreciated!

java - Is this a proper usage of Function interface? -

i trying familiar lambda functions. start decided write handy class called ternaryoperator . so, question did ideology right or missing should done in different way? public class ternaryoperator<t, u> implements function<t, u> { private final function<t, u> f; public ternaryoperator(predicate<? super t> condition, function<? super t, ? extends u> iftrue, function<? super t, ? extends u> iffalse) { this.f = t -> condition.test(t) ? iftrue.apply(t) : iffalse.apply(t); } @override public u apply(t t) { return f.apply(t); } } i see usage of class this: predicate<object> condition = objects::isnull; function<object, integer> iftrue = obj -> 0; function<charsequence, integer> iffalse = charsequence::length; function<string, integer> safestringlength = new ternaryoperator<>(condition, iftrue, iffalse); and can calc

regex - r stringdist or levenshtein.distance to replace strings -

i have large, dataset ~ 1 million observations, keyed defined observation type. within dataset, there ~900,000 observations malformed observation types, ~850 (incorrect) variations of 50 acceptable observation types. keys <- c("day", "evening","sunset", "dusk","night", "midnight", "twilight", "dawn","sunrise", "morning") entries <- c("day", "day", "sunset/dusk", "days", "dayy", "even", "evening", "early dusk", "late day", "nite", "red dawn", "evening sunset", "mid-night", "midnight", "midnite","day", "evening","sunset", "dusk","night", "midnight", "twilight", "dawn","sunrise", "morning") using gsub akin digging basement hand sh

python - opencv error : error while displaying rectangle -

i m not able rectify error. m following official opencv python tutorial. m passing video here , doing meanshift. source: https://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_video/py_meanshift/py_meanshift.html#meanshift below code: import numpy np import cv2 cap = cv2.videocapture("slow.mp4") # take first frame of video ret,frame = cap.read() # setup initial location of window r,h,c,w = 250,90,400,125 # hardcoded values track_window = (c,r,w,h) # set roi tracking roi = frame[r:r+h, c:c+w] hsv_roi = cv2.cvtcolor(frame, cv2.color_bgr2hsv) mask = cv2.inrange(hsv_roi, np.array((0., 60.,32.)), np.array((180.,255.,255.))) roi_hist = cv2.calchist([hsv_roi],[0],mask,[180],[0,180]) cv2.normalize(roi_hist,roi_hist,0,255,cv2.norm_minmax) # setup termination criteria, either 10 iteration or move atleast 1 pt term_crit = ( cv2.term_criteria_eps | cv2.term_criteria_count, 10, 1 ) while(1): ret ,frame = cap.read() if ret == true: hsv

Pypy sandbox - writing to /tmp -

i tring run python code in pypy sandbox. need output script doesn't interfere stdout. i've read lot of sources , of them mentions, sanboxed script can write files virtual /tmp. not able achieve (all sources missing example). if write access /tmp isn't possible, possible open pipe between sanboxed script , control script? if none of possible, write binary data stdout? i'd tag begginning , ending of output in stdout, control script distinguish user output , output. the virtual /tmp read-only; in fact attempt subprocess write file denied. if want change that, edit sources control outer process, far refuse attempt write. start do_ll_os__ll_os_open in rpython/translator/sandbox/sandlib.py.

angularjs - add an ng-model to ng-click that passes true false params -

i have button <a class="btn btn-primary" ng-click="isprivate = !isprivate"> {{isprivate ? "make event public" : "make event private"}} </a> i'm wanting have button once clicked passes true false controller. i've tried this <a ng-model="event.public" class="btn btn-primary" ng-click="isprivate = !isprivate"> {{isprivate ? "make event public" : "make event private"}} </a> any ideas im doing wrong? heres code in controller $scope.event.public = ''; i've found out can checkbox <input type="checkbox" id="public" ng-click="isprivate = !isprivate" ng-model="event.public" ng-true-value="'yes'" ng-false-value="'no'"> i'd prefer being button though rather checkbox you

java - Maven Multi Module Hot deploy in Jboss -

we have multi-module maven project, has deployed in jboss 7.1.1 server. takes of our time redeploying code changes. have seen use jrebel hot deployment, expense not meet 20 developers. so there workaround hot deployment of maven-multi-module project in jboss? here build configuration of our project in pom: <build> <pluginmanagement> <plugins> <plugin> <groupid>org.apache.maven.plugins</groupid> <artifactid>maven-compiler-plugin</artifactid> <version>2.3.2</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> <plugin> <groupid>org.jboss.as.plugins</groupid> <artifactid>jboss-as-maven-plugin</artifactid>

android - How to work with a Class that Implements Runnable in Java -

i not new threads, use threads run long processes, create instance of runnable class , put code want run in run() method, yesterday lecturer gave me task create simple program implements runnable class, class demonstrate how use start(), wait(), sleep(), join() , yield() method calls, said every time want run thread create instance of runnable class , add handler or looper implementing class have never done before bit lost, choose create simple contactbook program, program save , delete contacts file, 1 of these classes should implement runnable class, choose class saves , loads contacts file because part might take more time hence needs run on separate thread below classes person class (a blueprint of data each contact should have) public class person implements runnable{ private string fname; private string lname; private string number; private string calltime; public person() { this("", "","",""); } public person(stri

AudioKit unexpected crash ios with swift on AKOscillator - [AKOscillator operationName]: unrecognized selector sent to instance -

i receiving strange crash when using audiokit build swift based ios 8 application. followed videos , able build , launch audiokit based project using bridging header, etc. in main viewcontroller, have following code based on hello world example: override func viewdidload() { super.viewdidload() let inst = akinstrument() //let oscillator = akoscillator() //inst.setaudiooutput(oscillator) //akorchestra.addinstrument(inst) //inst.play() } that runs fine, second uncomment lines below initializing akinstrument, crash shortly after app launches: 0dbfs level = 32768.0 csound version 6.05 (float samples) aug 6 2015 libsndfile-1.0.26pre6 2015-10-22 11:19:15.024 nilg5[1281:37425] 1 midi sources 2015-10-22 11:19:15.025 nilg5[1281:37425] midi source 0: session 1 440.0 2015-10-22 11:19:16.072 nilg5[1281:36836] -[akoscillator operationname]: unrecognized selector sent instance 0x7fb6904b78b0 2015-10-22 11:19:16.160 nilg5[1281:36836] *** te

mysql - How do I select multiple maximum and minimums from a table -

i have written query has returned column of numbers , ordered lowest highest. need display highest , lowest value. planning on using simple select max(x),min(x) ... table contains multiple minimums , statement selects first minimum. example of table name x 1 b 1 c 1 d 2 e 5 how display name x 1 b 1 c 1 e 5 this example, there range of rows between max , min. you can join subquery return min , max . union remove duplicates if max = min . sqlfiddledemo create table tab(name nvarchar(100), x int); insert tab values ('a', 1), ('b', 1), ('c', 1), ('d', 2), ('e', 5); select t.* tab t join (select min(x) val tab union select max(x) val tab) sub on t.x = sub.val;

gzip - Reading gzipped text file line-by-line for processing in python 3.2.6 -

i'm complete newbie when comes python, i've been tasked trying piece of code running on machine has different version of python (3.2.6) code built for. i've come across issue reading in gzipped-text file line-by-line (and processing depending on first character). code (which written in python > 3.2.6) is for line in gzip.open(input[0], 'rt'): if line[:1] != '>': out.write(line) continue chromname = match2chrom(line[1:-1]) seqname = line[1:].split()[0] print('>{}'.format(chromname), file=out) print('{}\t{}'.format(seqname, chromname), file=mappingout) (for know, strips gzipped fasta genome files headers (with ">" @ start) , sequences, , processes lines 2 different files depending on this) i have found https://bugs.python.org/issue13989 , states mode 'rt' cannot used gzip.open in python-3.2 , use along lines of: import io io.textiowrapper(gzip.open(input[0], &quo

ios - Add handles around UIImageView -

so have few uiimageview's can "spawn" on screen, , scale,rotate, , move using gesture recognizer. want add 2 things, simple line around uiimageview let user know view selected. , button around line if tapped delete view. i've tried https://www.cocoacontrols.com/controls/spuserresizableview , couldn't implement right way in swift. i recommend creating simple uiview subclass contain uiimageview , uibutton (i don't quite understand want button positioned can setup constraints based on needs). subclass wrap whole functionality of 1 spawned imageview. then: creating delete action when uibutton tapped pretty straight forward. creating selection effect done several approaches: you create uiview (with backgroundcolor equal selectedstatecolor) behind uiimageview (slightly bigger uiimageview) simulate select action you use uiimageview layer , play bordercolor / borderwidth this: func handletap(gesturerecognizer: uigesturerecognizer) { //

postgresql - DB/SQL best practice: Validate data before insert, or TRY to insert and use error message -

this general software engineering principle question. "better": to validate data correct before inserting database, or to try insert, , interpret error message if doesn't succeed. ok. example: want add new movie database. movie must have unique name. try insert it, , let unique constraint catch it. - or - first select-query check if such movie exists? a movie belongs genere. do select query first see if genre exists in database, or let foreign key constraint "catch"/validate it? the problem checking beforehand ofc race condition -- other thread can insert movie title while you're validating -- there's no guarantee in multithreaded system. on other hand, error message (postgre)sql in plain english, it's not structured data (like e.g. json), requires parse in order understand went wrong generate non-technincal error message end user. is there best pracitice on this? has got common dilemma? the best practice have database w

html5 - SVG responsive design -

my svg logo responsive, i'm unsure why working, expecting far more complicated , feel i'm missing here here html logo: -the width of logo container defined bootstrap class col-xs-6 -all images set max-width {100%} in css -header height set auto <div id="logo" class="col-xs-6 clearfix"> <img src="images/logo.svg" alt="the website logo"> </div> here xml logo: <svg version="1.1" id="layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewbox="0 0 57.8 15" enable-background="new 0 0 57.8 15" xml:space="preserve"> <rect x="0.5" y="0.7" fill="#ffffff" stroke="#000000" stroke-miterlimit="10" width="56.8" height="13.8"/> <text transform="matrix(1 0 0 1 15.0075 10.044)"

ms access - Uploading a file to Azure Blob Storage using VBA and MS XMLHTTP -

i've been trying upload file azure storage using vba in microsoft access far without success. i have had search around , have found code looks promising can't work. seems many others have been looking similar solution or working azure vba. this code; private function pvpostfile(surl string, sfilename string, optional byval basync boolean) string const str_boundary string = "3fbd04f5-b1ed-4060-99b9-fca7ff59c113" dim nfile integer dim babuffer() byte dim spostdata string '--- read file nfile = freefile open sfilename binary access read nfile if lof(nfile) > 0 redim babuffer(0 lof(nfile) - 1) byte nfile, , babuffer spostdata = strconv(babuffer, vbunicode) end if close nfile '--- prepare body spostdata = "--" & str_boundary & vbcrlf & _ "content-disposition: form-data; name=""uploadfile""; filename=""" & mid$(sfilename, instrrev(sfilename, "\&

python - Read a string of 1's and 0's. Count numbers of successive 1's and number of successive 0's, until the end -

read string of 1's , 0's. count numbers of successive 1's , number of successive 0's, until end. for example, s = "10001110000111" output should be: 1 1's 3 0's 3 1's 4 0's 3 1's i need approaching using string functions (no find function), , while/for loops. i have this: mystring = input("please enter string of 0s , 1s: ") zerocount = 0 onecount = 0 index = 0 while index < (len(mystring) -1): if mystring[index] == "0": zerocount += 1 if mystring[index +1] == "1": zerocount = 0 elif mystring[index] == "1": onecount += 1 if mystring[index +1] == "0": onecount = 0 index += 1 what doing wrong? this quite similar what's called 'run length encoding' has nice entry on rosettacode.org def encode(input_string): count = 1 prev = '' lst = [] character in input_st

How to import a C# dll to python -

i've got third party c# dll has been created in dot net 4.5 , has platform target of x86. import python script , i've started off rob deary's answer here . can't example work. i'm using python version 2.7.6 , attributeerror shown below. file "c:\python27\lib\ctypes\__init__.py", line 378, in __getattr__ func = self.__getitem__(name) file "c:\python27\lib\ctypes\__init__.py", line 383, in __getitem__ func = self._funcptr((name_or_ordinal, self)) attributeerror: function 'add' not found please note aware of ironpython , python dot net need working c python. here's sample code generates custom c# library: classlibrary1.dll using system; using system.runtime.interopservices; using rgiesecke.dllexport; class test { [dllexport("add", callingconvention = callingconvention.cdecl)] public static int testexport(int a, int b) { return + b; } } and here's python script generates error i

Improve performance on SQL query with select top 1-statement before from-statement -

i have long complex sql query (in microsoft sql server 2012) need improve performance. have 1 issue sql query has 'select top 1' before from-statement. hard explain, below text have wrote example sql query issue: select player.firstname, player.lastname, lastgamegoals = (select top 1 goals playersummary playersummary.playerid = player.playerid order playersummaryid desc) player the sql above hockey players firstname , lastname , number of goals in last played game specific player. since database large slow because of select top 1-statement. i can of course add index better performance, can avoid 'select top 1' on every player row? how can improve performance? for statement: lastgamegoals = (select top 1 goals playersummary playersummary.playerid = player.playerid order playersummaryid desc) you want index. best index playersummery(playerid, playersummaryid, goals) . covering index subqu

javascript - Can't use cancelAnimationFrame. Nothing happens (chrome) -

problem: can't cancel requestanimationframe using chromes recognized cancelanimationframe. what tried: used console.log no errors displayed. console.logged cancelanimationframe , undefined, while request counterpart logs fine. tried different version of cancelanimationframe, including prefixed versions: cancelanimationframe webkitcancelanimationframe window.cancelanimationframe etc.. i tried putting canceling code function expected doesn't matter. question: why can't stop requestanimationframe? canceling way recommended? http://jsfiddle.net/p8hv15j4/2/ var elem = document.getelementbyid('test'); var currentpos = 0; var requestanimationframe = window.requestanimationframe || window.mozrequestanimationframe || window.webkitrequestanimationframe || window.msrequestanimationframe; function fn() { currentpos += 5; elem.style.left = currentpos + "p

php - Convert array data into Excel -

i converting array data excel using phpexcel. when excel file created, data stored row wise want store data column wise. array given below: array (size=3) 0 => string '8801755568952' (length=13) 1 => string '8801755556987' (length=13) 2 => string '8801755587985' (length=13) my array excel conversion code is: $objphpexcel->getactivesheet()->fromarray($csv_data, null, 'a1') $objwriter = phpexcel_iofactory::createwriter($objphpexcel, 'excel5'); return $objwriter->save($xls_output_path); my output is: 8801755568952 8801755556987 8801755587985 my desired output is: 8801755568952 8801755556987 8801755587985 if pass simple 1-dimensional array fromarray() method, phpexcel assumes single row, you're seeing. either convert array 2-dimensional array as phpexcel treat these values numeric, , they're larger limit 32-bit signed integer in php (and you're running 32-bit php), they&#

php - Showing URL in a webpage -

i need url based on table in database, this: <a href='edit.php?id=[]>e</a> here id should final id of table. means, if have total 45 id in database table, url should this: <a href="edit.php?id=45">e</a> i tried code below didn't succeed. please me. <?php include('config.php'); $query1 = "select id addd order id desc limit 1;"; $result = mysql_query($query1); $data = mysql_fetch_array($result); echo <a href='edit.php?id="$data[0]"'>e</a>; ?> try echo "<a href='edit.php?id={$data[0]}'>e</a>";

c# - how to search through a WebRequest -

how search through response of webrequest set of characters. example making program gets closings school district , need webrequest word "... closed today" , output entire line of text. here got far. returns page in html (i believe): using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.linq; using system.text; using system.windows.forms; using system.io; using system.net; namespace windowsformsapplication2 { public partial class form1 : form { public form1() { initializecomponent(); } private void combobox1_selectedindexchanged(object sender, eventargs e) { } private void label1_click(object sender, eventargs e) { } private void button_click(object sender, eventargs e) { get_closings(); } private void get_closings() { // create request url. webrequest request = webrequest.create ( &qu

haskell - Confusing types in ghci -

here code: n = [(a,b) | <- [1..5],b <- [1..5]] calcbmis xs = [bmi | (w, h) <- xs,let bmi = w / h ^ 2] when trying apply calcbmis n , following error: *charana> calcbmis n <interactive>:220:1: no instance (fractional integer) arising use of ‘calcbmis’ in expression: calcbmis n in equation ‘it’: = calcbmis n further investigation in ghci: *charana> :t calcbmis calcbmis :: fractional t => [(t, t)] -> [t] *charana> :t n n :: [(integer, integer)] what i'm assuming list produce of type (integer,integer) , cannot processed in calcbmis , takes in fractional . idea how fix problem? you can use div instead of (/) : calcbmis xs = [ bmi | (w,h) <- xs, let bmi = (w `div` h)^2 ] prelude> :t calcbmis calcbmis :: integral t => [(t, t)] -> [t] prelude> calcbmis n [1,0,0,0,0,4,1,0,0,0,9,1,1,0,0,16,4,1,1,0,25,4,1,1,1] as can see version can deal integral values - of course truncate (because of div ). o

javascript - How to convert a string to TYPES.LPTSTR.targetType.array -

i have supposed definitions follows: var config = { is64bit: ctypes.voidptr_t.size == 4 ? false : true, ifdef_unicode: true}; var types = { char: ctypes.char, wchar: ctypes.char16_t}; types.lpstr = types.char.ptr; types.lpwstr = types.wchar.ptr; types.lptstr = config.ifdef_unicode ? types.lpwstr : types.lpstr; i have string like: "omnikey ag smart card reader usb 0" and want convert types.lptstr.targettype.array format in if show tostring() follow: ctypes.char16_t.array(36)(["o", "m", "n", "i", "k", "e", "y", " ", "a", "g", " ", "s", "m", "a", "r", "t", " ", "c", "a", "r", "d", " ", "r", "e", "a", "d", "e", "r", " ", "u", "s", "b&q

angularjs - Kendo Dropdownlist Placeholder -

i using kendo dropdownlist , need placeholder dropdownlist shouldn't appear in list when select dropdown. tried using optionlabel value shows in list. var $dropdownelement; $dropdownelement = $("<input />"); $dropdownelement.appendto($dropdowncontainer); $dropdownelement.kendodropdownlist({ datatextfield: "text", datavaluefield: "value", datasource: dropdown.items, optionlabel: "select option", //shows option in dropdown popup: { appendto: $dropdowncontainer } }); i need solution can add placeholder , value shouldn't shown option in dropdownlist. you can find first element in dropwdownn list , hide make less chatty $dropdownelement.getkendodropdownlist().list.find("li.k-item").first().hide(); plunker dropdownlist (and combobox) example

python - Elegant conversion of tab separated log lines into a CSV matrix -

i have tab-separated log file lines that: event_a info1 info2 event_b info1 info4 event_c info2 info5 ... i want convert csv (with python) column has meaning. info1 e.g. id, info2 desintation, info4 coordinate etc. i can "sloppy" way: if "event_a" in line: columns = line.split() id = columns[1] i prefer have lookup matrix or table structure this, positions columns separated programming logic. there allows me define expressive overview here, code like: for line in csvfile: matches = event_table.match(line) match in matches: event_table.convert(match) # add commas in between values account empty columns i of course create class per event, seems overkill. looking central definition, can use. the output is: event_a, info1 info2 event_b, info1, , , info4 event_b, , info2, , , info5 ... event_365, , , , , , , , , , , , info12 edit: log file contains 100s of such event types, make code rather long , hard maintain d

javascript - Graph Lines cross the Y axis on mobile browser -

Image
i noticed there issue opened ie8 issue on google code page dygraphs . mentioned excanvas.js can tell in current version of dygraphs excanvas.js has been removed. the time see issue when load page on mobile. noticed title covers top portion of graph. not sure if last 1 can solved hoping there solution lines on y axis.

How might I define an array of methods within a PHP class? -

i need define several methods within class. methods similar, create array of method names , generate of methods array of names. don't need call methods, define them they're callable elsewhere. i don't have define these methods way, method names set in stone. something maybe: class projectcontroller { public function __construct() { $this->makemethods(); } public function makemethods() { $methods = ['documents', 'addenda', 'docreleases', 'drawings']; foreach($methods $m){ $method_name = 'get' . $m; /* * define method named $method_name on projectcontroller * (i know statement below wrong. how might fix it? i'm i'm using '$this' incorrectly here, i'm not sure use. '$this' should reference projectcontroller.) */ $this->$method_name = function(){ //

html - How to add line-spacing between two <li> -

i have unordered list in 1 of page designed using twitter bootstrap. <ul class="list-unstyled col-md-5 col-md-offset-3"> <li><span class="glyphicon glyphicon-link"></span>link1</li> <li><span class="glyphicon glyphicon-link"></span>link2</li> <li><span class="glyphicon glyphicon-link"></span>link3</li> <li><span class="glyphicon glyphicon-link"></span>link4</li> </ul> how can add line-spacing between li tags? just add margin li elements not last one. ul > li + li { margin-bottom: 5px; }

bash - How to change the pseudocode into real code? -

there 4 time servers, want synchronize local time ntp time server. arr=(s2c.time.edu.cn s2d.time.edu.cn s2e.time.edu.cn s2f.time.edu.cn) var in ${arr[@]}; # 2 lines pseudocode here if `ntpdate $var` secceed ,exit loop if none of ntp time server can used,echo "failure" done how change pseudocode real code? fix flaw codes: arr=(s2c.time.edu.cn s2d.time.edu.cn s2e.time.edu.cn s2f.time.edu.cn) switch = 0 var in ${arr[@]}; # 1 lines pseudocode here if `ntpdate $var` secceed ,assign switch = 1 ,exit loop done if["$switch" = "0"] ;then echo "synchronize local time ntpdate failure" fi how change if ntpdate $var secceed ,assign switch = 1 ,exit loop real bash script? your proposed algorithm has obvious flaw: loop on servers if ntp server can used -> exit loop if none of ntp server can used -> echo failure the flaw last step, "if none of ntp servers ...". doesn'

java - Converting Bit String to Double -

i have used double.doubletorawlongbits , long.tobinarystring convert double value string of bits . however, trying find methods convert string of bits double . double.longbitstodouble convert long representation of bits double , have been having trouble finding method convert string of bits long representation of bits . any question appreciated! thank time in reading this. given long n = ... string s = long.tobinarystring(n); you use long reconstructed = long.parselong(s, 2); to reconstruct long.

arrays - DB query result to custom object -

right have started develop small project, extend knowledge of web-app aspects , realise idea got last monday. so, i've got nodejs + mongo. project fun&education don't care performance etc, try new. mowing problem: i've got structured data, stored plain text file. after dancing around wrote script, convert datas objects (custom objects) , pushed them mongodb. problem is: after them db - plain objects. i'm lacking of sweet , great setters, getters etc. after thinking while found 1 possibility, how it: run through whole response array, , add .prototype functionality need (setters, getters, etc). seems have poor performance , approach seems silly. i ask you, right way so? example when use google apis - got custom objects, bunch of useful methods. other example - during summer working on project based on symfony2, i've used strange (in moment) doctrine2 orm layer. in oop world found awesome. same trick under hood - convert query result objects , returns them

SAS STUDIO - How do I MOVE an imported .csv file (now a .sas7bdat file) -

(sas studio / sas enterprise miner on demand -- web access school.) i uploaded , imported .csv file sas studio. import function let me select libraries webwork , work (temporary), not viewable sas em. import created webwork.input , "/home/my_username/.sasstudio/webwork/rs2999/import.sas7bdat. how move "../import.sas7bdat" file "/home/my_username/my_content/(etc)" can see sas em? (i can upload .sas7bdat files directly need them sas studio, , that's uploaded .csv file.) thanks you need base sas library in studio , sas em pointing same location. since in home directory metadata library overkill. recommend using libraries tab in studio , creating library "/home/my_username/my_content/(etc)" , in em open explorer ( view - explorer) , create library same location. not have have same name, best practice so.

angularjs - Trying to scope the users information -

i need use current user id filter on ng-repeat. i'm still trying grasp on angular, assumption may wrong. thinking if can put current users information (name, id, email etc) in scope, can use scope insert id filter in angular controller. so i've created users_controller.rb def index respond_with current_user end so shows current user information. i've added resource routes.rb resources :users then created factory retrieve json information in userservice.js .factory('userservice', [ '$http', function($http) { return { loadusers: function() { return $http.get(('/users.json'),{ cache: true}). success(function (data, status, headers, config) { if (status == 200) { console.log('succes') } else { console.error('error happened while getting user list.') } }) } }; } ]) then console log in browser says suc