Posts

Showing posts from March, 2013

android - Is it OK to use "mContext" (initialized at onCreate)? -

is bad habit, , why if is? in every activity adding right after oncreate ... mcontext = this; and use in other cases context required ? example toast.maketext(mcontext, mcontext.getstring(r.string.somestring), toast.length_long); edit: if have this...how context should passed? because this cannot applied (because of view.onclicklistener() ). somebutton = (button) findviewbyid(r.id.somebutton); somebutton.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { toast.maketext(mcontext, mcontext.getstring(r.string.warning), toast.length_long).show(); } }); is bad habit, , why if is? yes, bad habit. waste of code. this shorter mcontext , , have line of code setting data member. i disagree mr. damiean's suggestion of using getapplication() . use getapplication() when need application object. neither need nor want application object creating toast -- activity suitable context use there. applicat...

How do I use git-tfs and idiomatic git branching against a TFS repository? -

how use git-tfs idiomatically? the git idiom check out branches to root directory of repository. checking out branch replace contents of directory contents of branch. the tfs idiom check out each branch in different directory under root directory of repository (even master or trunk branch). checking out branch place in new directory next current one. using git-tfs , can clone tfs repository or branch git repository. want work on tfs repository multiple branches in manner consistent git branching idiom . i'm not sure what's technically possible or recommended :) clone whole tfs repository if clone whole repository out of tfs > git tfs clone http://<tfsurl>:8080 $/main that give me git master containing all tfs branches directories. [master]> dir trunk feature-logon feature-search release-0.0.1 add remote per tfs branch i don't know if can (or how to) map git remote each tfs branch. > git init . [master]> git tfs c...

Providing several non-textual files to a single map in Hadoop MapReduce -

i'm writing distributed application parses pdf files of hadoop mapreduce. input mapreduce job thousands of pdf files (which range 100kb ~2mb), , output set of parsed text files. for testing purposes, used wholefileinputformat provided in tom white's hadoop. definitive guide book, provides single file single map. worked fine small number of input files, however, not work thousands of files obvious reasons. single map task takes around second complete inefficient. so, want submit several pdf files 1 map (for example, combining several files single chunk has around hdfs block size ~64mb). found out combinefileinputformat useful case. cannot come out idea how extend abstract class, can process each file , filename single key-value record. any appreciated. thanks! i think sequencefile suit needs here: http://wiki.apache.org/hadoop/sequencefile essentially, put pdfs sequence file , mappers receive many pdfs fit 1 hdfs block of sequence file. when create sequen...

sql - Retrieve and insert into type objects in oracle -

i have created object type(address-city,state) in oracle 10g .then table cust_contact contains field of type address.can please provide sql query insert , retrieve values table including type? selection easy. include type column in query projection. assuming address column called contact_address: select id, contact_name, contact_address cust_contact / with inserts need specify type in statement: insert cust_contact values (some_seq.nextval , 'mr knox' , address(34, 'main street', 'whoville', 'su') ) /

visual studio 2010 - How to access MailItem from UserControl? -

hey guys, have usercontrol within default email compose form, want mailitem of window. is there easy way this? since composing email, must in outlook inspector. have code this: inspector inspector = window inspector; mailitem mailitem = inspector.currentitem mailitem;

swing java: display jbutton and image separately on the screen -

hi im trying add button screen, when user clicks on button random dice picture displayed somewhere else on screen. simple this code how i've tried doing it... although cant seem buttons appear picture. either 1 or other. doing wrong? any appreciated. im sure im using far code desired output. ava.util.random; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.awt.image.bufferedimage; import javax.imageio.imageio; class mycomponent extends jcomponent { public void paint(graphics g) { imageicon icon = new imageicon("dice1.png"); int x = 0; int y = 0; icon.painticon(this, g, x, y); } } class dice extends panel { bufferedimage image; public dice(){ jframe frame = new jframe("test"); jpanel panel = new jpanel(); frame.add(panel); jbutton button2 = new jbutton("roll die"); button2.addactionlistener(new actionlistener(){ ...

c++ - ActiveMQ CPP brokers URI problem -

i'm using activemq cpp 5.2.3. i'm trying add transport.commandtracingenabled=true tcp transport layer: failover://(tcp://10.10.10.1:61616transport.commandtracingenabled=true,tcp://10.10.10.2:61616?transport.commandtracingenabled=true)?randomize=true activemq doesn't accept it. hovewer 1 tcp transport works fine: failover://(tcp://10.10.10.1:61616transport.commandtracingenabled=true)?randomize=true i think mean version 3.2.3. can expand on "activemq doesn't accept it" means? looks you're missing '?' character after first ip/port failover://(tcp://10.10.10.1:61616transport.commandtracingenabled=true,tcp://10.10.10.2:61616?transport.commandtracingenabled=true)?randomize=true there uri fixes coming in v3.2.5 might also.

javascript - Jquery accordion activate from external links -

i having lot of trouble trying open j query ui accordion sections external links. calling form functions hyperlinks. links opening sections click original position. appreciated. here source. <script> $(function() { $( "#accordion" ).accordion({ autoheight: false, }); }); </script> <script> function clicked1(){ $("#accordion").accordion('activate' , 0) } function clicked2(){ $("#accordion").accordion('activate' , 1) } </script> <div class="demo"> <a href="" onclick="clicked1()">open1</a> <a href="" onclick="clicked2()">open2</a> <div id="accordion"> <h3>< href="#section1" >section 1</a></h3> <div> <p>mauris mauris ante, blandit et, ultrices a, susceros. nam mi. proin viverra leo ut odio. curabitur mal...

FasterCSV for importing users in rails -

hi, trying use fastercsv import users csv file i have <form action='/users/bulk_create' method='post'> <%= file_field_tag "csv_file" %><br/> <%= submit_tag("import") %> </form> in users controller have method like def bulk_create login, password, name, email = 0, 1, 2, 3 require 'fastercsv' parsed_rows=fastercsv.parse(params[:csv_file]) parsed_rows.each |row| puts "#{row[name]}" end end when above , inspect in log getting error as nomethoderror (undefined method `pos' nil:nilclass): app/controllers/users_controller.rb:688:in `bulk_create' fastercsv not reading file @ all. how make read installed gem using sudo gem install fastercsv since uploading file, must specify enctype attribute form multipart/form-data <form action='/users/bulk_create' method='post' enctype='...

Rails 3 - Removing a User but retaining content? -

i've seemed have gotten myself bit of pickle. i'm trying write way destroy users, still retain content. currently in app, company has many users, , users belongs 1 company. company can make user inactive if need to, i'd company able remove users account in cases of termination, etc. i going simply, on destroy, set foreign company_id key nil in user's table. however, doing this, company lose old user's work, can't happen, information populated doing queries on company_id. has thought of nice little way of getting around similar db design? or have go square 1 figure out way more effectively. thanks this more of interface issue data model issue. sure, shouldn't delete/destroy users if need retain information. if need way of removing users apart making them inactive, add option 'terminated' status. depends on how , display these terminated users in front end (or maybe never display them).

iphone - Core Data modeling of relationships -

Image
i'm modeling app in core data. have object called 'stats' have 'player', 'team', , 'game' associated each object. once these stats objects stored, imagine querying them 1 or more of these attributes (player, team, game). see model below. question 1: make sense model these 'relationships' opposed 'attributes'. question 2: when retrieving form nspredicates using objects , not have keep track of unique ids names each player, team, or game. if store player, team, , game objects (as opposed unique ids or names) each entity, best way retrieve them. following work if wanted retrieve stats objects particular 'team' (someteamobject) or need query objectid? nspredicate *predicate = [nspredicate predicatewithformat:@"team == %@", someteamobject]; thanks if understand question right, yes, makes sense model these separate objects relationships between them. when fetching various objects; could, example...

Resize Height of Object/Embed with jQuery? -

i have object/embed on page: <object type="application/x-shockwave-flash" width="100%" height="{$height}" id="chat_shell" data="js/8wayrun/irc/lightirc.swf?host={$server}{$params}{$extras}{$styles}"> <param name="movie" value="js/8wayrun/irc/lightirc.swf" /> <param name="allowfullscreen" value="true" /> <param name="wmode" value="transparent" /> <param name="flashvars" value="host={$server}{$params}{$extras}{$styles}" /> </object> when click button, activates jquery scripting... $('#chat_shell').animate({ height: $('#chat_shell').height() + slideheight }, slidespeed); but instead, when click button, following error: uncaught typeerror: cannot read property '0' of undefined why happening , how fix it? know possible solution wrap object/embed div, set height...

jsonp - jQuery, JSON-P and Google Translation : Various errors -

i'm developping greasemonkey user script provide direct translation of form fields inside intranet app. everything goes ok until call google translation api using code : var apiurl = 'https://ajax.googleapis.com/ajax/services/language/translate?v=1.0&langpair=fr%7cen&q='; $.getjson(apiurl+encodeuricomponent(text)+"&callback=?",function(data){ alert('translation complete'); //change text }); here problems : i'm forced use jsonp cross-domain request. in order that, added &callback=? string @ end of url. getjson callback isn't fired (but response data correct), , error in firebug console : jsonp1298988446807 not defined if use &callback=foo instead, ff doesn't seem it, request no longer post one, doesn't complete shows (in network panel) options request_url 405 method not allowed if create custom function specify callback, doesn't work either function isn't called (it con...

c# - One-To-Many mapping fluent NHibernate -

i trying one-to-many relation working. have following mappings: public class user { public user() { usercourses = new list<usercourse>(); } public virtual int id { get; private set; } public virtual ilist<usercourse> usercourses { get; private set;} } public sealed class usermap : classmap<user> { public usermap() { id(x => x.id, "id"); hasmany(x => x.usercourses).inverse().cascade.all().table("usercourse"); table("[user]"); } } public sealed class usercoursemap : classmap<usercourse> { public usercoursemap() { id(x => x.id, "id"); references(x => x.user, "userid"); map(x => x.role, "role"); } } i getting following exception if try make instance of user object , tries view courses: var user = (from u in userrepository.linq() // fetch user ...

mysql query result in php variable -

is there way store mysql result in php variable? thanks $query = "select username,userid user username = 'admin' "; $result=$conn->query($query); then want print selected userid query. of course there is. check out mysql_query , , mysql_fetch_row if use mysql. example php manual : <?php $result = mysql_query("select id,email people id = '42'"); if (!$result) { echo 'could not run query: ' . mysql_error(); exit; } $row = mysql_fetch_row($result); echo $row[0]; // 42 echo $row[1]; // email value ?>

php - Parse data from string "name:john email:john@example.com id:123456" -

basically, want access data between substrings (between "name:" , "email:", example) what's best way of doing this? you can first explode on space... $array = explode(' ',$string); and explode on : while looping through.... foreach($array $arr){ $temp = explode(':',$arr); echo $temp[1]; // value here }

css - Best way to detect touchscreens (ipad, iphone, etc)? -

i need load additional css page if being viewed on touch screen device ipad or iphone. whats easiest way this? easiest arguably http://www.modernizr.com/ .

C# - Compile a batch file programatically -

can programatically compile batch file form c#. meaning give location of file , c# library compiles file , gives output can tell me library c# can me write small intepreter c# batch files in windows not compiled. executed command processor. you can use process.start execute batch file within c# program.

iphone - app crashes when using kABPersinPhoneProperty -

i trying phone number phone book of iphone. app crashes try fetch number using kabpersonphoneproperty. code snippet here abaddressbookref addressbook = abaddressbookcreate(); nsmutablearray *allpeople = (nsmutablearray*)abaddressbookcopyarrayofallpeople(addressbook); int npeople = abaddressbookgetpersoncount(addressbook); cfrelease(addressbook); for(int i=0; < npeople; i++ ){ abrecordref person = [allpeople objectatindex:i]; nsstring *name = @""; cftyperef fname = abrecordcopyvalue(person, kabpersonfirstnameproperty); cftyperef lname = abrecordcopyvalue(person, kabpersonlastnameproperty); abmultivalueref multi = abrecordcopyvalue(person , kabpersonphoneproperty); nsstring *number = (nsstring *)abmultivaluecopyvalueatindex(multi, 0); if ([number length] > 0) { if(fname != null) { if (lname != null) { name = [[nsstring stringwithformat:@"%@", fname] stringbytrimmingcharactersinse...

Uploadify/jQuery, How could I display result of uploaded file? -

i see prints in server side script when gets file (via uploadify plugin in jquery). how can that? if go the official site documentation section, can find there the oncomplete function allows fire custom function when each file has completed uploading. so server side script pass data jquery script, know happening on server. there onerror events, able know errors or can create server log , trace there information server side script(it db, or simple text file), if don't want user know happening on server.

Facebook C# SDK and Access Token -

i'd able authenticate myself (my profile, not app) on own web application using facebook c# sdk. using graph api, can access token, token not seem work facebook c# seems stateless. the error thrown is: (oauthexception) active access token must used query information current user. i've poked around facebook c# sdk , documentation , of info i'm seeing redirect users login page not i'm looking for. does have sample of auto-logging in myself can pull own information? tia when "yourself" mean app or actual facebook user? if it's app, can access token posting url: https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=app_id_here&client_secret=app_secret_here you can use access token perform actions on behalf of users if have authorized app so.

build - Overriding 'clean' lifecycle in Maven -

i going through book explain how override 'default' lifecycle of maven. it says: define new lifecycle packaging type, you'll need configure lifecyclemapping component in plexus. in plugin project, create meta-inf/plexus/components.xml under src/main/resources. in components.xml add content shown below, , you're done. below configuration, i'm able customize default lifecycle 'jar' packaging type. if exeute $ mvn package straigh away executes 'package' phase skipping other phases of default lifecycle , executes 'echo' goal of 'maven-zip-plugin'. <component-set> <components> <component> <role>org.apache.maven.lifecycle.mapping.lifecyclemapping</role> <role-hint>zip</role-hint> <implementation> org.apache.maven.lifecycle.mapping.defaultlifecyclemapping </implementation> <configuration...

date - PHP: Adding years to a timestamp -

in php given utc timestamp add n number of years. should take consideration leap years. thank you. $newtimestamp = strtotime('+2 years', $timestamp); replace "+2 years" required. ref: http://php.net/manual/en/function.strtotime.php

c# - Finding checkboxes inside a gridview in wpf -

i have following code: <listview name="lvwyears" margin="0,32,191,29" itemssource="{binding path=yearcollection}"> <listview.view> <gridview> <gridviewcolumn> <gridviewcolumnheader> <checkbox click="checkbox_checked" horizontalalignment="left" content="year" padding="50,0,0,0" margin="20,0,0,0"></checkbox> </gridviewcolumnheader> <gridviewcolumn.celltemplate> <datatemplate> <checkbox click="checkboxindividual_click" name="cbxyears" verticalalignment="center" ...

java - EasyMock and Ibatis -

in dao layer doing database work calling stored procedures. wondering has been successful in testing dao layer using easymock? thanks damien i that's impossible. there's no way assert (with easymock or other mocking framework) dao called stored procedure, verify did etc. the thing can dao + easymock mock/stub dao, you're not testing dao instead collaborator acting on dao (typically kind of controller if we're speaking mvc). to integration test of dao/storedprocedures recommend dbunit : put testdata database (if you're using junit in @before method) call dao method under test if method returned result, compare expected data in (1) if method performed inserts/updates, call "read method" , compare result (1) in case dao provides crud business entity can test each operation of dao: testload - load db , compare (1) testinsert - insert new entity db reload , compare testupdate - modify existing entity, save db , reload/compar...

evented io - How does the Node.js event loop work? -

after playing node.js , reading async i/o & evented programming a lot i'm left question marks. consider following (pseudo) code: var http = require('http'); function onrequest(request, response) { // non-blocking db query query('select name users key=req.params['key']', function (err, results, fields) { if (err) { throw err; } username = results[0]; }); // non-blocking db query query('select name events key=req.params['key']', function (err, results, fields) { if (err) { throw err; } event_name = results[0]; }); var body = renderview(username, event_name, template); res.writehead(200, {'content-type': 'text/plain'}); res.write(body); res.end(); }; http.createserver(onrequest).listen(8888); // request a: http://127.0.0.1:1337/?key=a // request b: http://127.0.0.1:1337/?key=b (i think) understand ba...

How to prevent incoming messages by reaching the native inbox in android? -

i developing app holds messages in it's own inbox rather native inbox. this can achieved if incoming messages prevented reaching native inbox. there attribute android:priority in <intent-filter> , message can first received current receiver others. but not know how properly, know? i assume mean sms messages? best, , afaik, receive message via registering proper broadcastreceiver object, copying message database, marking read in sms contentprovider , deleting sms contentprovider. check out this article on how receive sms messages , check out this post on how use sms content provider. edit stand corrected, there method i've had limited success with. in broadcastreceiver can call abortbroadcast() method cancel broadcast. important thing here register receiver intent filter has higher priority (say, 100) receives sms before else does.

magento getting product type from product sku -

how can product type(simplee,configurable/grouped ...) using product sku or id, have loaded product collection , trying prict type by $_product->gettypeid() but not printing product type. please me thanks i think $_product->gettypeid() should work. if doesn't try $_product->getresource()->gettypeid()

python - How can an interpretive language avoid using Global Interpreter lock (GIL)? -

cpython uses global interpreter lock . linux has removed traces of big kernel lock . alternative these locks? how can system make full use of multi-core or multi-processor system without grinding halt? a gil wouldn't necessary if python used more advanced garbage collector ibm's recycler instated of primitive reference counting method. unladen swallow doing improve performance of python. more prommising answer stackless python , uses own micro-thread implementation instead of relying on operating system traditional cpython.

conditional - How do I create a "just for me" install for an admin user? -

when run install script admin user, puts start menu entries in "all users" profile. want start menu entries placed in current user's profile if admin user , choose install "just me". i can selecting 1 of 2 values #define, can't figure out how create constant conditionally included. have [code] section routine returns true if "just me" install has been chosen. here's scenario: #define startmenulocation = "{somegroup}" ; check justformeinstall #define startmenulocation = "{anothergroup}" ; check allusersinstall ... [icons] name: "{#startmenulocation}\{#myappname}" ; filename: "{app}\{#exename}" ; parameters: "{#commandargs}" ; comment: "starts {#myappname} {#myappversion}" ... [code] function justmeinstall : boolean ; begin result := (installationtype = itjustme) ; end ; function allusersinstall: boolean ; begin result := (installationtype = itallusers) ; end ; wh...

is php or javascript more secure when populating dropdown boxes -

which better security standpoint when populating html select box? option a: php <?php echo "<select name=\"empname\" id=\"empname\" class=\"text\" style=\"width:10em;\">\r\n";?> <?php include 'phpscripts/getemployeenamesdb.php'?> <?php echo "</select>\r\n";?> getemployeenamesdb.php $dropdown = ""; $tbl_name="employee"; // table name $result = mysql_query("select concat_ws(' ', firstname, lastname) 'wholename', empid $tbl_name order lastname") or die("cannot select result db.php"); while($row = mysql_fetch_assoc($result)) { $empid = $row["empid"]; $name = $row["wholename"]; $dropdown .= "<option value=\"$empid\">$name</option>\r\n"; } echo $dropdown; option b: javascript same information except use ajax call pop...

R! remove element from list which start from specific letters -

i create list of files: folder_gldas=dir(foldery[numeryfolderow],pattern="_obc.asc",recursive=f,full.names=t) unfortunately there 1 additional object remove (file name begin "nowy" - nowyevirainf_obc.asc ). how can find index of element on list remove typing: folder_gldas<=folder_gldas[-to_remove] ?? filter using regular expression. folder_gldas <- folder_gldas[!grepl("^nowy", folder_gldas)] (you can swap grepl str_detect in stringr .)

time - Waiting for specific date. Calendar Java Code Optimization -

i want perform task using java at specific, given hour . code works, doesn't good. i'm comparing 2 strings. tried compare dates using gettimeinmills() numbers aren't same. here's code: import java.util.calendar; class voter { calendar current,deadline; boolean keepgoing = true; public static void main(string[] args) { voter strzal = new voter(); strzal.shoot(); } public void shoot() { deadline = calendar.getinstance(); deadline.set(2011,6,21,11,20,00); while (keepgoing) { // wait 1 second try { thread.sleep(1000); system.out.print("."); } catch (interruptedexception ex) { ex.printstacktrace(); } current = calendar.getinstance(); if (deadline.gettime().tostring().equals(current.gettime().tostring())) { system.out.println("got it!"); keepgoing = false; } // end of if } // end of while } // end of shoot() method } i...

retrieve text value from an element with jQuery -

if have html element value in it: <span id="myspan">23</span> how can retrieve value (23) , use it? i've tried like: var num = $("#myspan").text(); does not seem work... able use number add other numbers it? you want parseint . should make sure selector returning dom elements expect to. var num = parseint($("#myspan").text(), 10);

How do i retrieve and display a timestamp from a mysql database using PHP? -

currently i'm using line of code echo date("f j y g:i:s", $row[date]); but gives me january 1 1970 2:33:31 i want normal because if don't date("f j y g:i:s", @ all, 2011-03-02 23:00:30 correct date, displayed in abnormal way typecast unix_timestamp inside query: select unix_timestamp(yourdatefield) yourtable since see responses other answer while ignored, let me elaborate: there 2 common date types. both numbers, represent duration since given date. one number of days (float) since 1900. 1 one day. fraction fraction of day. other number of seconds since 1970. can int (whole seconds) or float (including fractional seconds). if got first date, treat second format, arecounting days seconds. instead of 111 years since 1900, you're counting 111 seconds since 1970. explains why date. therefore, use unix_timestamp function, convert first float notation timestamp in seconds. needed because type php uses.

php - How to post to a Facebook feed with no image using the graph API? -

does know how make facebook not set default image if dont specify 'picture' argument? i have tried: blank = image auto set website link 0 = out fail no message null = fail error message removing 'picture' altogether array = image auto set website link i ran problem well, , found rather useless post. figured out, , thought i'd answer it's month old. i got around (as suggested in comment on this post ) specifying non-existent url image. used http://www.noimage.faketld mine, since that's pretty assuredly never going resolve anything. produces nice gray line (as if being quoted), don't think can removed, looks decent enough imo.

c# - Implicit conversion to System.Double with a nullable struct via compiler generated locals: why is this failing? -

given following, why invalidcastexception thrown? can't see why should outside of bug (this in x86; x64 crashes 0xc0000005 in clrjit.dll). class program { static void main(string[] args) { mydouble? = new mydouble(1.0); boolean compare = == 0.0; } struct mydouble { double? _value; public mydouble(double value) { _value = value; } public static implicit operator double(mydouble value) { if (value._value.hasvalue) { return value._value.value; } throw new invalidcastexception("mydouble value cannot convert system.double: no value present."); } } } here cil generated main() : .method private hidebysig static void main(string[] args) cil managed { .entrypoint .maxstack 3 .locals init ( [0] valuetype [mscorlib]system.nullable`1<valuetype program/mydouble> my, [1...

imagemagick - Extraction of a part from an image -

i want extract small rectangles image , want convert/roll small rectanges cylinders. no animation required. want have cylinders images. i using perlmagick api imagemagick . any help/suggestions shall appreciated. assuming know x,y coordinates , geometry of rectangles you're trying extract; use image::magick; ... $image = image::magick->new(); $x = $image->read($filename); die "$x" if "$x"; # 100x100 size of cropped image, +40+40 giving x , y # offsets (i.e. upper-left coordinate of cropped image) $image->crop(geometry=>"100x100+40+40"); you'll have more specific cylinders, if it's think check fred's cylinderize script . examples given imagemagick command-line arguments there's bit of work convert perl equivalent (or call them using perl's exec() function).

javascript - elRTE error 0x80004005 in Firefox -

error: uncaught exception: [exception... "component returned failure code: 0x80004005 (ns_error_failure) [nsidomnshtmldocument.execcommand]" nsresult: "0x80004005 (ns_error_failure)" location: "js frame :: http://localhost/mypage/admin/elrte/js/elrte.min.js :: <top_level> :: line 34" data: no] why getting error in firefox, elrte plugin? didn't try in other version of firefox. in firefox 5 i'm getting error? display:none in style parent div occurs problem, explain want in here, http://elrte.org/redmine/boards/4/topics/3279

sql - Deleting rows from parent and child tables -

assume 2 tables in oracle 10g tablea (parent) --> tableb (child) every row in tablea has several child rows related in tableb. i want delete specific rows in tablea means have delete related rows in tableb first. this deletes child entries delete tableb last_update_dtm = sysdate-30; to delete parent rows rows deleted in child table this delete tablea not exists (select 1 tableb tablea.key=tableb.key); the above will delete rows in child table (last_update_dtm = sysdate-30) false. tablea not have last_update_dtm column there no way of knowing rows delete without entries in child table. i save keys in child table prior deleting seems expensive approach. correct way of deleting rows in both tables? edit to explain better trying achieve, following query have done trying if there no constraint between 2 table. delete tablea exists ( select 1 tableb tablea.key=tableb.key , tableb.last_update_dtm=sysdate-30) delete tableb last_update_dtm=systdate-30 t...

How can I check Rails record caching in unit tests? -

i'm trying make unit test ensure operations / not query database. there way can watch queries, or counter can check @ worst? if intent discern whether or not rails (activerecord) caches queries, don't have write unit test - already exist , part of rails itself. edit: in case, see if adapt 1 of strategies rails team uses test activerecord itself. check following test link above: def test_middleware_caches mw = activerecord::querycache.new lambda { |env| task.find 1 task.find 1 assert_equal 1, activerecord::base.connection.query_cache.length } mw.call({}) end you may able following: def check_number_of_queries mw = activerecord::querycache.new lambda { |env| # assuming object set perform operations myobject.first.do_something_and_perform_side_operations puts activerecord::base.connection.query_cache.length.to_s } end i haven't tried such thing, might worth investigating further. if above return number of cached qu...

javascript - Mute YouTube sound in Delphi TWebBrowser -

i'm coding small video previewing tool in delphi 2010, want mute videos programmatically, because said, it's previews. i've tried several versions of code, results in script error, , in end it's unable it. webbrowser1.controlinterface.document.queryinterface(ihtmldocument2, doc); doc.parentwindow.execscript( 'document.getelementbyid("movie_player").mute()', 'javascript' ); also tried wait little longer control complete browsing, still nothing. try call code in twebbrowser's ondocumentcomplete event. event fired when document inside loaded, object, if it's expected there, downloaded , present. without showing of javascript code can't tell more. but differently. implement code this one directly navigated web page. can mute sound in onyoutubeplayerready event handler means when youtube player loaded. it's better call function later on because may produce short sound burst because of delay between twebbrowser...

How do I declare a constructor for an 'object' class type in Scala? I.e., a one time operation for the singleton -

i know objects treated pretty singletons in scala. however, have been unable find elegant way specify default behavior on initial instantiation. can accomplish putting code body of object declaration seems overly hacky. using apply doesn't work because can called multiple times , doesn't make sense use case. any ideas on how this? classes , objects both run code in body upon instantiation, design. why "hacky"? it's how language supposed work. if braces, can use them (and they'll keep local variables being preserved , world-viewable). object initialized { // initalization block { val somestrings = list("a","be","sea") somestrings.filter(_.contains('e')).foreach(s => println("contains e: " + s)) } def dosomething { println("i initialized before saw this.") } } scala> initialized.dosomething contains e: contains e: sea initialized before saw this. scala> in...

c# - Dynamic binding between control in WP7 XAML -

i trying draw simple line in wp7 xaml such 1 below. static coordinate values works fine. <line stroke="white" x1="1" y1="1" x2="200" y2="1" /> what need bind coordinate values relative other controls on same canvas based on matching property value such id or name . once correct control bound, need left and/or top canvas locations. using vague pseudocode, here able do... <line stroke="white" x1="{binding canvas.left, source={binding <a_control_where_a_property_equals_some_value>}}" y1="1" x2="200" y2="1" /> i've tried number of binding scenarios no success. complexity windows phone 7 (wp7) binding , not full blown xaml. note: controls added @ runtime not statically defined. any suggestions??? the best can hope use elementname . other that, you'd need expose common property somewhere both controls bound to. p...

java - Confusing method bindings -

the output of simple program this base . public class mainapp{ private void func(){ system.out.println("this base"); } public static void main(string[] args){ mainapp newobj = new derived(); newobj.func(); } } class derived extends mainapp{ public void func(){ system.out.println("this derived"); } } my question when using line mainapp newobj = new derived(); not creating object of derived class using reference of base class mainapp . so, when using object call it's method why don't method derived class? why method base class. using line, mainapp newobj = new derived(); , working reference of mainapp or working object of derived class . 1 correct? the reason you're getting base class method base class version of func declared private , , java not allow private methods overridden subclasses. means if extend base class , pure coincidence decide name private member function sam...

apache - How to rewrite 301 the old ugly urls to the new beautified working urls? -

a little problem that's itchying me last months. first news: of massiv community able rewrite ugly urls nice ones: e.g. website.com/page.ast?ln=nl website.com/nl/page but google shows ugly urls in search: website.com/nl/page.ast?ln=fa my site page's code have canonical settings: <link rel="canonical" href="http://website.com/nl/page"> <meta name="original-source" content="http://website.com/nl/page"/> however results apparently still indexed under wrong, ugly urls! q1. why google ignore canonical more beautiful link? perhaps best mechanical way: redirect website.com/nl/webpage.ext?ln=yy website.com/nl/webpage removing unnessecary part doesnt .xxx?ln=yyyy (where xxx 2 or 3 char extension , yyy language (can nl , be , fr zh-cn etc) example of ugly old files nice beautified urls /en/somepage.ast?ln=fr /en/somepage /fr/home.php?ln=zh-cn /fr/home /xx/zzzzzz.ext?ln=yyyy /x...

java - unchecked cast warning - how to avoid this? -

this question has answer here: how address unchecked cast warnings? 24 answers i'm getting " type safety: unchecked cast object arraylist " warning on line readobject() , in code snippet: // read event list theeventarraylist = new arraylist<event>(); string filename = "eventdata.dat"; fileinputstream fis; try { fis = openfileinput(filename); objectinputstream ois = new objectinputstream(fis); theeventarraylist = (arraylist<event>) ois.readobject(); fis.close(); } event simple class comprised of strings, calendars, booleans, , ints. arraylist written using objectoutputstream in mirror image operation above. application code used in executed many times day on month no failures, compiler warning bothers me , don't want suppress if can "checked" properly. suppress it. other alternati...

iphone - Have a question about saving to plist -

i have .plist filled data ships app. it's array of dictionaries other arrays/dictionaries in it. the values take array , use in app may name, "computer". i'm adding feature let user create own item, instead of choosing loading array. should save item same .plist, or create separate .plist each user? then, how pull info both standard .plist , user created .plist , load them 1 tableview? if you're writing ios, can't save same plist file because can't write application bundle. 1 thing save copy of plist application's documents folder, , modify same plist, way data unified in single file. or can load original plist application bundle, make mutable copy of nsarray , load additional plist documents folder user's objects, , append them nsmutablearray calling addobjectsfromarray . or can keep them in separate nsarray display them in table view 1 returning [originaldataarray count] + [userdataarray count] tableview:numberofrowsin...

java - doGet called twice jetty server -

i using embedded jetty server within java application. doget() method being called twice. being called result of (method.equals(method_get)) condition within service method of httpservlet class. i tried request using both chrome , explorer had same result. can see reason doget being called twice.. public class helloservlet extends httpservlet{ private string greeting="hello world"; public helloservlet(){} public helloservlet(string greeting) { this.greeting=greeting; system.out.println("started server" + greeting); } protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { response.setcontenttype("text/html"); response.setstatus(httpservletresponse.sc_ok); response.getwriter().println("<h1>"+greeting+"</h1>"); response.getwriter().println("session=" + request.getsession(tr...

Django queryset to match all related objects -

let's have foreignkey coconut swallow (ie, swallow has carried many coconuts, each coconut has been carried 1 swallow). let's have foreignkey husk_segment coconut. now, have list of husk_segments , want find out if of these have been carried gripped particular swallow. i can have swallow.objects.filter(coconuts_carried__husk_sements__in = husk_segment_list) show swallow has gripped @ least 1 husk segment in list. now, how can show every husk segment swallow has ever carried in list? i can have swallow.objects.filter(coconuts_carried__husk_sements__in = husk_segment_list) show swallow has gripped @ least 1 husk segment in list. no, wrong, gives list of swallows have carried @ least 1 husk segment *husk_segment_list*. if i've understood right, talking checking specific swallow. so, description guess models this: class swallow(models.model): name = models.charfield(max_length=100) class coconut(models.model): swallow = models.forei...

c# - decrypt an encrypted value? -

i have old paradox database (i can convert access 2007) contains more 200,000 records. database has 2 columns: first 1 named "word" , second 1 named "mean". dictionary database , client wants convert old database asp.net , sql. however, don't know key or method used encrypt or encode "mean" column in unicode format. software has been written in delphi 7 , don't have source code. client knows credentials logging in database. problem decoding mean column. what have compiled windows application , paradox database. software can decode "mean" column each "word" method and/or key in own compiled code(.exe) or 1 of files in directory. for example, know in following row "zymurgy" means "Ł…ŲØŲ­Ų« Ų¹Ł…Ł„ ŲŖŲ®Ł…ŪŒŲ± ŲÆŲ± Ų“ŪŒŁ…ŪŒ Ų¹Ł„Ł…ŪŒ, ŲŖŲ®Ł…ŪŒŲ± Ų“Ł†Ų§Ų³ŪŒ" since application translates that. here record looks when open database in access: word mean zymurgy 5obnggukpddad7l2lnvd9lnf1mdd2zdbqrxngscuirk5h91svmy0kprcue/+ql9ormp99m...

C# - DatagridView and ContextMenuStrip -

i have datagridview 5 columns , context menu strip have items , sub items. when right click on last column want open context menu. i tried code, it's open context menu strip without sub items. datagrid.columns[datagrid.columns.count].headercell.contextmenustrip = contextmenustrip1; it looks want open contextmenustrip if user right clicks header of datagridview's last column. use datagridview mousedown event , in event check these conditions , if they're met call show method of contextmenustrip. like this: private void datagridview1_mousedown(object sender, mouseeventargs e) { if (e.button == mousebuttons.right) { var ht = datagridview1.hittest(e.x, e.y); // see if user right-clicked on header of last column. if (( ht.columnindex == datagridview1.columns.count - 1) && (ht.type == datagridviewhittesttype.columnheader)) { // positions menu @ mouse's location. contextmenustr...

Proper way to create packets along with sending and receiving them in socket programming using C -

i had written small client-server code in sending integers , characters client server. know basics of socket programming in c steps follow , all. want create packet , send server. thought create structure struct packet { int srcid; long int data; ..... ..... ..... }; struct packet * pkt; before doing send(), thought write values inside packet using pkt-> srcid = 01 pkt-> data = 1 2 3 4 i need know whether on right path, , if yes can send using send(sockfd, &packet, sizeof(packet), 0) for receiving recv(newsockfd, &packet, sizeof(packet), 0) i have started network programming, not sure whether on right path or not. of great if can guide me question in form (theoretical,examples etc). in advance. the pointer pkt not defined in application. have 2 options: 1) declare pkt normal variable struct packet pkt; pkt.srcid = 01; .... send(sockfd, &pkt, sizeof(struct packet), 0); 2) s...

ruby - Unable to update gems on production server -

can not update gems on production server. i've tried bundle install --deployment , bundle install --without development test but keep getting: you trying install in deployment mode after changing gemfile. run `bundle install` elsewhere , add updated gemfile.lock version control. if development machine, remove gemfile freeze running `bundle install --no-deployment edit i don't know if correct, needed quick fix. ran bundle install --no-deployment bundle update ran bundle install --deployment again the instructions bit confusing. it's saying you've modified gemfile on development machine , pushed changes rather running bundle install before committing changes. by running bundle install update gemfile.lock file. should pushed server it's more important gemfile . consider gemfile plans gemfile.lock file. always remember to: run bundle install if change gemfile , make sure. if it's slow, pass --local through forces use loca...

functional programming - Haskell function definition syntax -

i'm doing lists concatenation in following ways (an example, using ghc): myconcat :: [[a]] -> [a] myconcat xs = foldr (++) [] xs myconcat = foldr (++) [] can explain me please why , how above definitions work , 1 not: myconcat xs = foldr (++) [] is last line of code intentionally not allowed (for reason constructs might become confusing, useless, etc) or deeper, maybe related currying... i hope can shed light on this, puzzles me :/ later edit: besides explanations given below, i've found source of information on matter section "partial function application , currying" chap. 4 "functional programming" book "real world haskell" . book available freely online. lets review different versions: myconcat xs = foldr (++) [] xs this usual way, providing argument, consumed foldr . type [[a]] -> [a] , because have argument of type [[a]] on left side, yields [a] when fed right side. myconcat = foldr (++) [] here fol...

iphone - MPMoviePlayerController Fullscreen mode doesn't actually display over the entire screen -

i've implemented video play functionality within app, , working perfectly, except 1 issue. whenever fullscreen toggle button tapped, or if double-tap screen, of course meant toggle video being played in it's natural wide screen state (black seen above , below video) zoomed state, video takes entire screen of 480x320. me, video adjusts in size, doesn't come close taking entire screen. works correctly in every app can think of plays videos, such fandango, youtube, etc. in zoomed mode, of course you're losing part of picture, because it's off screen, since way render 2.40:1 image on full screen while still maintaining aspect ratio zoom. again, every other app can think of works way, it's not working me. so, have tried can think of full screen zoomed feature work, no luck. any ideas? after testing, appears due format/encoding of video itself. don't know specficis, however. know depending on video being played, feature may or may not work...

c# - Could not find resource assembly error when i try to pass data from terminal to webservice -

i try pass data (string) terminal (windows mobile) webservice i have connection , got error: could not find resource assembly thanks in advance that means there's error in windows mobile application. searches right exception, can't find : http://blogs.msdn.com/b/netcfteam/archive/2004/08/06/210232.aspx

cocoa - Lion iCal like NSWindow -

i trying create nswindow 1 in lion ical ( http://www.lutrindigital.cc/wp-content/uploads/2011/04/lion_ical_preview-400x275.png ) mean custom titlebar. this application in mac app store, private api prohibited. do know how can achieve this? thanks , regards, check out this: http://parmanoir.com/custom_nsthemeframe

java - HtmlCleaner returns "???" when parsing non-english web site -

when try parse websites google or apple htmlcleaner goes fine. when try parse chinese web site text looks "???". what causes problem , how solve it? character encoding issue.you need set encoding based on contents before doing on content.

optimization - mod_rewrite - which hosting account to redirect to? -

let's have 2 domains www.mydomain.com , www.mydomain.co.uk our main site on www.mydomain.com we have separate hosting account, on same server, www.mydomain.co.uk - have .htaccess file redirects mydomain.com [code] rewriteengine on rewritecond %{http_host} ^([^.:]+\.)*mydomain\.co.uk\.?(:[0-9]*)?$ [nc] rewriterule ^(.*)$ http://www.mydomain.com/?referrer=mydomain.co.uk [r=301,l] [/code] we have set blog, on www.mydomain.com/blog/ problem: want subdomain: http://blog.mydomain.co.uk forward http://www.mydomain.com/blog/ "blog.mydomain.co.uk" more popular (as exists on google blog). solution: can either direct "blog.mydomain.co.uk" subdomain "mydomain.co.uk", , set .htaccess on .co.uk hosting account redirect (301) mydomain.com/blog/ or we can direct "blog.mydomain.co.uk" subdomain "mydomain.com" , set .htaccess on sire redirect above. just wondering choose? there difference between above, in terms of search engin...

python - Cherrypy vs. Apache/mod_wsgi -

what pros/cons? -stability -developer friendliness -system resources -scalability in experience best performance running wsgi app wsgi server fapws or gevent (some benchmarks here: http://nichol.as/benchmark-of-python-web-servers ). can configure nginx proxy_pass .

Facebook Connect vs localhost -

Image
we trying build app facebook connect on local server. when give url follows, still not work on local system: here errors get: api error code: 191 api error description: specified url not owned application error message: redirect_uri not owned application. you need set same url canvas url under core settings of application settings

linux - SETENV: Bad : modifier in $ ($) -

i using tcsh terminal in linux. in other terminal used set path license file follows: export path="$path:$model_tech" tcsh shell not recognise command tried following: setenv path "$path:$model_tech" set path "$path:$model_tech" setenv path=("$path:$model_tech") but following error: bad : modifier in $ ($). what great if me here out quickly, tried quite few combinations nothing works. drop = setenv license_file "/usr/local/softwarex/license.dat" from man page tcsh: setenv [name [value]] without arguments, prints names , values of environā€ ment variables. given name, sets environment variable name value or, without value, null string.

eclipse - Testing tool that supports testng -

which eclipse version testing testng ? i've used eclipse plugin 3.3, 3.4, 3.5 , 3.6. i've been using update site http://beust.com/eclipse recommended in documentation .

xsd - Expected or Recommended usage of the Maven JAXB 2.x Plugin -

i'm new xml schema , jaxb , wondering best or expected approach using maven jaxb plugin ( http://static.highsource.org/mjiip/maven-jaxb2-plugin/generate-mojo.html) is. i have simple xml document format i've defined schema. i'm interested in reading compliant xml file java, i'll want add properties pojos won't in xml, used @ runtime. by default plugin places generated code ${project.build.directory}/generated-sources/xjc. think want copy generated code /src/main/java/whatever , add to/modify code add properties. when change schema, i'd merge changes form newly generated pojos own ones. the alternative tell plugin place generated source directly /src/main/java , perhaps subclass pojos add own properties, i'm not sure whether marshaling/unmarshaling can still made use extended classes. anyone have guidance on approach more normal or pitfalls of each are? in place i'd leave generated sources corresponding jar can built maven without furt...