Posts

Showing posts from January, 2013

ruby on rails - Activerecord mass assignment to virtual attribute -

i'm posting following datas: {"commit"=>"create", "conversation"=>{... , "watchers_ids"=>["2", "3", "4", "5", ...]}} to following action def create @conversation = @current_project.conversations.new(params[:conversation]) ... end and following class class conversation < rolerecord include watchable end with module module watchable def self.included(model) model.attr_accessible :watchers_ids end def watchers_ids=(ids) add_watchers( ids ) end def watchers_ids ... end ... end however, mass assignment don't work virtual attribute. idea? there's code that's missing there... if have has_and_belongs_to_many :watchers should able assign watcher_ids without having custom module stuff. then if can't attribute protected attr_protected or, more likely, attr_accessible call in model. can set manually: @conversati...

javascript - Is there a JQuery event to determine when an element's list of children has changed? -

i'm hoping find jquery event tell me when element collection has grown or shrunk after addition/removal of child element. you can count child elements use conditional statement check whether count changed. <div> <span></span> <span></span> <span></span> <span></span> <span></span> </div> alert($('div').children().length);

sql - database normalisation -

i'm building query , i'm building it, i'm realizing it'd easier write if of tables contained redundant fields; it'd save few joins. however, doing mean database model not totally normalized. i'm aiming performance; having denormalized database impede performance? i'm using sql server. thanks. i don't know implementation is, helps have redundant index references, not redundant fields per se. for example, have 3 tables: tbl_building, tbl_room, , tbl_equipment. (an equipment belongs room, belongs buildng) tbl_building has buildingid, tbl_room has roomid , reference buildingid. save join if tbl_equipment had reference both roomid , buildingid, though infer buildingid roomid. now, not if, example, have field buildingsize on tbl_building , copy buildingsize field tbl_room , tbl_equipment.

html - PHP: DOMDocument loadHTML returns an error when using HTML5 tags -

such <section> . there can this? i've run issue php's domdoc , xsl functions. have load document xml. thats way got <video> tag work. update: can try adding elements & entities <!doctype html5 > long $doc->resolveexternals = true .

How to compare user input with db password when using PHP's sha256 hash method? -

say set new users password this: $salt = random_string(40) // method spits out random // 40 alpha-numeric character string $password = hash('sha256', $_post['password'] . $salt); how compare users input hashed db password when wants log in? at login time, fetch password hash , salt stored in database @ registration time (using account name, or email-address) hash provided password same method , same salt compare hash hash stored. if same, password matches. the key here store salt.

javascript - How to dynamically remove a stylesheet from the current page -

is there way dynamically remove current stylesheet page? for example, if page contains: <link rel="stylesheet" type="text/css" href="http://..." /> ...is there way later disable javascript? points using jquery. well, assuming can target jquery should simple calling remove() on element: $('link[rel=stylesheet]').remove(); that remove all external stylesheets on page. if know part of url can remove 1 you're looking for: $('link[rel=stylesheet][href~="foo.com"]').remove(); and in javascript this example of remove query selector , foreach array array.prototype.foreach.call(document.queryselectorall('link[rel=stylesheet]'), function(element){ try{ element.parentnode.removechild(element); }catch(err){} }); //or similar var elements = document.queryselectorall('link[rel=stylesheet]'); for(var i=0;i<elements.length;i++){ elements[i].parentnode.remov...

How do I name variables dynamically in C#? -

is there way dynamically name variables? what need take list of variable names input file , create variables names. possible? something like: variable <dynamic name of variable here> = new variable(input); assume have variable class taken care of, , name of variable contain in string called strline . use dictionary<string, variable> . e.g. var vartable = new dictionary<string, variable>(); vartable[strline] = new variable(input);

c# - WPF DataGrid Validation Bug? -

this may intended functionality, sure seems bug me. i'm using out-of-the-box wpf datagrid, bound observablecollection , attempting use validation rules in order provide nice user feedback. needless there more issues can count, i'll stick immediate. here summary of problem: bind itemssource property observablecollection<t> populate collection edit item in grid in way cause validation error programatically remove item observablecollection<t> when these steps performed, gridview recognizes item has been removed collection, , removes row grid. however, the grid stuck in invalid state , no further actions can performed through ui on grid! again, seems quite major bug me being able programmatically remove items collection kind of big deal. has run this? suggestions how around it? it worth noting have created separate solution isolate problem, answers questions might have: does object implement inotifypropertychanged ? yes is custom collection...

java - Log into twitter? -

ok, trying boolean if have logged in or not. using twitter4j library , gave me following 3 things at. http://twitter4j.org/en/code-examples.html https://github.com/yusuke/sign-in-with-twitter/blob/master/src/main/java/twitter4j/examples/signin/signinservlet.java https://github.com/yusuke/sign-in-with-twitter/blob/master/src/main/java/twitter4j/examples/signin/callbackservlet.java i have no idea how log in , if logged in successfully. thanks, , have no code btw... did copy code , try different things. ps. on separate note how learn how use elses library? twitter uses oauth. there no concept of having logged in external app. there instead concept of app being authorized communicate account on twitter. on how learn use else's library... that's general question... reading documentation start, irc channel relevant language (or library if has own irc channel). i've found people on irc channels helpful when have specific code problem trying sol...

wrap and center text in gd and php -

i have line of text need wrap , center in gd image. using ttf font well. can give me assistance please? i have managed text wrap doing following, need center: function wrap($fontsize, $angle, $fontface, $string, $width){ $ret = ""; $arr = explode(' ', $string); foreach ( $arr $word ){ $teststring = $ret.' '.$word; $testbox = imagettfbbox($fontsize, $angle, $fontface, $teststring); if ( $testbox[2] > $width ){ $ret.=($ret==""?"":"\n").$word; } else { $ret.=($ret==""?"":' ').$word; } } return $ret; } to center both horizontally , vertically: half height imagettfbbox of whole text (with new lines) , substract half height of image ( $start_x ). now split text new lines, create ttfbox every line , it's height ( $h ) , half width ( $w ). draw line starting half image width + $w , $start_x , add ...

java - Android onTouchListener, easier way to implement -

well, have 16 buttons. want find easier way add them ontouch listener, i'm new android/java i'm not sure work. here's code right now. public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main) . button btn_main1 = (button) findviewbyid(r.id.cmd_main1); button btn_main2 = (button) findviewbyid(r.id.cmd_main2); button btn_main3 = (button) findviewbyid(r.id.cmd_main3); button btn_main4 = (button) findviewbyid(r.id.cmd_main4); button btn_main5 = (button) findviewbyid(r.id.cmd_main5); button btn_main6 = (button) findviewbyid(r.id.cmd_main6); button btn_main7 = (button) findviewbyid(r.id.cmd_main7); button btn_main8 = (button) findviewbyid(r.id.cmd_main8); button btn_main9 = (button) findviewbyid(r.id.cmd_main9); button btn_main10 = (button) findviewbyid(r.id.cmd_main10); button btn_main11 = (button) findviewbyid(r.id.cmd_main11); button btn_main12 = (button...

python - How do I match vowels? -

i having trouble small component of bigger program in works on. need have user input word , need print index of first vowel. word= raw_input("enter word: ") vowel= "aeiouaeiou" index in word: if index == vowel: print index however, isn't working. what's wrong? try: word = raw_input("enter word: ") vowels = "aeiouaeiou" index,c in enumerate(word): if c in vowels: print index break for .. in iterate on actual characters in string, not indexes. enumerate return indexes characters , make referring both easier.

java - Is there any way to use firefox's cookies with the Apache HttpClient class? -

i don't know ton cookies, if they'd compatible, etc, etc. if possible, can show example of how? i'm not quite sure mean "use firefox cookies". here's snipet of code wrote grab data goolge reader api, passing cookie along apache httpclient request. it needs send cookie google gives upon connection ("sid") along request. looking for? // obtain sid getmethod getlogin = new getmethod("https://www.google.com/accounts/clientlogin?service=reader&email="+ login+"&passwd="+password); client.executemethod(getlogin); string logintext = getlogin.getresponsebodyasstring(); // value of sid logintext.substring (4,firstlinelength) bufferedreader reader = new bufferedreader(new stringreader(logintext)); string sid = logintext.substring(4, reader.readline().length() ); getmethod grabdata = new getmethod("http://www.google.com/reader/atom/user/-/state/com.google/broadcast"); gra...

how to integrate or call or interface with a 3rd party widget within a GWT app? -

i making app in gwt. dashboard , have out of widgets. now when ship out, there use case customer might want create own gwt widget , use in dashboard app. as understand it, not able since cannot ship our source code needed compile whole app again once tag of widget/module gets gwt.xml file of app. i cannot use other gwt make dashboard. , widget flash heapmap, jquery widget/plugin, gwt module, jsp page renders visualization end. so far thoughts have been provide widget in app wrapper in form of iframe , call main page (they provide url), , have api let app , widget talk. but know if there other / better approaches? this problem solved google's opensocial widgets. there few opensource implementations: http://shindig.apache.org/ one. can integrating in app. added bonus can display widgets other applications (such atlassian jira ) serve opensocial widgets.

jquery - parse JSON null values to get &nbsp;? -

i'm parsing json object (from yql) includes null values, this: { "color": "red", "size": null, "brand": "nike", }, { "color": null, "size": "xxl", "brand": "reebok", }, { "color": "blue", "size": "small", "brand": null, }, i'm using jquery generate markup it: function (data) { $("#content").html('<table></table>'); $.each(data.query.results.row, function (i, item) { $("table") .append('<tr><td class="color">' + item.color + '</td><td class="size">' + item.size + '</td><td class="brand">' + item.brand + '</td></tr>'); }); what can (in jquery ideally) change null's blank space, or...

android - The connection to adb is down, and a severe error has occurred -

possible duplicate: the connection adb down, , severe error has occured i trying develop application android in latest release of eclipse. when try build , run, following comes up: [2011-02-17 17:08:03 - <programname>] connection adb down, , severe error has occured. [2011-02-17 17:08:03 - <programname>] must restart adb , eclipse. [2011-02-17 17:08:03 - <programname>] please ensure adb correctly located @ 'c:\<sdk-directory>s\platform-tools\adb.exe' , can executed. now, have updated adt plugin, have latest version of android sdk; adb.exe is, in fact, in platform-tools directory , can executed. i've tried found on google: i tried adb kill-server , adb start-server i tried run without emulator started i have given directory in path (i tried platform-tools in path , tried having both platform-tools , tools in path). notes: running windows 7. also, have tested apps in eclipse. error new me since upgrading sdk. i got...

Is there a Perl module or technique that makes using long namespaces easier? -

some namespaces long , annoying. lets downloaded hypothetical package called foofoo-barbar-bazbaz.tar.gz, , has following modules: foofoo::barbar::bazbaz::bill foofoo::barbar::bazbaz::bob foofoo::barbar::bazbaz::ben foofoo::barbar::bazbaz::bozo foofoo::barbar::bazbaz::brown foofoo::barbar::bazbaz::berkly foofoo::barbar::bazbaz::berkly::first foofoo::barbar::bazbaz::berkly::second is there module or technique can use that's similar c++ 'using' statement, i.e., there way can do using foofoo::barbar::bazbaz; which let me do my $obj = brown->new(); ok $obj->isa('foofoo::barbar::bazbaz::brown') ; # true # or... ok $obj->isa('brown'); # true the aliased pragma this: use aliased 'foofoo::barbar::bazbaz::bill'; $bill = bill->new; aliased syntactic sugar use constant bill => 'foofoo::barbar::bazbaz::bill'; # or sub bill () {'foofoo::barbar::bazbaz::bill'} the downside of normal usage of pack...

noise reduction - SINGULAR VALUE Decomposition simple code in c -

i looking singular value decomposition(svd) code in c, please me? i found many sources cannot run them, looking version svd code provide 3 matrix of s, v , u me. you can use numerical recipies code svdcmp.c reference . in case found more accurate opencv one, both work fine.

c# - Environment.GetFolderPath returns null in WMI provider -

i have decoupled wmi provider (windows service) configured file lives in c:\programdata\companyname folder. when service loads uses environment.getfolderpath(enviornment.specialfolder.commonapplicationdata) method grab c:\programdata portion of path. while service running attempt write same file, through wmi call service, using same method call time fails; returning null. is there fact i'm running in context of wmi causes happen? i have been having same problems, perhaps can offer solution. different usage attempting special folders on web server write temporary files indeed having issues user runs (runs under defualtapppool domain group rather user even) had blanks returned on local win 7 machine attempts get environment.getfolderpath(environment.specialfolder.applicationdata); however did manage use appdomain.currentdomain.getdata method wanted, has several different options find different folders in file structure instead of being user based works b...

java me - Print exception stack trace in JavaME, for the Samsung JET -

my research shows general question exceptionally popular. , in main there no 1 solution phones using cldc/midp framework. i have developed app works on phones have tested far (mostly nokia's) throws ioexception on samsung jet s8003. any ideas how can possibly obtain trace on specific phone? i can't answer platform, on years i've found best approach these kinds of problems implement kind of tracing facility in code can see code path led exception. see answers question ideas on how accomplish this: logging in j2me . the nice thing approach makes lot easier debug customer problems when run app on phone model you've never heard of, if there's easy way them enable tracelog , have sent automatically.

java - Fastest way to read a file line by line with 2 sets of Strings on each line? -

what fastest way can read line line each line containing 2 strings. example input file be: fastest, way to, read one, file line, line .... can large file there 2 sets of strings on each line need if there spaces between string e.g. "by line" currently using filereader = new filereader(file); bufferedreader br = new bufferedreader(a); string line; line = br.readline(); long b = system.currenttimemillis(); while(line != null){ is efficient enough or there more efficient way using standard java api (no outside libraries please) appreciated thanks! it depends mean when "efficient." point of view of performance ok. if asking code style , size, pesonally small correction: bufferedreader br = new bufferedreader(new filereader(file)); string line; while((line = br.readline()) != null) { // line. } for reading stdin java 6 offers yet way. use c...

coldfusion + xml get node according to date -

xml trickiness. i'm trying isolate node sports "match" in progress or next upcoming match. thisschedulexml: <data> <sport type="union"> <schedules> <competition id="48" name="sr" type="union" group=""> <match id="1684" round="week 1" previewarticleid="" matchreportarticleid="" status="upcoming" alternateid="1"> <matchdate startdatelocal="2011-02-18 19:35:00" dayname="fri" shortdate="18-feb">2011-02-18 19:35:00</matchdate> <venue id="30" timezoneid="nzdt" gmtminutes="780" venue="westpac stadium" location="wellington">westpac stadium, wellington</venue> <hometeam id="8" alternateid=...

php - How do I remove this numbers from text? -

нани1,Ñпални1 视频3,教程3, книги3,ÑÐºÐ°Ñ‡Ð°Ñ 5‚web2.0 above forieng form of foreign languages stored in mysql. want remove numbers above lines. 1 , 3 , 5 etc. , want keep web2.0 note:- there 300k lines. above sample. preg_replace('/(\w)\d+$/m', '$1', $tags); the above 1 option cases fails in above case... $str = 'нани1,Ñпални1 视频3,教程3, книги3,ÑÐºÐ°Ñ‡Ð°Ñ 5‚ '; $str = preg_replace('/\d+/', '', $str); var_dump($str); output string(122) "нани,Ñпални 视频,教程, книги,ÑÐºÐ°Ñ‡Ð°Ñ ‚ " codepad . update <?php $str = 'нани1,Ñпални1 视频3,教程3, книги3,ÑÐºÐ°Ñ‡Ð°Ñ 5‚web2.0 '; $str = preg_replace('/(?<!\w|\.)\d+/', '', $str); var_dump($str); output string(130) "нани,Ñпални 视频,教程, книги,ÑÐºÐ°Ñ‡Ð°Ñ ‚web2.0 " i not sure exactly exclusions, won't match number proceeded...

python - Numpy Lookup (Map, or Point) -

i have large numpy array: array([[32, 32, 99, 9, 45], # [99, 45, 9, 45, 32], [45, 45, 99, 99, 32], [ 9, 9, 32, 45, 99]]) and large-ish array of unique values in particular order: array([ 99, 32, 45, 9]) # b how can (no python dictionaries, no copies of a , no python loops) replace values in a become indicies of values in b ?: array([[1, 1, 0, 3, 2], [0, 2, 3, 2, 1], [2, 2, 0, 0, 1], [3, 3, 1, 2, 0]]) i feel reaaly dumb not being able off top of head, nor find in documentation. easy points! here go a = array([[32, 32, 99, 9, 45], # [99, 45, 9, 45, 32], [45, 45, 99, 99, 32], [ 9, 9, 32, 45, 99]]) b = array([ 99, 32, 45, 9]) ii = np.argsort(b) c = np.digitize(a.reshape(-1,),np.sort(b)) - 1 originally suggested: d = np.choose(c,ii).reshape(a.shape) but realized that had limitations when went larger arrays. instead, borrowing @unutbu's clever reply: d = np.argsort(b)[c].reshape(a.sh...

c# - Asynchronous webservice in Asp.net -

how can set asynchronous web service in asp.net? i want call webservice post data database, don't care if response failed or succeeded. i can use .net 2.0 or 3.5 , can in vb or c#. when create service reference in visual studio click "advanced..." button , check off "generate asynchronous operations". you'll have option make asynchronous calls against web service. here's sample of both synchronous , same asynchronous call public web service. // http://wsf.cdyne.com/weatherws/weather.asmx?wsdl using(var wf = new weatherforecasts.weathersoapclient()) { // example synchronous call wf.getcityforecastbyzip("20850"); // example asynchronous call wf.begingetcityforecastbyzip("20850", result => wf.endgetcityforecastbyzip(result), null); } it might tempting call beginxxx , not result since don't care it. you'll leak resources though. it's important every beginxxx call matched correspo...

Import other Django Apps models into View - should be basic -

i realise i'm doing basic wrong here, not sure is. i'm not getting errors, i'm not getting of model data displayed when load page. here's i'm trying do: apps: base, blog, resume i'm trying models blog , resume show in view of base. both blog , resume apps work fine on own. base/views.py from django.core.urlresolvers import reverse django.shortcuts import render_to_response testpro.blog.models import post testpro.resume.models import project def main(request): """main listing.""" posts = post.objects.all().order_by("-created") projects = project.objects.all().order_by("-created") return render_to_response("list.html", dict(posts=posts, projects=projects, user=request.user)) list.html template {% extends "bbase.html" %} {% block content %} <div class="main"> <h3>blog posts</h3> <!-- posts --> <ul...

sql - update one table with data from another -

table 1: id name desc ----------------------- 1 abc 2 b def 3 c adf table 2: id name desc ----------------------- 1 x 123 2 y 345 how run sql update query can update table 1 table 2's name , desc using same id? end result is table 1: id name desc ----------------------- 1 x 123 2 y 345 3 c adf how can done for: sql server mysql postgresql oracle for mysql: update table1 join table2 on table1.id = table2.id set table1.name = table2.name, table1.`desc` = table2.`desc` for sql server: update table1 set table1.name = table2.name, table1.[desc] = table2.[desc] table1 join table2 on table1.id = table2.id

PHP and dynamic magic constants -

i working on class in im trying pull way set __function__ magic constant in php dynamically. code far <?php class testfunction { var $method = __function__; public function __construct() { } public function testmethod() { return $this->method; } } its not working.. im not sure if possible... trying think outside box. the __function__ constant return name of executing function when use inside function. __method__ same method of class have use inside class method. in example if replaced __function__ __method__ wouldn't work. if you're after name of class try __class__

sql - database data structure using powers of two -

i'm designing data structure , wanted know if missing doing way. lets have column day of type int. 1 : monday 2 : tuesday 4 : wednesday 8 : thursday 16 : friday 32 : saturday 64 : sunday if wanted store monday , friday input 17 day column. if wanted store tuesday , wednesday enter 6 etc. is valid way of storing data. how query if wanted select record contained saturday , variation of days, or saturday not wednesday. possible? fast? what concept called? some people may tell code 'smell' because represents denormalisation, think valid use of bit-mask field: -- contains saturday , other combination of days select * table (daybitcolumn & 32) = 32 -- contains saturday , other combination of days, except wednesday select * table (daybitcolumn & 32) = 32 , (daybitcolumn & 4) = 0 edit: pointed out @andriy m, can written more succinctly as: select * table (daybitcolumn & 36) = 32 ['&' bitwise and]

android - Phone open 6th sms on installing application -

i developing android application named autosms.i wan when open application should automatically open 6th sms in inbox.can tell me.how should pursue thanks in advance tushar check out question info on how read smss contentprovider: android 1.5: reading sms messages

objective c - Storing NSMutableArray of UIViews in NSUserDefaults -

i have read several posts i'm not able fix error. if please help. here code use. have nsmutablearray called list. -(void) awakefromnib { prefs=[[nsuserdefaults standarduserdefaults]retain]; if ([prefs arrayforkey:@"list"]) { list=[[nsmutablearray alloc]initwitharray:[prefs objectforkey:@"list"]]; } else { list=[[nsmutablearray alloc]init]; } } -(void)savedata { nslog(@"saving data!"); [prefs setobject:list forkey:@"list"]; } - (void)dealloc { [self savedata]; [prefs synchronize]; [prefs release]; } you cannot store uiview instances in user defaults, objects can serialized in property list (see here ) also, @justin said, not retain or release defaults object.

c++ - Does std::sort implement Quicksort? -

possible duplicate: which type of sorting used in function sort()? does std::sort implement quicksort? there 2 algorithms traditionally used. std::sort use quicksort , or @ least variation on quicksort called introsort , "degenerates" heapsort when recursion goes deep. from standard: complexity: o(n log(n)) comparisons. std::stable_sort use mergesort , because of stability requirement. note mergesort requires space in order efficient. from standard: complexity: @ n log 2 (n) comparisons; if enough memory available, n log(n). i have yet see std::sort implementing timsort promising , has been adopted in python (crafted in fact), java , android (to date).

monodevelop - How to compile a F# project without buying Visual Studio -

i have found cool project written in f#: https://github.com/fholm/ironjs oss nice, need assembly. compile self, seems there no free ide open f# project (.fsproj). don't have visual studio , there no express version f#. i have found site http://tomasp.net/blog/fsharp-in-monodevelop.aspx seems cross-platform doesn't include windows. this monodevelop add-in doesn't work: http://functional-variations.net/addin/ have used f# on windows without visual studio? you can downlaod vs2010 shell here http://www.microsoft.com/downloads/details.aspx?familyid=8e5aa7b6-8436-43f0-b778-00c3bca733d3&displaylang=en then install f# compiler etc here http://www.microsoft.com/downloads/en/details.aspx?familyid=effc5bc4-c3df-4172-ad1c-bc62935861c5 . then you'll have full ide support f# intellisense, projects etc. doesn't cost penny , works charm! gj

Creating a procedure in mySql with parameters -

i trying make stored procedure using mysql. procedure validate username , password. i'm running mysql 5.0.32 should possible create procedures. heres code i've used. sql syntax error. go create procedure checkuser (in @brugernavn varchar(64)),in @password varchar(64)) begin select count(*) bruger bruger.brugernavn=@brugernavn , bruger.pass=@password; end; thank in advance i figured out now. here's correct answer create procedure checkuser ( brugernavn1 varchar(64), password varchar(64) ) begin select count(*) bruger bruger.brugernavn=brugernavn1 , bruger.pass=password; end; @ points global var in mysql. above syntax correct.

ios - Save image data to sqlite database in iphone -

i want save image data sqlite database can't ... - (void) savedata: (article*) article :(nsmutablearray*) rsslist { sqlite3_stmt *statement; if (sqlite3_open([self.databasepath utf8string], &articlesdb) == sqlite_ok) { nsstring* sqlformat = @"insert articles (guid, title, summary, mainlink, pubdate, author, imagelink, body, favorites, smallimage) values ('%@', '%@', '%@', '%@', '%@', '%@', '%@', '%@', '%@', ?)"; // correct summary. nsstring* summary = [nsstring stringwithstring:article.summary]; summary = [summary stringbyreplacingoccurrencesofstring:@"'" withstring:@"''"]; // correct title nsstring* title = [nsstring stringwithstring:article.title]; title = [title stringbyreplacingoccurrencesofstring:@"'" withstring:@"''"]; // c...

How can I react on Mouse events in a Java applet and then paint accordingly? -

my homework is write applet draw house shown on left in figure 14-32. when user clicks on door or windows, should close. figure on right shows house door , windows closed. i want java applet where, if user clicks on rectangle, 1 sudden created , drawn. here code far. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class test2 extends japplet { private final int currentx = 0; public void init() { addmouselistener(new mymouselistener()); } public void paint (final graphics g) { super.paint (g); g.drawrect(100, 100, 200, 200); } private class mymouselistener extends mouseadapter { currentx = e.getx(); } } take @ java tutorial | how write mouse listener . determine when , user clicks. once have these (x,y) coordinates can check if lie within window or door , if so, draw else. sample code: public void mouseclicked(mouseevent e) { int x = e.getx(); ...

from new import classobj in Python 3.1 -

how can change given python 2.x statement compiled on 3.1. the code line not works. from new import classobj the error "there no module new". in python 2.x new.classobj type of old-style types. there no old-style types in python 3.x. port code python 2.x python 3.x first need bring latest python 2.x standards, , in case means stop using old-style classes , use new-style classes. so answer instead of classobj use type , you'll need upgrade 2.x code use type first , @ porting python 3.x btw, see pep 3108 list of modules removed in python 3.x. in particular: new just rebinding of names 'types' module. can call type built-in types easily. docstring states module no longer useful of revision 27241 (2002-06-15).

xml - Using XS:date i want date in format YYYYMMDD -

using xsd want accept date of format yyyymmdd in xml field .. how can i saw in example work ?? xml schema defines datetime iso8601 exceptions , should stick this, otherwise serious interoperability issues. if want send/receive date using different format, use simpletype regular expression restriction , parse/format date in application code: <xs:simpletype name="customdate"> <xs:restriction base="xs:string"> <xs:pattern value="\d{8}"/> </xs:restriction> </xs:simpletype> if really want mess around built-in types (highly inadvisable), xml framework/library might have support that. instance in java/jaxb can apply custom transformers/formatters type, in client/server code still using date object (not 8-digit string ), marshalled/unmarshalled using custom routine.

alertbox in android -

alertdialog.builder alt_bld = new alertdialog.builder(this); when wrote error shawn that the constructor alertdialog.builder(new runnable(){}) undefined .. tell me m do... are trying run dialog runnable? cannot pass runnable context. should replace "this" youractivityclassname.this in order pass activity's context constructor. if construction within thread, guess it's kinda wrong, cause shound't perform ui operations different threads. should use handlers pass messages main activity.. may wrong though, cause don't see whole code

.net - Serialize Entity Framework object, save to file, read and DeSerialize -

the title should make clear i'm trying - entity framework object, serialize string, save string in file, load text file , reserialize object. hey presto! but of course doesn't work else wouldn't here. when try reserialise "the input stream not in valid binary format" error i'm missing somewhere. this how serialise , save data: string filepath = system.configuration.configurationmanager.appsettings["customerslitesavepath"]; string filename = system.configuration.configurationmanager.appsettings["customerslitefilename"]; if(file.exists(filepath + filename)) { file.delete(filepath + filename); } memorystream memorystream = new memorystream(); binaryformatter binaryformatter = new binaryformatter(); binaryformatter.serialize(memorystream, entityframeworkquery.first()); string str = system.convert.tobase64string(memorystream.toarray()); streamwriter file =...

asp.net - Access User Control DataGrid Controls from parent page -

here code- gridview gvcondition = (gridview)this.findcontrol("uccondition").findcontrol("gvcondition"); gvcondition.datasource = objconditionfieldcollection; gvcondition.databind(); but throwing exception object reference not set instance of object. how can access user control's gridview control parent page? i don't know trying access usercontrol's gridview, why don't expose public property in usercontrol returns gridview(f.e. conditionview )?

iphone - Re-using Android layouts -

on iphone context, when add view subview of view, happens our subview handled correctly, because in xib class handling actions. how can achieve on android? since don't have kind of relation between .xml layout , class uses it, how can achieve that? the main purpose is, example: while having 1 common header , 1 common footer entire application, want add different views "content view" between header , footer. you can use layout " include " functionality. allows create layout file header , 1 footer, , include these layouts activity's main layout. , if want include header + footer in multiple activities , these layouts have events want handle, create baseactivity handles these events, , have other activities extend baseactivity. example pseudocode: title.xml <linearlayout><imageview/><textview/></linearlayout> footer.xml <linearlayout><textview/><textview/></linearlayout> main.xml <r...

asp.net mvc 3 - Drawing a part of a page only after another part was "submitted" -

asp.net mvc noob here i writing quiz application user can select preferences (e.g. difficulty, number of question etc.), , once hit submit button - got new page questions. the preferences represented "preferences" object, , questions ienumerable of question. this worked well. now decide both parts should in same page - , don't know how accomplish that: should have new model class composition of these 2 parts? , - how make "questions" part appear after user completed filling preferences , clicked button? should use ajax? read little partial views , rendersection.. couldn't understand approach appropriate scenario. so how should draw 2 parts of page, second displayed after first submitted? thanks. how familiar ajax? if had guess think way want have ajax call linked action when user submits preferences. action can return partial view can have appear on page without reload via ajax.

c# - Asp.net Dynamic ashx Stylesheet not always working on postback -

help. have site when customers can add own style rules websites. whole process works perfectly, when page dynamic stylesheet posts back, of stylesheet rules load. initial page loads of styles, , postbacks loads fine well, on of postbacks (about 60%) styles randomly dropped. lifecycle issue? random, have nothing trace. there way load dynamically generated stylesheet , persist throughout session, dismiss it? thanks!!! answers here spot on, has got know whats going on. so if understand right css file there of rules being applied? sure there no other stylesheets after 1 user uploads conflicting/overriding users' sheet? have been looking in firebug @ see sheets loaded , styles being overridden getting styles from?

flex - difference between swfLoader and ModulLoader -

what difference between swfloader(load application) , moduleloader(load module)? better use? thanks the swfloader used load sub-applications while moduleloader used load modules, stated yourself. the difference modules have tight link application loaded in , cannot used standalone. subapplication on other hand separate application has no direct link application loaded in. depending on use cases, might consider 1 or other. there stuff available adobe here be sure check section " comparing loaded applications modules ".

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

i using bbpress installation without wordpress integration. the redirect of rewriteengine @ forum site works: rewriteengine on rewritecond %{http_host} ^forum.mysite.com$ rewriterule (.*)$ http://www.forum.mysite.com/$1 [r=301,l] the problem login pppress. bbpress login not recognize: http://www.forum.mysite/bb-login.php . it redirects to: http://forum.mysite.com/bb-login.php . i tried permalink settings none , name based, same issue. does uses redirect in bbpress or how can eliminate "double" content , redirect permanently www.? i redirected www.forum.mysite.com forum.mysite.com , achieved eliminate "double" content.

iphone - How to detect touch on UIImageView inside UIScrollview? -

i have uiscrollview in app , populate lots of uiimageviews approx 900. small , consist of 2 different images on , on again. now having lot of trouble detecting touch on 1 of these uiimageviews. i have assigned them unique tag able distinguish between them struggling detect touch. the goal able change image of touched uiimageview. due large amount of views involved simple loop checking touch coordinates against each uiimageviews frame hanging app. does have suggestions? thanks in advance. ben the best way solve issue subclass uiscrollview, add touchesbegan etc methods it. @interface myscroll : uiscrollview { }

security - How safe is this procedure? -

i'm going use kind of approach store password: user enters password application salts password random number then salted password encrypt encryption algorithm randomly selected array of data (consisting predefined table of chars/bytes) for simplicity can used table of digits, in case of digits random array long enough integer/biginteger. then store in db salt (modified value) , encrypted array to check password validity: getting given password read salt db , calculate decrypt key try decrypt encrypted array if successfull (in mathematical mean) compare decrypted value byte byte does contains chars/bytes known table. instance integer/biginteger? if - password counts valid what think procedure? in few words, it's kind of alternative using hash functions... in approach encryption algorithm used calculation of non-inversible value. edit # encrypt/decrypt function works this: key=hash(password) cyphertext = encrypt(plaintext, key) plaintext = decryp...

php - Cascading Select Boxes - Jquery -

having problem dynamically populated select boxes using jquery. basically, code calls php script populates select box (utilitymainchart). let's brings 2 options the select box utilitymainchart, want next select box (parametermainchart) populated options whichever option first in utilitymainchart select box. as right now, select boxes populate initially, line var building = $('#utilitymainchart').val(); never returns value of select box. means change select box result in ones below becoming blank, since no value picked up. my code javascript shown below: var data = "1" + "_" + building + "_"; var url = "/charts/data/utilitymanagermenupopulate.php?data=" + data; $('#utilitymainchart').load(url); var building = $('#utilitymainchart').val(); var data = "2" + "_" + building + "_" + utility; var url = "/charts/data/utilitymanagermenupopulate.php?data=" + data; $('#para...

ssh - How to backport SShSession to Ant 1.7.1 -

i stuck ant 1.7.1 moment reasons wont into. i'd able use sshsession ant task create ssh tunnels of servers. sshsession introduced in ant 1.8.0. i have no experience custom ant tasks. difficult backport task 1.8.0 1.7.1 ? should go learn more on how ? thanks ! it looks source sshsession task compatible ant 1.7. source task , , compile against ant 1.7 , jsch jar. create taskdef pointing class you've created (jsch.jar need in ant lib dir or specified using -lib option) , should go.

visual c++ - Conversion of string to time_t -

is there way convert string value time_t format? thanks in advance. one approach parse string various components , use them fill tm structure. once have structure filled data can use c function mktime convert structure time_t type. there might more ideal ways in visual c++, in normal c/c++ way i'd untill i'd find better algorithm.

flash - Uploadify suddenly stopped working completely in Chrome 10 -

i'm using uploadify allow multi file uploading in web application. has worked across ie 7,8, 9, ff 3.6, safari , chrome. today discovered accident working in each browser yet not in chrome. i'm on chrome 10.0.648.82 beta. issue there can select files upload, yet after nothing happens. put alerts in uploadify events , non fired. went official demo site: http://www.uploadify.com/demos/ ...and discovered not work chrome there anymore either. running chrome default can be, updated version itself. have default settings intact , no popup-blockers, ad blockers or other add-in installed. tried debug using http fiddler, conclude no http request made @ after selecting files upload. does knows going on? chrome issue or flash issue? there known resolutions? ps: on windows 7 64-bit. i agree, think chrome or flash issue (since google ship flash inside chrome). the uploadify demo page working me in chrome 12.0.725.0 (which current dev release ). try switching dev or b...

Getting the bound Datarow of a Datagrid on postback in ASP.NET 4 -

i want find out bound datarow or datatable of datagrid on postback. have buttoncolumn in grid. on click of button, i'm trying determine datarow can access primary key , pass page. primary key not bound , therefore not visible in row. for example have list of customers, edit button. on clicking of edit button, want open customeredit.aspx?id=10. able trap click event on server side in datagridcustomer_itemcommand event. not able access datarow of e.item.itemindex. on postback i'm not binding datagrid. on accessing datagridcustomer.datasource, "nothing". there way datasource or datarow? thanks you can't. databind method calling page load method, when it's not postback iterate through source build controls. after that, source not kept...only resulting controls. i suggest build url edit page instead of relying on postback. in few words, create hyperlinkcolumn in datagrid, , specify text fields , datafields build full url.

php - Wordpress If No Meta Field, Then Do This - How? -

i have following code in wordpress displaying meta values, want not display value if not filled in. how set if/else around this? <?php $my_meta = get_post_meta($post->id,'_my_meta',true); ?> <div class="archive_images_one"><a href="<? echo $my_meta['image_one']; ?>" title="<? echo $my_meta['image_one_lightbox_title']; ?>" rel="lightbox"><img border="0" width="300px" height="200px" src="<? echo $my_meta['image_one']; ?>" alt="android , iphone app development"></a></div> <div class="archive_images_bottom"> <div class="archive_images_bottom_one"><a href="<? echo $my_meta['image_two']; ?>" title="<? echo $my_meta['image_two_lightbox_title']; ?>" rel...

database - How to migrate Drupal data to Django? -

i want migrate part of drupal 6 site django application, drupal based questions , answers section think work better osqa . i've created question related authentication part of integration , purposes of question can assume drupal users recreated, @ least usernames, in django database. question data migration drupal django. in drupal have questions nodes of 'question' content type cck fields , answers these questions standard comments. need find best way of moving data osqa in django. at first thought use south i'm not sure if best fit needs. for think best approach write django app connects drupal database, query questions corresponding comments , users , insert directly django's database using correct models , django methods. am on right path? other suggestions? thanks! at first thought use south i'm not sure if best fit needs. no, south not kind of migration. intra-project migrations, , want have it, doesn't here. "migr...

c# - Websocket help! -

i'm working on websocket application. have server written in c#. have tested using c# application sending , receiving data. problem occurs when use javascript on chrome developer tool (console) , use websockets connect server. i receive header string websocket script, 2 keys , last 8 characters hashing. i used header string keys generate hash code , crate header send chrome(j script on developer tool). issues:- the onopen event never triggered , websocket not receive header(i assume). use onerror capture errors. never occur. the readystate on websocket 0 or 2(always). but when send disconnect response server, websocket triggers onclose method. (so assume open not ready communicate) any suggestions??????? here's javascript if helps. websocket = new websocket('ws://my server ip here:8080'); try { websocket.onopen = function(evt) { open(evt) //websocket.send("message send"); alert("message sent...")...

callback function parsing JSON in JQuery -

i'm new jquery , maybe n00b question. , english not best. i wrote service in google app engine application delivers data in json format, works ok, wasn't able parse json data using jquery: var url= 'myapp.appspot.com/myservice.json?someparams'; $.getjson(url, function(json){ alert("success parsing json"); // never reached code .... }); after few days of reading posts , tutorials felt slideshare: http://www.slideshare.net/andymckay/cross-domain-webmashups-with-jquery-and-google-app-engine while reading slide 23 noticed "callback=?" parameter , tried code in slide 42: class myjsonhandler(webapp.requesthandler): def get(self): ## retrieve data db or memcached jsondata = json.dumps(data) if self.request.get('callback'): self.response.out.write('%s(%s)' % (self.request.get('callback'), jsondata)) else: self.response.out.write(jsondata) and in jq...

C/C++ overwriting array bounds -

what way detect bugs overwrite array bound? int a[100]; (int = 0; i<1000; i++) a[i] = i; it helpful collect list of different strategies people have used in experience uncover bugs of type. example, doing backtrace on point of memory fault (for me doesn't work because stack has been corrupted). static code analysis (e.g. lint) runtime memory analysis (e.g. valgrind) avoid fixed-size buffers, prefer dynamically sized containers use sizeof() instead of magic numbers whenever can

ASP.NET: Programmatically fire a server-side event in window.opener with JavaScript -

i have dropdownlist fires off server-side databinding in onselectedindexchanged event. <asp:dropdownlist id="ddlgroup" runat="server" autopostback="true" onselectedindexchanged="selectgroup" /> elsewhere in page, javascript opens popup. when popup filled out , submitted, want use javascript fire onselectedindexchanged event in opener page. found other code similar: if (window.opener != null ) { var cf = window.opener.document.forms['aspnetform']; if (!cf) { cf = window.opener.document.aspnetform; } cf.__eventtarget.value = "pradded"; cf.__eventargument.value = "winclosed"; cf.submit(); } i think i'm looking for, i'm not sure should go in eventtarget , eventargument parts, or if need @ all. want fire onselectedindexchanged event handler ddlgroup . possible/practical? secondary question: can make parent page refresh afte...

c# - Is there a way to persist authentication from one web app to another, nested web app in ASP.NET? -

so company has asp.net web app, targeting .net 3.5. tasked building ticketing system them. don't need use resources of company app, except authentication. target .net 4.0 , use 4.0 goodies entity framework , mvc 3.0. if create application targeting .net 4 nested within main web app in iis, there way persist authentication not require different session within 4.0 web app? please let me know if being unclear. thank you. if use membership authentication can share sessions between different web applications provided following true: all of them share same machine key - can set machinekey explicitly in each web.config same value. you using same authentication cookie name (i.e. .aspxauth default) there might other ways, how got work. also see article reference: forms authentication across applications

iphone - Stopping the audio after playing with AVAudioPlayer -

hi guys hope can me issue. what when user left view b view a, audio plays, when user left view view b, audio stops. so when user left view b (removing viewb superview) main view view a, methods playit & hahaplay called. when user left view view b (view add subview b) stopplaying method called instead. here's problem, stopplaying method called, audio not stopped. realised alert shown reason statement> [audioplayer stop]; not functioning. i've defined audio player in header file fyi. all methods below in viewcontroller called soundview. sorry might doing whole thing in wrong way, maybe of can enlighten me , correct mistakes? -(void)playit{ filepath = [[nsbundle mainbundle] pathforresource:@"6431" oftype:@"aiff"]; fileurl = [[nsurl alloc] initfileurlwithpath:filepath]; audioplayer = [[avaudioplayer alloc] initwithcontentsofurl:fileurl error:nil]; } -(void)...

emacs - Controlling the actions with org-mode -

when have python code in "/abc/hello" -rwxr-xr-x , have [[/abc/hello]], click link run hello code. can change action can edit (open editor) abc/hello file? i tried this (setq org-link-abbrev-alist '( ("edit" . "mate %s"))) with [[edit:/abc/hello]] , doesn't work. i tried file:/abc/hello , doesn't work neither. solved ("mate" . "shell:/usr/local/bin/mate %s") and turn confirmation off (setq org-confirm-shell-link-function nil) leo alekseyev gave me answer quetion @ post .

apt - Maven: Can I speed up mvn site? -

is there quicker way generate site maven preview? background: i'm using mvn site generate website includes documentation our project. i'm using the apt format, simple, , few mistakes made, want feedback after adding large amount of content don't have spend time searching syntax errors. the problem site takes 2 minutes generate each time, , quicker feedback how site looks , if made mistakes while typing docs. isn't huge issue but, situation improved. also, in order me out i'm using vim syntax highlighting , if need quick preview on there nice plug-in eclipse allows me preview whether or not apt working correctly (of course, it's not same generated maven, it's close enough). i'm open other suggestions, generating quick preview maven best option productivity. configure 'reporting' section turn off don't want. dependency analysis, example, takes long time. @ doc project-info-reports-plugin.

Use Javascript to reload the page and specify a jquery tab -

i want use javascript reload page. can't use window.location.reload(); i'm using jquery tabs , want specify tab selected after reload. setting window.location.href best way this? i.e. window.location.href = window.location.href + '#tabs-4'; all have pass var in url (post) javascript retreive , select tab associated var

How to remove unconverted data from a Python datetime object -

i have database of correct datetimes few broke so: sat dec 22 12:34:08 pst 20102015 without invalid year, working me: end_date = soup('tr')[4].contents[1].rendercontents() end_date = time.strptime(end_date,"%a %b %d %h:%m:%s %z %y") end_date = datetime.fromtimestamp(time.mktime(end_date)) but once hit object invalid year valueerror: unconverted data remains: 2 , great im not sure how best strip bad characters out of year. range 2 6 unconverted characters . any pointers? slice end_date im hoping there datetime-safe strategy. yeah, i'd chop off numbers. assuming appended datestring, work: end_date = end_date.split(" ") end_date[-1] = end_date[-1][:4] end_date = " ".join(end_date) i going try number of excess digits exception, on installed versions of python (2.6.6 , 3.1.2) information isn't there; says data not match format. of course, continue lopping off digits 1 @ time , re-parsing until don't exception. you...

How to specify the encoding of an XML document using Javascript -

hello trying create document using javascript , there's problem encoding of document, because reject non-ascii characters, string im passing "verificación" replaced "�", how can fixed that. this code: function createdoc(string){ if (window.domparser) { parser = new domparser(); doc = parser.parsefromstring('<?xml version="1.0" encoding="utf-8"?>'+string, "text/xml"); } else // internet explorer { doc = new activexobject("microsoft.xmldom"); doc.async = "false"; doc.loadxml('<?xml version="1.0" encoding="utf-8"?>'+string); } return doc } thanks in advance. javascript strings utf-16 -encoded. try specifying that. where string come from? string correct before parsing it? also, when being displayed? encoding expected there?

iphone - create uibutton subclass -

i tried subclass uibutton include activity indicator, when use initwithframe:(since i'm subclassing uibutton i'm not using buttonwithtype:) button doesn't display. how set button type in case?: my view controller: activityindicatorbutton *button = [[activityindicatorbutton alloc] initwithframe:cgrectmake(10, 10, 300, 44)]; [button addtarget:self action:@selector(buttonpressed) forcontrolevents:uicontroleventtouchupinside]; [button settitle:@"older posts..." forstate: uicontrolstatenormal]; [cell addsubview:button]; [button release]; my activityindicatorbutton class: #import <foundation/foundation.h> @interface activityindicatorbutton : uibutton { uiactivityindicatorview *_activityview; } -(void)startanimating; -(void)stopanimating; @end @implementation activityindicatorbutton - (id)initwithframe:(cgrect)frame { if (self=[super initwithframe:frame]) { _activityview = [[uiactivityindicatorview alloc] initw...

Java Generics, Create an instance of Class<T> -

i trying write generic method deserializing json model. problem don't know how class generic type t. code looks (and doesn't compile way) public class jsonhelper { public <t> t deserialize(string json) { gson gson = new gson(); return gson.fromjson(json, class<t>); } } i tried else, type, throws error had class jsonhelper<t> , tried this class<t> persistentclass = (class<t>) ((parameterizedtype)getclass() .getgenericsuperclass()) .getactualtypearguments()[0]; the method signature looks this com.google.gson.gson.fromjson(string json, class<t> classoft) so, how can translate along t when call jsonhelper.deserialize<myobject>(json); instance of correct object? you need class instance somewhere. is, deserialize() method needs take class<t> parameter, underlying fromjson() method. your method signature should gson's: <t> t deserialize(string json, cla...