Posts

Showing posts from May, 2010

php - Can't Understand 1 Line of Code in C++ STL Source: Lower_Bound/Upper_Bound -

i writing code find last key value no more given integer php. e.g.,array(0=>1,1=>2,2=>3,3=>3,4=>4). given integer 3, find key 3.(binary search) and looked references binary search on internet. find this, find first key value no less given integer c++. says: template <class _forwarditer, class _tp, class _distance> _forwarditer __lower_bound(_forwarditer __first, _forwarditer __last, const _tp& __val, _distance*) { _distance __len = 0; distance(__first, __last, __len); _distance __half; _forwarditer __middle; while (__len > 0) { __half = __len >> 1; __middle = __first; advance(__middle, __half); if (*__middle < __val) { __first = __middle; ++__first; __len = __len - __half - 1; } else __len = __half; // <======this line } return __first; } well, why using "__len = __half;" rather "__len = __half + 1;"? won't

Get NSImage from NSTextField in Swift -

i used retrieve nsimage in subclass of nstextfield obj-c this: nsdictionary *attributedval = [[self attributedstringvalue] attributesatindex:i effectiverange:&effectiverange]; if ([[attributedval allkeys] containsobject:nsattachmentattributename]) { nstextattachment *attachment = [attributedval valueforkey:nsattachmentattributename]; nscell *attachmentcell = (nscell *)[attachment attachmentcell]; ... [[attachmentcell image] name] ... } when try same in swift can't seem able cast attachmentcell compiler error: let attributedval = attributedstringvalue.attributesatindex(i, effectiverange: effectiverange) if let attachment = attributedval[nsattachmentattributename] as? nstextattachment { let attachmentcell = attachment.attachmentcell nscell // not work ... } thanks nate cook. following works: let attributedval = attributedstringvalue.attributesatindex(i, effectiverange: effectiverange) if let attachment = attributedval[nsa

python - How to get the value from a timedelta? -

when sqlalchemy returns: {u'age': datetime.timedelta(12045),} how 12045? i've tried str() , strftime() , , bunch of others, nothing works. from docs , use .total_seconds() length of timedelta. note timedelta you've provided showing days value, timedelta includes seconds , microseconds well. if want days, use .days . age = datetime.timedelta(12045) print(age.total_seconds()) # 1040688000.0 print(age.days) # 12045, not full value represented delta

Capturing Splunk dashboards to PDF -

i want capture splunk dashboard pdf sending periodic email. inbuilt pdf generator doesn't creates pdf in splunk. there open source tools can used cutycapt can capture screen via linux commands pages authentication. you try phantomjs . it uses webkit internally , has screen capture capability allowing export web page png/jpeg/pdf.

regex - How to insert a string between particular characters in Python? -

say have large parent string containing many characters. how can insert string between match of characters (and additionally, erase characters between matching characters)? for example, largestring guaranteed contain single set of ###### 's (6 hash characters). how can insert smallstring between it, ending similar (i guess better 'create string', since strings immutable): largestring = "lorem ipsum ###### previous text erased ###### dolor sit amet" smallstring = "foo bar" newstring = "lorem ipsum ###### foo bar ###### dolor sit amet" any ideas? assume use bit of regex... something like >>> import re >>> largestring = "lorem ipsum ###### previous text erased ###### dolor sit amet" >>> smallstring = "foo bar" >>> re.sub(r'(?<=###### ).*(?= ######)', smallstring, largestring) lorem ipsum ###### foo bar ###### dolor sit amet' (?<=###### ) postive b

Entity Framework and One to Many Relationships not saving right -

i worked entity framework several years ago, , may me being bit rusty. have detached entities, in turn have multiple child entities. in case it's person entity , each person has multiple addresses. myperson.firstname="update first name"; //assuming have address in first entry //with appropriate primary keys , foreign key ids, do: myperson.addresses.first().line1="update line 1"; myperson.addresses.add(new address(){line1="weee",line2="aaaa" postal="12345", type="work"}); mydb.person.attach(myperson); mydb.entry(myperson).state=entitystate.modified; mydb.savechanges(); when scenario this, expect first name. updates first name, , expected blanks out other fields (lastname, birthday etc etc) in above code. doesn't create new address person, nor update existing address. i don't recall requiring work database context know how update related entities associated person above. in google searches seem hearin

python - pandas read frame and subsequent type manipulation issue -

hello rookie pandas , have particular behavior want know reason for sqlnew = 'select fund_no,start_date,end_date,cash,bond,small_cap,large_cap,international odsact.act_src_fund_mapping;' actualfundmapping = psql.read_frame(sqlnew,cnxn) 'everyworks fine until above' actualfundmapping.dtypes:: fund_no object start_date object end_date object cash float64 bond float64 small_cap float64 large_cap float64 international float64 'so since want stuff datetime.datetime(2013,1,1) in actualfundmapping['start_date'] try changing dtype below actualfundmapping['start_date'] = pd.to_datetime(str(actualfundmapping['start_date'])) actualfundmapping['end_date'] = pd.to_datetime(str(actualfundmapping['end_date'])) actualfundmapping['fund_no'] = actualfundmapping['fund_no'].astype(np.int64) 'but existence tests come false datetime.datetime(20

Jquery Mobile persistent footer - change content on all pages -

i have problem persistent footer on page. creating web app jquery mobile. link project site when click add1 button footer updates"order(1)" , increments, when navigate second page see "order" , no number. my question is, how can fix that? i want keep same footer pages. i viewed project site , code has bugs. ill explain 1 one. you using same id name (objednavka) more once. id name must unique in document , not used more once. if want update many elements have same name use class instead. you don't need use pagebeforecreate have multi-page template (many pages) in 1 document , first gets loaded @ pageload. need create navbars @ once update orders , totals simultaneously. to add 1 variable better method use plus plus (myvar++) instead of updating whole order button again includes (order) text when click add 1 use span class="objednavka" next order , update new number there. we don't use $(document).ready(function() {

c# - What's the value in removing and/or sorting Usings? -

i've run remove , sort usings matter of course, because seems right thing do. got wondering: why this? certainly, there's benefit clean & compact code. , there must benefit if ms took time have menu item in vs. can answer: why this? compile-time or run-time (or other) benefits removing and/or sorting usings? as @craig-w mentions, there's small compile time performance improvement. the way compiler works, when encounters type, looks in current namespace, , starts searching each namespace using directive in order presented until finds type it's looking for. there's excellent writeup on in book clr via c# jeffrey richter ( http://www.amazon.com/clr-via-4th-developer-reference/dp/0735667454/ref=sr_1_1?ie=utf8&qid=1417806042&sr=8-1&keywords=clr+via+c%23 ) as why ms provided menu option, imagine enough internal developers asking for same reasons mention: cleaner, more concise code.

how to say "same class" in a Swift generic -

if swift generic type constraint protocol name, can require 2 types, constrained protocol, same type. example: protocol flier {} struct bird : flier {} struct insect: flier {} func flocktwotogether<t:flier>(f1:t, f2:t) {} the function flocktwotogether can called bird , bird or insect , insect, not bird , insect. limitation want. far, good. however, if try same thing class name, doesn't work: class dog {} class noisydog : dog {} class wellbehaveddog: dog {} func walktwotogether<t:dog>(d1:t, d2:t) {} the problem can call walktwotogether wellbehaveddog , noisydog. want prevent. there 2 questions here: is there way walktwotogether can't called wellbehaveddog , noisydog? is bug? ask because if can't use generic this, hard see why useful generic constraint class name @ all, since same result normal function. not answer, per se, more data perhaps... problem when call: walktwotogether(noisydog(), wellbehaveddog()) swift can treat bo

PHP Apache Rewrite Rules and Variables -

i'm trying action value variables in url. real url index.php?action=ok&id=45&name=lg-optimus friendly url home/ok/1/lg-p88 this above friendly url show when redirect page this header('location: /home/ok/' . $id . '/' . $name); the page script contains code variables $ok = isset($_get['ok']) ? $_get['ok'] : ""; if($ok=='ok'){ echo "<div class='popup'>"; echo "<strong>{$card-name}</strong> added!"; echo ""; echo "</div>"; } but 'undefined index ok '. the .htaccess file contains code # turn rewrite engine on rewriteengine on rewritecond %{request_filename} !-d rewritecond %{request_filename} !-f rewritecond %{request_filename} !-l # rewrite index.php rewriterule ^home index.php [nc,l] # rewrite card-name rewriterule ^home/([0-9]+)/([0-9a-za-z_-]+)$ index.php?action=$1&id=$2&name=$3 [qsa

java - Is there a nice way create new Object with some parameters in its constructor and also to have CDI beans injected in it? -

example: @dependant public class somestartingpoint { @inject private someservice someservice; public void dosomething(long along, mycustomobject myobject) { notabean notabean = new notabean(along, myobject); someservice.dostuffwithnotabean(notabean); } } public class notabean { @inject private wouldbeperfectifthiswouldbemanagedbean somehowinjectedbean; public notabean(long along, mycustomobject myobject) { //set state } } so question is, there nice way have injected notabean object, supposed have state in it, created new()? of course, in current situtation pass wouldbeperfectifthiswouldbemanagedbean argument constructor, not related question. there's cdi 1.0 way , cdi 1.1 way this. 1.1 way easier 1.0, hence why created it. here's example deltaspike: https://github.com/apache/deltaspike/blob/34b713b41cc1a237cb128ac24207b76a6bb81d0c/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/provider/beanprovider.ja

java - Eclipse and Git - Repositories from GitHub not available from Import menu (Projects from Git are available) -

i trying install doc4xj git per instructions listed here --> http://www.docx4java.org/blog/2012/05/docx4j-from-github-in-eclipse/ i have installed git in eclipse (kepler) update site: http://download.eclipse.org/egit/updates i @ step select "repositories github", option not listed. option have "projects git". i have installed version 3.5.2.201411120430-r. have installed following (everything available http://download.eclipse.org/egit/updates ) eclipse git team provider eclipse git team provider 3.5.2.201411120430-r eclipse git team provider - source code 3.5.2.201411120430-r task focused interface eclipse git team provider 3.5.2.201411120430-r jgit co jgit mmand line interface java implementation of git 3.5.2.201411120430-r command line interface java implementation of git - source code 3.5.2.201411120430-r java implementation of git 3.5.2.201411120430-r java implementation of git - optional http support using apache h

How to label payments in Gravity Forms Paypal Pro -

the situation: company wants enable donations through website. there 2 ways user can donate. 1. technology. 2. invest in project. the set-up: using gravity forms , paypal payments pro add-on payment processing on website. ('working great.') my issue: i'de ensure payments labeled when passed paypal account. i.e want know when donates money should go. although payments go 1 account. in paypal pro can add comments transactions. need able automatically add comment when form submitted. the solution: use below code add comment filter gravity forms pay pal pro. when payment processed given form, appears in paypal account comment. add_filter( 'gform_paypalpaymentspro_args_before_payment','add_donation_comment', 10, 2 ); function add_donation_comment( $args, $form_id ) { // not edit $args or $form_id // apply form 1 if ( 1 == $form_id ) { // replace '1' form id $args["comment1"] = 'field project'; // comment1 arg

c++ - C:2061 error on identifier vector despite vector is included in my .h file? -

i having c2061 error on private methods on classifier.h file. can see, have #include vector, , using public struct. can please me understand overlooking? #ifndef classifier_h #define classifier_h #include "patient_data.h" #include <qobject> #include <vector> #include <stdlib.h> class classifier : public qobject { q_object public: explicit classifier(qobject *parent = 0); ~classifier(); void classify(std::vector<patient_data>data, patient_data i); struct createsdtable { std::vector<int>sum[3]; //element 0 = tumor, element 1 = stage, element 2 = adjuvant std::vector<long>mean[3]; std::vector<long>error[3]; std::vector<long>sdl[3]; std::vector<long>sd[3]; }; createsdtable currentvsneutropenic; createsdtable currentvsnonneutropenic; private: std::vector<int> calculatesums(vector<patient_data> data, patient_data i, neut

regex - Issue with as_hex() function in perl -

i trying write code cidr ipv6. basicall, getting cidr perfix in code , convert binary. then using as_hex() function in bigint library, convert hexadecimal. that works fine. the problem when try hexadecimal inverted binary. how cant it, prints out white spaces. prefix : 78 actual binary: 0b11111111111111111111111111111111111111111111111111111111111111111111111111111100000000000000000000000000000000000000000000000000 hex: ffff:ffff:ffff:ffff:fffc:0000:0000:0000 inverted binary: 0b00000000000000000000000000000000000000000000000000000000000000000000000000000011111111111111111111111111111111111111111111111111 hex: 3fff:ffff:ffff:f:::: any ideas???? i think need handle leading zeros, as_hex seems rid of default. using 2 binary sequences provided: use math::bigint; sub paddedhex { ($binary) = @_; $x = substr(math::bigint->new($binary)->as_hex(), 2, -1); return sprintf("0x%032s\n", $x); } @binaries = qw/ 0b11111111111111111111111111

css rule in stylesheet but not applied in browser -

i'm making grid in html: *, *:after, *:before { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box sizing: border-box; } .mygrid { margin: 0 0 20px 0; } &:after { content: ""; display: table; clear: both; } [class*='col-'] { float: left; padding-right: 20px; } .grid &:last-of-type { padding-right: 0; } .col-1-2 { width: 33.3%; } .col-2-3 { width: 66.6%; } .content { background-color: #8ab9ff; padding: 20px; } <div class="mygrid"> <div class="col-1-2"> <div class="content"> <p>text text text</p> </div> </div> <div class="col-2-3"> <div class="content"> <p>text text text</p> </div> </div> </div> all changes apply on document except last rule on .content . wh

Running Hadoop on GPFS -

what other options hadoop derive fs.default.name option? i'm trying hadoop running on gpfs instead of hdfs. have configured hadoop use libgpfs.so, libgpfshadoop.so, , hadoop-1.1.1-gpfs.jar libraries provided ibm. i'm running trouble core-site.xml config (i suspect) , starting namenode. ssh working , configured correctly. launching namenode with: sbin/hadoop-daemon.sh --config $config_dir --script hdfs start namenode results in: 014-12-05 14:55:50,819 info org.apache.hadoop.hdfs.server.namenode.namenode: fs.defaultfs gpfs:/// 2014-12-05 14:55:50,941 warn org.apache.hadoop.util.nativecodeloader: unable load native-hadoop library platform... using builtin-java classes applicable 2014-12-05 14:55:51,063 fatal org.apache.hadoop.hdfs.server.namenode.namenode: failed start namenode. java.lang.illegalargumentexception: invalid uri namenode address (check fs.defaultfs): gpfs:/// has no authority. @ org.apache.hadoop.hdfs.server.namenode.namenode.getaddress(namenode.jav

C++ Problems with Class Arrays -

//#program read in ppm file , display in command prompt# //#also must able take 2 pictures , superimpose 1 on other# #include "image.h" #include "p3loader.h" #include "p6loader.h" #include <iostream> #include <fstream> #include <string> // sets height , width zero image::image() { width = height = 0; } // copies image class image::image(const image& copy) { width = copy.width; height = copy.height; loader = copy.loader; pixels = new color[copy.height]; for(int = 0; < copy.height; i++) { pixels = new color[copy.width]; } for(int h = 0; h < copy.height; h++) { for(int w = 0; w < copy.width; w++) { pixels[h*w] = copy.pixels[h*w]; } } } // zeros pixels out image::~image() { delete[] pixels; } //loads file user selects in main void image::loadimage(string filename) { ifstream picture;

c# - FindControl doesn't find control -

i setting gridview can select several events , add eventid's comma delimited string. going subscription service, need know events user wants subscribed to. i used template field add checkbox use indicator of event items wanted. so gridview looks this <asp:gridview id="gridview1" runat="server" allowpaging="true" allowsorting="true" autogeneratecolumns="false" datasourceid="sqldatasource1" pagesize="15" viewstatemode="enabled" selectedrowstyle-backcolor="purple"> <columns> <asp:templatefield> <itemtemplate> <asp:checkbox id="eventselected" runat="server" /> </itemtemplate> </asp:templatefield> <asp:boundfield datafield="eventid" headertext="eventid" insertvisible="false" readonly="tr

python - pcolormesh with masked invalid values -

Image
i'm trying plot one-dimensional array pcolormesh (so color varies along x-axis, constant in y-axis each x). data has bad values, i'm using masked array , customized colormap masked values set blue: import numpy np import matplotlib.pyplot plt import matplotlib.cm cm import copy = np.array([3, 5, 10, np.inf, 5, 8]) = np.ma.masked_where(np.isinf(a), a) imdata = np.vstack((a, a)) myhot = copy.copy(cm.hot) myhot.set_bad('b', 1) fig, ax = plt.subplots() im = ax.pcolormesh(imdata, cmap=myhot) plt.colorbar(im) plt.show() it works fine if don't have np.inf value, blank plot if do. seem have misunderstood way set_bad works because additional warning: runtimewarning: invalid value encountered in true_divide resdat /= (vmax - vmin) what should doing effect want? you need mask imdata , not a : import numpy np import matplotlib.pyplot plt = np.array([3, 5, 10, np.inf, 5, 8]) imdata = np.ma.masked_invalid(np.atleast_2d(a)) cmap = plt.cm.hot cmap.set_

web scraping - "Rescue" command in R? -

i have code: library(rvest) url_list <- c("https://github.com/rails/rails/pull/100", "https://github.com/rails/rails/pull/200", "https://github.com/rails/rails/pull/300") mine <- function(url){ url_content <- html(url) url_mainnode <- html_node(url_content, "*") url_mainnode_text <- html_text(url_mainnode) url_mainnode_text <- gsub("\n", "", url_mainnode_text) # clean text url_mainnode_text } messages <- lapply(url_list, mine) however, make list longer tend run a error in html.response(r, encoding = encoding) : server error: (500) internal server error i know in ruby can use rescue keep iterating through list, though attempts @ applying function fails. there similar in r? one option use try() . more info, see here . here's implementation: library(rvest) url_list <- c("https://github.com/rails/rails/pull/100",

java - Logger in HashMap -

i'm using java logger class log stuff , depending on data need configure log routes. let have following code: public class loggerlocator { private static hashmap<string, logger> loggermap = new hashmap<string, logger>(); private static int count = 0; public logger getlogger(string id) { if(!loggerlocator.loggermap.containskey(id)) { configure(id); } return loggerlocator.loggermap.get(id); } private void configure(string id) { logger logger = logger.getlogger(loggerlocator.class.getname()); filehandler fh = new filehandler(string.format("/home/abc/logs/mylog_%d.log", id), true); filehandler.setformatter(new myformatter()); logger.addhandler(fh); } loggerlocator.count++; loggerlocator.loggermap.put(id, logger); } my problem when extress test sending lot of requests server, printed count variable in every request, expected have value of 1 instead of getting value of 2 , 2 files name mylog_{id}.log, my

javascript - How to debug add-on main.js, not just content scripts for Firefox extension? -

my extension code layed-out in file system. i'm trying write add-on sdk extension because of restartless properties. i'm able debug, set breakpoints in launch.js , proc.js code, far haven't been able set break point in main.js. any idea why main.js doesn't show under 'sources' when in debug mode? or may missing? i'm using firefox developer edition on \sergixten \lib -main.js \data -launch.js -proc.js thanks help/hints! sergio use addon debugger add-on debugger available since firefox 31. enable (see on mdn page how to) , addons manager, click debug on addon.

Visualizing time series in spirals using R or Python? -

Image
does know how in r? is, represent cyclical data left plot right plot? http://cs.lnu.se/isovis/courses/spring07/dac751/papers/timespiralsinfovis2001.pdf here example data. day = c(rep(1,5),rep(2,5),rep(3,5)) hour = rep(1:5,3) sunlight = c(0,1,2,3,0,1,2,3,2,1,0,0,4,2,1) data = cbind(day,hour,sunlight) this seems pretty close: # sample data - hourly 10 days; daylight 6:00am 6:00pm set.seed(1) # reproducibility day <- c(rep(1:10,each=24)) hour <- rep(1:24) data <- data.frame(day,hour) data$sunlight <- with(data,-10*cos(2*pi*(hour-1+abs(rnorm(240)))/24)) data$sunlight[data$sunlight<0] <- 0 library(ggplot2) ggplot(data,aes(x=hour,y=10+24*day+hour-1))+ geom_tile(aes(color=sunlight),size=2)+ scale_color_gradient(low="black",high="yellow")+ ylim(0,250)+ labs(y="",x="")+ coord_polar(theta="x")+ theme(panel.background=element_rect(fill="black"),panel.grid=element_blank(),

android - Test accessibility (talkback) for application -

i making application accessibility compliant. providing correct data accessibility framework giving android:contentdescription="your string" in xml. also have seen android developer guide on making applications accessible overview of steps need take ensure application works correctly accessibility services. now problem testing these in each , every screen taking more time. app has 30 screens , each time go module take 15-20 mins when talk on. can suggest tool/ better way test app? @unof right, 1 tool can use lint show warnings missing content description. i'm experimenting google accessibility test framework, can automate of tests: https://github.com/google/accessibility-test-framework-for-android besides advice use emulator supports talk back, i'm using genymotion gapps installed , easier/faster cases using actual device, if going test multiple gestures, i'll recommend using genymotion remote control feature: https://docs.genymotion.com/con

windows - How to kill and start all sql server processes and services in task manager -

i newbie sql server , want kill sql server processes , services in task manager. processes , services used sql server, eat ram. when don't use sql server cause overload windows , windows slows down. want kill of them how can do? in fact in computer management can stop services , processes 1 one takes time. how can stop processes , services 1 click-one operation easily? how can start processes , services 1 click-one operation easily? used windows 7. you don't want kill processes task manager. instead reconfigure sql server use appropriate amount of memory: exec sys.sp_configure n'max server memory (mb)', n'200' --200 mb go reconfigure override go

java - What is @SuppressWarnings("deprecation") and how do I fix it? -

i following youtube tutorial , came across error. at line, @suppresswarnings("deprecation") comes up. player targerplayer = bukkit.getserver().getplayer(args[0]); here simple healing plugin. package me.roofer.youtube; import java.util.logging.logger; import org.bukkit.bukkit; import org.bukkit.chatcolor; import org.bukkit.command.command; import org.bukkit.command.commandsender; import org.bukkit.entity.player; import org.bukkit.plugin.plugindescriptionfile; import org.bukkit.plugin.java.javaplugin; public class youtube extends javaplugin { public static logger logger = logger.getlogger("minecraft"); public static youtube plugin; @override public void ondisable() { plugindescriptionfile pdffile = this.getdescription(); youtube.logger.info(pdffile.getname() + " has been disabled!"); } @override public void onenable() { plugindescriptionfile pdffile = this.getdescription(); youtu

python - f.readline() != '0' even if reading a line containing only 0 -

i not have trouble setting variables in program var = f.readline() function, having trouble if statement when comes reading out of text file. trying see if 0 in text file , every time use if f.readline() == '0': acts if not equal 0. example of script below: f = open("file.txt","r") myvar = f.readline() f.close if myvar == "0": print "the variable 0" raw_input("press enter continue") else: print "the variable not 0" raw_input("press enter continue") my code come out the variable not 0 why this? , how can use if statement readline function? the readline method not remove trailing newlines lines. need manually: myvar = f.readline().rstrip() otherwise, myvar equal "0\n" , not equal "0" . also, forgot close file calling close method: f.close() # notice parenthesis of course, using with-statement better: with open("file.txt&qu

c# - Concurrent users on Application result in MySQL Database Error -

i have c# web application connects mysql database. when multiple users access site @ same time see "there open datareader associated command must closed first" error. application works fine when 1 person accessing site. i found multiple articles sited multipleactiveresultsets=true in connection string, applies sql server not mysql. i traced error runsql function handles bulk of database queries unable find solution. this straight forward function, takes raw sql code, list of parameters, enum translates 1 of many possible database connection strings, , bool determines if need set transaction. i @ loss. public datatable runsql(string querystr, list<mysqlparameter> parameters, connectiontype connection, bool transaction) { datatable results = new datatable(); mysqlconnection con = new mysqlconnection(getconnection(connection)); mysqltransation trans; mysqlcommand command; con.open(); //if transaction requested, tie 1 query if(tra

python - Multiple dtypes in a Numpy array -

i have following data set in numpy array: array 1: [[a, 1, 20] [a, 3, 40] [b, 1, 20] [b, 2, 40] [c, 5, 90]] array 2: [[a, 2] [a, 5]] what i'm trying accomplish following: array2[0,0]=a , , array2[0,1]=2 want interpolate first array find a,2,30 . to i'm using np.where(array1==item)[0] looks 'a' , can't interpolate though because dtype used import string, not int. it's been while since i've used numpy if i'm in weeds please let me know. i'm not entirely clear on you're trying do, sounds want specify aggregate dtype. this explained in detail in dtype docs. for example, here's way specify each row has 1-character string , 64-bit native float (when don't care field names are): dt = np.dtype('u1, f8') there of course other ways write this; read full page details. and, assuming you've read in loadtxt , docs there have nice example of using such dtype. example: >>> s2 = 'a 2

Add Date/Time Validation to Excel's Cell -

i have work schedule have created , place code in there verifies entries proper time format , not text. i have basic part of code done i'm having difficulty searching through various cells. unfortunately cells 1 big list or easy enough code work. started create multiple ranges , going create statements cycle through figure there must simpler way. i'm new site can't attach image of schedule. can see below though in code various cells in range. any appreciated. private sub worksheet_change(byval target range) dim cel range, targ range dim v variant dim daterng range dim emp1a range, emp1b range dim emp2a range, emp2b range dim emp3a range, emp3b range dim emp4a range, emp4b range dim emp5a range, emp5b range dim emp6a range, emp6b range dim emp7a range, emp7b range dim emp8a range, emp8b range dim emp9a range, emp9b range dim emp10a range, emp10b range dim emp11a range, emp11b range dim emp12a range, e

multithreading - How does CountDownLatch works in Java? -

this question has answer here: how countdownlatch used in java multithreading? 10 answers i studying synchronization in java. not able understand exact mechanism of countdownlatch. does countdownlatch 'counts down latch' (waits completion of number of threads) per number of threads given @ declaration? here code tried understand: public class latchexample implements runnable { private countdownlatch latch; private int id; public latchexample(int id, countdownlatch latch){ this.id=id; this.latch = latch; } public static void main(string[] args) { countdownlatch latch = new countdownlatch(5); executorservice executor = executors.newfixedthreadpool(3); (int = 0; < 7; i++) { executor.submit(new latchexample(i,latch)); } try { latch.await();

Formatting output to resemble a table in C++ -

i using sprintf format data. same output when formatted using printf works cannot use printf using output data send email. for(...) { sprintf(sluns, "%-50s%-50s%-50s%-3d%-14s", str1, str2, str3, int1, str4); string srow(sluns); stable = stable + "\n" + srow; } the output of stable looks below. width not constant columns. because converting row elements c string ? name1 str1 str2 10 str3 name1 str1 str2 10 str3 name111 str1 str2 10 str3 i see have c++ tag on question. i'll recommend use c++ . you can use left , setw iomanip achive want. example: #include <string> #include <iostream> #include <strstream> #include <iomanip> using namespace std; string str1 = "str1"; string str2 = "str2"; string str3 = "str3"; string str4 = "str4"; int = 10; int main() { strstream str; str << lef

python - Py2Exe file closing at end, probably due to -

i made py2exe executable, it's "programming quiz". made in pygame , when run exe, works until end. assume because end has pygame text in it. error below. here's portion of code doesn't work exe normal .py: def endgame(): global programmer if programmer < 0: programmer = 0 font = pygame.font.sysfont(none, 25) text = font.render("you are: " + str(programmer) + "% programmer.", true, black) gamedisplay.blit(text, (170,200)) error: c:\python27\programming survey\dist>survey.exe survey.exe:43: runtimewarning: use font: dll load failed: specified module c ould not found. (importerror: dll load failed: specified module not found.) traceback (most recent call last): file "survey.py", line 223, in <module> file "survey.py", line 217, in main file "survey.py", line 43, in endgame file "pygame\__init__.pyc", line 70, in __getattr__ notimplementederror: font m

Checking rails form data against key before saving to database -

i'm attempting write app allows users register different id numbers account through use of form. ids have own model , table follows: mysql> show columns in hp_ids; +------------+--------------+------+-----+---------+----------------+ | field | type | null | key | default | | +------------+--------------+------+-----+---------+----------------+ | id | int(11) | no | pri | null | auto_increment | | id_string | varchar(255) | yes | | null | | | pin_number | int(11) | yes | | null | | | user_id | int(11) | yes | mul | null | | | created_at | datetime | yes | | null | | | updated_at | datetime | yes | | null | | +------------+--------------+------+-----+---------+----------------+ the id number saved under id_string the trick that, in order register id, user must enter corresponding pin prove have right

Heroku/Django Static files -

in local development environment href={% static "datetimepicker-master/jquery.datetimepicker.css" %}/> loads fine. in heroku, says csrf error think because trying load local host. how configure settings.py load static files correctly? file structure is: /project /app /staticfiles /mysite install dj-static (a django static file server) (getting started django on heroku) installing pip : pip install dj-static settings.py # static asset configuration import os base_dir = os.path.dirname(os.path.abspath(__file__)) static_root = 'staticfiles' static_url = '/static/' staticfiles_dirs = ( os.path.join(base_dir, 'static'), ) wsgi.py from django.core.wsgi import get_wsgi_application dj_static import cling application = cling(get_wsgi_application())

C++: why isn't the destructor designed like delete of a pointer? -

if delete pointer first time, release memory , assign null pointer. if delete pointer (with null value) second time, nothing happens, , no error throws out. then why isn't destructor designed delete of pointer, manuall call destructor of object, , assign object, null. destructor can called many times without error? [update] meant assign null explicitly pointer. the whole purpose of constructors , destructors avoid manual calling of destructor. it's designed objects automatically destroyed when no longer in use. makes harder programmer accidentally forget delete object; or use object has been deleted.

excel - Set focus on ComboBox (ActiveX Control) after code execution -

i have excel file combobox (name = "combobox1"). after running script (basically pasting selected value in "the next row" of column) want focus reset on combobox @ end of script, doing allowing me type next entry in combobox without having click on combobox text field first. this job in excel 2013 have working in 2007 well: combobox1.activate anyone idea? or: can replace combobox in-cell dropdown list (data validation) , same data validation 1 have in combobox @ moment, have issue: combobox can choose have dropdown list active, in-cell data validation not case, @ least not if want able type in cell after list shown alt+up or application.sendkeys "%{up}" any idea here?

android - NewView in CustomCursorAdapter is not getting called -

i have customcursoradapter taking cursor activity. public class pastjourneylistadapter extends cursoradapter { private static final string tag = "<pastjourneylistadapter>"; private final layoutinflater minflater; private cursor cursor; @suppresswarnings("deprecation") public pastjourneylistadapter(context context, cursor c) { super(context, c); cursor = c; minflater = layoutinflater.from(context); log.d(tag, "6" + c.getcolumncount() + c.getcount() ); } @override public void bindview(view view, context context, cursor cursor) { log.d(tag, "1"); textview journeytitle = (textview) view.findviewbyid(r.id.past_journey_title); journeytitle.settext(cursor.getstring(cursor.getcolumnindex("name"))); textview journeyplace = (textview) view.findviewbyid(r.id.past_journey_place); journeyplace.settext(cursor.getstring(cursor.getcol

c - pthread condition not being satisfied -

i creating multi threaded application runs forever until user sends interrupt (i.e. ctrl+c), output_report() method run. here sample of code: void output_report(int signo) { printf("exiting!\n"); pthread_mutex_lock(&mutex_num_of_threads); programclosing = true; while (numofthreads != 0){ pthread_cond_wait(&allthreadscompletecond, &mutex_num_of_threads); } pthread_mutex_unlock(&mutex_num_of_threads); printf("closing now!\n"); //this part not reached pthread_exit(null); // needed? exit(0); } void dispatch(struct pcap_pkthdr *header, const unsigned char *packet, int verbose) { static bool thread_settings_initialised = false; //only run first time dispatch method runs if (thread_settings_initialised == false){ thread_settings_initialised = true; if (signal(sigint, output_report) == sig_err) fprintf(stderr, "\ncan't catch sigint\n");

Multiple compositions in UML -

in uml class diagram, technically correct have 2 possible compistion relationships leading 1 class? i.e. have inventory class, has composition of inventory class. want have same relationship container class taking place of inventory. so, can have 2 compositions, or need turn these aggregations? you can have many composite associations on class level. each instance can part of 1 composition @ specific moment in time. uml superstructure says: if whole has aggregationkind = composite part can included in @ 1 composite @ time this article wrote tries explain difference: uml composition vs aggregation vs association

idris - Unsolved metavariable for function that has no inhabited arguments -

i getting unsolved metavariable foo in code below: namespace funs data funs : type -> type nil : funs (::) : {b : type} -> (a -> list b) -> funs (list a) -> funs (list a) data funptr : funs -> type -> type here : funptr ((::) {b} _ bs) b there : funptr bs b -> funptr (_ :: bs) b total foo : funptr [] b -> void how convince idris foo has no valid patterns match on? i've tried adding foo f = ?foo and doing case split in emacs on f (just see might come up), removes line, leaving foo unsolved meta. it turns out need enumerate possible patterns foo 's argument, , idris able figure out, 1 one, un-unifyable foo 's type: foo : funptr [] b -> void foo here impossible foo (there _) impossible

java - Firing bullet from gun's current position to mouse x & y position -

please i'm kinda lost in coding. so i've created bullet class: package javagame.states; import org.newdawn.slick.color; import org.newdawn.slick.gamecontainer; import org.newdawn.slick.graphics; import org.newdawn.slick.image; import org.newdawn.slick.input; import org.newdawn.slick.slickexception; import org.newdawn.slick.geom.vector2f; import org.newdawn.slick.state.statebasedgame; public class bullet { private vector2f pos; private vector2f speed; private int lived = 0; private boolean aktiv = true; private static int max_lifetime = 2000; public bullet (vector2f pos, vector2f speed){ this.pos = pos; this.speed = speed; } public bullet(){ aktiv = false; } public void update(int t){ rotation++; if(aktiv){ vector2f realspeed = speed.copy(); realspeed.scale((t/1000.0f)); pos.add(realspeed); lived += t; if(lived > max_li

google app engine - Data modeling in datastore -

i started using datastore, i'm still not sure few things. i have fallowing entities: property: {id, number, name, long, lat} address: {name, postcodetype} city: {name} country: {name} user: {name, username} so logic behind user have multiple properties , means property hold user key . as described above property has properties, not sure on how associate address city , country . i think solution store keys 3 entities in property entity . type property struct { id int64 `json:"id" datastore:"-"` number int8 `json:"number"` name string `json:"name"` long float64 `json:"long"` lat float64 `json:"lat"` addresskey *datastore.key citykey *datastore.key countrykey *datastore.key userkey *datastore.key createdat time.time } is attempt above start or need different. a list of countries changes, programmers use enum (or go

php - Changing text logo to image logo in Wordpress -

i trying change text logo image logo. spotted code in header.php. not sure how change it. using point theme. here code: <?php if ($mts_options['mts_logo'] != '') { ?> <?php if( is_front_page() || is_home() || is_404() ) { ?> <h1 id="logo" class="image-logo"> <?php list($width, $height, $type, $attr) = getimagesize($mts_options['mts_logo']); ?> <a href="<?php echo home_url(); ?>"><img src="<?php echo $mts_options['mts_logo']; ?>" alt="<?php bloginfo( 'name' ); ?>" <?php echo $attr; ?>></a> </h1><!-- end #logo --> <?php } else { ?> <h2 id="logo" class="image-logo"> <?php list($width, $height, $type,