Posts

Showing posts from February, 2014

sql - How to write the quantile aggregate function? -

i have following table: create table #temp (cola varchar(max), colb varchar(max), date date, value int) insert #temp values('a','b','7/1/2010','11143274') insert #temp values('a','b','7/1/2010','13303527') insert #temp values('a','b','7/1/2010','17344238') insert #temp values('a','b','7/1/2010','13236525') insert #temp values('a','b','7/1/2010','10825232') insert #temp values('a','b','7/1/2010','13567253') insert #temp values('a','b','7/1/2010','10726342') insert #temp values('a','b','7/1/2010','11605647') insert #temp values('a','b','7/2/2010','13236525') insert #temp values('a','b','7/2/2010','10825232') insert #temp values('a','b','7/2/2010...

pygame - Compiled python script returns WindowsError: [Error 3] after using py2exe -

so have been writing game while , have finished. due fact game meant class , used libraries teacher isn't going bother installing need make single executable run independent of python , games dependencies. ran py2exe , completed when run exe error: traceback (most recent call last): file "main.pyw", line 1, in <module> file "zipextimporter.pyo", line 82, in load_module file "libs\__init__.pyo", line 3, in <module> windowserror: [error 3] system cannot find path specified: 'c:\\users\\matt\\workspace\\cos125\\src\\dist\\includes.zip\\libs/*.*' i have figured out cause of error is. stems auto importer have installed each package. in init .py files packages use following code simple "from libs import *" import files in lib package. make each file loaded if loaded each 1 "from libs.module import *". the code in init file follows: import os, sys path = os.path.dirname(__file__) dirlist = os.listdir(...

jQuery draggable and invoke function -

i have table of games laid out in grid , want drag square anther square, , invoke function. game squares must have id corresponding game represent (or contain div id). i want drag table cell other table cell , invoke ajax action both id numbers, can swap game bookings. i don't know start , can't find close. yes, have how to, doesn't show me how extract id number each element. you should able need when drop performed. if basic set is: <table><tr><td id="cell_1"></td><td id="cell_2"></td></tr></table> just set cells draggable , droppable in drop event: $('td').draggable().droppable({ drop: function(event, ui) { var dragged_id = ui.draggable.attr('id'); // cell dragged var dropped_id = $(this).attr('id'); // cell dropped $.ajax(...); } });

r - Inverse of which -

am missing obvious here? appears inverse function of which missing base r (googling , search on "r inverse which" returns myriad of unrelated links)? well, not can't write one, relieve frustration being missing , r-muscle flexing challenge: how go writing one? what need function like: invwhich<-function(indices, totlength) that returns logical vector of length totlength each element in indices true , rest false . there's bound lot of ways of accomplishing (some of low hanging fruit), argue why solution 'best'. oneliner anyone? if takes account of other parameters of which ( arr.ind ??), that's better... one-liner solution: invwhich <- function(indices, totlength) is.element(seq_len(totlength), indices) invwhich(c(2,5), 10) [1] false true false false true false false false false false

Rename default branch in TortoiseHG -

is possible rename 'default' 'production' in tortoisehg? you cannot directly tortoise2.0+ settings , through command-line hg . documented in hgbook : mercurial lets assign persistent name branch. there exists branch named default. before start naming branches yourself, can find traces of default branch if them. to start working named branches , use hg branches command $ hg branch production marked working directory branch production $ hg branch production check if change reflected in tortoisehg

Get back my java source code from .war file? -

i lost netbeans project folder of project working on @ time. somewhere on server here @ company work at, deployed it. means (hopefully) can still hold of .war file. is possible 'unpack' .war , .java source files working on @ time? thanks in advance! if .java sources aren't in war (and should not be), you'll have take additional step of decompiling them using tool jad. this time set version control system, subversion or git or mercurial, never happens again. habit of using source code management, if you're sole developer working on project.

c# - Select Top(x) while x.Kind = "value" -

how select top of list long items @ top of list have property specific value. i need linq statement see there break in sequence , return top 2 items. problem don't know how many items going have correct property value. i have been working through problem linqpad 4. code below copy , past linqpad 4. results, "q", should not contain somedata effectivedate of 4/5/2011 because kind property on hsc2 "kindtwo". i trying find value resent value of "kind" , take top records match value until record doesn't match value. void main() { var hsc1 = new somedata {effectivedate = new datetime(2011,4,5), kind = "kindone"}; var hsc2 = new somedata {effectivedate = new datetime(2011,4,10), kind = "kindtwo"}; var hsc3 = new somedata {effectivedate = new datetime(2011,4,20), kind = "kindone"}; var hsc4 = new somedata {effectivedate = new datetime(2011,4,25), kind = "kindone"}; var = new [] {hsc1,...

HTML5 state of current implementations -

is there site can see implementation state of html5 features inside browsers. (video, audio, drag , drop, web storage, flexible box etc) regards, stefan yes. http://slides.html5rocks.com

R - Avoiding for loops with automatic iteration -

this contrived example i'm using understand r better. lets want subset character vector called "test". want return each element value third character last character. doesn't work: test = c( "jane" , "jerry" , "joan" ) substr( test , 3 , length( test ) ) expecting: "ne" , "rry" , "an" is there way without loop? use nchar() . it's vectorized: > test = c( "jane" , "jerry" , "joan" ) > substr( test , 3 , nchar( test ) ) [1] "ne" "rry" "an" given nchar return vector of lengths, , substr likewise vectorized, , expects work vector arguments, 1 potential puzzle why accepts scalar argument of 3 . answer here scalars start , stop arguments recycled match length of input character vector. could, therefore, use 1:2 start argument , alternating complete , complete strings: > substr( test , 1:2 , nchar( test ) ) [1] ...

html5 - How do I use Google Chrome 11's Upload Folder feature in my own code? -

google chrome 11 supports uploading folders. feature implemented in google docs, , have been unable find api documentation on how use in code. from can see, click upload folder link in google docs, displays "browse folder" dialog (a call shbrowseforfolder looks of it), select folder, , contents of folder uploaded google docs. as feature requires upgrading google chrome latest version, or other browsers running java applet, assume can use feature in own websites? i love have feature in content management system maintain! you should able see demo here: http://html5-demos.appspot.com/static/html5storage/demos/upload_directory/index.html basically works setting attribute "webkitdirectory" on file input element. <input type="file" id="file_input" webkitdirectory="" directory=""> then when user has selected folder, itterates across "e.target.files" object list of files included in selection (...

c# - Phone 7 (Mango) background URL polling? -

whats recommended way poll url every 5min (in background) on phone 7 (mango) device ? are periodic agents limited 30min polling ? should looking push notifications ? any pointers/hints appreciated. thanks yop should looking push notification (it's lot more complicated periodic agent...) but periodic agent set 30 mins (and 25sec of code execution think) , there nothing can it. note user can decide deactivate periodic agent in options. but pushing notifications every 5 minutes on phone might not idea anyway... it's gonna drain battery quickly! what trying accomplish?

python - Finding a subimage inside a Numpy image -

i have 2 numpy arrays (3-dimensional uint8) converted pil images. i want find if first image contains second image, , if so, find out coordinates of top-left pixel inside first image match is. is there way purely in numpy, in fast enough way, rather using (4! slow) pure python loops? 2d example: a = numpy.array([ [0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11] ]) b = numpy.array([ [2, 3], [6, 7] ]) how this? position = a.find(b) position (0, 2) . this can done using scipy's correlate2d , using argmax find peak in cross-correlation. here's more complete explanation of math , ideas, , examples. if want stay in pure numpy , not use scipy, or if images large, you'd best using fft based approach cross-correlations. edit: question asked pure numpy solution . if can use opencv, or other image processing tools, it's easier use 1 of these. example of such given piquer below, i'd recommend if can use it.

c++ - Issue with QHash -

i been trying , trying work refuses work. read qt documentation , i'm unable insert function function. when build following complication errors /home/mmanley/projects/streamdesk/libstreamdesk/sddatabase.cpp: in constructor 'sddatabase::sddatabase()': /home/mmanley/projects/streamdesk/libstreamdesk/sddatabase.cpp:27:44: error: no matching function call 'qhash<qstring, sdchatembed>::insert(const char [9], sdchatembed (&)())' /usr/include/qt4/qtcore/qhash.h:751:52: note: candidate is: qhash<key, t>::iterator qhash<key, t>::insert(const key&, const t&) [with key = qstring, t = sdchatembed] make[2]: *** [libstreamdesk/cmakefiles/streamdesk.dir/sddatabase.cpp.o] error 1 make[1]: *** [libstreamdesk/cmakefiles/streamdesk.dir/all] error 2 here header file: class sdstreamembed { q_object public: sdstreamembed(); sdstreamembed(const sdstreamembed &other); qstring friendlyname() const; ...

iphone - Turning a cell in a UITableView on/off on the same cell, in the same view -

is possible make 1 cell in uitableview have on/off behavior? basically, when click cell, becomes green, want. doesnt go viewcontroller or anything. when click same cell again, in same view, want green disappear , return it's previous color state. this how have didselectrowatindexpath - (void)tableview:(uitableview *)tableview didselectrowatindexpath:(nsindexpath *)indexpath { nsstring *selectedphrase = [datatable objectatindex:indexpath.row]; [self setcurrentphrase:selectedphrase]; } this seems easy question. know can drop in [tableview deselectrowatindexpath:indexpath animated:yes]; makes unhighlighted right away after click it. thanks! aaron you change background color of uitableviewcell on selection, may use bool tell fill in background (whether green or clear color). access cell through below method - (uitableviewcell *)cellforrowatindexpath:(nsindexpath *)indexpath use below reference code. - (void)tableview:(uitableview *)tablevie...

ios - NSURLConnection Delegate In A Different Class -

is possible set delegate of nsurlconnection different class? in class a have following method: - (void) foo { nsstring *url = [@"http://foo.bar"]; nsurlrequest *request = [nsurlrequest requestwithurl:[nsurl urlwithstring:url]]; [[nsurlconnection alloc] initwithrequest:request delegate:self.classb]; } the delegate methods i've implemented in class b never called, though.

mod rewrite - Prevent users from accessing files using non apache-rewritten urls -

may noob question i'm starting playing around apache , have not found precise answer yet. i setting web app using url-rewriting massively, show nice urls [mywebsite.com/product/x] instead of [mywebsite.com/app/controllers/product.php?id=x]. however, can still access required page typing url [mywebsite.com/app/controllers/product.php?id=x]. i'd make not possible, ie. redirect people error page if so, , allow them access page "rewritten" syntax only. what easiest way that? , think necessary measure secure app? rewritecond %{redirect_url} ! ^/app/controllers/product.php$ rewriterule ^app/controllers/product.php$ /product/x [r,l] rewriterule ^product/(.*)$ /app/controllers/product.php?id=$1 [l] the first rule redirect request /app/controllers/product.php no redirect_url variable set clean url. rewrite (last rule) set variable when calling real page , won't redirected.

Jquery animate while hover -

i'm looking basic feature: want animate div in it's position while mouse hovers on area of window. i've figured out how , when fire off animate function problem is, it's limited in time. i'm looking way move div relative it's position while hovering. cheers, janik edit: i've created jdfiddle. didn't know before. jsfiddle.net/ru2mz/7 render out problem: want continuous movement or animation of object while mouse on button. basic animation $('#id').animate({left: 100},100) wouldn't work since it's limited fixed end position , fixed amount of time. $('#somediv').bind('mouseenter', function () { this.iid = setinterval(function () { anidiv(); }, 25); }).bind('mouseleave', function () { this.iid && clearinterval(this.iid); }); function anidiv() { $('#somediv').animate({ marginleft: '-=20...

mysql - Duplicated data entries in PHP array -

i'm not sure if appropriate on here since more of understanding issue on part i''m curious know why receive output: response id: 3 question id: 1 question: middle name? title: how know michael array ( [0] => array ( [0] => 3 [r_id] => 3 [1] => 1 [question_id] => 1 [2] => middle name? [question] => middle name? [3] => how know michael [title] => how know michael ) ) when run php script: // grab response data database generate form $query = "select qr.response_id r_id, qr.question_id, q.question, quiz.title " . "from quiz_response qr " . "inner join question q using (question_id) " . "inner join quiz using (quiz_id) " . "where qr.user_id = '" . $_session['user_id'] . "'"; $data = mysqli_query($dbc, $query) or die("mysql error: " . mysqli_error($dbc) . "<hr>\nquery: $query"); $questions = ...

How to find out user defined function in SQL server 2005? -

i creating sql data dictionary.i using sql server 2005.i wanted know user defined function.i expanded database.under programability :- function:- table value function , scalar value function. assuming asking how list functions programatically select schema_name(schema_id) schema_name, name, object_definition(object_id) definition sys.objects type_desc in ('sql_scalar_function','sql_table_valued_function', 'sql_inline_table_valued_function','clr_table_valued_function')

python - Script languages: Max. Line Length -

i have written script stores digital signatures in binaries , script files. question regarding scripts: currently, these signatures stored in 1 single line (a comment) such as: #!/usr/bin/perl print "hello" print " world\n" #signature:asdasg13412sdflsal4sf etc........ the example perl, done scripting languages (perl, python, shell scripts etc.) question is: can trouble if length of line containing signature long? how interpreter handle this? if so, max. line length can use? most scripting languages have long enough limits, if indeed have formal limit on length of lines. posix recommends 2048 minimum. how long signatures? likely, not more 1024...in case, wouldn't worry. if doesn't work language, should report bug rather else.

linq - How to change default behavior of .Where method in EntityFramework 4.1? -

i'd change default behavior of .where method specific case(s). all business objects inherit baseobject has property int id {get; set;} // base class public abstract class baseobject { public abstract int id {get; set;} } i have 2 classes: public partial class user : baseobject { public override int id {get; set;} public string username { get; set; } public int profileid { get; set; } public virtual profile profile { get; set; } } public partial class profile : baseobject { public override int id { get; set; } public string name { get; set; } public virtual icollection<user> users { get; set; } public static profile getadminprofile() { return new profile(){id = 3, name = "admin profile"}; } } i write // throws unable create constant value of type 'profile'... exception user admin = users.where(user.profile == profile.getadminprofile()).firstordefault(); instead of user admin = users....

internet explorer - In IE8, how do you make it ignore the Browser Mode setting? -

in ie8, if use developer tools, can specify browser mode , document mode, , overrides default behavior. can helpful, have problem. i trying see default behavior, not set in developer tools. there way disable developer tools can see looks else? the developer tools override applies when change it. can close browser , restart go default behavior.

sqlite3 - SQLite installation problems -

i downloaded binaries windos sqlite , extracted them. there 3 files a shell dll analyzer when try run create database , table sqlite shell get.... sqlite version 3.7.8 2011-09-19 14:49:19 enter ".help" instructions enter sql statements terminated ";" sqlite> sqlite3 test.db ...> create table tbl1(one varchar(10), 2 smallint); error: near "sqlite3": syntax error sqlite> when try run create database , table command line(vista) shell get.... microsoft windows [version 6.0.6000] copyright (c) 2006 microsoft corporation. rights reserved. c:\users\codenamejupiterx>sqlite3 test.db 'sqlite3' not recognized internal or external command, operable program or batch file. c:\users\codenamejupiterx> does have ideas????? you run command sqlite3 test.db start sqlite shell. (your first example) in there, not need part of command again, issue "create table " command.

winforms - How to start /stop a windows service through a Windows Form application -

i wish start , stop windows service application via windows form application. ons tart of application wish start windows service, , on application exit wish stop service. how can achieved? you want use servicecontroller class . initialize service name, , call start() , stop() methods. using system.serviceprocess; servicecontroller sc = new servicecontroller("my service name"); if (sc.status == servicecontrollerstatus.stopped) { sc.start(); } //etc..

C++ toString member-function and ostream operator << integration via templates -

i'm beginner c++ developer , have question tostring , ostream operator integration via templates. have such code: struct methodcheckertypes{ typedef unsigned char truetype; typedef long falsetype; }; template<typename t>struct hastostring{ template<typename k>static typename methodcheckertypes::truetype test(decltype(&k::tostring)); template<typename> static typename methodcheckertypes::falsetype test(...); static const bool value = sizeof(test<t>(0)) == sizeof(typename methodcheckertypes::truetype); typedef decltype(test<t>(0)) valuetype; }; template<typename t, typename k> struct ifdef{}; template<> struct ifdef<typename methodcheckertypes::truetype, ostream&>{ typedef ostream& type; }; class withtostring{ public: string tostring() const{ return "hello"; } }; template<typ...

c# - File permission (write) -

hello, once got code work out erros, , downloaded file. gives me permission error, don't acesscontrol pop window should show. anyways, how can code download file? webclient request = new webclient(); request.credentials = new networkcredential(txtftpuser.text, txtftppassword.text); byte[] filedata = request.downloaddata(fulldownloapath);//dnoces.dreamhost.com filesecurity security = file.getaccesscontrol(downloadto); filesystemaccessrule rule = new filesystemaccessrule(@"builtin\users", filesystemrights.fullcontrol, accesscontroltype.allow); file.setaccesscontrol(downloadto, security); try { filestream f = file.create(downloadto/*+@"\"+file*/); f.write(filedata, 0, filedata.length); f.close(); messagebox.show("completed!"); } catch(exception e) { messagebox.show(e.message); } what in 'downloadto' variable ? i'm little confused code. since can perform getaccesscontrol() assume must contain folde...

python - Delete files of given types IFF there are no other file types in folder -

i want delete files of type [cue,jpg,png,m3u,etc.] if , if in folder or other files of [cue,jpg,png,m3u,etc.] type. have function can me files of type [cue,jpg,png,m3u,etc.] in given folder , return list, need delete of according conditions above. give example: file q.jpg in folder itself. after myfunc() finishes, deleted. edit sorry unclearness. let me give better example: have 2 folders, alpha , beta in folder gamma . in alpha , there 3 files: 1.mp3, 2.mp3, folder.jpg . in beta , there 1 file cover.jpg . after myfunc() finishes, 1.mp3, 2.mp3, folder.jpg should untouched while cover.jpg should deleted. it sounds have 2 steps: 1) given list of extensions, list of files in folder matching extension. 2) if files in directory have extension matching list, remove them note doesn't include information how traverse directory structure, or directories test ... sample code has single directory hard-coded in. import os dir = "mydirectory" extl...

Render HTML unescaped in a JSP page -

i've field on db contains html text , need print jsp page. how can render html? using <c:out value="${text}" /> can see text html tags. in other words, escaping html. the <c:out> default escapes xml entities < , > , & , " , ' prevent xss attacks. so solve problem, either don't use <c:out> (works on jsp 2.0 , newer): ${text} or add escapexml="false" attribute : <c:out value="${text}" escapexml="false" /> you need ensure html trusted, or easy xss attack hole. jsoup may helpful in this, see xss prevention in jsp/servlet web application .

c# 4.0 - Creating a JSON object in MonoTouch (C#) -

how manually create json object in monotouch(4.0)? the system.json namespace available, ( jsonobject , jsonarray , jsonprimitive , jsonvalue ) abstract, can't : jsonobject myobject = new jsonobject(); i need manually build json object, , not want use datacontractserialisation. for reference purposes : -i need transfer json object server web call later. (but can handle part) use json.net http://json.codeplex.com/

css - HTML : Div on Image -

i have following html. how can dragdiv shown on top of image? <div id="pnlcontainer" class="container"> <img id="cropbox" src='1.jpg' /> <div class="dragdiv" id="dragdiv"> </div> </div> .dragdiv { width:400px; background-color:transparent; border:2px solid #cccccc; position:relative; left:20px; top:20px; padding:0px; margin:0px; height:50px; } currently, you're moving dragdiv down , away image. if change code -20px , -20px on .dragdiv css, on image. or, give "pnlcontainer" relative positioning, absolutely position both "dragdiv", , "cropbox" - shouldn't need z-index - positioning, div appear on image in case. either way fine. bottom line - positioning them correctly in case div on image. <style type="text/css"> #pnlcontainer { position: relative; } #...

algorithm - Best data structure for a given set of operations - Add, Retrieve Min/Max and Retrieve a specific object -

i looking optimal (time , space) optimal data structure supporting following operations: add persons ( name, age ) global data store of persons fetch person minimum , maximum age search person's age given name here's think of: keep array of persons, , keep adding end of array when new person added keep hash of person name vs. age, assist in fetching person's age given name maintain 2 objects minperson , maxperson person min , max age. update if needed, when new person added. now, although keep hash better performance of (3), think may not best way if there many collisions in hash. also, addition of person mean overhead of adding hash. is there can further optimized here? note: looking best (balanced) approach support these operations in minimum time , space. it looks need data structure needs fast inserts , supports fast queries on 2 different keys (name , age). i suggest keeping 2 data structures, 1 sorted data structure (e.g. balanced b...

osx - How do I create a Delete-Line Keyboard shortcut in Xcode 8? The Xcode 3 solutions do not work anymore -

Image
in previous versions of xcode possible create key binding delete current line. there different solutions , described example here: xcode: delete line hot-key xcode duplicate/delete line http://bigdiver.wordpress.com/2009/09/11/configure-homeend-key-bidings-on-mac-os-x/ http://www.betadesigns.co.uk/blog/2010/02/03/custom-xcode-shortcuts/ all solutions include modifying 1 of these files: ~/library/application support/xcode/key bindings/*.pbxkeys ~/library/keybindings/defaultkeybinding.dict ~/library/keybindings/pbkeybinding.dict a resource existing shortcuts in xcode 4 http://cocoasamurai.blogspot.com/2011/03/xcode-4-keyboard-shortcuts-now.html . there many listed regarding deletion, none "delete line". but, these solutions not work since xcode 4 . update : issue still same of xcode 5.1.1 update : issue still same of xcode 6.1 gm seed 2 update : still applies xcode version 7.3 (7d175) of 26th april 2016 update : 6 years later xcode 8.3 ...

java - How to bring overlapping SurfaceView to the front? -

i doing matlab-style heat map plot in android , decided use overlapping combination of glsurfaceview heat map (if don't know heat map is, don't worry it) , surfaceview axes labelling, bitmaps on top of heat map, etc. way glsurfaceview can things @ , canvas-based surfaceview can things at. surfaceview has transparent background glsurfaceview can seen through it. my problem glsurfaceview appears come "top" when rendered, , not able force surfaceview go top using "bringtofront()" method. there way this? have turned continuous rendering off, manually render surfaceview ("auxiliary") when render glsurfaceview. public void ondrawframe(gl10 gl) { log.d(tag, "heatmapview ondrawframe"); gl.glclear(gl10.gl_color_buffer_bit | gl10.gl_depth_buffer_bit); gl.glmatrixmode(gl10.gl_modelview); gl.glloadidentity(); heatmap.draw(gl); auxiliary.draw(); // surfaceview draw } /** * function draws our heat map on scree...

Is there a security threat if I enable a user to add CSS? -

is not secure enable user add own rules of css personal page, in (for example) social website ? it not secure . there multiple ways embed javascript in css such gets executed @ least browsers. google "xss css" , through top hits. don't unless you're willing hardcore sanitization of css, , clean mess when sanitization inevitably bypassed , users' cookies compromised.

translating a ruby script to python -

my problem following i have ruby script looking this module parent module son_1 ... code here end module son_2 ... code here end class 1 ... code here end class 2 ... code here end end and need script translated python little confused ? first made : i turned "module parent" python package i made "module son_1" , "module son_2" 2 files inside package and defined last 2 classed in __init__ file of package ( "module parent" ) my questions : is solution correct ? and if , there better 1 ? it should on file system : - parent/ ------- __init__.py << empty file or can have classes if need, way python treat parent package ------- son_1.py ------- son_2.py - test.py then in actual code in test.py : from parent import son_1, son_2, one, 2 c = one('something') b = son_1.something() #or import parent import parent.son_1 import par...

database design - Hibernate and "greatest value wins" logic -

i have high_scores table in database, has 2 values: player_id highest_score i need repository method saves new high score. don't want dirty code optimistic lock retry logic simple. i'd executed line: update high_scores set highest_score = :new_high_score player_id = :player_id , highest_score <= :new_high_score that accomplish goal fine, although i'd have worry creating high score if user didn't have one. need make sure never overwrite high score lower score, that's sort of locking table needs. is there way ask hibernate this, or need resort custom sql? hibernate supports bulk update (from 3.3 on). edit: check: http://docs.jboss.org/hibernate/core/3.3/reference/en/html/batch.html#batch-direct making easier (from hibernate docs): session session = sessionfactory.opensession(); transaction tx = session.begintransaction(); string hqlupdate = "update customer c set c.name = :newname c.name = :oldname"; // or string hqlupdat...

android - The specified child already has a parent and click event -

that code... for(int i=0;i<siteslist.getpdf().size();i++) { bitmap bmp; url url=null; inputstream is; imageview iv=null; tr=new tablerow(this); tr.setlayoutparams(new layoutparams( layoutparams.wrap_content, layoutparams.wrap_content)); (int j=0;j<2;j++) { iv=new imageview(this); try { s1=siteslist.getthumbnail().get(count); url = new url(s1); count++; conn=(httpurlconnection)url.openconnection(); conn.setdoinput(true); conn.connect(); = conn.getinputstream(); bmp = bitmapfactory.decodestream(is); iv.setimagebitmap(bmp); iv.setlayoutparams(new layoutparams( layoutparams.fill_parent, layoutparams.fill_parent));...

javascript - Getting the sum of a collection (all models) with backbone.js -

i'm learning backbone. have following window.serverlist = backbone.collection.extend({ model: server, cputotal: function(){ if (!this.length) return 0; /* * not sure how sum them * this.get('cpu') integer each of collections */ return this.get('cpu'); } }); i'm calling render method of view this window.appview = backbone.view.extend({ // .... render: function(){ var total_cpu = serverlist.cputotal(); var items = serverlist.length; } }); the variable total_cpu empty items correct. ideas ? i know collection working have plenty of items in there, need add cpu's each item in collection page summary. for know todos example http://documentcloud.github.com/backbone/docs/todos.html have similar setup. here best way know how: cputotal: function() { return this.reduce(function(memo, value) { return memo + value.get("cpu") }, ...

logging - HOW to get MFCC from an FFT on a signal? -

short , simple: hi simply... want know steps involved mfcc fft. detailed: hi all. working on drum application want classify sounds. matching application, returns name of note play on drum. its simple indian loud big drum. there few notes on there 1 can play. i've implemented fft algorithm , obtain spectrum. want take 1 step further , return mfcc fft. this understand far. based on linear cosine transform of log power spectrum on nonlinear mel scale of frequency. it uses triangulation filter out frequencies , desired coefficient. http://instruct1.cit.cornell.edu/courses/ece576/finalprojects/f2008/pae26_jsc59/pae26_jsc59/images/melfilt.png so if have around 1000 values returned fft algorithm - spectrum of sound, desirably you'll around 12 elements (i.e., coefficients). 12-element vector used classify instrument, including drum played... this want. could please me on how this? programming skills alright. im creating application iphone. openframeworks. any ...

windows - Batch command date and time in file name -

i compressing files using winzip on command line. since archive on daily basis, trying add date , time these files new 1 auto generated every time. i use following generate file name. copy paste command line , should see filename date , time component. echo archive_%date:~-4,4%%date:~-10,2%%date:~-7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.zip output archive_20111011_ 93609.zip however, issue am vs pm . time stamp gives me time 9 (with leading blank space) vs. 10 naturally taking 2 spaces. i guess issue extend first 9 days, first 9 months, etc. well. how fix leading zeroes included instead of leading blank spaces archive_20111011_093609.zip ? another solution: for /f "tokens=2 delims==" %%i in ('wmic os localdatetime /format:list') set datetime=%%i it give (independent of locale settings!): 20130802203023.304000+120 ( yyyymmddhhmmss.<milliseconds><always 000>+/-<timedifference utc> ) from here, easy: set dateti...

c++ - Have an issue where menu is re-occurring. using switch statement -

i having problem program runs again after runs 1 time. when runs every selection ran correctly no errors never exits program. anyone? i feel dumb, put while statement repeat itself. ok if take of while statement, else need take off can run it? #include <iostream> using namespace std; int main() { int in1, in2, in3; char selection; { cout << " welcome cs221 homework 2 menu\n"; cout << " ====================================\n"; cout << " 1. multiply 2 integers\n"; cout << " 2. divide 2 integers\n"; cout << " 3. check if number within range 10-20\n"; cout << " 4. find minimum of list of 3 numbers\n"; cout << "\n"; cout << " 0. exit\n"; cout << " ====================================\n"; cout << " enter selection: "; cin >> selection; cout << endl; switch (selection) { case '1...

php - adding 1 to last row of mysql table -

hi i'm trying select last id in table add 1 value. selecting last row find problem i'm having problems +1 think because it's array i'm not sure. $result = mysql_query("select `id` `users` order `id` desc limit 1"); $row = mysql_fetch_row($result); $pin = $row[0]+1; echo ($row[0]); //returns id echo ($pin); // returns null any thoughts on great. try this: select max(id) + 1 users but if doing insert, grab mysql_last_insert_id() find out inserted. otherwise have issues concurrency. your id setup autoincrement correct? should never never never never ever assign primary key yourself. db servers job.

Parent and Child DIV's not nested position change jquery javascript question -

if have 2 divs, div , div b (assume both absolute positioned).. want amke when div a's position changes, div b (which "child" of div a, event though 2 separate divs, not nested), div b's position changes same offsets div did. if move div b's position... div b moves , div a's position unaffected. change in positon dragging div example. if possible, able make can have 3rd div, , "child" of div or b, , same action apply. (ex1. if div c , b children of div a, moving div update position of div c , b) ex2. if div c child of div b, when moving diva, div b , c updated. if divb moved, div b , c updated. if moving div c, div c updated. update: hussein's code similar want, problem div of class .b happens snap opposed preserving current position , adding offset .a moves. assuming using jquery ui draggable() , use drag event achieve this. may need modify code further suit needs, example below should on right track. $('.a, .b'...

select - Multiple Conditional Statements in a Javascript function -

i haven't used javascript sometime. i'm trying following script working if select "ireland" in dropdown, ireland select menu appears below. same goes america , canada. http://jsfiddle.net/mcgarriers/dpse4/ however it's not working. can take , explain why? i'm sure it's simple. many @ all. now working : http://jsfiddle.net/dpse4/3/ you needed pass "select" node function , instead of form.

python - how many unread bytes left in a file? -

i read periodically 16-bit frames file, last frame need know if there enough data , file valid format. f.read(16) returns empty string if there no more data more or data if there @ least 1 byte. how can check how many unread bytes left in file? for that, you'd have know size of file. using file object, following: f.seek(0, 2) file_size = f.tell() the variable file_size contain size of file in bytes. while reading, f.tell() - file_size number of bytes remaining. so:

vi - Vim: copy/delete line from the first none blank character to the last none blank character -

most time when copy or delete code in vim use yy or dd , got indent spaces. there quick command can yank line without leading or trailing spaces? i'm not wizard, but: ^v$gey works me. can make alias. edit : here's better 1 doesn't rely on visual mode. ^yg_

Inverted index in Lucene -

i want know class in lucene generates inverted index ? thanks the inverted index created in class named freqproxtermswriter , based on information retrieved documents, such term frequency , document frequency , term position etc.

java - HADOOP: emitting a Matrix from a mapper -

hi new hadoop map reduce, wanted know there outputformat type can allow me emit matrix(2d array) directly mapper (without converting 1d). need urgently since have include in btech project take at: http://hadoop.apache.org/common/docs/current/api/org/apache/hadoop/io/twodarraywritable.html guess that's need.

Is there a handy GUI for REST manual services testing? -

while developing rest service want able manually submit data (e.g. put or post method) specific url , see response. tool know soapui, not commercial product, bit overcomplicated while task simple. there a question soapui alternatives , discussion there soap services, while need rest :-) ideas? know can write such tool myself pretty easily, i'd prefer not reinvent bicycle if there one. update: mark cidade 's answer ok, i'd wish tool run on linux too... update 2: solution of choice came httprequester firefox extension . i have discovered , installed restclient , firefox add-on (it's ideal me development on ff, both on windows , linux). no idea if it's yet. :) edit: i've started using extensively since, , it's good, gives lot of data response and request.

Android TabActivity instance in ViewGroup's chaild Activity -

i have tabhost app 3 activities,in first tab created viewgroup.every thing working fine my problem want tabactivity instance view group's chaild activity how can this... trying in view group's child activity tab_activity tabobj = (tab_activity)getparent(); abobj.somemethod(); i got class cast exception,i think getting view group activity instance, want tabactivity instance,please me if 1 knows answer tab_activity tabobj = (tab_activity)getparent().getparent(); treid also... thanx in advance i tested it: if tabactivity extends standard android.app.tabactivity tab_activity tabobj = (tab_activity)getparent(); should work designed. edit: ah. want this: tab_activity tabobj = (tab_activity)((childactivity)getcontext()).getparent(); from inside viewgroup.

How can I keep HTML styling in a php form storing data in MySQL? -

so have box user enters data "a description" , stores in mysql. however, html tags such <img src=""> , <a href=""> , etc. not store there in 'description' field. how can allow html codes passed through mysql? this description input box looks like: <?=form_textarea( 'description', $channels->description, 'class="field" style="width:306px; height: 70px; margin-left:5px;"' )?> this form gets passed: $this->form_validation->set_rules( 'description', lang('user_edit_channel_description'), 'trim|required|strip_tags|xss_clean' ); and posted mysql here: $rows['description'] = $this->input->post('description'); you need use form of strip_tags function second parameter, allows specify html tags allowed. explained in this post , need create callback function call because two-parameter version of strip_...

php - display database field in textbox -

i trying display database input in textbox editing. cant seem working?! page links forum post edit button. firstly, don't know how database info particular field displayed , don't understand how make sure post user clicks edit post displayed. my code looks this <?php #data preparation query $id=$_get['id']; # selects title , description fields database $sql = "select a_answer $tbl_name question_id='$id'"; $result=mysql_query($sql); $rows=mysql_fetch_array($result); ?> <h3>edit</h3> <form action="save_edit.php" enctype="multipart/form-data" method="post" name="myform" /> <table> <tr> <td><b>answer</b></td> <td><textarea cols="80%" rows="10" name="a_answer"><?php echo $row['$a_answer']; ?></textarea></td> </tr> </table> <in...

compiler construction - can compile c++ in eclipse - Cannot run program "autoreconf": Launching failed -

i installed eclipse helios week ago. first installed without cdt. today installed cdt along autotool (this can seen in list of possible updates). afterwards, installed mingw (wascana) written in manual of cdt. after create hello world project in eclipse error (blinking non stopable) in console tab: invoking autoreconf in build directory: d:/eclipse/proj/workspace/testcpp configuration failed error (cannot run program "autoreconf": launching failed) can me this? else need install or config cdt work? thanks, eli the autotools plug-in doesn't work on windows yet. there fix in place upcoming indigo eclipse release. the main problem windows doesn't know how run shell scripts (which autoreconf is). have launch shell manually , ask run it. , that's fix is.

java - Scrolling SWT Table is slow when running with exe4J -

i have swt desktop app distributed using install4j , runs under exe4j. the app contains table displays list of documents downloaded server. thread handles download , makes call-backs select current row , update row icon when download complete. this works fine in ide (eclipse) , when start app clicking on jar. when running installed package runs slower. noticable when sort table. download schedule different order of table items and, when items selected, table scrolling , down show current item. scrolling blocks 2 seconds , large parts of table not drawn completely. logging suggests delay in waiting syncexec() run. what be? why run fine when started directly not in exe4j? i mailed support chaps , said 'it related fact executable has xp manifest while java.exe excutable not'. has else had kind of problem? just heard support. they suggested following: then must application manifest. don't need mageui, can edit [install4j installation dire...

Lite/Embedded alternatives to SQLite (in Android)? -

are there alternatives sqlite db? mean kind of light/embedded sql dbs derby or hypersonic? the h2 database engine supports android .

c# - Model relationships about implementing vote system -

i confused voting system implementation. want know vote , vote down counts of post , save voters voted or down. use below model it. public class post : entity { public string title { get; set; } public virtual user owner { get; set; } public virtual list<user> upvoters { get; set; } public virtual list<user> downvoters { get; set; } } i feel bit of problem in design because if have represent vote , vote down count of post think have process 2 query.using navigation properties counts cause performance problems if need counts. right? second aproach below confuse me because voteupcount , votedowncount should handled manualy developer. , reupdate values when voter changed vote , looks bit of code smell. public class post : entity { public string title { get; set; } public virtual user owner { get; set; } public int voteupcount { get; set; } public int votedowncount { get; set; } public virtual list<user> upvoters { get; set;...

javascript - Displaying Flickr photos using the Galleria jQuery plugin -

i'm trying import/show photos flickr photostream (or set) using galleria (http://galleria.aino.se/). couldn't find useful info in galleria documentation. how go doing that? there flickr plugin included in galleria download version 1.2.4 makes these things easy. here docs plugin, including examples: http://galleria.aino.se/docs/1.2/plugins/flickr/

asp.net - Run stored procedure in C#, pass parameters and capture the output result -

this simple task want acheive asp.net makes quite difficult, next impossible. followed question running stored procedure in c# button found out executenonquery not return output query. i tried other approach can't seem pass paremeters in way sqlconnection myconnection = new sqlconnection(myconnectionstring); sqlcommand mycommand = new sqlcommand(); mycommand.commandtype = commandtype.storedprocedure; mycommand.commandtext = "usp_getcustomer"; mycommand.selectparameter <-- not exist can write simple code, how can implement it? passing @username , @month (both character strings) stored procedure , returns number want capture , assign label control. thank you the output query this. runs complex query, create temp table , runs select @@rowcount and capturing that. don't use sqlcommand. executenonquery() if want data result set. make sure procedure uses set nocount on then use sqlcommand. executescalar() return (int)mycommand.execu...

actionscript 3 - flash simple button with text -

i have simple button in flash cs5 - as3 called btn1 dynamic text called text_txt inside inside it. the goal change text however... btn1.visible=true; // works fine this.btn1.text_txt.text="hello"; // give null error my question is: how programatically change text inside button ? because have flashdevelop can show how programmatically. if dealing sprite object(which recommend) following how access textfield in sprite object: var textfield:textfield = new textfield(); textfield.name = "textfield"; textfield.mouseenabled = false; var rectangleshape:shape = new shape(); rectangleshape.graphics.beginfill(0xff0000); rectangleshape.graphics.drawrect(0, 0, 100, 25); rectangleshape.graphics.endfill(); var buttonsprite:sprite = new sprite(); buttonsprite.addchild(rectangleshape); buttonsprite.addchild(textfield); addchild(buttonsprite); var tf:textfield = textfield(buttonsprite.getchildbyname("textfield")); tf.text = "button sprite ...

mysql - How can I combine this php statement to get the results of multiple variable inputs? -

this wordpress query not wordpress related question. shows posts have meta_key extra1 , meta_value test <?php $customkey1 = extra1; ?> <?php $customvalue1 = test; ?> <?php query_posts('meta_key=' . $customkey1 . '&meta_value=' . $customvalue1 . ''); ?> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <?php the_title(); ?> <?php endwhile; ?> <?php endif; ?> my question how can still show posts have extra1 metakey , test metavalue posts have extra2 metakey , test2 metavalue in same query. combination of 2 or more variables. so want combine results of 2 queries? check out may need make 2 query objects , combine them. something (note, not have wordpress installed, nor use wordpress. assuming api not lie): <?php // query $the_query = new wp_query( $args ); $the_second_query = new wp_query( $args ); // loop while ( $the_query->have_posts() ) : $the_query->the_post...

best way to convert eclipse project to a tomcat servlet? -

i working on servlet using eclipse. runs fine when use junit tests inside of eclipse. problem need run same servlet using tomcat. having trouble getting work though. error seems when code attempts load jdbc drivers connect mysql. think has location of jar files. i wondering if rather trying figure out stuff tomcat, there way guys recommended export project eclipse tomcat? bro, think have port numbers in database connect url. take these out dont need them , causing errors.

ruby - Blocking Call In Popen -

pipe = io.popen('./myblockingprogram') while line = pipe.gets puts "hello world" end where myblockingprogram program blocks until receives data on network, , prints text stdout. tested running bash directly works great. however, when run program above, never see "hello world" lines printed stdout (the console). wrong popen starts whole new process... , therefore though makes blocking call should not prevent main ruby program running due global interpreter lock? is there better way structure program this, want read text lines output program , process results in way (there no terminating condition, may run forever)? make sure myblockingprogram flushes output buffer when writes stdout. a simple example myblockingprogram is: #!/bin/ruby 100.times sleep 10 $stdout.puts "hello world" $stdout.flush end without flush command don't see result pipe until subprocess finishes. flush command, see intermediate results ...

When resize() in JQuery, trigger fires multiple times -

i use paul irish smartresize when resize window function inside resize() fires multiple times causing accordion not work properly. have idea why happens? here code running: http://jsfiddle.net/rebel2000/pnah7/6/ $(document).ready( function(){ (function($,sr){ // debouncing function john hann // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/ var debounce = function (func, threshold, execasap) { var timeout; return function debounced () { var obj = this, args = arguments; function delayed () { if (!execasap) func.apply(obj, args); timeout = null; }; if (timeout) cleartimeout(timeout); else if (execasap) func.a...

How can I disable vectorization while using GCC? -

i compiling code using following command: gcc -o3 -ftree-vectorizer-verbose=6 -msse4.1 -ffast-math with optimizations enabled. but want disable vectorization while keeping other optimizations. most of gcc switches can used no prefix disable behavior. try -fno-tree-vectorize (after -o3 on command line).

google chrome - Replace remote JavaScript file with a local debugging copy using Greasemonkey or userscript -

while debugging client app uses google backend, have added debugging versions of functions , inserted them using chrome developer tools script editor. however there number of limitations approach, first editor doesn't seem work de-minified files, , when js file 35k lines long, problem. another issue initialization done during load time, uses original "unpatched" functions, hence not ideal. i replace remote javascript.js file own local copy, presumably using regex on file name, or whatever strategy suitable, happy use either firefox or chrome, if 1 easier other. so basically, @brockadams identified, there couple of solutions these types of problem depending on requirements, , follow either 1 of 2 methods. the browser api switcharoo. the proxy based interception befiddlement. the browser api switcharoo. both firefox , chrome support browser extensions can take advantage of platform specific apis register event handlers "onbeforeload" or...

Getting price before and after discount separately using nokogiri n Ruby on Rails -

i'm trying learn on scrap these values put in 2 different task: get 35.00 entire text get 42.00 entire text below html: <p style="font-size: 30px; margin-left: -10px; padding: 15px 0pt;"> $35.00 - $42.00 </p> the code im using entire text below: node = html_doc.at_css('p') p node.text you can whole text node.text , that's far need go nokogiri. there use scan find numbers , bit of list wrangling ( flatten , map ) , you're done. this: first, second = node.text.scan(/(\d+(?:\.\d+))/).flatten.map(&:to_f) that should leave 35.0 in first , 42.0 in second . if know numbers prices decimals can simplify regex bit: first, second = node.text.scan(/(\d+\.\d+)/).flatten.map(&:to_f)