Posts

Showing posts from March, 2013

android - Don't know how use wait() and notify() in Java -

this question has answer here: how use wait , notify in java? 12 answers i want make inside thread return did string, , i'd wait string other thins. i've been reading wait() , notify() dint it. can me? here create thread operations new thread( new runnable() { @override public void run() { synchronized(mensaje) { try { mensaje.wait(); mensaje = getfilesfromurl(value); } catch (interruptedexception e) { e.printstacktrace(); } } } }).start(); and here wait string mensaje changes if string not "" show button , text synchronized(mensaje) { if (mensaje.equals("")) { try { mensaje.wait(); } catch (interruptedexception e) { e.printstacktrace(); } } btnok.s

java - Implement sound Interval Arithmetic -

how implement sound interval arithmetic in java? i need implement sound interval arithmetic java. let's take type double example, use iterval [ 0.09999....005 , 0.1000000...05 ] describe value range information of value " 0.1 ", because " 0.1 " cannot strictly represented ieee-754 standard, namely double type in java. when considering operation 0.1 * 0.1 , practical result may 0.01000...5 , or 0.00999..5 within different rounding modes. interval arithmetic result should [ lefthand , righthand ], , lefthand should less 0.01000...5 , righthand should more 0.00999..5 . when use type double implememnt arithmetic, meet 2 questions: when calculate left-hand of interval, want set rounding mode down, left-hand value less practical value. namely, need calculate number doule type less practical value , number double type more practical value. call interval arithmetical sound. i need function calculate maximum in 4 double numbers.namely, double max ( d1,

android - Define an attribute that extends a class in java -

i have following class: class foo { public void sayhello(){ system.out.println("hello"); } } and want class hold reference class extends foo (but can't foo). (erroneous syntax): class bar { private <e extends foo> e mfoo; } is possible? how can without declaring in class name this? class bar <e extends foo> { private e mfoo; } if can make foo abstract class might solve if main point e can't instance of foo. if foo isn't abstract still do public abstract class abstractfoo extends foo { } and declare e of type abstractfoo.

python - tkinter window title when using class to hold widgets -

i'm trying add window title tkinter application. .title('mytitle') seems work fine on simple examples, not i'm encapsulating widgets in class. here's simple example using "hello, again" tutorial www.pythonware.com/library/tkinter/introduction/ why not work? thanks! from tkinter import * class app: def __init__(self, master): frame = frame(master) frame.pack() self.button = button(frame, text="quit", fg="red", command=frame.quit) self.button.pack(side=left) self.hi_there = button(frame, text="hello", command=self.say_hi) self.hi_there.pack(side=left) def say_hi(self): print "hi there, everyone!" root = tk() app = app(root) root.title('blob') root.mainloop() as per marcin kowalczyk's comment, window size small show title. curiously, without widgets window expanded show title, hence assumption wasn't there.

c# - Generating big files in .NET -

i ask on 2 things .net executables: .net executable in pe format. mean address generated cil compiler beginning of file ( address+size_of_headers )? or these address used when executing image in memory? is possible generate (by cil compiler) executable size greater 4gb? if yes, compiler if has call method end of file or branch byte above 4gb limit? it's true have never seen c# executable greater 4gb, i'm curios. i think you're confusing how executing cil works how executing native code works. with cil, code in executable file not executed. (with desktop clr , without ngen) clr reads cil , generates actual executable code on fly (that's why part of clr called “just in time compiler”). cil opcodes call use tokens reference methods , other members. in generated native code, translated address of native code method. opcodes br contain offsets relative next cil instruction , can jump inside current method. on x86, compiled instructions jne , cont

windows memory segmentation & Ollydbg -

a few questions windows memory segmentation. every process in windows got own virtual memory. mean each each process has own task (i mean own task descriptor or task gate) ? i opened simple exe ollydbg , saw each call intruction dll function taking me jumping table. jumping table had jumping instructions dlls 1 : jmp dword ptr ds:[402058] my question why uses data segment , not cs selector base address? if open memory map , find stored @ 402058 find containes resorces. if understand correctly addresses of dll function stored in ds ? i noticed memory map organized owner. shouldn't organized segments code in cs data in ds etc ? thank you 1. process has it's own virtual address space. not understand you're referring "task descriptor or task gate", windows operating system holds descriptor each process, called process control block , contains information process (such identification, access tokens, execution state, virtual memory mappin

vim - Varying font size in gvim windows -

can make font size in nerdtree window smaller in other windows of gvim? generally need large font size of 15 i'd folder tree window of nerdtree 12 - possible set using code in _vimrc . have following simple setting: set guifont=consolas:h16:cansi slightly duplicated question , answered here: stackoverflow post stackoverflow post not possible bro. vim uses same font size windows. 1 (if not :d) limitation of vim.

sql server - Multiple Row Update SQL Trigger from Single Update SQL Statement -

ok. quite new sql triggers , have had issues them. insert trigger works fine, , delete trigger also. @ first, doing delete on multiple rows delete one, managed figure 1 out myself :) however, after extensive searching (here , on google) unable find satisfactory answer update trigger have. if update like update customers set customeruser = 0 customerstatus = 3 then unfortunately, 1 record updated, , other remain were. obviously, no good. the trigger using is: alter trigger [dbo].[trg_triggername] on [dbo].[user_customers] update declare @customerid int; declare @customervenue int; declare @customeruser int; declare @customerarea int; declare @customerevent int; declare @customerproject int; declare @customerstatus int; select @customerid=i.customerid inserted i; select @customervenue=i.customervenue inserted i; select @customerarea=i.customerarea inserted i; select @customerevent=i.customerevent inserted i; select @customerproject=i.customerproject inserted i; select @

windows xp - what is different between scrum, XP and RUP -

can u tell me shortly difference , similarity between methodologies: scrum, xp , rup. can u compare using table, better me understand. im new this. shortly information cuz may use in exam. appreciate. thanks. they part of agile software development. thus, share common features being iterative. cover different parts of swdev. see picture: http://en.wikipedia.org/wiki/agile_software_development#software_development_life_cycle scrum: way of doing projects. gives framework of habits apply team work , improve teamwork on time. xp: set of development habits. more focused on how quality build code. xp nice tool set scrum development team (the guys writing code in scrum) rup: full fledged sw development method on own. start earlier scrum in life cycle , gives advice on project endings. big companies ibm use it, tend take agility away (making release cycles long kills agility)

Playframework 2 using Jquery to request from server -

i want request jquery application method wich has string arg, have problem passing value of string. in html have script: <script> var search; $("#search").keyup(function () { if($(this).val() != search){ search = $(this).val(); //alert(search); $.get("@routes.application.autocomplete("+search+")", function (data) { //some stuff done here }); return false; } }).keyup(); my application method like: public static result autocomplete(string search) { system.out.println("searching for: "+search); final list<string> response = new arraylist<string>(); response.add("test1"); response.add("test2"); return ok(json.tojson(response)); } what happens jquery not sending value of search var instead sending string "search" . how can concatenation of string inside jquery get()? thanks yo can not mix serv

delphi - How to create a dialog at runtime and get a return value? -

i want create dialog current form class, , expect value dialog. this sample coding. with tformclass(findclass('tf_dialog_partner')).create(application) try showmodal; value := dialogpublicvar; except free; end; dialogpublicvar public variable of tf_dialog_partner (tform's descendant) class, right in coding current class doesn't use tf_dialog_partner's unit in uses clause, use findclass function, can create new form fine. this coding error because current class not aware of tf_dialog_partner's attributes, doesn't recognize dialogpublicvar. please help, how make current class aware of dialogpublicvar. thanks everyone. if value being returned integer, simple option have showmodal() return value. when dialog ready close, can set modalresult property desired value, , showmodal() return value. otherwise, can change variable published property of class, , use rtti access via functions available in typinfo.pas unit.

How get object's method by string in twig -

in php can object method as: $methodname="getid"; $obj->{$methodname}(); is there such features in twig? upd: : {% set method='getid' %} {{ obj[method]() }} now use extention: {{ getter(obj, method) }} but maybe there standard solution? a standard solution exist, similar extension: {{ attribute(obj, method) }}

Are there any python libraries that can safely interpret obfusticated javascript strings? -

i want able de-obfusticate javascript strings in python javascript code maybe malicious. there libraries available this? i started build own realised bigger undertaking first realised. not have safely map javascript string functions python ones (including regex), i'd have deal arrays, loops, variables relevant loop, etc. edit: here's example of mean str1 = 'sdfhsjkdfhidhgjkdfngjkdfhgjkdfpdhfgkdfjuhdfjkghdfkgjtdfhgjkdfgf'; str2 = str1.replace(/[a-z]/g, ''); str2 should equal "input" and here's example: arr = ['-', 'm', '1', 'a', 'a', 'l', 's', 'i', 'r', 'c', 'f', 'i', '#', 'o', '[', 'u', '$', 's']; str = "" (i=1; i<arr.length; i+=2) { str = str + arr[i]; } str should "malicious" a option jsbeautifier , can handle free obfuscators (actually, obfuscator know)

osx - Better to use a Mac or PC to develop for Typescript? -

i'v got access both, prefer stay mac, unless there going major drawbacks trying develop ts on mac? no major drawbacks @ all. use ts on mac , works fine! if you, stick mac. on mac, easier use (in opinion)!

java - JDBC driver MS Access connection -

i want connect ms access file java gui program,but have problem connection.... i have windows 7 64b, , ms office 2007. when opened odbc driver manager in control panel havent found driver microsoft access (maybe when started odbc started running 64bit odbc, think running 32bit odbc. read , make : "jdbc-odbc connection window 7 64 bit machine.. 1 . right click data source (odbc)..go properties change folloing thing target [ %systemroot%\syswow64\odbcad32.exe ] start in : [ %systemroot%\system32 ] press enter , continue admin source: source link " ) when start in conctrol pannel odbc can see driver screenshoot my program code(i tried 2 ways have same error): public void connect() { try { class.forname("sun.jdbc.odbc.jdbcodbcdriver"); // string databasefile = "d:java/invertory.mdb"; // string database = // "jdbc:odbc:driver=" //

java - Setting content view hierarchy -

i'm developing app implements simple compass. i'm creating , manipulating compass in class (rose.java) extends imageview. on main activity want add rose object layout , have code public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); sensormanager = (sensormanager) getsystemservice(sensor_service); sensor = sensormanager.getdefaultsensor(sensor.type_orientation); rose = new rose (this); setcontentview(rose); } the thing is, know, using setcontentview "rose" going full screen , rest of elements of layout won't show. i'm asking alternate method adds rose object layout without neglecting rest of elements. thanks in advance. you allocate width , height of linearlayout in xml. define linearlayout in xml file , define width , height of choice. place layout like. add content of custom view linearlayout setcontentview(r.id.activity_main); linearlayout ll = (linearlayout) findviewbyid(r

javascript - Playing a video when clicking on an element of an image. -

i want know if it's possible play video when click on element of image, , play video if click on element of same image ? for instance, imagine picture of room : - if click on area tv set is, image disappears , video1 starts. - if click on chair, same thing video2 starts instead. is possible using html5 , javascript? if so, how going ? thanks lot reading ! yes, possible. i'm assuming have basic understanding of html , javascript. work on browsers have support html5 , video element specifically. first, add video element page <video id="video" width="600"> <source type="video/mp4"> browser not support html5 video. </video> then let's assume have 2 images, video 1 , video 2 <img src="tv.png" id="video1btn" onclick="loadvideo1()" value="load video 1" /> <img src="chair.png" id="video2btn" onclick="loadvideo2()" value=&

php - Google Chrome maximum cookie expiry date -

i creating website when created new cookie php line : setcookie('subscribed', 'true', time() + 365*24*3600*100, '/', null, false, true); i realised browser (google chrome) refused cookie. when looked @ cookies in google chrome wasn't there. started fiddling different settings until saw worked : setcookie('subscribed', 'true', time() + 365*24*360, '/', null, false, true); which meant changing expiration time lower value did work means of making work. my question is, lowest expiration time can set cookie in google chrome? know of policy? i have tried on 64bit os chrome browser , apache server, , works flawlessly. shows cookie's expiration time somewhere in year 2113. dev-null-dweller right: date beyond 03:14:07 utc on tuesday, 19 january 2038 wrap around time close 1900, forcing cookie disappear (on 32bit platforms, is). work around setting cookie expiration times no more 10 years in future, or so. beyon

ios - Prevent UIWebView From Scrolling Too Far -

i have 2 buttons, scroll , scroll down used scroll webpage in uiwebview . issue is, once hit top or bottom of page can keep scrolling. can scroll until entire webpage off of uiwebview . know code need plug in prevent happening? i've been researching while , going on head. possible detect webpage has ended? code i'm using scroll, have feeling need throw if statement in here check if has hit top of webpage. //scroll up: -(ibaction)scrollcontentup:(id)sender { [_viewweb.scrollview setcontentoffset:cgpointmake(0,_viewweb.scrollview.contentoffset.y - 40.0) animated:yes]; } //scroll down: -(ibaction)scrollcontentdown:(id)sender { [_viewweb.scrollview setcontentoffset:cgpointmake(0,_viewweb.scrollview.contentoffset.y + 40.0) animated:yes]; } by way, it's ipad app. +you need like: //scroll up: -(ibaction)scrollcontentup:(id)sender { if(_webview.scrollview.contentoffset.y - 40 >= 0) { [_viewweb.scrollview setcontentoffset:cgpoint

crash - c++ non-comprehensible crashing behaviour -

so created dll today , it's crashing no reason... this works: testa++; testb++; const char *t = "test"; if (t == "adoinfosidnoxucnviune") { } this crashes @ testb++: testa++; const char *t = "test"; if (t == "adoinfosidnoxucnviune") { testb++; } where testa , testb integers.. t isnt string it's compared with, don't it you comparing pointers, not values pointers point to. either use strcmp or use std::string . the crash has occur elsewhere. because pointing 2 different objects, code in either "if" statement not executed because values in pointers different. somewhere in code, testing value of testb . in first example, testb incremented. in second example, testb not incremented. have initialized testb ? seriously, when single stepped debugger, last line executed before crash?

audio - Create an MP3 file (or WAV, etc) in Android app from layered MediaPlayers -

i working on dj application lets user manipulate instrumental layers being played simultaneously through multiple mediaplayers. currently, have been able reconstruct songs within application replaying time-stamped data of user inputs (which has been saved in .txt file) through same thread used mix layers. ultimately, write audio file (mp3, wav, etc.) can downloaded or replayed outside of app; however, haven't had luck figuring out date. if has idea how or suggestion of should researching figure out, appreciate it! let me know if question makes no sense (first time posting). thanks!

security - How can i remove specific characters from htaccess or redirect such URL -

i have url's eg abc.com/page.php?page=abc and abc.com/page.php?page=abc/yzy now want either remove ' / ' parameter , rewrite url or redirect abc.com hello can use mod_rewrite if using apache easily. http://httpd.apache.org/docs/current/mod/mod_rewrite.html here have tutorial it: http://www.sitepoint.com/guide-url-rewriting/ it module kind of things. if need more it.

Run a PHP page on the server after time periods automatically -

i have php page read , write data in database. there way can run php page on server automatically (not request of client) every n seconds? rather having cronjob, might easier/more efficient have 'daemon' style script. a script running, , @ set intervals. <?php while(true) { do_stuff(); sleep(30); } (more efficent, because script doesn't need full start every time it's run. can hold configuration etc, between calls do_stuff.) how run process background , never die? of course 'do_stuff()' might calling script function do_stuff() { file_get_contents('http://example.com/scripts/calc.php'); }

php - Fatal error: Allowed memory size of 33554432 bytes exhausted -

this question has answer here: how parse , process html/xml in php? 27 answers $html = file_get_html('http://www.oddsshark.com/mlb/odds'); echo $html; when ehcoed, error message in title of question appears? i've had problems similar before. in cases, didn't need increase memoery in php.ini. rather, there missing curly bracket needed close loop. page i'm requesting via file_get_html function appears fine in browser, won't let me echo html via php. any ideas? why not use library more memory optimized, simple html dom not necessary longer: $html = new domdocument; $html->loadhtmlfile('http://www.oddsshark.com/mlb/odds'); echo $html->savehtml(); more suggestions available reference question topic: how parse , process html/xml in php?

In R how to insert in a model a variable that is a function of a binary variable? -

i know how insert variable function of binary variable. sorry if question not sound clear, pretty new @ r. here example of trying do: using multiple linear regression, model consists of evaluating y predictors x1, x2, x3, x4 , x5 x1, x2, x3 normal (continuous?) variables , x4, x5 binary variables (take values 0 or 1) far model in r looks model<-lm(y~x1+x2+x3+x4+x5) change x1 variable dependant on rather x4 takes value 0 or 1 (x1 function of x4) , model y change. have absolutely no clue how this, if appreciated. the "*" operator used build interactions in formulas. there's interaction function it's sensibly used when both contribution variables categorical: model<-lm( y ~ x1*x4 + x2+x3+x5) that produce interaction term can interpreted change in slope x1 when x4 == 1. there terms slope of x1 (when x4==0) , x4. x4 term interpreted "level-shift". it's better use predict function rather trying spend time decoding interactions. if x4

c++ - which one the following centroid is the centroid of object in image? -

Image
i want mass center of circle shape binary image, output give more 1 mass center. i'm using code opencv web tutorial document image moment , modified little bit. fyi, i'm using c++ api opencv. and output is: i expect, text output give maybe 3 centroid 3 contour, reality 7 contours (contours[0],...,contours[6]). which 1 centroid? or, 1 contour area of circle shape? then modified code, remove contours (because real picture noise, , want specific contours, circle shape, must remove other contours, line , character) using: contours.erase() i want centroid area contour between 100 till 500. but, output become strange.. the centroids fly anywhere contours. then, still, there 5 centroid 5 contours (contours[0],...,contours[4]). what must do? want centroid of circle shape (above number 3). i'm need advice. thank much! :d *sorry bad english.. what do: find contours (and store in vector of point) ( cv::findcontours ) apply custom particle filt

php - mysqli prepeare on array? -

i writing own library querying database , want encapsulate mysqli_prepeare() , mysqli_bind methods, want write generic method dynamic number of parameters. mean can pass example: array("is", $integerid, $stringname). the solution have found is: function prepeare($notescapedsql, $attrs) { $query = mysqli_prepare($this->dbconn, $notescapedsql); $ref = new reflectionclass('mysqli_stmt'); $method = $ref->getmethod("bind_param"); $method->invokeargs($query,$attrs); } but not working me, did not spent time on debuging because not elegant way of solving problem since uses reflection not supported on earlier versions of php. there sollutions or suggestions? i don't know why use reflection class , why didn't use $query returns mysqli_stmt object. moreover, invokeargs call_user_func_array take array second parameter. so, best use typehint array on second parameter in function prepeare . you ca

groovy - Setting a class property to an Enum value -

i have abstract groovy class have attribute of type enum. however, i'm not clear on how set up. i have this: abstract class person { protected int heightfeet, heightinches, weight protected string firstname, lastname protected occupationtype occupation protected person(int hf, hi, w, string fn, string ln, int ocp){ this.heightfeet = hf this.heightinches = hi this.weight = w this.firstname = fn this.lastname = ln this.occupation.value = ocp } and enum looks : public enum occupationtype { teacher(1), administrator(2), counselor(3), doctor(4), nurse(5), ... occupationstype(int value) {this.value = value} private final int value public int value() {return value} } so typically sort of nullpointerexception cannot set value null object. not sure i'm missing, or if @ possible. java.lang.nullpointerexception: cannot set property 'value' on null object @ org.codehaus.groovy.runtime.nullobject.setproperty(nullobject.java:66) @ org.codehau

php - random image not working correctly -

i have create array diusplay random file name mysql database. unfortunatly doesnt show correctly. i need explode work based on file id show correct banner picturse tv series. <?php include '../connect/dbseries.php' ?> <?php include 'sbarray.php' ?> <?php $names = explode ("|", $row['4']); ?> <center><?php while($row=mysql_fetch_array($result2)){ echo '<a href="episodemenu.php?id='.$row['id'].'"><img src="../images/series/'. $names[array_rand($names,1)].'" width="800" height="150" style="padding:2px;"></a>'; } ?> </center> my array page <?php $result2 = mysql_query("select id, pretty_name, sortname, genre, bannerfilenames, c

java - Android send data via socket -

i send simple date through tcp. working threads, dont know why when try run code stop imediatelly here that. have set permissons well. what did wrong? beginner please me package com.example.teszt; import java.util.date; import java.io.ioexception; import java.io.outputstream; import java.io.printwriter; import java.net.socket; import java.net.unknownhostexception; import android.os.bundle; import android.app.activity; import android.view.menu; import android.view.view; import android.widget.edittext; import android.widget.textview; public class mainactivity extends activity { textview date; edittext textout; textview textin; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); date=(textview)findviewbyid(r.id.text1); ////////////////////////////////////////////////////////////////////////// } public void shownewdate(view v)

vhdl - Getting wrong results in post synthesis simulation -

i writing code matrix transpose in vhdl taking input in row major , 1 element of matrix per every clock cycle , store data in column major format after send tha data in coloumn major format element element every clock cycle output . code below simulating post synthesis results not right can plz how synthesize code correct results library ieee; use ieee.std_logic_1164.all; use ieee.numeric_std.all; entity matrix_trans_sysgen generic(n: integer :=3); port (my_clk : in std_logic; my_ce : in std_logic; input_matrix : in std_logic_vector(5 downto 0); output_matrix : out std_logic_vector(5 downto 0) ); end matrix_trans_sysgen; architecture behavioral of matrix_trans_sysgen type t1 array (natural range<>) of std_logic_vector(5 downto 0); signal : t1((n*n)-1 downto 0) :=(others => (others =>'0')); signal output_there : std_logic :='0'; signal x : integer range 0 2*n :=0; signal y : integer range 0 2*n :=0; signal z : integer range 0 2*n*n :=0; begin --

Active Facebook access token iOS error -

i'm trying integrate facebook ios app running snag. when first ran code worked seems in facebook cache causing error: "an active access token must used query information current user." i use these 2 functions attempt upload photo: +(bool)loginandpostimage:(uiimage*)image andmessage:(nsstring*)message { nsarray *permissions = [nsarray arraywithobjects:@"publish_stream", nil]; [fbsession.activesession closeandcleartokeninformation]; return [fbsession openactivesessionwithpublishpermissions:permissions defaultaudience:fbsessiondefaultaudienceonlyme allowloginui:yes completionhandler: ^(fbsession *session, fbsessionstate state, nserror *error) { [self sessionstatechanged:session state:state error:error];

c# - How can I create a better looking DataGridView? -

Image
i'd create nicer-looking datagridview display data sql database in. specifically, i'm looking replicate this: is there sort of add-on visual studio me datagridview looking this? or have missed formatting/display options? i've done kind of thing many times, , other answers correct in have manually setting cell styles. there 3rd party options, after messing them while end scrapping because of limitations run proprietary controls (plus cost money). if able use wpf instead of winforms, though, highly recommend using it. easier kinds of styling using wpf's mvvc pattern.

java - Get if someone is using a JComboBox? -

like title says, need know if using combobox. i.e. when box dropped down. is there method this? maybe actionlistener? use jcombobox#addpopupmenulistener() : combobox.addpopupmenulistener(new popupmenulistener() { @override public void popupmenuwillbecomevisible(popupmenuevent e) { // ... } @override public void popupmenuwillbecomeinvisible(popupmenuevent e) { // ... } @override public void popupmenucanceled(popupmenuevent e) { // ... } });

java - What's a good-practice replacement of System.out.println? -

my application has output content user. throughout classes i've been using system.out.println, since program isn't intended run command line isn't suitable. i had thought of making classes extends jpanel , having content append textarea. i've been reading isn't move, , issue arises in i'll have pass jpanel class classes output text. is there good-practice alternative system.out.println? if not, how suggest proceed? have suggestions of java logging, don't want output file. you should have limited user interaction in of classes , in fact ui code should separate in own set of class. should strive write model (non-ui) code can work in console application, swing application, swt application or other ui library type application. way code can work sop or gui's see fit. wager > 90% of java classes created professional coders have no ui code within them. also please note logging , user interaction code 2 orthogonal concepts. @ logging way co

Python writing binary files, bytes -

python 3. i'm using qt's file dialog widget save pdfs downloaded internet. i've been reading file using 'open', , attempting write using file dialog widget. however, i've been running a"typeerror: '_io.bufferedreader' not support buffer interface" error. example code: with open('file_to_read.pdf', 'rb') f1: open('file_to_save.pdf', 'wb') f2: f2.write(f1) this logic works text files when not using 'b' designator, or when reading file web, urllib or requests. these of 'bytes' type, think need opening file as. instead, it's opening buffered reader. tried bytes(f1), "typeerror: 'bytes' object cannot interpreted integer." ideaas? if intent make copy of file, use shutil >>> import shutil >>> shutil.copyfile('file_to_read.pdf','file_to_save.pdf') or if need access byte byte, similar structure, works: >>>

css - How do I position divs into 3 columns, reposition into 2 when on narrow screen -

Image
yes, realise title of question poor. feel free improve it. i'm trying build css page has following requirements. there 6 'boxes'. each pair of boxes has equal total height the middle pair (boxes 3 , 4) have equal height they should arranged on below mockup, in 3 columns on wide screen they should arranged on second mockup below, in 2 columns on narrow screen should arranged in single column there should no gap between box , 1 directly below/above it i trying done using twitter bootstrap it's not requirement i'd prefer 100% css solution on css+jquery/other js solution it's corporate website sadly, has work in ie8+ (ie7 nice too, although not must if can have reasonable fallback) here's jsfiddle play with: http://goo.gl/o2yoy you can combination of column-count , media queries: .inner{ width: 100%; display: inline-block; } #outer{ column-count:3; -webkit-column-count:3; /* safari , chrome */ -moz-column-

javascript - How can I count the total number of inputs with values on a page? -

i'm hoping super simple validation script matches total inputs on form total inputs values on form. can explain why following doesn't work, , suggest working solution? fiddle: http://jsfiddle.net/d7ddu/ fill out 1 or more of inputs , click "submit". want see number of filled out inputs result. far shows 0 . html: <input type="text" name="one"> <input type="text" name="two"> <input type="text" name="three"> <textarea name="four"></textarea> <button id="btn-submit">submit</button> <div id="count"></div> js: $('#btn-submit').bind('click', function() { var filledinputs = $(':input[value]').length; $('#count').html(filledinputs); }); [value] refers value attribute , different value property . the property updated type, attribute stays same. means can elem.value

forms - Rails Using Edit action in a Show View -

i'm trying update object in it's show view. i've been following railscasts habtm checkboxes . getting following error: no route matches [put] "/accounts/4/edit" here form: <%= form_for @account, :url => { :action => "edit"} |form| %> <%= hidden_field_tag "account[checklist_ids][]", nil%> <% checklist.all.each |checklist| %> <%= check_box_tag "account[checklist_ids][]", checklist.id, @account.checklist_ids.include?(checklist.id) %> <%= checklist.task %><br/> <% end %><br/> <%= form.submit "update checklist", class: 'btn' %> <% end %> /app/controllers/accounts_controller.rb class accountscontroller < applicationcontroller before_filter :authenticate_user! respond_to :html, :json def show @account = account.find(params[:id]) @notes = @account.notes.all @contacts = @account.contacts.all

ruby - Error message: -bash: /etc/profile.d/rvm.sh: No such file or directory -

after installing ruby on mac, every time start terminal, message: last login: sun may 19 00:47:06 on ttys000 -bash: /etc/profile.d/rvm.sh: no such file or directory what mean? need fix this? if how? every time start terminal or new tab in terminal, begin bash shell session. can set commands run every time start bash session. typical use cases include setting aliases (e.g. gst git status ), environment variables, , running other bash scripts. place put these initial bash commands in ~/.bashrc or ~/.bash_profile . start checking files see if have reference file /etc/profile.d/rvm.sh . also, check whether said file exists on machine. if doesn't, can safely delete corresponding line bashrc or bash_profile . if exist, there's else funny going on you'll have debug. also note, way rvm works, requires run script every time. if have rvm , plan on using it, work? if not, might need find appropriate rvm script lives on machine , add bashrc or bash_profi

2d - 360 degree gravity game mechanic like “They Need To Be Fed” game -

i fan of "they need fed" game , want understand game mechanic @ deeper level. resources basic box2d (or similar) physics behind 360 degree gravity game mechanic ? first of all, understand how make character orbit circle or box without falling down using box2d or similar physics from understanding, need set world's gravity 0 , apply centripetal force character. i have searched around web tutorials ideally answer above questions , perhaps provide additional resources regarding efficiency, camera motion , on haven't found anything. try using changing gravity -(void) changegravitybyxvariant:(float) xvariant andyvariant:(float)yvariant{ world->setgravity(b2vec2(xvariant, yvariant)); } i have tested , works..... can't find easier

javascript - variable is already defined -

Image
sometime need replace variable value another so use method var $$test = "first", $$test = "second"; the code work fine use jsfiddle jshint button check error on javascript (it helped me lot) but got error '$$test' defined so ideal method re define variable thank :) you're getting error because you're declaring same variable twice. var = foo, = bar; is same as: var = foo; var = bar; just break code in 2 lines, , won't warning. this: var = foo; = bar; also notice if declare variable value, , right after change value, first line noop .

Account balance - Google Spreadsheet SQL Query -

a b c d e f g date amount account 5/5/2013 bank food 200 bank 5/5/2013 work bank 1200 food 5/5/2013 bank rent 400 work 5/5/2013 work bank 1200 rent how can resulting balance in column f? and what's performant option? i know how sum , rest values, don't know how put them cleanly in f column. what tried i made this: in h1 =query(a1:d99,"select b, sum(d) d > 0 group b") in j1 =query(a1:d99,"select c, sum(d) d > 0 group c") getting: h j k sum amount sum amount bank 600 bank 2400 work 2400 food 200 rent 400 now, if rest k - i, balance. but, how can correspondent elements? mean bank bank , on. if have accounts listed in e2 down, enter array formula in f2: =arrayformula(if(len(e2:e);sumif(c2:c;e2:e;d2:d)-sumif(b2:b;e2:e;d2:d);iferror(1/0

php - Search form for Prices -

i have form trying search different prices. manage search address , city information prices no search results show up. not sure if in html side or php side going wrong. using 2 drop down lists set number of price ranges. html <select name="pricemin"> <option value="min(900)">900</option> <option value="min(1000)">1000</option> <option value="min(2000)">2000</option> <option value="min(3000)">3000</option> <option value="min(4000)">4000</option> <option value="min(5000)">5000</option> <option value="min(6000)">6000</option> <option value="min(7000)">7000</option> <option value="min(8000)">8000</option>

Private member functors for a C++ class -

i'm writing class have member methods have data associated them, mechanical systems of robot require use of. thought write them functors, (this isn't actual code): class myrobot : public robot { public: myrobot(); void runrobot(); private: command do_something_, do_another_thing_; } and initialize do_something_ lambda in constructor like: do_something_( [] { do_first_thing(); do_second_thing(); } ); and tell do_something_ requirements has: do_something_.requires( system_a ); do_something_.requires( system_b ); and in runrobot() tell robot's scheduler execute commands: void myrobot::runrobot() { scheduler.add(do_something_); scheduler.add(do_another_thing_); } but have come realize number of commands grows, less manageable constructor myrobot become, every command have body defined there. make corresponding private method each command , initialize them function pointer instead of lambda, seems more convoluted. subclass command

node.js server not receive all binary data (or client not sending all binary data) -

i'm new node.js , running problem basic, i'm sure i'm not "getting" something, here go: i've got 2 programs... server.js simple express/node.js server accepts post of binary data client.js simple request/node.js client streams contents of large file server i've been scouring stackoverflow suggestions , think i've small example of issue: client: var fs = require('fs'); var request = require('request'); fs.createreadstream('test2.zip').pipe(request.post('http://localhost:3000/')); server: var express = require('express'); var app = express(); app.post('/', function(req, res){ var size = 0; req.on('data', function (data) { size += data.length; console.log('got chunk: ' + data.length + ' total: ' + size); }); req.on('end', function () { console.log("total size = " + size); }); req.on('error&

javascript - Using NodeJS buffer -

i have following code: var packet = "\xff\xff\xff\xff"; packet += "\x6d"; packet += "127.0.0.1:" + this.port; packet += "\x00"; packet += this.name; packet += "\x00"; packet += this.map; packet += "\x00"; packet += "game1"; packet += "\x00"; packet += "x-z"; packet += "\x00"; packet += string.fromcharcode(this.players.length); packet += string.fromcharcode(this.maxplayers); packet += string.fromcharcode(this.protocol); packet += "\x64"; packet += "\x6c"; packet += "\x00"; packet += "\x01"; packet += "\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x01\x00\x01\x00"; return new buffer(packet, "binary"); i'm creating buffer string now, think isn't practice , string concatenation not efficient. how can replace buffer functions , write buffer directly? can't understand how buffer works, example, how write 4 \xff byt

java - How Change URL in GWT application? -

i wish if can me in issue, how can change address bar content when change page in gwt? (e.g: on aboutus www.mysite.com/aboutus) also if user type in address bar (www.mysite.com/aboutus) gwt application forward aboutus page? thanks you use activities , places. it's way structure web app. application organized in places, views, , activities, view contains code builds interface, , activity contains view does. each place/activity/view corresponds url. apps simple , convenient way organize things.

audio - Why won't my android program close when I close it? -

i made android app plays mario sound when jump. works fine (sort of), when close it, still works. tried using ondestroy method, dosen't seem delete objects created or something... here code. http://pastebin.com/gckrbkv9 try putting code stop playing inside onpause() instead of ondestroy() so: @override public void onpause() { super.onpause(); sp.stop(jump); sp.release(); } it's quite possible activity not yet destroyed , sent background, ondestroy() not yet called if "close" app.

How to store php array to text -

i have php array this. $config['sample'] = array( 'key1' => 'val1', 'key2' => 'val2' ); and want value in $config['sample'] write in text file this. $newcfg['sample'] = array( 'key1' => 'val1', 'key2' => 'val2' ); how convert php array value text string before write text file? ps. 1. cannot use serialize because when write file, must ready use in php same $config['sample'] value. ps. 2. cannot use json encode/decode also. same reason cannot use serialize. use var_export works. @fr4nk you looking var_export . exports variable executable php code. write text file.

javascript - Save Draggable Div Position -

i had added drag , move div website, using common header each pages. my drag , move div code follows: script: <script type="text/javascript"> $(function() { $( "#draggable" ).draggable(); }); </script> div: <div class="student_avatar_header" id="draggable" title="drag , move..."> texts... </div> css: .student_avatar_header { width: 100px; height: 100px; position: absolute; left: 10px; top: 20px; border-radius: 250px; z-index: 9998; box-shadow: 2px 2px 12px #008abc; cursor: move; } this drag , move function working fine, question had added draggable div header appear visit pages website, want set cookie function or possible remember last position dragged. example here home page, drag div page bottom, when go about page div appear not previous position, appear default position. need display previous position visit pages website, note:

post - PHP code how to clean user input from $_POST -

i have php code: <?php $score11 = $_post['passmarks12']; if($_post['passmarks12'] > 100){ $grade11 = ""; } elseif ($_post['passmarks12'] < 45){ $grade11 = "fail"; } $strg = " $grade11"; echo $strg; ?> the code printing "fail" regardless of sent in. i want if passes in blank or invalid input fails. and how should cleanse input? this php code make sure $_post not empty before comparing 100. <?php $score11 = $_post['passmarks12']; if(empty($_post['passmarks12']) || $_post['passmarks12'] > 100) $grade11 = ""; elseif ($_post['passmarks12'] < 45) $grade11 = "fail"; $strg = " $grade11" ; echo $strg; ?>

javascript - JQuery list append item not selectable -

i have weird issue jquery append list. <ul id="idnicheitems" class="clscrollitems ui-widget-content ui-corner-all"> <li id="nicheitem_1"> item 1</li> <li id="nicheitem_2"> item 2</li> <li id="nicheitem_3"> item 3</li> <li id="nicheitem_4"> item 4</li> </ul> the list part of list box type control using $("#idnicheitems li").hover(function(){ $(this).addclass("cllisthighlight"); },function(){$(this).removeclass("cllisthighlight");}); this works fine. after json query later on append new item list . when inspect using firebug looks every other item in list - ids unique - looks fine. the trouble can not highlight or select it. my thoughts have call above "$("#idnicheitems li") . hover ..again attach hover function after inserting node - not seem work - unless have bug in bug fix. a

r - working with large lists that become too big for RAM when operated on -

short of working on machine more ram, how can work large lists in r , example put them on disk , work on sections of it? here's code generate type of lists i'm using n = 50; = 100 word <- vector(mode = "integer", length = n) (i in 1:n){ word[i] <- paste(sample(c(rep(0:9,each=5),letters,letters),5,replace=true),collapse='') } dat <- data.frame(word = word, counts = sample(1:50, n, replace = true)) dat_list <- lapply(1:i, function(i) dat) in actual use case each data frame in list unique, unlike quick example here. i'm aiming n = 4000 , = 100,000 this 1 example of want list of dataframes: func <- function(x) {rep(x$word, times = x$counts)} la <- lapply(dat_list, func) with actual use case runs few hours, fills ram , of swap , rstudio freezes , shows message bomb on (rstudio forced terminate due error in r session). i see bigmemory limited matrices , ff doesn't seem handle lists. other options? i

performance - Matlab: Speed-up reading of ascii file -

i wrote piece of code works fine, way slow purposes: %%% load nodal data %%% path = sprintf('%sfile.dat',directory); fid = fopen(path); num_nodes = textscan(fid,'%s %s %s %s %d',1,'delimiter', ' '); num_nodes = num_nodes{5}; header = textscan(fid,'%s',7,'delimiter', '\t'); k = 0; while ~feof(fid) line = fgetl(fid); [head,rem] = strtok(line,[' ',char(9)]); if head == '#' k = k+1; j = 1; time_steps(k) = sscanf(rem, [' output @ t = %d']); end if ~isempty(head) if head ~= '#' data(j,:,k) = str2num([head rem]); j = j+1; end end end fclose(fid); nodal_data = struct('header',header,'num_nodes',num_nodes,'time_steps',time_steps,'data',data); the ascii reading matlab looks this: # number of nodes: 120453 #x y z