Posts

Showing posts from April, 2015

python - Efficiently joining two dataframes based on multiple levels of a multiindex -

i have dataframe large multiindex, , secondary dataframe multiindex subset of larger one. secondary dataframe kind of lookup table. want add columns lookup table larger dataframe. primary dataframe large, want efficiently. here imaginary example, want join df2 df1: in [11]: arrays = [ ['sun', 'sun', 'sun', 'moon', 'moon', 'moon', 'moon', 'moon'], ....: ['summer', 'winter', 'winter', 'summer', 'summer', 'summer', 'winter', 'winter'], ....: ['one', 'one', 'two', 'one', 'two', 'three', 'one', 'two']] in [12]: tuples = list(zip(*arrays)) in [13]: index = pd.multiindex.from_tuples(tuples, names=['body', 'season','item']) in [14]: df1 = pd.dataframe(np.random.randn(8,2), index=index,columns=['a','b']) in [15]: df...

wpf - Get a rectangle of a newly added ListViewItem -

i add new record listview's itemssource collection: source.add(newrecord); after action i'm trying rectangle of corresponding item: listviewitem newitem = list.itemcontainergenerator.containerfromitem(newrecord) listviewitem; rect rc = layoutinformation.getlayoutslot(newitem); but, unfortunately, rc (0, 0, 0, 0). seems when call getlayoutslot method, new listviewitem not yet arranged. how can obtain correct information directly after adding new record? any appreciated. calling list.updatelayout(); before line listviewitem newitem = ... should rectangle immediately. but generally, not recommend use updatelayout() anywhere in wpf program. layout procedures in wpf asynchronous performance reasons. therefore, better if program determined rectangles of list items @ later point in time. here mean "later point in time": source.add(newrecord); dispatcher.begininvoke(dispatcherpriority.loaded, new action(() => { listviewitem...

perlscript - Perl script appending date -

am running perl script ever day on server , getting below output script. trying modify script include current hour part of output. how can go doing this? this current script: #!/usr/bin/perl #prism performance log parser use strict; $cbal_total; $cbal_count =0; $stck_total = 0; $stck_count =0; $chg_total = 0; $chg_count =0; $rmac_total = 0; $rmac_count =0; $rmd_total = 0; $rmd_count =0; $cbalt; $stckt; $rmact; $rmdt; $chgt; $total; $count; $cbal; $stck; $hour; $chg; $rmac; $rmd; $lesthresh=0; $gtthresh=0; $stck_lesthresh=0; $stck_gtthresh=0; $rmd_lesthresh=0; $rmd_gtthresh=0; $chg_lesthresh=0; $chg_gtthresh=0; $rmac_lesthresh=0; $rmac_gtthresh=0; %checkbal; %subtypecheck; %charging; %remoteact; %remotedct; $chgkey; $cbalkey; $stckkey; $rmackey; $rmdkey; @value; $ct; $component; $component2; while (my $line =<>) { chomp; s/\r//g; @f = split(/\|/, $line); $i; $hour = substr($f[0],11,2); ($i==0;$i<=100; $i++) { if (($f[$i]=~m/c...

r - produce multiple time series in different plot and save in working directory -

this appears quite simple have no idea how go it. dataframe looks this: var1 var2 var3 var4 var5 var6 ..... var57 1 23 67 89 63 34 ..... 90 2 34 43 43 23 23 ..... 32 3 45 65 45 32 54 ..... 43 4 45 32 18 61 87 ..... 39 5 23 74 53 54 76 ..... 54 6 21 65 34 34 12 ..... 97 . . . . . . ..... . . . . . . . ..... . . . . . . . ..... . 365 54 78 54 12 90 ..... 53 i want produce separate plots , save them in working directory var1 against variables. plot(var1 ~ var2) plot(var1 ~ var3) plot(var1 ~ var4) plot(var1 ~ var5) . . . . . plot(var1 ~ var57) is there way automate dont have produce each individual plots @ time , save in working directory? thanks lot. pdf("plots.pdf") for(i in 2:ncol(df)) plot(df[,1] ~ df[,i]) dev.off()

linux - Bash reading from file and parsing each line -

this question has answer here: loop iterates once `ssh` in body [duplicate] 1 answer i need manage updates of particular software on several customers' linux servers. updates provided sending .tar.gz files each server , inflating overwriting old software files. i've put customers' server list in txt file this: user1@customer-server-1-address:22:/path/to/software/server1:null:customer1name user2@customer-server-2-address:2222:/path/to/software/server2:/etc/vpnc/client1.conf:customer2name user3@customer-server-3-address:22:/path/to/software/server3:null:customer3name char ":" acts field separator; field 1 server address, 2 port, 3 path software, 4 used tell if vpn tunnel enabled first, 5 customer name. i've managed create following script: #!/bin/bash [...] while ifs=':' read -ra array; if [ "${array[3]}" !=...

python - Why does deleting a directory structure and then re-creating it immediately after raise an exception? -

i've reduced issue this: import os, shutil shutil.rmtree("wtf", true) os.makedirs("wtf") now, when run following error: traceback (most recent call last): file "wtf.py", line 4, in <module> os.makedirs("wtf") file "c:\program files (x86)\python34\lib\os.py", line 244, in makedirs mkdir(name, mode) permissionerror: [winerror 5] access denied: 'wtf' what causing this?

html - Using ~ to make another element change style -

sorry misleading title, pretty hard describe problem in few words. basically want when hover on caption want headline block text underline. right have jsfiddle on every other caption 1 hovering. jsfiddle: http://jsfiddle.net/gnfpj/1/ css: .caption { width: 480px; height: 270px; float: left; margin-left: 5px; margin-top: 5px; } .caption p { background-color: #000; color: #fff; margin-top: -53px; height: 50px; padding: 7px; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; opacity: 0.7; font-family: verdana, sans-serif; font-size: 12px; line-height: 19px; } .caption p span { font-weight: bold; font-size: 14px; } .caption:hover ~ .caption p span { text-decoration: underline; } .caption { text-decoration: none; } you want simple descending selector: .caption:hover p span { text-decoration: underline; } http://jsfiddle.net/gnfpj/2/

python - Is there a type discrepancy that is causing this 'NoReverseMatch' in Django? -

according django docs, noreversematch happens when "a matching url in urlconf cannot identified based on parameters supplied." i getting following noreversematch error. question is: why parameter supplied not being caught url? expecting parameter of different type? i'm still not comfortable django urls. "reverse 'recall' arguments '(<unordered_group: countries>,)' , keyword arguments '{}' not found. 0 pattern(s) tried: []" this question revised django noreversematch url issue after suggestions tried. edited: images/urls.py (project level) from django.conf.urls import patterns, include, url django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^images/', include('images_app.urls', namespace="images_app")), url(r'^associate/', include('associate.urls', namespace="associate")), url(r'^admin/', include(admin....

Add API to Polymer web component -

i building polymer web component should respond mouse/touch events. bind on-tap="{{$.myelement.show}}" show function in element: show: function(e) { // event here } is there anyway define public api in polymer. route going @ moment have attributes="event" on element parent element has on-tap="{{updateevent}}" : updateevent: function(e) { this.$.myelement.event = e; } the element has: eventchanged: function() { show(this.event); } which seems boilerplaty (think made word). can add show function element prototype somehow? if show() method on element, use on-tap="{{show}}" . show() part of element's public api. but looks want call element's method? came in pull request: https://github.com/polymer/polymer-dev/pull/30 what have setting this.$.myelement.event = e; , using eventchanged() in myelement works. can call element's method directly: updateevent: function(e) { this.$.myelement.show(); ...

c# - Why does this single line of code cause Visual Studio to crash? -

with 1 line of code, can cause vs2012 crash consistently. (by "crash" mean when hit build , visual studio hangs indefinitely , have kill task manager.) here's code (in custom user control): public class transparentpanel : system.windows.forms.panel { protected override void onpaintbackground(painteventargs pe) { this.invalidate(); //this offending line } } to reproduce problem, create control based on above code , add windows form; try build solution . "build started..." displayed in status bar , vs , permanently freeze up. tried troubleshooting , using devenv /log , activity log displayed no errors or warnings. question is, why code fatal c# compiler? (it causes problems in ide too. example, after adding transparent control, properties pane becomes frozen whenever form designer open.) side question: should bug reported microsoft? if so, how? (i tried submit bug on the ms connect site , apparently accepting bugs vs2013.) [if wa...

html - Submit form without reloading or leaving current page (php- mysql) -

thank in advance. every time user call summarize in form, user validation not necessary since there few of them idea every time form submitted username goes input field, user doesn't have type names on , over. problem way have php code insert values db reloading same form-url if remove line, once submit takes me blank page. have php code takes username in session , write in input field fine. since reloading page session gets killed. the question how set username in input field after submit form. here code: <?php if(isset($_post['add'])) { $dbhost = 'localhost'; $dbuser = 'xxxxx'; $dbpass = 'xxxxx'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('could not connect: ' . mysql_error()); } $sql = "insert callwrapper ". "(data,user,date) ". "values('$_post[dataentered]','$_post[user_name]',curdate())"; mysql_select_db('ugsports'); $retval = mysql_quer...

php - Drupal login form not displaying -

i'm creating custom drupal theme , keep getting locked out of site because can't log in. i have default login block in content region, when log out doesn't show when go localhost:8888/nations_dp/?q=user i'll post screenshot of blocks once logged in changing theme , stuff. have checked visibility settings block, , checked displaying anonymous users?

asp.net - Uploading files: Access to path denied -

i've given iusr full control on folder when upload files gives me error: access path 'c:\inetpub\wwwroot\vivaweb\usr_up_img\desert.jpg' denied. description: unhandled exception occurred during execution of current web request. please review stack trace more information error , originated in code. exception details: system.unauthorizedaccessexception: access path 'c:\inetpub\wwwroot\vivaweb\usr_up_img\desert.jpg' denied. asp.net not authorized access requested resource. consider granting access rights resource asp.net request identity. asp.net has base process identity (typically {machine}\aspnet on iis 5 or network service on iis 6) used if application not impersonating. if application impersonating via <identity impersonate="true"/>, identity anonymous user (typically iusr_machinename) or authenticated request user. grant asp.net access file, right-click file in explorer, choose "properties" , select security tab. click "add...

FTP/SFTP access to an Amazon S3 Bucket -

is there way connect amazon s3 bucket ftp or sftp rather built-in amazon file transfer interface in aws console? seems odd isn't readily available option. just mount bucket using s3fs file system (or similar) linux server (e.g. amazon ec2) , use server's built-in sftp server access bucket. install s3fs add security credentials in form access-key-id:secret-access-key /etc/passwd-s3fs add bucket mounting entry fstab : <bucket> /mnt/<bucket> fuse.s3fs rw,nosuid,nodev,allow_other 0 0 for details, see guide setting sftp access amazon s3 .

c# - WinForms DataGridView TextError only shows after forced refresh -

so have form datagridview getting data datatable following code (alternativemenu form, manager.values datatable). public alternativemenu(manager m) { initializecomponent(); manager = m; dataview.autosizecolumnsmode = datagridviewautosizecolumnsmode.fill; dataview.allowusertoaddrows = false; dataview.multiselect = false; dataview.datasource = manager.values; valuevalidation(); } the valuevalidation method checks invalid values , changes cell error text , background color. public void valuevalidation() { foreach (datagridviewcolumn column in dataview.columns) { foreach (datagridviewrow row in dataview.rows) { validatecell(row.index, column.index); } } } private void validatecell(int row, int column) { if (!manager.validatevalue(row, dataview.columns[column].name)) { dataview.rows[row].cells[column].errortext = "placeholder error text"; dataview.rows[row].cells[column].style.backcolor = color....

javascript - Array created from .get() won't populate html select -

this question has answer here: how return response asynchronous call? 21 answers here's rundown. have external .txt file has number of locations (one per line) need have loaded script populate dropdown. i'm using .get() pull in data, , putting array. looks correct, dropdown isn't populated. doing tests, found if manually populate array when declare data declare there loads fine. also, if try doing array such turning string nothing happens, , if try checking length reports 0. i've tried making new array , pushing content of first it, no dice. i've tried using makearray, didn't work. here's code far: var siteidarray = []; var path = "*snipped*/siteid.text"; var option = ""; $.get(path, function(data) { siteidarray = data.split("\n"); console.log(siteidarray); }); (i = 0; < siteidarray.length; i++) {...

jquery - Scrolling Causes Stuttering In Responsive Slider -

i've been working on fun solution create full page image slider that's responsive viewers browser, , once browser scrolls allows user see content below. i used bit of jquery , thought had found solution worked perfectly! until got end of project , tried scroll , down. noticed when scroll , down framerate seems bit choppy. doing research people saying may because of ".animate" in jquery. goal here avoid plug-ins , wondering if 1 offer me helpful solution? i'm new jquery , web development in general i've created code pen project may able fork , me out. here jquery: function slideswitch() { var $active = $('.image.active'); if ( $active.length === 0 ) $active = $('.image:last'); var $next = $active.next().length ? $active.next() : $('.image:first'); $active.addclass('last-active'); $next.css({opacity: 0}) .addclass('active') .animate({opacity: 1}, 600, function()...

I installed PostgreSQL on mavericks, but running `which psql` does not do anything. Did it install correctly? -

i installed postgresql using downloadable graphic installer . i'm able launch pgadmin postgresql's gui. however, when run which psql on terminal, i'm not getting path (and based on read here should yield path provided postgres installed). after looking @ stackoverflow post , should have done via homebrew. should uninstall postgresql got via graphic installer, , re-install using homebrew? noob here, , appreciate patience. if you've installed using postgres.app, path binary should under /applications/postgres.app/. try running @ terminal, can see on system it's under /applications/postgres.app/contents/macos/bin. $: find /applications/postgres.app/ -name "psql" -print /applications/postgres.app/contents/macos/bin/psql if want add path variable, use this tutorial .

python - Unique Value Index from two fields -

i'm new pandas , python, , use help. i have code below, want. creates dummy variables unique values in field , indexes them unique combinations of unique values in 2 other fields. what 1 row each unique combination of fields used index. right multiple rows 'asset subs end dt' = 10/30/2008 , 'reseller csn' = 55008 if dummy variable comes 3 times. rather have 1 row combination of index field values 3 in dummy variable column. code: df = data df = df.set_index(['asset_subs_end_dt','reseller_csn']) dummies=pd.get_dummies(df['expertise']) something like: df.groupby(level=[0, 1]).expertise.count() when groupby , same index grouped together. assuming data in expertise notnull , new dataframe returned unique index values , count per each index. try out yourself, play around results, , see how can combined existing dataframe final result want.

ios - Strings which should be equal compare as not equal -

this question has answer here: string comparison in objective-c 3 answers i want build app shows string every day, don't know how detect new day has come. i tried setting string initialstring records day of last time opened app, , string nowstring records current time. if initialstring != nowstring , show new string in uilabel in app , update initialstring same nowstring . if they're same, nothing happens. heres code; compiler says both strings not same when are. implementation file: #import "quoteviewcontroller.h" #import "quotes.h" @interface quoteviewcontroller () @end @implementation quoteviewcontroller @synthesize view1; @synthesize view2; //will used in future. //@synthesize view3; - (void)viewdidload { // additional setup after loading view, typically nib. [super viewdidload]; [self addchildviewcontr...

Sub-resources of the resource. Is this a valid REST? -

i want expose portion of big rest resource resource (sub-resource). valid so? problems possible approach? there better way? for example, have collection of computers. each computer in collection (main resource) have it's own sub-parts (sub-resources). /api/computers/117/chassis /api/computers/117/motherboard /api/computers/117/cpu where computers collection , chassis , motherboard , cpu sub-resources of computer #117 . yes is. can have problems when want access resources specific type of cpu, it's okay if have /api/cpus/123

c# - Convert.ToDouble() overflows with SqlDataReader value -

Image
convert.todouble(rdr["value"]) throws "conversion overflows" error when value 75875563.7000000000000000000000 displayed in sql server. stack trace: @ system.data.sqlclient.sqlbuffer.get_decimal() @ system.data.sqlclient.sqlbuffer.get_value() @ system.data.sqlclient.sqldatareader.getvaluefromsqlbufferinternal(sqlbuffer data, _sqlmetadata metadata) @ system.data.sqlclient.sqldatareader.getvalueinternal(int32 i) @ system.data.sqlclient.sqldatareader.getvalue(int32 i) @ system.data.sqlclient.sqldatareader.get_item(string name) @ dataapi.models.title.titledb.gettitleperformance(nullable`1 startdate, nullable`1 enddate) in c:\00 bi source\biportal\dataapi\dataapi\models\title\titledb.cs:line 44 can give me clue on why is? this decimal capacity. can use decimal (16,4) on sql server side (or precision need)? decimal (16,4) means 16 chars, 4 digits after ,

PHP How remove element from html dom? -

this question has answer here: how delete element domdocument? 3 answers we have index.php code: <div class="test"> text text text text</div> <div class="test2"> text text text text</div> <div class="test3"> text text text text</div> <div class="test4"> text text text text</div> in file test.php use code: ob_start(); // start output buffer include 'index.php'; $template = ob_get_contents(); // contents of buffer ob_end_clean(); return $template; tell me please how remove div class test2 , content in him html in $template ? p.s.: want remove div class test2 regardless of attributes inside div tag. okay, have html structure in variable. can remove preg_replace. $template = preg_replace('/<div.*?class="test2".*?>.*?</div>/...

algorithm - Elo rating system without order of game played -

i looking rating system similar elo rating system in chess. problem have elo system depends on order games played. eg. player starting elo 1000 player b starting elo 1000 if player b wins on have lets 1015 points , 985. if keeps on playing , wins against other people, have higher ranking b, if b stops playing. don't want that. b should still stronger a. how can realise that? there number of schemes amount writing down win/lose/draw record matrix , typically calculating largest eigenvalue of matrix related this. 1 summary @ http://java.dzone.com/articles/ranking-systems-what-ive , points more technical papers including https://umdrive.memphis.edu/ccrousse/public/math%207375/perron.pdf - "the perron-frobenius theorem , ranking of football teams". if can more information out of game win/lose/draw might better using this. work on soccer has used number of goals , against @ each match try , work out strengths of each team's offense , defense separatel...

java - What is causing this animation flicker and how do I remove it? -

i have made tiny android application attempt resolve issue i've been seeing on different app. i'm trying achieve effect textview starts off screen, scrolls on. what did looks it's working on 4.0.4, when use android virtual device (4.1.2) there "flicker" showing textview in original place before animation starts. i've noticed same thing on friend's tablet (4.4). i uploaded video show issue here . my layout: <relativelayout android:layout_width="match_parent" android:layout_height="match_parent"> <textview android:id="@+id/txtv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> during mainactivity's onresume() function move textview off screen starting position: @override protected void onresume(){ super.onresume(); view v = findviewbyid(r.id.txtv); animation hi...

ios - Converting between coordinate spaces SpriteKit -

Image
i have node shape of box in scene. shape node should have own coordinate space, if declare point @ (100,100) in nodes coordinate space , rotate box pi/4 rad point should change in scenes coordinate space. my problem cant work, i'm using following code convert point in nodes coord space scenes coord space, placement of node 200,200 in scene: startpointinnodespace = cgpointmake(0, size.height/2); cgpoint start = [self.scene convertpoint:cgpointmake(startpointinnodespace.x, startpointinnodespace.y) fromnode:self.parent]; cgpoint end = [self.scene convertpoint:cgpointmake(startpointinnodespace.x, startpointinnodespace.y + 100) fromnode:self.parent]; nslog(@"start position in node: (%f,%f)\nend position in node: (%f,%f)",startpointinnodespace.x,startpointinnodespace.y,startpointinnodespace.x,startpointinnodespace.y + 100); nslog(@"start position in scene: (%f,%f)\nend position in scene: (%f,%f)",start.x,start.y,end.x,end.y); the code inside subclass of sksp...

javascript - Given the array used with ng-repeat, can I select an individual item created with each item? -

i have angular app builds list of zones map data. zones displayed both in sidebar in divs using ng-repeat, , on map vector features. when user selects zone on map, need scroll zone's div in sidebar. jquery can perform scrollto action given element, , know zone selected; can reference div matches item? i cannot use index because there may sorting or filtering on ng-repeat array. other options? edit: here's relevant code: <div class="turf" ng-repeat="zone in layers.zones.features" ng-class="{ selected: zone === selectedzone && zone !== highlightedzone, hover: zone === highlightedzone }" ng-click="selectzone(zone); $event.stoppropagation()"> <h2>{{zone.name}}</h2> <input type="text" class="form-control" ng-model="zone.name" /> {{zone.users}} users present </div> openlayers call function when 1 of zones on map clicked...

assembly - Massive performance improvement g++ 4.6 vs 4.7 vs 4.8 in aesni -

i've been working time on comparison between cpu aesni , gpu aes. i've updated g++ compiler (from 4.6 4.8) , saw significant increase in performance (~2x) cpu aesni. i have simplified c code "simulate" aes encryption using aesni instructions (listed bellow). __m128i cipher_128i; _aligned(16) unsigned char in_alligned[16]; _aligned(16) unsigned char out_alligned[16]; // store plaintext in cipher variable encrypt memcpy(in_alligned, buf_in, 16); cipher_128i = _mm_load_si128((__m128i *) in_alligned); cipher_128i = _mm_xor_si128(cipher_128i, key_exp_128i); /* 9 rounds of aesenc, using associated key parts */ cipher_128i = _mm_aesenc_si128(cipher_128i, key_exp_128i); cipher_128i = _mm_aesenc_si128(cipher_128i, key_exp_128i); cipher_128i = _mm_aesenc_si128(cipher_128i, key_exp_128i); cipher_128i = _mm_aesenc_si128(cipher_128i, key_exp_128i); cipher_128i = _mm_aesenc_si128(cipher_128i, key_exp_128i); cipher_128i = _mm_aesenc_si128(cipher_128i, key_exp_128i); cipher...

ruby on rails - has_many belongs_to association with a foreign key -

let's have 2 models venue , photo . each venue can have many photos , can have one featuredphoto . each photo can belong many venues , can featuredphoto of more 1 venue too. i have general has_and_belongs_to_many relationship set , working through join table these models: class photo < activerecord::base mount_uploader :image, photouploader has_and_belongs_to_many :venues end class venue < activerecord::base has_and_belongs_to_many :photos end to add featuredphoto, seems need add column called featured_photo_id venue model , set has_many, belongs_to association between two. i'm not sure add foreign_key info. right? class photo < activerecord::base mount_uploader :image, photouploader has_and_belongs_to_many :venues has_many :venues end class venue < activerecord::base has_and_belongs_to_many :photos belongs_to :photo, foreign_key: "featured_photo_id", class_name: "photo" end or have add foreign_key info both ...

javascript - Jquery Slidetoggle, how to allow to show only one element? -

this html: <ul> <li> list <ul> <li>item 1</li> <li>item 2</li> <li>item 3</li> <li>item 4</li> <li>item 5</li> </ul> </li> <li> list 2 <ul> <li>item 1</li> <li>item 2</li> <li>item 3</li> <li>item 4</li> </ul> </li> </ul> and js: $('ul li ul').hide(); $('ul li').click(function() { $(this).children().slidetoggle(); }); i want create slidetoggle, example: when user click "list" , after open user click list 2 list 1 hiding. demo: http://jsfiddle.net/7dxab/ want 1 open when user click. thanks! try this: $('ul li ul').hide(); $('ul li').click(function() { var _this = $(this); ...

Segmentation Fault 11 Building Binary Trees in C -

when run code length of binary tree segmentation fault: 11 error. i've tried correcting , way can run calling size function left or right nodes. when run way (which according me correct) error. #include <stdio.h> #include <stdlib.h> #include <time.h> #include <assert.h> struct node { int data; struct node* left; struct node* right; }; typedef struct node node; node* newnode( int data ){ node* node = malloc( sizeof(node) ); assert(node); node->data = data; node->left = null; node->right = null; return node; } node* insert( node* node, int data ) { if( node == null){ return newnode(data); } else{ if( data <= node->data ){ node->left = insert(node->left, data); } else{ node->right = insert(node->right,data); } } return node; } node* buildonetwothree() { node* root = newnode(2); root->left = newnode...

php - How do I update the source code with mamp? -

i downloaded mamp 3 php 5.5.10. created new file php , put in htdocs folder , displayed correctly in chrome. added html , displayed nothing. checked source code , had 1 blank line. how fix displays html , php? also, why happen? initial php was <?php echo 'hi';?> then changed <!doctype html> <html> <head> <title>food</title> </head> <body> <?php echo 'hi'; ?> <form method="post" <?php echo "action=\"$_server['php_self']\"";?>> <input type="text" name="food" placeholder="enter food name"> <input type="submit" value="submit"> </form> </body> </html> this line goofy: <form method="post" <?php echo "action=\"$_server['php_self']\"";?>> change to: <form method="post" action="<?php echo $_server[...

date - PHP is not returning the correct time DateTime class -

i have been trying tackle hours , can not seem figure out @ hours of trying find solution maybe of me here code snippet: $phxtime = new \datetimezone('america/phoenix'); $datetime = new \datetime(); $datetime->settimezone($phxtime); echo $datetime->format('y-m-d h:i:s a'); here output of above code: 2014-05-29 09:13:10 it should 4:13:10 pm (my computer time) how fix this: assuming running centos 6.5 64 bit yum install ntp -y service ntpd start after of completed, recheck date , should in order! this works expected me: $phxtime = new \datetimezone('america/phoenix'); $datetime = new \datetime(); $datetime->settimezone($phxtime); echo $datetime->format('y-m-d h:i:s'); but results in 24 hour time: 2014-05-29 16:20:05 perhaps should write in 12 hour format am/pm , remove \ in front of new datetimezone , new datetime : $phxtime = new datetimezone('america/phoenix'); $datetime = new datetime(); $d...

angularjs recursive ng-include not refreshing when onload variable changes -

given example at: http://jsfiddle.net/8lhjh/ the easiest way can explain interaction steps... problem case: select item 1, see item1.items in box 2 select item 2, see item1.items in box 2 still! (should item2.items in box 2) functional case: select item 1, see item1.items in box 2 select --root--, removes box 2 select item 2, see item2.items in box 2 i think problem somewhere ng-include recursion... <div ng-if="level < path.length && path[level] && citem.items[path[level]] && citem.items[path[level]].items" ng-include="'item_select_recur.html'" onload="citem=citem.items[path[level]];level=level+1;"></div> solved it! http://jsfiddle.net/8lhjh/1/ the magic in manually updating box 2's scope (see jsfiddle complete example): nextelement.scope().citem = parentitem.items[$scope.path[level]];

wordpress - How can I make a direct person-to-person chat widget for my website that doesn't use server resources? -

i add live text chat website, without using many server resources or third party application. i'm not concerned keeping chat log/history @ point. how go making website chat widget (preferably wordpress friendly) use server resources establish initial connection between 2 logged in users, let them chat live without relaying message through server? technically feasible? product exist already? i've searched not find one-time-fee live chat solutions don't route through server or through third-party server. this has been addressed here , 2011/2012. a quick googling seems suggest webrtc might choice sort of thing. a few more minutes of research yields this , javascript library working webrtc. even better: here example of php chat server using webrtc. you'll want, seeing wordpress php. hopefully enough info started. luck!

linux - Quickest way to remove 70+ strings from a file? -

i have 70+ strings need find , delete in file. need remove entire line in file string appears in. i know can use sed -i '/string remove/d' filea.txt remove them 1 @ time. however, considering have 70+, take time doing way. is there way can put these 70+ strings in file , have sed go through them 1 one? or if create file containing strings, there way compare 2 files removes line filea contains 1 of strings? you use grep : grep -vf file_with_words.txt file.txt where file_with_words.txt file containing list of words, each word being on different line , file.txt file want remove lines from. if list of words contains regex metacharacters, tell grep consider fixed strings (if want): grep -f -vf file_with_words.txt file.txt using sed , you'd need say: sed '/word1\|word2\|word3/d' file.txt or sed -e '/word1|word2|word3/d' file.txt you use command substitution construct pattern too: sed -e "/$(paste -sd'|' file_...

jquery - Scrolling div using scrolltop() and div position.top only working correctly once, then strangely -

i'm making scroller website, using fixed div navigation, , wrapper div part scrolled using .scrolltop on nav click handlers. it working if click links first time after refresh, subsequent use of nav sends scroll random positions. i'm thinking might have fact using wrapper , not using scrolltop directly on 'html, body'? the click handlers i'm using nav buttons this: $('#mylink3').click(function() { $('#wrapper').animate({scrolltop: $('#environment3').position().top}, 1000); }); the test site here: http://testbed.shottotheface.org . thanks help! i'm going cross eyed on 1 , feels should such simple answer. cooper [edit] i tried removing #wrapper , using click handler this: $('#mylink2').click(function() {$('body, html').animate({scrolltop: $('#environment2').offset().top}, 1000); }); but don't seem having luck..? tried .offset #wrapper earlier today... still doing wrong...

objective c - Show error [NSConditionLock lockWhenCondition:beforeDate:] when call background methods iOS -

when run multiple methods in background, app shows error below. says cannot execute background methods. [nsconditionlock lockwhencondition:beforedate:]: deadlock (<nsconditionlock: 0x166ae1a0> '(null)') *** break on _nslockerror() debug. why app getting error? how can solve issue?

Setting an environment for a codeception Acceptance Test -

i've been trying out codeception acceptance tests. i'd able set environment use selenium tests don't need javascript can use faster phpbrowser driver , tests need js can this: $scenario->env('selenium'); $i = new webguy($scenario); $i->wantto('ensure teacher login works'); etc... however when set env test runs , says acceptance tests (0) - no tests run. commenting out line , tests run. class_name: webguy modules: enabled: - phpbrowser - webhelper - webdebug config: selenium2: url: 'http://test.r5' browser: firefox phpbrowser: url: 'http://test.r5' env: selenium: modules: enabled: - selenium2 config: url: 'http://test.r5' browser: firefox how can set 1 acceptance test run selenium? ref http://codeception.com/docs/07-advancedusage#environments ...

How to detect key using pitch of audio ios app -

is there body can me in finding pitch of audio file. have code in pitch calculating via mic, want detect pitch signal , strength? for need use avaudioplayer . give peakpowers pitch of audio . these peakpowers signal strength , can animation that. audioplayer.meteringenabled = yes; [audioplayer updatemeters]; if([audioplayer ismeteringenabled] ){ (int currchannel = 0; currchannel < [audioplayer numberofchannels]; currchannel++) { //strength of audio channel nslog(@"channel# %d %0.2f %0.2f", currchannel, [audioplayer peakpowerforchannel:currchannel], [audioplayer averagepowerforchannel:currchannel]); } }

Open Password Protected Excel Workbook C# -

i trying open password protected excel workbook. have tried many different ways of unprotecting programatically or inputting password, yet every time program runs, m prompted input password. doing wrong? public class attenfile { private excel.application excel; private excel.workbook wb; private excel.worksheet worksheet; private excel.range range; private const int startrow = 3; private int row; private static object missingvalue = system.reflection.missing.value; public attenfile(string attenfiledir) { excel = new excel.application(); wb = excel.workbooks.open(attenfiledir, missingvalue, missingvalue, missingvalue, "nso" ); wb.unprotect("nso"); worksheet = (excel.worksheet) wb.sheets[1]; worksheet.unprotect("nso"); range = worksheet.usedrange; } }

sql - Firebird Database Split String on Field -

currently working firebird 1.5 database , attempting pull data in correct format natively sql. consider following database: id | full name 1 jon doe 2 sarah lee what trying achieve simple split on full name field (space) within query. id | first name | last name 1 jon doe 2 sarah lee the issue faced firebird position() introduced in v2.0. there known workaround split on space has come across? much appreciate assistance! for firebird 1.5 solution find udf either combines both functions, or provides position (i don't use udfs, not sure if 1 exists). if none available might have write one. the other solution write stored procedure functionality, see example: position of substring function in sp create procedure pos (substr varchar(100), str varchar(100)) returns (pos integer) declare variable substr2 varchar(201); /* 1 + substr-lenght + str-length */ declare variable tmp varchar(100); begin if (substr null or str null...

objective c - Can't call a method from another class using object -

i trying call method class using object. there comes no warnings or errors, call not been made. execution not been transferred method specified. @interface epub : nsobject - (void) paginatechapters; @implementation epub - (void) paginatechapters; { (int i=0; i<chapterlinks.count; i++) { [self splitattributedstringtopages:[chapterfiles objectatindex:i] withchapter:[chaptersasattributedstringarray objectatindex:i]]; } } then tried call using it's object @interface epubrootviewcontroller : uiviewcontroller { epub *loadedepub; } @implementation epubrootviewcontroller -(void) viewdidload() { loadedepub = [[epub alloc]init]; } -(void)releasedata { loadedepub=nil; } -(void)changefontsize:(id)sender { [self releasedata]; [loadedepub paginatechapters]; } your loadedepub object nil when call method on it. must initialize object before respond method calls.

linux - Socket Select() is working but Poll() is not working correctly -

i calling function eventonsocket() again , again check if there event on sockets. my code working fine if use select if use poll code not working correctly. in case of poll, getting timeout error. here working code select. int eventonsocket() { int retval = -1; int socketmax = -1; struct timeval tv; tv.tv_sec = 15; //sec tv.tv_usec = 0; //microsec fd_zero(&m_rfds); for(int = 0; < m_socklist.size(); i++) { int socketid = task->m_socklist.at(i); if(socketmax < socketid) socketmax = socketid; fd_set(socketid, m_rfds); } if(socketmax > 0) { retval = select(socketmax+1, &m_rfds, null, null, &tv); return retval; } else return -1; } but when use poll in same way timeout error. in poll assigning socket fds once in vector when call function first time , call function again , again check event on sockets. here code poll. int eventonsocket() { ...

java - Convert Object to String -

i have couple class in i'm getting , setting few things , calling in main method. when call class in main method gives me object instead of name,address , age. know structure complicated want keep structure because later on adding lot of things this. amazing if tell me how this. appreciate this. below code classes this first class public class methodone { public string getname() { string name = "userone"; return name; } public int getage() { int age = 17; return age; } public string getaddress() { string address = "united states"; return address; } } this second class public class methodtwo { string name; string address; int age; public methodtwo(methodone objectone) { name=objectone.getname(); address=objectone.getaddress(); age=objectone.getage(); } public string getname() { return name; } ...

Get message ID in Azure queue -

is there way message id after insert in queue azure ? cloudstorageaccount storageaccount = cloudstorageaccount.parse(storageconnectionstring); cloudqueueclient queueclient = storageaccount.createcloudqueueclient(); cloudqueue queue = queueclient.getqueuereference("myqueue"); queue.createifnotexist(); cloudqueuemessage message = new cloudqueuemessage("hello, world"); queue.addmessage(message); // message id here ? only way message id by getting message . have fetch messages queue using getmessage or getmessages method. there's no guarantee message created getmessages can return 32 visible messages top of queue.

javascript - typescipt say to all public variables "undefined" -

i got following code module absence { export var instance: absenceviewmodel; export class viewmodel { public items: knockoutobservablearray<absenceitem>; public reloaddata() { this.items.removeall(); } } } in page create instance using this absence.instance = new absence.absenceviewmodel(); now when call absence.instance.reloaddata(); it in browser console cannot read property 'removeall' of undefined but imported knockout libary , other needed stuff. present. when use internal instance absence.instance.items.removeall(); what wrong? edit: i wrote dcklaration of viewmodel , declaration of instance in separate js file. these files loaden in page. after page ready instantiate instance of viewmodel hand in debug console. in call method reloaddata . can sure classes available @ moment when call methods. i'm not yet familiar get mechanism in typescript, while able solve issue it, i'm adding a...

Select Top 10 Sales Amounts Every Month, Every Year SQL Server 2008 -

select tr.createdon, st.be_storecountry, st.be_storelocationcategory, st.be_name storename, br.be_name brand, sum(sd.be_amount) total filteredbe_transaction tr, filteredbe_store st, filteredbe_salesdetails sd, filteredbe_brand br sd.be_itembrand = br.be_brandid , tr.be_storename = st.be_storeid , tr.be_transactionid = sd.be_transactionid , tr.createdon between '1/1/2008' , '1/1/2014' group tr.createdon, st.be_storecountry, st.be_storelocationcategory, st.be_name, br.be_name order tr.createdon desc this query , returns 286 rows. need modify top 10 sales amount every month, every year. each month of year 2008 2014 must have 10 corresponding results , must max sales amounts. 1 can please? you use partition break subsets based on month , year, , select top 10 each such subset result, so: ;with cte ( select tr.createdon, st.be_storec...

c# - The .mdf is not being created in App_Data -

i working on c# asp.net web forms project in visual studio ultimate 2013 while following http://goo.gl/1hk73 tutorial (but not doing exact same project). however, not make create .mdf file in app_date. i have created entity classes, dbcontext, seeded 1 of table single item, added connectionstring web.config: <add name="testingsystem" connectionstring="data source (localdb)\v11.0;attachdbfilename=|datadirectory|\studenttestingsystem.mdf;integrated security=true" providername="system.data.sqlclient" /> , , initialized database in global.asax.cs application_start() method: database.setinitializer(new testingsystemdatabaseinitializer()); i have looked similar problems, nothing worked me (i had done or did not work). i have refreshed app_data folder in solution explorer , used show files option nothing changed. my testingsystemdatabaseinitializer: using system.collections.generic; using system.data.entity; namespace student_testing_...

wix - At what step of MSI (InstallExecuteSequence) UAC is prompted? -

when execute msi uac on uac not prompted time. trying read registry entry in custom action before "costfinalize". registry read function consider default value if registry entry not found. in case registry entry there fails read because key doesn't have read permission "user". although admin have full permission. registry read seems happening before uac prompt. how can make sure uac prompted @ start registry read can successful. issue explanation we have old installer written in wix. writing registry entry install location this hklm\software\companyname\product\install\compinstalldir = [installdir]\product\component. this registry entry have permission admin user doesnt have read permission dont know why (i didnt write code). there other entries under hklm\software\companyname\product\install now have make changes in installer code upgrade. in have read install location i.e., [installdir]product\component , trim [installdir]. have existing custom...