Posts

Showing posts from March, 2010

skip the first input of a text file in c -

anyone knows how in c language? input: (input.txt) 2 word word word output: file contains: 2 word word are: word word *i'am new in c programming, , practicing self. have little code, not fixing yet problem. here's code: #include<stdio.h> int main(){ file* f = fopen("input.txt","r"); char c; int l = 1; if(f == null){ printf("file not found!"); return; } c = getc(f); while(c != eof){ if(c == ' '){ l++; } c = getc(f); } fclose(f); printf("file contain: %d word",l); return 0; } thanks! #include<stdio.h> int main(){ file *f = fopen("input.txt","r"); int wc, first_time = 1; char word[128]; fscanf(f, "%d", &wc); printf("file contain: %d word\n", wc); printf("word are: "); fscanf(f, "%*s");//skip while(1...

Boost C++ XML parsing -

i familiar on how parse xml boost, if xml has , including 3 levels. however, having trouble following example: (please ignore slight lack of logic in xml since adaptation of cannot change. structure important) <content> <room> <roomname>livingroom</roomname> <description> <color>red</color> <size>small</size> </description> <description> <color>blue</color> <size>big</size> </description> </room> <room> <roomname>bathroom</roomname> <description> <color>green</color> <size>medium</size> </description> </room> </content> i have...

python - h5py: slicing dataset without loading into memory -

is possible slice h5py dataset in 2 subsets without loading them memory? e.g.: dset = h5py.file("/2tbhd/tst.h5py","r") x_train = dset['x'][:n/2] x_test = dset['x'][n/2:-1] no. you need implement own class act view on dataset. an old thread on h5py mailing list indicates such datasetview class theoretically possible implement using hdf5 dataspaces, not worth many use cases. element-wise access slow compared normal numpy array (assuming can fit data memory). edit: if want avoid messing hdf5 data spaces (whatever means), might settle simpler approach. try this gist wrote. use this: dset = h5py.file("/2tbhd/tst.h5py","r") simpleview import simpleview x_view = simpleview(dset['x']) # stores slices, doesn't load memory x_train = x_view[:n/2] x_test = x_view[n/2:-1] # these statements load data memory. print numpy.sum(x_train) print numpy.array(x_test)[0] note slicing support in simple exa...

Graphite adding new resolution to a metric -

given have metric (stats.counters.prod.failedbuildmessages) , want extend resolution (stats.counters.prod.failedbuildmessages.1, stats.counters.prod.failedbuildmessages.2, stats.counters.prod.failedbuildmessages.3 etc') don't want lose previous data , still use long can, how can overlay data? seems once add sub counters failedbuildmessages node loses data. is there way it? you should send old metric alongside new one. different metrics if share same hierarchy. i in order have coarser/finer details on metric , works quite well.

C Union and simultaneous assignment to members -

this question has answer here: floating point numbers not work expected 6 answers in following code #include<stdio.h> int main() { union myunion { int intvar; char charvar; float floatvar; }; union myunion localvar; localvar.intvar = 10; localvar.charvar = 'a'; localvar.floatvar = 20.2; printf("%d ", localvar.intvar); printf("%c ", localvar.charvar); printf("%f ", localvar.floatvar); } i understand union can hold 1 value @ time. when assign char value, int overwritten, n when assign floatvalue, char overwritten. expecting garbage values int , char variables , 20.200000 float variable last value assigned. following output i'm getting on vs express gcc 1101109658 Ü 20.200001 unable understand why float value changed ? this has nothing union ,...

java - Retrieving query parameters in order in JAX-RS UriInfo -

in jax-rs need iterate (arbitrary) given query parameters in request... in original order in uri! if inject @context uriinfo uriinfo can use uriinfo.getqueryparameters() multivaluedmap of query parameters, grouped query parameter name. if care original order of query parameters? there way iterate name/value pairs? or must extract them manually uriinfo.getrequesturi() ? if i'm stuck manual extraction, there standard or well-maintained , updated library can use doing this? custom solution apache httpclient library: public void process(@context uriinfo uriinfo) { string querystring = uriinfo.getrequesturi().getquery() //todo: extract charset content-type header, if present list<namevaluepair> queryparams = urlencodedutils.parse(querystring, "utf-8") for(namevaluepair param : queryparams) { //do need } }

AngularJS pass Javascript object to controller -

i'm trying pass javascript object angularjs controller , having no luck. i've tried passing init function: <div ng-controller="gallerycontroller" ng-init="init(jsobj)"> and on controller side: $scope.init = function(_jsobj) { $scope.externalobj = _jsobj; console.log("my object.attribute : " + _jsobj.attribute ); }; though above doesn't seem work. alternatively, i've tried pulling attribute angularjs controller interested in use in inline <script> tag: var jsobj.parameter = $('[ng-controller="gallerycontroller"]').scope().attribute ; console.log("my object.parameter: " + jsobj.attribute ); can tell me: best practice regarding this? i don't have option rewrite plain javascript object part of 3rd party library. let me know if need provide further clarification , in advance guidance! -- johndoe try setting value: angular.module('myapp') .value...

javascript - underscore.js .keys and .omit not working as expected -

i'm running mongodb access via mongoose store user records. have underscore on server. have restful api route returns collection (array of objects) database. want return full collection client but remove password element each object doesn't sent client. before says anything, use bcrypt salt , hash password in final version :) today have 1 entry in database, user 'administrator'. here's code in route: app.get('/users', function(req, res) { user.find().sort({'username': 'ascending'}).exec(function(err, data) { _.each(data, function (element, index, list) { console.log('username=' + element.username); console.log('password=' + element.password); delete element.password; console.log('keys: ' + _.keys(element)); console.log('password=' + element.password); console.log(_.omit(element, 'password')); }); res.json(data); }); }); what sent browser...

java - Android: open hidden webview activity or fragment -

i'm developing android app shows listview. when user clicks on item on list, need app opens regular activity details and, in background or in "hidden mode", opens webview load url (of blog). i need because want trace items opened, analyzing google analytics information on blog; in way, everytime clicks on item, i'll find information on blog. is there way it? the correct way open hidden webview call webview.setvisibility(view.gone) on oncreate method

data structures - Efficient way of printing hash of hash of arrays in Perl -

i writing script involves printing contents of hash of hash of arrays. ex (pseudo code): my %hash = (); $hash{key1}{key2} = ['value1', 'value2', 'value3', . . .]; or $hash{key1}{key2} = @array_of_values; basically want able number of key combinations , able loop through of possible key/value pairs (or more correctly stated key,key/array pairs since each value array of values , each array has 2 keys associated it) , print output in following format: "key1, key2, value1, value2, value3, . . .\n" ex: #!/usr/bin/perl use strict; use warnings; # initialize hash %hash = (); $string1 = "string1"; $string2 = "string2"; # push strings onto arrays stored in hash push @{$hash{a}{b}}, $string1; push @{$hash{a}{b}}, $string2; push @{$hash{c}{d}}, $string2; push @{$hash{c}{d}}, $string1; # print elements of hash # (want loop possible key/value pairs) local $, = ','; print "a, b, "; print @{$hash{a}{b}}; p...

sql - How to write a select inside case statement -

i have stored procedure contains case statement inside select statement. select invoice_id, 'unknown' invoice_status, case when invoice_printed null '' else 'y' end invoice_printed, case when invoice_deliverydate null '' else 'y' end invoice_delivered, case when invoice_deliverytype <> 'usps' '' else 'y' end invoice_edeliver, invoice_contactlname+', '+invoice_contactfname contactname, dbo.invoice left outer join dbo.fninvoicecurrentstatus() on invoice_id=cust_invoiceid cust_statusid= 7 order inv_created at line case when invoice_deliverytype <> 'usps' '' else 'y' end invoice_edeliver i need check valid email address (if email valid, display y, else display n). so line read: if invoice_deliverytype <> 'usps' '' else ( if isnull(select emailaddr dbo.client client_id = substring(invoice_id, 1, 6)), 'y', 'n') ho...

javascript - Canvas Ball bounces in wrong direction when pong paddle is moving -

i start off note. tried using jsfiddle reason html5 canvas not work. workaround used http://jsbin.com/gugihuwegopa/1/ . edit site, click edit button @ top right corner of window. anyway, problem is, when paddle not moving, ball bounces correctly off sides (the nomove variable has nothing that, make disappear "w" key). however, when move paddle mouse towards ball, gets stuck inside paddle. think because not updating location of paddle fast enough ball ends inside of it, , code continues cause ball bounce while inside. (until moving paddle rapidly away , gets unstuck). yes have tried putting cxt.fillrect before cxt.arc() . ball travel through paddle well. figure way fix factoring in direction of ball in 2 if statements: if(y+ymove>=w && y+ymove<=w+h && x>=s && x<=s+l ) ymove*=-1; //top , bottom if(x+xmove>=s && x+xmove<=s+l && y+ymove<=w+h && y+ymove>=w ) xmove*=-1; //left , right some other meth...

c# - The 'await' operator can only be used with an async lambda expression -

this question has answer here: the 'await' operator can used within async lambda expression 1 answer i'm trying copy list of files directory. i'm using async / await. i've been getting compilation error the 'await' operator can used within async lambda expression. consider marking lambda expression 'async' modifier. this code looks like async task<int> copyfilestofolder(list<string> filelist, iprogress<int> progress, cancellationtoken ct) { int totalcount = filelist.count; int processcount = await task.run<int>(() => { int tempcount = 0; foreach (var file in filelist) { string outputfile = path.combine(outputpath, file); await copyfileasync(file, outputfile); //<-- error: compilation error ct.throwifc...

java - How to fill an array with random numbers from 0 to 99 using the class Math? -

i wrote code, there no conversion double int. public class array { public static void main(string[] args) { int i; int[] ar1 = new int[100]; for(int = 0; < ar1.length; i++) { ar1[i] = int(math.random() * 100); system.out.print(ar1[i] + " "); } } } how can corrected? it should like ar1[i] = (int)(math.random() * 100); when cast, cast type should in brackets e.g. (cast type)value

python - Connect to SSH using paramiko throue TOR -

i want know how add tor / proxy connection: def check_server(host, user, password, port=22): ssh = paramiko.sshclient() ssh.set_missing_host_key_policy(paramiko.autoaddpolicy()) #failed approch #proxy = paramiko.proxycommand("127.0.0.1:9010") if is_work_sshd(host,port): return 2 try: ssh.connect(host, username=user, password=password, port=port) ssh.close() except: return 1 return 0 i made google search lot of time didn't found answer question ! , there way php phpseclib :( if have answer python you're welcome :)

php fatal error wordpress -

i'm getting error on website: fatal error: call member function get_settings() on non-object in /home4/gabeweb/public_html/store/wp-content/plugins/woocommerce/includes/class-wc-install.php on line 291 this line 291 : foreach ( $section->get_settings() $value ) { can me resolve issue? can't admin of wordpress site due error. thank you. there appears problem plugin. if rename woocommerce folder within wp-content/plugins/ plugin deactivated, allowing admin area.

android - How to use asyncTask to load images from resources -

here in custom adapter, in list view there 1 imageview. loading list of images in listview. want load new images in asynctask idont know how implement asynctask , tutorials refers image downloading using drawable resources, kindly guide me through how implement asynchronous loading of images replace image in current visible view. class myadapter extends baseadapter { private context context; private int images[]; public myadapter(context context, int images[]) { this.context = context; this.images = images; } @override public int getcount() { // todo auto-generated method stub return images.length; } @override public object getitem(int position) { // todo auto-generated method stub return images[position]; } @override public long getitemid(int position) { // todo auto-generated method stub return position; } class myviewholder { imageview imageview...

twitter - 0Auth handshake failed in R -

i attempting set tweet sentiment analysis tool in r, keep getting errors in relation 0auth not completing it's handshake. it's using tutorial found online, i'm new r , coding in general i'm stumped. any light can shed on appreciated: install.packages("twitter") install.packages("plyr") install.packages("stringr") install.packages("ggplot2") install.packages("streamr") library(twitter) library(roauth) library(plyr) library(stringr) library(ggplot2) ## windows users need file download.file(url="http://curl.haxx.se/ca/cacert.pem", destfile="cacert.pem") requesturl <- "https://api.twitter.com/oauth/request_token" accessurl = "https://api.twitter.com/oauth/access_token" authurl = "https://api.twitter.com/oauth/authorize" consumerkey = "conkey code" consumersecret = "consec code" cred <- oauthfactory$new(consumerkey=consumerkey, ...

php - Send mail to each array value -

i have array $emails. print_r($emails) output following: array ( [0] => array ( [user_email] => ) [1] => array ( [user_email] => mail_1@gmail.com ) [2] => array ( [user_email] => mail_2@gmail.com ) ) now want send emails email addresses in array. tried: foreach($emails $contact) { $to = $contact; $subject = 'the subject'; $message = 'hello'; mail($to, $subject, $message, $headers); } what is: warning: mail() expects parameter 1 string, array given foreach($emails $contact) { $to = $contact['user_email']; $subject = 'the subject'; $message = 'hello'; mail($to, $subject, $message, $headers); }

parallel processing - make -jN blocks on second run when using an order-only prerequisite in sub-sub-target -

i've been having strange problem makefile using order-only prerequisite , parallel mode: when running in sequential mode, first time makefile job, , next times, nothing , returns, expected. when running in parallel mode (-j4 instance), first time job, next times hangs. process blocked doing nothing, doesn't exit. still responsive in sense if terminate using ctrl-c, cleans intermediate files may have created , stops. in parallel mode, if make clean , runs again without problem. likewise, if touch all source files, works (again, in parallel mode). if touch some of source files, runs fine until it's done them, hangs. so created minimal working example, main folder contains folder named 'txt' *.txt file in (could file) , makefile txt_files = $(shell ls txt/*.txt) a_files = $(patsubst txt/%.txt, a/%.txt, $(txt_files)) all: a: $(a_files) dir: @if [ ! -d "a" ]; echo "create directory a" && mkdir -p a; fi a/tmp_%: txt/%...

c - array is full of the last element in a file -

i have procedure readtokens() takes file , array , tokenizes file , puts things array when access array, full of last element. why? here readtokens() method: void readtokens(char *filename, char** a[]) { file *fp; char *token; int count = 0; fp = fopen(filename, "r"); if (fp == 0) { fprintf(stderr,"file %s not opened reading\n", filename); exit(1); } token = readline(fp); while(!feof(fp)) { a[count] = token; ++count; free(token); token = readline(fp); } fclose(fp); } you should not call free(token) , since still have pointer in a[count] . since you're freeing it, memory can reused, , apparently it's being used when readline() reads next line. each time read line, reuses same memory , overwrites next line. result, elements of a[] contain pointers same line. a[count] = token doesn't make copy of token, assigns pointer. this assumes readline() uses malloc() allocate memory line reads. if doe...

powershell - How do I send each result of Get-AdGroupMembership to my array? -

i'm trying recurse ntfs folder structure, , output csv file displays each user account permissions on folders. in script outputs correctly except portion discovers group , proceeds enumerate users in group using get-adgroupmember. while debugging, can see each user within group (even nested groups) outputted, guess i'm not "arraying" each output of command , sending onward "out" array. i marked section i'm having trouble with. folks provide appreciated. thanks! $answer = read-host 'do wish use answer file? file must named answer.csv , must reside in same directory script. (default [n])' if ($answer -eq "y") { $ansfile = import-csv answer.csv | select src,outdir,domain,user,pwd $list_dir = $ansfile.src $outpath = $ansfile.outdir $domainname = $ansfile.domain $admin = $ansfile.user $pwd = $ansfile.pwd } else { { $list_dir = read-host 'enter directory path searched/recursed' $testlist_dir = test-path...

html - How to use JavaScript to scale an image to fit -

i have 67x67 px image scale down 45x45 fit anchor not know how adjust it. html is: <a class="compareprofilepic" id="compareprofilepic1" href="#"> <span id="compareprofilepicactionbtn1" class="autocenter"> </span> </a> my css is: a.compareprofilepic { height: 45px; width: 45px; border-radius: 50%; float: left; margin-right: 10px; cursor: default !important; } and js is: document.getelementbyid('compareprofilepic1').style.csstext = 'background-image: url(img/pic1.jpg)'; all searches led changing size of holding image, needs stay 45x45. suggestiosn on how scale image size? thanks tips or pointers. take here: i used document.getelementbyid('compareprofilepic1').style.backgroundsize = "45px 45px";

hadoop - Sqoop Free-Form Query Causing Unrecognized Arguments in Hue/Oozie -

i attempting run sqoop command free-form query, because need perform aggregation. it's being submitted via hue interface, oozie workflow. following scaled-down version of command , query. when command processed, "--query" statement (enclosed in quotes) results in each portion of query interpreted unrecognized arguments, shown in error following command. in addition, target directory being misinterpreted. preventing running, , can done resolve it? ${env} , ${shard} variables being parsed, reflected in last error message. thank you! =========== import --connect jdbc:mysql://irbasedw-${shard}.db.xxxx.net:3417/irbasedw_${shard}?donttrackopenresources=true&defaultfetchsize=10000&usecursorfetch=true --username iretl --password-file /irdw/${env}/lib/.passwordbasedw --table agg_daily_activity_performance_stage -m 1 --query "select sum(click_count) agg_daily_activity_performance_stage \$conditions group 1" --target-dir /irdw/${env}/legacy/agg/acti...

android - determine which EditText field is selected on focus -

i have table multiple rows, each containing edittext corresponds dimension. want have sort of listener return whichever edittext selected. can done getcurrentfocus(); or onfocuschange(); ? my idea have user select/focus dimension field want edited, , completing field using output slope/angle device's gyroscope when "write data" button pressed. i'd using selected_dimension_edittext.settext(gyro_value); you can know edittext has focus id of view this: edittext edtext1 = (edittext)findviewbyid(r.id.edittext1); edittext edtext2 = (edittext)findviewbyid(r.id.edittext2); onfocuschangelistener mfocuschangelistener = new onfocuschangelistener() { @override public void onfocuschange(view v, boolean hasfocus) { // todo auto-generated method stub if(hasfocus){ //check if view has focus switch (v.getid()){ case r.id.edittext1: { //code ...

c - Should "freopen'ed" stdout be closed? -

in c or c++ program can use freopen redirect output (i.e. stdout file descriptor) file (or discard reopening file descriptor /dev/null or sink). the question is: if so, should take care of closing file descriptor explicitly before program ends execution? why? on platforms? happens in general , in specific case if don't close file descriptor? should take care of closing file descriptor explicitly before program ends execution? from freopen(3) man page : the freopen() function opens file name string pointed filename , associates stream pointed stream it. original stream (if exists) closed. so no, don't have close original file * . should close 1 freopen call, though. btw - these file * variables, not file descriptors. why? because documentation says don't have to. on platforms? any correctly implement freopen(3) defined c standard. what happens in general , in specific case if don't close file descriptor? the operating sy...

sql - Blobs and Liquibase generateChangeLog -

we have started using liquibase @ our shop. use postgresql 9.3 we trying use liquibase --difftypes=data generatechangelog to create changelogs our activitii tables. these tables use bytea columns store png data. however, when run generatechangelog, value liquibase not in column. instead getting this. <insert tablename="act_ge_bytearray"> <column name="id_" value="148802"/> <column name="rev_" valuenumeric="1"/> <column name="name_" value="image/jpeg"/> <column name="deployment_id_"/> <column name="bytes_" value="[b@4d513b99"/> <column name="generated_"/> </insert> the actual data in bytes_ binary representation of png file. wont paste here long, can see, liquibase not copy on correct data. is there way address generatechangelog returns whats stored in byte...

jquery - passing an object through a variable function -

here relatively straightforward code build 2 years ago: var armed=false; function autosave(){ if(armed){ $('#console').html('submitting..'); $('#autosave').val(1); $.ajax({ url: '/gf5/console/resources/bais_01_exe.php', data: $('#form1').serialize(), method: 'post', }).done(function(data){ //$('#cs').html('saved'); $('#console').html('saved'); armed=false; }); $('#autosave').val(''); }else{ $('#console').html('idle'); } settimeout('autosave()',7000); } function arm(){ armed=true; //$('#cs').html('active'); } $(document).ready(function(){ $('input[type=text],textarea').keyup(arm); $('input[type=checkbox]').click(arm); $('input[type=hidden]').change(arm); $(...

How to find two records sharing the same Month and Day of birth in SQLITE3 -

i have table person , in have name , birthday. for example, have table called person insert person values ( 'alice', '1986-10-10'); insert person values ( 'kate', '1992-10-10'); i type in query produce alice , kate ( query displays entries share month , day, year doesn't matter). birthday used store date , used date data type. i have other values different birthdates, can't seem figure out query produce alice , kate (because share month , day of birthday) this have far, not producing anything: select name person birthday '_____xx__xx'; your query work (with corrected pattern), need ensure dates in correct format. documentation: a time string can in of following formats: 1. yyyy-mm-dd ... so need use format dates. "1992-3-3" not recognized date; need use "1992-03-03". or can use julian dates makes arithmetic convenient reading things little harder without use of date/time functions. ...

swift - Zoom in Universal Storyboard Preview (XCode 6) -

i know how zoom in , out in universal storyboard, how can in storyboard preview? can see fourth of ipad renderer only, none less multiple devices @ once. i found out answer double click in white space. hope helps out

html - How to edit WordPress CSS written as inline CSS? -

this question has answer here: how can override inline styles external css? 4 answers i'm trying edit css of wordpress template. i using firefox find css styles , found line need edit, looks this: <div style="transition: height 350ms ease 0s; height: 450px;" class="og-expander"> what want change height: 450px height: 100% . i have tried editing og-expander class' height, didn't work. realized height property within og-expander disabled because of inline css, can't find place edit inline css. i have searched through other css files well, failed find it. you can override style added directly element !important after style statement in css files. instance .og-expander { height: 350px !important; transition: 0 !important; } also, might try searching php files edit place directly. if added in cor...

What does the following function do in Scheme programming language -

(define (unknown (lambda (x y) (cond ((null? y) y) ((x (car y)) (unknown x (cdr y)))) (else (cons (car y) (unknown x (cdr y))))))) i'm newbie when comes scheme , wanted know purpose of function came across in textbook. main doubt lies ((x (car y)) does. how expression executed without operators , yet don't come across errors while compiling. although i'm unable run program because values input x apparently not applicable function. please help. scheme functions can take functions arguments, , can return functions. code makes sense if pass in function argument. if call code this: (unknown even? '(1 2 3 4 5)) then should return list (1 3 5). filtering function returns members of y result of applying function x member false.

Python multiprocessing within mpi -

i have python script i've written using multiprocessing module, faster execution. calculation embarrassingly parallel, efficiency scales number of processors. now, i'd use within mpi program, manages mcmc calculation across multiple computers. code has call system() invokes python script. however, i'm finding when called way, efficiency gain using python multiprocessing vanishes. how can python script retain speed gains multiprocessing when called mpi? here simple example, analogous more complicated codes want use displays same general behavior. write executable python script called junk.py. #!/usr/bin/python import multiprocessing import numpy np nproc = 3 nlen = 100000 def f(x): print x v = np.arange(nlen) result = 0. i, y in enumerate(v): result += (x+v[i:]).sum() return result def foo(): pool = multiprocessing.pool(processes=nproc) xlist = range(2,2+nproc) print xlist result = pool.map(f, xlist) print...

sql server - c# windows forms logout -

how make logout button in c# windows forms closes mssql connection. i have login form sends username , password 1 form another. connection string on form2 placed under public partial class , looks this: public static sqlconnection con = new sqlconnection(@"data source=" + globalvariables.hosttxt + "," + globalvariables.porttxt + "\\sqlexpress;database=ha;persist security info=false; uid='" + globalvariables.user + "' ; pwd='" + globalvariables.psw + "'"); sqlcommand mysqlcmd = con.createcommand(); i've created logout button on form2 goes first login form, doesn't seem close sqlconnection. can press login button again without entering user , password , through form2 again. so first time have enter username , password , second time dont need to. the code use logout button is: con.close(); this.close(); form fmlogind = new logind(); fmlogind.show(); here whole code on second form: using system; ...

forceclose - Keep log in text file on device when app force close on android -

my android app force close time when running on device.i want store error log in text file on device.so can see reason behind force close.because difficult identify when sudden force close occure when app running. can provide me way create log file on sd card. thanks in advance. i have following code when app start after adding code app not force close,and log file showing null. thread.setdefaultuncaughtexceptionhandler(new thread.uncaughtexceptionhandler() { @override public void uncaughtexception(thread thread, throwable ex) { log.e("uncaught exception", thread.tostring()); log.e("uncaught exception", ""+ex.getmessage()); try { printwriter out = new printwriter("mnt/sdcard/log.txt"); out.println(ex.getmessage()); out.close(); } catch (filenotfoundexception e) { e.printstacktrace(); } ...