Posts

Showing posts from July, 2012

json is not converting to csv in python 3.5 -

#!/usr/bin/env python import requests import csv import json import sys s = requests.session() r = s.get('https://onevideo.aol.com/sessions/login?un=username&pw=password') r.status_code if r.status_code == 200: print("logged in successfully") else: print("check username , password") filename = open('outputfile3.csv', 'w') sys.stdout = filename data = s.get('https://onevideo.aol.com/reporting/run_existing_report?report_id=102636').json() json_input = json.load(data) entry in json_input: print(entry) your assignment of sys.stdout = filename not idiomatic, many people may not understand doing. key misunderstanding appear have python interpret either fact have imported csv or extension of file have opened , automatically write valid lines file given list of dictionaries (which .json gets parsed as). i present full example of how write dictionary-like data contrived json reproducability: jsonstr =...

javascript - How do I save data from a checkbox array into database -

function check_uncheck(truefalse) { var boxes = document.forms[0].chkboxarray.length; var form = document.getelementbyid('checkform'); (var = 0; < boxes; i++) { if (truefalse) { form.chkboxarray[i].checked = true; } else { form.chkboxarray[i].checked = false; } } } <form name="checkform" id="checkform" method="post" action="checkboxes1.php"> <input type="checkbox" name="chkboxarray" value="1" /><br /> <input type="checkbox" name="chkboxarray" value="2" /><br /> <input type="button" name="checkall" value="check boxes" onclick="check_uncheck(true)" /> <input type="button" name="uncheckall" value="uncheck boxes" onclick="check_uncheck(false)" /> <input type="submit" value="sav...

c# - Certain GStreamer pipelines not considered to be a bin? -

i can run simple launch pipeline command line thus: gst-launch-1.0 videotestsrc ! ximagesink and, gst-inspect-1.0 , ximagesink appears support gstvideooverlay interface can bind specific gtk widget. however, when trying within code happened find lying around on net, seems pipeline not considered bin (and hence, widget id not being given it). the code follows, first create pipeline , set capture bus messages: gst.element playbin = gst.parse.launch("videotestsrc ! ximagesink"); gst.bus bus = playbin.bus; bus.addsignalwatch(); bus.message += msgcallback; then process bus messages: private void msgcallback(object o, messageargs args) { // care window id binding requests. gst.message msg = args.message; if (! gst.video.global.isvideooverlaypreparewindowhandlemessage(msg)) return; // source of message. gst.element src = msg.src gst.element; if (src == null) return; // find element supporting interface , notify bind...

ios - Are NSNotificationCenter events received synchronously or asynchronously? -

if class registers nsnotificationcenter events of type , class posts event of type, code in receiver execute before (synchronously) or after (asynchronously) posting class continues? - (void)poster { [[nsnotificationcenter defaultcenter] postnotificationwithname:@"myevent" object:nil]; nslog(@"hello poster"); } - (void)receiver { [[nsnotificationcenter defaultcenter] addobserver:self selector:@selector:(myselector) name:@"myevent" object:nil]; } - (void) myselector:(nsnotification *) notification { nslog(@"hello receiver"); } in code example above, "hello receiver" printed before or after "hello caller"? as stated in documentation nsnotificationcenter nsnotificationcenter class reference notifications posted synchronously. a notification center delivers notifications observers synchronously. in other words, postnotification: methods not ret...

Combining Lists in python with common elements -

i generating lists '1' , '0' in them: list_1 = [1,0,0,1,0,0] list_2 = [1,0,1,0,1,0] i trying combine them if '1' appears in either list, appears in new list, , replaces '0' new_list = [1,0,1,1,1,0] what code be? use bitwise or | on list comprehension , using zip function: >>> [x | y x,y in zip(list_1, list_2)] [1, 0, 1, 1, 1, 0] if lists don't have same length, use zip_longest itertools module: >>> l1 = [1,1,1,0,0,1] >>> l2 = [1,0,1,1,1,0,0,0,1] >>> >>> [x | y x,y in zip_longest(l1, l2, fillvalue=0)] [1, 1, 1, 1, 1, 1, 0, 0, 1] another way, use starmap , remember in python3, yields generator have convert list after that, way: >>> itertools import starmap >>> operator import or_ #bitwise or function passed starmap >>> list(starmap(or_, zip_longest(l1,l2, fillvalue=0))) [1, 1, 1, 1, 1, 1, 0, 0, 1]

c# - Get last 3 characters of string -

how can last 3 character out given string? example input: am0122200204 expected result: 204 many ways can achieved. simple approach should taking substring of input string. var result = input.substring(input.length - 3); another approach using regular expression extract last 3 charcters. var result = regex.match(input,@"(.{3})\s*$"); working demo

linux - Where to securely store php scripts on a web server? -

i'm creating ios application when click button, executes script on apache web server , returns data associated. have these scripts inside /var/www/html/ if manually type in address of said script in url, returns data. how restrict data application? i debating storing password in source code , have authenticate server, wondering if there's better option.

wordpress - Suggestions on why site is slow/how to speed up? -

i know website image based, have limited plugins as can , compressed css , styling. shouldn't slow is. reason why or can speed up? thanks in opinion 1- using css , javascript 2- eliminate render-blocking javascript , css in above-the-fold content 3- should optimize image 4- can upgrade server faster server 5- enable compression , browser caching , ..... edit: how improve above steps: 1- better performance better keep page size under 600kbit it's because of theme or plugin use, if can, change template optimize version , reduce unnecessary plugins. on other hand there features can handle few codes, rather install new plugin new plugins has self javascript , css 2-put javascript codes on footer befoter </body> ( help ), , create javascript loader css, insert css on head.( help ) simple example of render-blocking <!doctype html> <html> <head> <title>title</title> <!-- not insert css or javascript here --> ...

html - Bootstrap3 Navbar fill content -

Image
i fit navbar options in container this: tried using website methods, couldn't working, broke responsive. can please explain me best way using bootstrap? thank you i created fiddle take look, may you. use margin doing this .navbar.navbar-default.navbar-fixed-top { margin: 6px 10px 0px 5px; } #blue{background-color:blue !important; height: 57px;} .navbar-collapse.in, .navbar-collapse.collapsing { clear: left; } .navbar.navbar-default.navbar-fixed-top { margin: 6px 10px 0px 5px; } #blue{background-color:blue !important; height: 57px;} <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <div id="blue...

php - CodeIgniter controllers unreachable -

i developed web application using xampp , codeigniter. best way handle clean routing has been set virtualhost point on folder containing project in xampp/apache/conf/httpd.conf, using routing routes in route.php file, e.g., $route['page1'] = "page1controller/page1function"; i use href or header using root base folder: href="/page1" all works on locally , never use base_url() or such functions. switching production server, don't have rights except personal folder , subfolders when execute it, root folder becomes root of domain, not project folder. i tried base_url() doesn't work, pages aren't found, when not using $route . is there way handle without refactoring links in code or way refactoring? edit instead of using "/page1" , i'm using "./page1" access location of index.php folder. however, i'm still not able access other pages neither php, nor html/js. assuming routing working on l...

events - Why does collision work properly for convex polygon based physicsBody but touchesMoved doesn't -

i setup sksprite (s1) have physicsbody polygon path: s1.physicsbody = [skphysicsbody bodywithpolygonfrompath:path]; and other 1 (s2) has physicsbody generated surrounding rectangle: s2.physicsbody = [skphysicsbody bodywithrectangleofsize:e.size]; and collisions of 2 sprites fine, happen when actual pixels s1's polygon path , surrounding rectangle s2 collide (and not surrounding rectangles each of sprites). fine. touchesmoved in s1 - has polygon based body - occurs when surrounding rectangle touched - though has polygon based physicsbody (see above code setting physicsbody of s1). how can solve problem , have event fire when should, when actual pixels (defined polygon based physicsbody) touched? i tried detecting body @ point: skphysicsbody * draggedoverbody = [self.physicsworld bodyatpoint:location]; draggedovernode = draggedoverbody.node; and detects bounding rectangle instead of polkygon physicsbody. frustrating.

javascript - How to use an iframe as input for YT.Player -

the docs should use div container <iframe> element appended. that works: new yt.player('player', { height: '390', width: '640', videoid: 'm7lc1uvf-ve', events: { onready: onplayerready, onstatechange: onplayerstatechange } }); but should have element <div id="player"></div> on page. is possible if have iframe element embedded video use iframe in yt.player constructor? i have this: new yt.player('iframeid').playvideo(); but playvideo isn't there because player not loading (i guess that's happening because providing iframe id). is there way connect existing iframe yt.player instance? i wrote quick hack it: get video id <iframe> url, replace iframe div , initialize player: ytplayeriframe = (function () { function youtube_parser(url){ var regexp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/; var ...

java - Spring 3.0.3 and JMS 2.0 Support -

i upgrading application's jms 1.1 2.0 . my application having spring 3.0.3 , uses jmstemplete . is there official ( spring or jms ) documentation mentioning support jms 2.0 spring 3.0.3? i searching in order find out weather spring related change required in application or not. it should work since 1.1 apis still supported in 2.0. if want use new 2.0 shared subscription feature (on topics), need upgrade @ least spring 4.1 .

Python Vector Class Constructor Arguments -

i need write class constructor has these criteria: constructor should take single argument. if argument either int or long or instance of class derived 1 of these, consider argument length of vector. in case, construct vector of specified length each element initialized 0.0. if length negative, raise valueerror appropriate message. if argument not considered length, if argument sequence (such list), initialize vector length , values of given sequence. if argument not used length of vector , if not sequence, raise typeerror appropriate message. im not sure how write appropriate errors, im supposed use class errors: class failure(exception): """failure exception""" def __init__(self,value): self.value=value def __str__(self): return repr(self.value) >>> vector(3) vector([0.0, 0.0, 0.0]) >>> vector(3l) vector([0.0, 0.0, 0.0]) >>> vector([4.5, "foo", 0]) vector([4.5, 'foo', ...

java - JMS consume multiple topics -

i new java , working on project consumes multiple (different) topics , sends server. wondering best way handling multiple topics is. from understand each consumer tied 1 topic, if had consume multiple topics need 1 consumer each different topic. since consumer makes blocking call need invoke thread per consumer consume these topics in parallel. and if wanted improve throughput further practice have 1 boss thread per consumer (attached topic) , allow each boss thread setup worker threads improve performance accordingly? please advice if practice , if not other alternative options? , there known design patterns handle problem why chose consumer model instead of listener model? i have 1 more constraint is, after consumer receives message needs send message receiving server. if receiving server down (during new version push) have pause consuming messages until receiving server up. in case having message listener wouldn't because wouldn't able pause listener when recei...

android - Not able to access the XML file from layout getting Resource not found exception and xml file is in res folder -

this code accessing search_product_item.xml @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); if (rootutil.isdevicerooted()) finish(); if (getresources().getboolean(r.bool.portrait)) { span_count = 2; setrequestedorientation(activityinfo.screen_orientation_portrait); } else { span_count = 4; setrequestedorientation(activityinfo.screen_orientation_landscape); } setcontentview(r.layout.search_product_item); this search_product_item xml file <?xml version="1.0" encoding="utf-8"?> <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"...

php - Searching in Laravel relationship for second table -

i have 2 table having polymorphic relationships. table1 history id|amount|type|created_at|updated_at table2 accounts id|amount|name|account_number|accountable_id|accountable_type|created_at|updated_at history have summary of accounts table. accounts table having polymorphic fields (accountable) now executing query in history table results includes accounts table also. the question want search data in accounts table payer name in account table. when hit query on history table pass payer name can fetch accounts having specific payer name. you may need set relationship between history , accounts can query along lines of: $histories = histories::wherehas( 'accounts' function ($query) use ($name) { $query->where('name', $name); } )->get(); but question not clear, , don't have names field in accounts in limited schema provided, can't give better answer. read more here: https://laravel.com...

Hazelcast and spring boot -

i'm using spring boot 1.3.3 , hazelcast build looks like: <plugin> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-maven-plugin</artifactid> <version>${spring.boot.version}</version> <configuration> <executable>true</executable> <layout>zip</layout> <embeddedlaunchscriptproperties> <mode>service</mode> <usestartstopdaemon>false</usestartstopdaemon> </embeddedlaunchscriptproperties> </configuration> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugi...

android - Draw the line on Captured image -

i captured image camera want preview image , draw line finger on image zoom perfection in image. can provide example code or ideas. you should canvas: http://developer.android.com/reference/android/graphics/canvas.html and more drawline method (it's presented in link above)

How to set default open with(dialog) option to my android app? -

Image
i have file in devise called test.csv. when click on file opened through app.how set default open with(dialog) option app in android? above sample dailog.how add app dialog list? i think may want read csv file. csv file path. see following. public static void readcsv(file file) { bufferedreader reader = null; stringbuilder stringbuilder = new stringbuilder(); try { inputstreamreader isr = new inputstreamreader(new fileinputstream(file));// csv file reader = new bufferedreader(isr); string line = null; // every time read 1 line while ((line = reader.readline()) != null) { stringbuilder.append(line); stringbuilder.append("\n"); } } catch (exception e) { e.printstacktrace(); } { try { reader.close(); } catch (ioexception e) { e.printstacktrace(); } } } the stringbuilder.tostring() csv file's content. sorry engli...

.pluck returning undefined in Meteor -

trying pull list of ratings collection of reviews , average them come aggregated average rating plate. when @ data output ratings variable nothing "undefined undefined undefined". averagerating: function() { var reviews = reviews.findone({plateid: this._id}); var ratings = _.pluck(reviews, 'rating'); var sum = ratings.reduce(function(pv, cv){return pv + cv;}, 0); var avg = sum / ratings.length; //testing output var test = ""; var x; (x in reviews) { text += reviews[x] + ','; } return test; } sorry if super newbie question, i've been @ hours , cannot figure out. i figured out issue. listed above var reviews gets set cursor apparently .pluck not work on. first converting cursor array of objects able use .pluck. updated code looks this: averagerating: function() { var reviewscursor = reviews.find({plateid: this._id}); //converts cursor array of objects var reviews = re...

php - Filter currency in wocoommerce and convert it from usd to inr for ccavenue -

i using ccavenue payment gateway on wordpress site. plugin url https://wordpress.org/plugins/ccavenue-payment-gateway-woocommerce/ having 1 issue base currency inr , ccavenue accepts payment in inr only, when user switch currency usd ccavenue taking $40 inr40. want convert currency before getting ccavenue page. code snippet same is. public function generate_ccavenue_form($order_id){ global $woocommerce; $order = new wc_order($order_id); $redirect_url = ($this -> redirect_page_id=="" || $this -> redirect_page_id==0)?get_site_url() . "/":get_permalink($this -> redirect_page_id); //for woocoomerce 2.0 $redirect_url = add_query_arg( 'wc-api', get_class( $this ), $redirect_url ); $order_id = $order_id.'_'.date("ymds"); $checksum = $this -> getchecksum($this -> merchant_id, $order->order_total, $order_id, $redirect_url, $this -> working_key); $ccave...

utf 8 - changing encoding UTF8 to UTF8 BOM with rebol -

i have file encoded utf-8. i'd change utf-8 + bom . this wrote, didn't work: write/binary %mycontacts.csv insert read/binary %mycontacts.csv #{efbbbf} what should do? when doing pipeline of processing, return result of insert series position passed in: >> str: "ution" >> print insert str {rebol} ution note if use intermediate variable (as above) variable point beginning of newly inserted content after operation: >> print str rebolution if don't want use intermediate variable, want beginning of inserted content, you'll need skip backwards length of content inserted: >> print skip insert str {rebol} -5 rebolution but if know inserted @ head of series can use head: >> print head insert str {rebol} rebolution so because you're inserting @ head of series byte-order marker, following should work case: write/binary %mycontacts.csv head insert read/binary %mycontacts.csv #{efbbbf}

Representing a graph as backbone.js model/collection -

i looking example how represent graph , nodes , edges backbone.js model. hope can point me example how elegantly. thanks martin (assuming you'd store metadata nodes - name etc) a simple way might representing graph collection of node models. each of these models have property containing array of edges represented id of node connect - collection.tojson() return like: [ { id: 1, name: 'first node', edges: [2, 4] }, { id: 2, name: 'second node', edges: [1, 3, 4] }, { id: 3, name: 'third node', edges: [2] }, { id: 1, name: 'first node', edges: [1, 2] } ] the implement methods calculate distance between nodes or derive clusters in collection class. now mentioned simple implementation, might woefully inefficient depending on operations on graph. if you'd reading , find efficient way store graph information in hash-like (model) or list-like...

javascript - jQuery collapse bootsstrap and jQuery slide -

i have page 4 rows , 2 cols, in each of rows bootstrap accordion , image in other column. when header clicked accordion opens(bootstrap collapse) , hidden div images shown under image visible (slide jquery). so 1 click 2 divs open(accordion body+hidden div), works 4 accordions when use different ids accordions, stay open. when use same id accordions closing accordion body have problems. the jquery slide needs noconflict , click function(the onclick isn't way go read somewhere) , else statement. what want doesn't matter header click, clicked accordion opens + hidden div images shown. is there out there.....who can help. function slide(slides) { $('.slidepic').each(function(index) { if ($(this).attr("id") == slides) { $(this).slidedown(200); } else { $(this).slideup(200); } }); } a 2 row version of page here: http://jsfiddle.net/supmn/1/ try this: http://jsfiddle.net/supmn/4/ means, g...

c# - Decompressing a Zip file from a string -

i'm fetching object couchbase 1 of fields has file. file zipped , encoded in base64. how able take string , decompress original file? then, if i'm using asp.mvc 4 - how send browser downloadable file? the original file being created on linux system , decoded on windows system (c#). you should use convert.frombase64string bytes, decompress, , use controller.file have client download file. decompress, need open zip file using sort of zip library. .net 4.5's built-in ziparchive class should work. or use library, both sharpziplib , dotnetzip support reading streams. public actionresult myaction() { string base64string = // linux system byte[] zipbytes = convert.frombase64string(base64string); using (var zipstream = new memorystream(zipbytes)) using (var ziparchive = new ziparchive(zipstream)) { var entry = ziparchive.entries.single(); string mimetype = mimemapping.getmimemapping(entry.name); using (var decomp...

apk - How to know the number of beta users of my app? -

Image
google play developer console allows developers upload beta apk , , invite google group use it. how know how many users using beta? the google play developer console has changed lot since original answer. if using open beta testing go to: release management / app releases / manage beta and see this: note: if number of testers not showing, might because number has not yet reached threshold. this answers question "how many people have opted beta testing?" may or may not op interested in. analytics way discover how many using beta version.

ios - How do I make a custom border around a UIView? -

i'm trying make semi-transparent border around uiview. idea show picture have border cover edge of picture yet still allow see behind border. want border have different border-widths different sides. on top have border of 80 pts, on bottom want border of 60 pts, , on sides want border of 10 pts. know using code : uiview.layer.bordercolor = [uicolor bluecolor].cgcolor; uiview.layer.borderwidth = 10; will give uniform border of width 10 around inside of uiview, how set different border widths different sides of uiview? here's simple solution. add label onto uiview, clear text on label , set label background color border color. set origin (x,y) of label origin (x,y) of view. , set width of label width of uiview, set height 1 or 2 (for border height @ top of uiview). , should trick. or else can use uibezierpath class same..

Convert Json format to xml format -

i have query select data: public function getstafflist(staffcode string) ienumerable dim query = (from c in staff c.staffid= staffcode select c) return query end function after using code below return json: public function getpersonlistjson(personcode string) string return jsonconvert.serializeobject(getstafflist(staffcode)) end function the json format below: "[{\"$id\":\"1\",\"personid\":10001.0,\"personname\":\"staff1\"}]" if want return xml format, how do? thanks update: try using following code return xml public function getpersonlistjson(personcode string) string dim json = jsonconvert.serializeobject(getstafflist(staffcode)) dim rootjson = "{""root"":" & json & "}" dim xml = jsonconvert.deserializexnode(rootjson) return xml.tostring() end function the value of xml during debug is: <root xmlns:json=...

cron - Java App engine backend shuts down abruptly, how to resume work? -

i have cron job runs every 30mins , queues task executed on dynamic backend (b2). backend loops , work, sleeps few minutes , repeats work till complete job on after few hours, after backend shuts down. (till backend running, no new task actioned) now 2 days in row, have seen backend stop abruptly (after 1.5hrs) familiar "process terminated because backend took long shutdown.". have searched through forums not identify why backend shuts down (apart theoretical list of reasons appengine doc provides). have checked ds/memcache operations, memory , looks normal. upgraded backend b1 b2, no luck. q1. know how debug issue further? q2. after wish job should completed. if register shutdown hook lifecyclemanager.getinstance().setshutdownhook(), way ensure job resumed (considering cron job still 29minutes away next execution, , want job stuff every 2 minutes) yes same has happened me. have backend uses constant memory , cpu. apengine shuts down periodically, after 15...

vb.net - Access to the path "......." is denied? -

i have windows form application loads datagridview. in 1 of columns hyperlinks image files. when these links clicked code shown below runs open image. however, have new user on system has issues viewing of images. at first found user did not have access 1 of subfolders in image path. after corrected, user can access full image path , view images through windows explorer. however, when running application , clicking hyperlinks, user receiving: error: access path '\\server\folder1\folder2\folder3\image.tif' denied. in procedure: fqimagingfiltereddatagridview_cellclick any ideas going on? user has full rights directory, individual rights, , can view images through windows explorer, application still treats user denied. here code: private sub fqimagingfiltereddatagridview_cellclick(byval sender object, byval e system.windows.forms.datagridviewcelleventargs) handles fqimagingfiltereddatagridview.cellclick try if e.rowindex = -1 exit sub if e.c...

java - How can I determine the WBXML value for an XML tag in ActiveSync for Exchange? -

i'm extending android email client, , add conversation threading exchange activesync account. appears client sends requests using wbxml. to add of conversation specific tags (for example, conversationmode ) request, need know wbxml value of tag. where can find this? the value of wbxml tag activesync can found on msdn in code pages section active sync . the conversationmode tag value can found on page , , it's value 0x27

c# - How to count the number of matches of files in a directory -

i looking many questions after answering this. how find if in directory exists @ least 1 (and better if give me number of) files matches regular expression? i know can loop files in directory with answer but there way of counting without looping? i try count() don't work taken linked question / answer, should work: int count = directory.getfiles(@"c:\temp").count(path => regex.ismatch(path, pattern));

unit testing - How establish Scalatest in a Play project with intelliJ -

i search since few days solution make unit tests scalatest framework, , didn't find right solution make work... i've searched in official website, many tutorials on net... nothing. any tutorials or tips ? for example of scalatest being used in play project, can @ source scalatest.org website itself: https://github.com/scalatest/scalatest-website scalatest.org simple (just html text mostly) there no tests yet, there example test classes here: https://github.com/scalatest/scalatest-website/tree/master/test the one-line change required sbt build file add scalatest project here: https://github.com/scalatest/scalatest-website/blob/master/project/build.scala

java - How to add background image to docx document through apache poi? -

how can add background image docx document through apache poi or other java framework. have xml block, defined background, in result document that <w:document xmlns:wpc="http://schemas.microsoft.com/office/word/2010/wordprocessingcanvas" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officedocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officedocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordprocessingdrawing" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingdrawing" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010...

Javascript Object or new function for function handler -

i bit confused 1 of following right way create handler containing functions...an object function or new function itself? say, handler calculator functions... calculatorhandler = new function(){ this.add = new function(a, b){ return + b; }; this.sub = new function(a, b){ return a-b; }; }; or calculatorhandler = { this.add: function(a, b){ return + b; }, this.sub: function(a, b){ return a-b; } }; are there advantage/disadvantage of 1 on other? if want have "basket" hold functions together, use object, there no need constructor function: calculatorhandler = { add: function(a, b){ return + b; }, sub: function(a, b){ return a-b; } }; note how this in example incorrect refer scope define calculatorhandler object in (probably global - window). on other hand if want build calculator have data , operations on it, can use oop-like approach in first exa...

go - In golang how can I write the stdout of an exec.Cmd to a file? -

i trying run shell command, capture stdout , write output file. however, seem missing few steps, file trying write empty when program exists. how can capture stdout of command , write file? package main import ( "bufio" "io" "os" "os/exec" ) func main() { cmd := exec.command("echo", "'what heck up'") // open out file writing outfile, err := os.create("./out.txt") if err != nil { panic(err) } defer outfile.close() stdoutpipe, err := cmd.stdoutpipe() if err != nil { panic(err) } writer := bufio.newwriter(outfile) err = cmd.start() if err != nil { panic(err) } go io.copy(writer, stdoutpipe) cmd.wait() } you need flush writer. add following: writer := bufio.newwriter(outfile) defer writer.flush()

encoding - Java―read, process and write UTF-8 file -

i trying write reads utf-8 encoded file can have encoding errors, process content , write result output file encoded in utf-8. my program should modify content (kind of search , replace) , copy rest 1 one. in other words: if term search equals term replace, in- , output-file should equal well. generally using code: in = paths.get( <filename1> ); out = paths.get( <filename2> ); files.deleteifexists( out ); files.createfile( out ); charsetdecoder decoder = standardcharsets.utf_8.newdecoder(); decoder.onmalformedinput( codingerroraction.ignore ); decoder.onunmappablecharacter( codingerroraction.ignore ); bufferedreader reader = new bufferedreader( new inputstreamreader( new fileinputstream( this.in.tofile() ), decoder ) ); charsetencoder encoder = standardcharsets.utf_8.newencoder(); encoder.onmalformedinput( codingerroraction.ignore ); encoder.onunmappablecharacter( codingerroraction.ignore ); bufferedwriter writer = new bufferedwriter( new ou...

PHP date() - how to display a date that is not today's? -

this question has answer here: php, tomorrows date date 10 answers the date() function in php returns current time , date, example date('l js f'); would return tuesday 24 september in calendar app i'm buiding, display 7 dates, starting current day: tuesday 24 september, wednesday 25 september, ... monday 30 september is there easy way date()? if not, possible somehow add 1 day date? thanks help date('l js f', strtotime("+1 day"));

Java printing timezone with full text -

i wanted print "20130925 050054 america/new_york" dateformat, using following code print instead prints "20130925 050054 pdt". wondering, if "zzz" can changed print full name, "america/new_york"? dateformat df = new simpledateformat("yyyymmdd hhmmss zzz"); df.settimezone(timezonefromconfigfile); string startdate=df.format(c.gettime()); perhaps work: dateformat df = new simpledateformat("yyyymmdd hhmmss"); df.settimezone(timezonefromconfigfile); string startdate = df.format(c.gettime()) + " " + c.gettimezone().getid(); not sure if want middle line. should set in c instance of calendar already.

path - Listing a single file in multiple directories with python -

i have found many methods list every file in multiple directories, so: root = "c:\\test\\" path, subdirs, files in os.walk(root): name in files: print(os.path.join(path, name)) however, need list 1 file in each directory. not looking particular order, not need randomness either. there way single file (preferably "first") in each directory save resources take list every file? (this windows filesystem, if relevant.) try following code: import os root = "c:\\test\\" path, subdirs, files in os.walk(root): if files: print(os.path.join(path, min(files))) update to exclude initial directory: import os import itertools root = "c:\\test\\" path, subdirs, files in itertools.islice(os.walk(root), 1, none): if files: print(os.path.join(path, min(files))) used min first (alphabetically) filename.

quickbooks - Intuit Partner Program Legacy List IDs and Txn IDs -

i have product uses qbsdk integrate quickbooks. data linked list ids , txn ids. running test apps , looking @ ipp docs appears ids returned ipp data services not list ids or txn ids. appears not have way access legacy ids in order upgrade data references new ipp generated ids. what migration options moving qbsdk ipp?

css - <!DOCTYPE html> breaking my page! Why? -

problem: images not showing until resize browser, or else fraction of each image showing; outcome random each time page reloaded. 10 different results reloading page 10 times. after resizing window, page show should look, when sizing page original size, continue working. after having trouble simple webpage, js fiddle here (working fine): http://jsfiddle.net/grdvw/5/ i found 1 change make page's source removing <!doctype html> no other changes fixed problem, removing tag fixes it, 100%. why this?? html: <!doctype html> <html> <head> <link rel="stylesheet" type="text/css" href="style/style.css"> <title>title</title> <meta name="keywords"> <meta name="description" content="the gamemode hub minecraft server network bringing of minecraft's best , brightest server owners present gaming community largest collection of minecraft servers in world!"> ...

python - Which Beautiful Soup version is included in XBMC? -

i trying website scraping in python in combination xbmc. when @ website of beautiful soup latest version version 4. when @ xbmc says version 3.2.0 ( http://wiki.xbmc.org/index.php?title=add-on:beautifulsoup ) does version used in xbmc? on xbmc forum 3.2.1: http://forum.xbmc.org/showthread.php?tid=174201&pid=1513469#pid1513469

jsf - How to get id of current component in EL -

i'm working jsf , primefaces, need value of id of component. because i'm building dinamycally panels diferent id, show panel need compare if current panel, show it. for example if i've next panel <p:outputpanel id="#{bean.getid}" autoupdate="true" renderer=#{@this.id == bean.currentpanel} > </p:outputpanel> and bean public class bean(){ private int numberpanels =0; private int currentpanel = 0; public int getid(){ //...a process return different id } // getter's , setters } obviously, @this.id doesn't work. so, how value of id of componente ne jsf primefaces? there implicit #{component} object in el scope evaluates current ui component. given information, you'll following attribute: rendered="#{component.id eq bean.currentpanel}"

facebook meta og:image doesn't show image -

why doesn't facebook show image. this debug link: here there meta tag, , image exist, doesn't show on debug. image url strange, used django filer thumbnail , generate image. works regular image url.

java - why i can't persist object by openjpa? - incorrect validation -

in web applicaton use openjpa on apache tomcat (tomee)/7.0.37 server. use netbeans auto generate class ("entity class database..." , "session beans entity class..."). my user.class: @entity @table(name = "user") @xmlrootelement @namedqueries({ @namedquery(name = "user.findall", query = "select u user u"), @namedquery(name = "user.findbyiduser", query = "select u user u u.iduser = :iduser"), @namedquery(name = "user.findbylogin", query = "select u user u u.login = :login"), @namedquery(name = "user.findbypassword", query = "select u user u u.password = :password")}) public class user implements serializable { private static final long serialversionuid = 1l; @id @generatedvalue(strategy = generationtype.identity) @basic(optional = false) @notnull @column(name = "id_user") private short iduser; @size(max = 8) @column(name = "login") privat...

c# - How do you create nested groups with linq via lambda/method expressions -

is possible? example, how rewrite working code below lambda expression? public void querynestedgroups() { var querynestedgroups = student in students group student student.year newgroup1 newgroup2 in (from student in newgroup1 group student student.lastname) group newgroup2 newgroup1.key; } // 3 nested foreach loops required iterate // on elements of grouped group. hover mouse // cursor on iteration variables see actual type. foreach (var outergroup in querynestedgroups) { console.writeline("dataclass.student level = {0}", outergroup.key); foreach (var innergroup in outergroup) { console.writeline("\tnames begin with: {0}", innergroup.key); foreach (var innergroupelement in innergroup) { console.writeline("\t\t{0} {1}", innergroupelement.lastname, innergroupelement.firstname); } } } var names = myclass1list .selec...

jsf - p:datatable with two lists as input -

i have 2 lists. 1 of strings contains column names(which names of properties have displayed) , 1 of objects populate table. right use html table , ui:repeat display info: <table border="1px"> <tr> <ui:repeat value="#{bean.columnnames}" var="col"> <th><h:outputtext value="#{col}" /> </th> </ui:repeat> </tr> <ui:repeat value="#{createreportbean.reportresults}" var="row"> <tr> <ui:repeat value="#{createreportbean.columnnames}" var="col"> <td><h:outputtext value="#{row[col]}"</td> </ui:repeat> </tr> </ui:repeat> </table> i'm doing because need attributes contained in columnnames displayed. can achieve similar p:datatable?

ios - Adding a UIBarButtomItem but it does not showup on interface -

i trying add go button viewcontroller programatically not show on interface via simulator. missing in code?? there build errors blank screen! #import "viewcontroller.h" @interface viewcontroller () @end @implementation viewcontroller - (void) performadd:(id)paramsender{ nslog(@"button got called"); } - (void)viewdidload { [super viewdidload]; // additional setup after loading view, typically nib. self.view.backgroundcolor = [uicolor blackcolor]; self.title =@"go back"; self.navigationitem.rightbarbuttonitem = [[uibarbuttonitem alloc] initwithbarbuttonsystemitem:(uibarbuttonsystemitemadd) target:self action:@selector(performadd:)]; } - (void)didreceivememorywarning { [super didreceivememorywarning]; // dispose of resources can recreated. } @end

html - Pushing the button down, just center after the text -

Image
how can push button down after text, stands now, stuck @ top before text. should go after text: current result: desired result: here html/css markup: <!doctype html> <html> <head> <meta charset="utf-8"> <style type="text/css"> /*-------------------------------------------------------------------------------------------------- custom alert box --------------------------------------------------------------------------------------------------*/ #alertbox_container { left: 50%; padding: 10px; top: 50%; margin: 0; padding: 0; height: 100%; border: 1px solid #808080; position: relative; color: rgb(11,63,113); } #alertbox { height: 100px; width: 400px; bottom: 50%; right: 50%; position: absolute; font-family: arial; font-size: 9pt; } #alertbox_titlebar { line-height:24px; width: 100%; filter:progid:dximagetransform.microsoft.gradient(startcolorst...