Posts

Showing posts from August, 2010

Rails design of an online newspaper -- controllers -

i have started ruby on rails 3 project make online version of newspaper. front page has news headlines, sports headlines , life headlines. has headlines different sections of site. all stories stored in 1 table , photos in table. simple set up. trying dry can't seem avoid it. on index action page have sports stories , on sports action page have sports. my question should make different controller every category? or have main controller categories actions? ( doing now? ) i have single story controller takes querystring determine category. in other words, if go /stories/ you front page, lists (or portion of all) stories. if want sports go /stories/?category=sports and story controller filters list of stories (and presumably alters view headings, etc.) based on querystring.

Should I put all Android view attributes into the style? -

i've seen android devs promote form of declarative layout: <textview style="@style/my_textview_style" /> i.e. pretty attributes (including id) go style definition. makes shorter layout files, step far? what recommend goes in style definition, , should stay in layout, , why? i've started doing android dev year, have prior experience of development. issues important, "way" use tools, habits, more efficient. appreciate sharing views on works you, clarity, efficiency, maintainability, app reliability. i've pondered question , becomes more pertinent when dealing multiple device sizes , densities. putting information styles can limit use, when dealing landscape , portrait layouts. example landscape layout may in fact wholly different in composition require similar styles. in these cases helps use . notation ammend style differences, example. <mypage> <mypage.portrait> <mypage.landscape> see below information

iphone - Correct format for loading vertex arrays from file -

Image
i've been banging head on keyboard past couple of weeks on this. i'm trying load array of floats (glfloat) , array of unsigned shorts (glushort) text file equivalent arrays in objective-c can render contained objects. i've got arrays loaded vector objects as vector<float> vertices; and vector<glushort> indices; but reason can't figure out why can't these render. here code rendering above: glvertexpointer(3, gl_float, sizeof(vertices[0])*6, &vertices[0]); glnormalpoitner(gl_float, sizeof(vertices[0])*6, &vertices[3]); gldrawelements(gl_triangles, sizeof(indices)/sizeof(indices[0]), gl_unsigned_short, indices); sample arrays below: vertices: (vx, vy, vz, nx, ny, nz) {10, 10, 0, 0, 0, 1, -10, 10, 0, 0, 0, 1, -10, -10, 0, 0, 0, 1, 10, -10, 0, 0, 0, 1}; indices: (v1, v2, v3) {0, 1, 2, 0, 2, 3}; the text file want load these arrays rendering looks this: 4 //number of vertices ###vertices### v 10 10 0 0 0 1 v -10 10 0 0 0 1 v -10

ruby - Forwarding requests UDPSocket -

i have basic ruby program, listens on port (53), receives data , sends location (google dns server - 8.8.8.8). responses not going original destination, or i'm not forwarding them correctly. here code. nb i'm using eventmachine require 'rubygems' require 'eventmachine' module dnsserver def post_init puts 'connected' end def receive_data(data) # forward data conn = udpsocket.new conn.connect '8.8.8.8', 53 conn.send data, 0 conn.close p data.unpack("h*") end def unbind puts 'disconnected' end end em.run em.open_datagram_socket '0.0.0.0', 53, dnsserver end any thoughts why or tips debug, appreciated. the obvious problems are: udp comms connectionless, use 4 argument version of send instead of connect you're not receiving data socket talking 8.8.8.8 you're not sending data ( #send_data ) original c

javascript - Lose the Ajax-SliderExtender after Page Refresh (F5) -

i'm using ajax sliderextender in updatepanel. set behaviorid , call $find('behavorid').add_valuechanged function in $document.ready. fine when press f5 , refresh page, lose slider in 1/3 (wtf) chance. if set var slider = $find('behavorid') , recognises slider null. i've run in chrome, ie8 , met same problems. any ideas? solutions? regards didn't find solution. used jquery slider instead.

Multiple magento stores on single domain -

i'm setting website has retail store , wholesalers store. products in each different not matter of adjusting pricing user types. need have wholesale section password protected available logged in users. i'm using module achieve works @ store level hence need 2 stores rather separate categories. my directory structure follows: www.mysite.com - wordpress install current cms pages , blog etc www.mysite.com/store - magento install i want www.mysite.com/store/retail & www.mysite.com/store/wholesale 2 shops. so question - firstly sound the right reasonable approach achieve this. secondly - still trying head around website/store/view system correct in need 1 website, , 2 stores view each. know of tutorial doing sort of setup, i've found few they're setting different domains same install. thanks advise. the simplest way (and used) give 2 stores store codes "retail" , "wholesale". done in admin menu system > manage stores .

How can I find missing or mismatched braces / parens in emacs? -

when code fails compile , tells me missing closed brace, there easy way find in emacs? for languages c, c++, , java, command check-parens check parens ( () ), brackets ( [] ), , braces ( {} ): m-x check-parens <ret> the point move bracketing character unmatched, , status line report problem. it's idea use in conjunction show-paren-mode others have said.

Mercurial: how to push to default branch? -

i'm using mercurial , bit of newbie. committed change repo successfully, ran hg pull , hg update - no merges , no conflicts showed up. then tried push remote repo, , got dreaded: abort: push creates new remote heads! hg glog shows following: @ changeset: 576:c4c58970f141 | tag: tip | user: me | parent: 566:70e287df5439 | | o changeset: 575:7ae70ddd2b6e | | branch: mongo | | | o changeset: 574:904da90475ef | | branch: mongo | | | o changeset: 567:cad7a006965b |/ branch: mongo | o changeset: 566:70e287df5439 | user: me | looks has created new branch in repo, fine: want push changes default branch, don't know how. how can push changeset 576? need specify it's branch default? mercurial's push command has -r option limit push changes given revision: if -r/--rev used, specified revision , ancestors pushed remote repository. this implicates limit branch you're going pus

iphone - Interact with a view controller from another view controller -

i want view controller check if there image on view controller when click button. of there image simulator not execute loop. code: - (ibaction)buttonclicked:(id)sender { iphotoviewcontroller *photo = [[iphotoviewcontroller alloc] initwithnibname:@"iphotoviewcontroller" bundle:nil] ; if (photo.mainview.image) { = (uibutton *) sender; self.selectedimage = [_images objectatindex:but.tag]; iphoto2appdelegate *delegate = [[uiapplication sharedapplication] delegate]; [delegate.navcontroller popviewcontrolleranimated:yes]; [photo release]; } thanks, praveen you creating new instance of iphotoviewcontroller means image want use must available in nib file. , being available in nib file means available in project creating new iphotoviewcontroller see if image there seems bit strange. is there perhaps instance of iphotoviewcontroller somewhere have loaded image? if instance need check. but perhaps te

C++ - calling a method from a class template -

i'm having problem class template in c++. i'm making hash table. i'm using functor class template specify hash function each instance of table. ie: 1 table has integers keys, strings values. have strings keys , integers values, etc... class hashstring { public: unsigned long operator()(std::string& key, const unsigned int tablesize) { // ..... } }; template<typename keytype, typename valuetype, class hashfunctor> class hashtable { public: // .... private: hashfunctor myhash; }; and let's want call method called "myhash" hash key, @ first call doing: myhash(key, table.size()) but gcc doesn't find function overload hashfuntor(string, unsigned int) example. could tell me how call myhash? (note: not change structure of functors) edit: error message actual solution instantiated ‘void tp3::table<typeclef, typedonnee, fonchachage>::insert(const typeclef&,

java - mHandler isn't set from within a synchronized block in Android SDK -

looking through android sdk framework source code, i've come across this: private final class gpslocationproviderthread extends thread { public gpslocationproviderthread() { super("gpslocationprovider"); } public void run() { process.setthreadpriority(process.thread_priority_background); initialize(); looper.prepare(); mhandler = new providerhandler(); // signal when initialized , ready go minitializedlatch.countdown(); looper.loop(); } } (this froyo's frameworks/base/location/java/com/android/internal/location/gpslocationprovider.java) gpslocationproviderthread inner class of gpslocationprovider , , mhandler member instance variable of gpslocationprovider . variable set within thread's run() method, no synchronization applied, , mhandler not volatile . why work? , if 99% of time work, it's not guaranteed work,

Using NHibernate to report a table with two sums -

i have 3 tables: people, purchases, payments 1-to-many relationships between people , purchases, , people , payments. i want generate report of people showing sum of purchases , payments. i can generate report people showing sum of payments or purchases, vis: var query = detachedcriteria.for<people>("people") .createalias("payments", "paymentsmade"); query.setprojection(projections.projectionlist() .add(projections.groupproperty("id"), "id") .add(projections.sum("paymentsmade.amount"), "totalpayments") can in single query in nhibernate? either using criteria api (preferred) or hql. try this: var query = @"select (select sum(pu.amount) purchase pu pu.people.id = ppl.id), (select sum(pa.amount) payments pa pa.people.id = ppl.id) people ppl"; var results = session .createquery(query) .list();

RSS feed basics - just repeatedly overwriting the same file? -

really simple question here: for php-driven rss feed, overwriting same xml file every time "publish" new feed thing? , syndicates it's registered pop in time time check it's new? yes. rss reader has url of feed , regularly requests same url check new content.

mercurial - How to set the default push/pull repository from TortoiseHG -

for 1 of repositories, doesn't remember name of repository pulling , pushing to. don't have problem of other repositories on machine. way fix this? as of version 3.0 there no "setting" choosing default url. instead must create alias of "default" url want. to so, workbench, right click on repository , select settings. click edit file , add line (see below) specifies default path desired repository. default = url of repository

swf chart not displayed in chrome -

i want display chart of swf type. displayed proeprly in firefox , ie in chrome not displayed. in chrome chart displayed after click on chart div. data chart loaded displayed on click. my code is: <?php $link = "/flash/chart.swf?thexml=".urlencode(url_for('@chartcompare?series='.$seriesname.'&id='.$seriesid.'&source='.$sourcename,true)); ?> <div style="margin-top:10px; margin-bottom:10px"> <object style="z-index:-1" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="560" height="180" id="chart" align="middle" > <param name="allowscriptaccess" value="samedomain" /> <param name="allowfullscreen" value="false" /> <param name="wmode" value="transparent"> &

python - How do I make PIL take into account the shortest side when creating a thumbnail? -

currently, function below...the image resized based on longest side. basically image has larger height, height 200px. width just...whatever... if image has larger width, width 200px, , height adjust accordingly. how flip around!? want function take account shortest side. am writing function incorrectly?? def create_thumbnail(f, width=200, height=none, pad = false): #resizes longest side!!! doesn't care shortest side #this function maintains aspect ratio. if height==none: height=width im = image.open(stringio(f)) imagex = int(im.size[0]) imagey = int(im.size[1]) if imagex < width or imagey < height: pass #return none if im.mode not in ('l', 'rgb', 'rgba'): im = im.convert('rgb') im.thumbnail((width, height), image.antialias) thumbnail_file = stringio() im.save(thumbnail_file, 'jpeg') thumbnail_file.seek(0) return thumbnail_file use resize

Objective C memory leak problem -

i have memory leak problem in following objective c code. bold asterisked( *** ) line line memory leak (mentioned in instrument). idea of it? thanks. - (uiimage*)part:(float)part ofimage:(uiimage*)imgobject withmask:(uiimage*)imgmask { uiimage *imgresult = nil; cgrect rcmask = cgrectmake(0.0f, 0.0f, imgmask.size.width, imgmask.size.height); cgrect rcobject = cgrectmake(0.5f * (rcmask.size.width - imgobject.size.width), 0.0f, imgobject.size.width, imgobject.size.height * part); byteptr picturedata = (byteptr)malloc(rcmask.size.width * rcmask.size.height * 4); cgcontextref picturecontext = cgbitmapcontextcreate(picturedata, rcmask.size.width, rcmask.size.height,8, rcmask.size.width * 4,cgimagegetcolorspace(imgobject.cgimage), kcgimagealphapremultipliedlast | kcgbitmapbyteorder32big); cgcontextcliptomask(picturecontext, rcmask, imgmask.cgimage); cgimageref imginrect; imginrect = cgimagecreatewithimageinrect(imgobject.cgimage, rcobject); cgconte

java - How can I pass an ArrayList from one servlet another? -

i have sent arraylist1 1 servlet another. works. want pass arraylist2 jsp/servlet, error: java.util.nullpointer exception . how can resolve this? requestdispatcher disp2 = request.getrequestdispatcher("newservlet.java"); should requestdispatcher disp2 = request.getrequestdispatcher(pathtoyourservlet); the path end of page adress: http://localhost/yourapp/ pathtoyourservlet

multithreading - Two questions about iphone threading -

how create nsthread iphone gps yes. has processor local caches (data/code might still cached) , local memory (in numa aware systems) i suggest performing googling, considering numa (and numactl ) case in linux.

iphone - Android Offline Webapp Resources -

i made offline card game webapp iphone , android when doing this, went entirely off of abundant iphone offline webapp information on web. however, seems work on android 1 exception. when open after killing web connection, states error not being able connect. after canceling, works fine. my question this: has found decent resources regarding android offline web apps? or hack? ios devices seems support in more intuitive way. update: had forgotten issue posted about. seems have been resolved while. think may have been fixed in android 2.1. seemed have not noticed there no error message. however, still not run html 5 webapps cleanly ios in nav bar still present when running desktop bookmark. after messing stuff bit, iphone/ios stuff seems work fine. might because android browser webkit based. whatever reason, file manifest respected bottom line, iphone html5 mobile app documentation seems work fine android. here's quick example runs on both: http://w

iphone - Delete Destructive Button like in UIActionSheet -

Image
i need create button programmatically in image i know destructive button in uiactionsheet. there way use distructive button uibutton ? thanks, tariq unfortunately there no way set destructive button uibutton ,unless create custom button red gradient background image this can create red button methode specified above or this

Altering Google AppEngine Datastore Table While Preserving Data -

i using python developing google app engine application. question while in development several times need modify data models adding, deleting or changing data type of fields. modifying models doesn't take effect until use clear_datastore destroys data. true or doing thing wrong ? the datastore schema-less; means can have entities of same kind different properties. changes do take effect, existing data not automatically updated new schema. under covers entities protocol buffers, dict (key-value pairs). when want make changes schema and have existing data needs updated too, you'll need convert in way. often, need write special script load original entity, convert new schema, re-put it. google has article discussing topic.

java - openFileOutput throws exception -

i writing data xml files in android app. looked how file io , found need use openfileoutput. far can tell there nothing wrong code keeps throwing exception @ line have try-catch wrapped around in following code: public void writesearchxml(arraylist<string> searches, string file) throws exception { // try { // file newxmlfile = new file(file); // newxmlfile.createnewfile(); // } catch (exception e) { // } try { // following line throws exception every time fileoutputstream out = openfileoutput(file, context.mode_world_writeable); } catch (exception e) { throw new exception("failing on fileoutput stream searches."); } fileoutputstream fout = openfileoutput(file, context.mode_world_readable); // create xmlserializer in order write xml data xmlserializer serializer = xml.newserializer(); // set fileoutputstream output serializer, using utf-8 // encoding

Parse HTML in Objective-C -

hello! this iphone this trying achieve: this website expands urls bit.ly/miniscurl creator got api says have go website: http://expandurl.appspot.com/expand?url=yoururl so when put: http://expandurl.appspot.com/expand?url=bit.ly/miniscurl it returns new website information: { "status": "ok", "end_url": "http:\/\/miniscurl.dafk.net", "redirects": 1, "urls": ["http:\/\/bit.ly\/miniscurl", "http:\/\/miniscurl.dafk.net"], "start_url": "http:\/\/bit.ly\/miniscurl" } and great! how information nsstring , search through different tags. @ last got this: nsstring *status = ok; nsstring *end_url = http:\/\/miniscurl.dafk.net"; etc... also nsarray containing redirects (if there more one) have been great! conclusion: i need: a fast , easy way html source website. a fast , easy way search through nsstring , cut in different pieces. t

svn - How can I see all the revisions where a given line of a file has been modified? -

i working ankhsvn in visual studio 2008 , , trying figure out way see revisions specific line of given file has been modified (created/changed), can trace when given bug has been introduced. i pretty sure possible scripting magic svn in command-line (see this question ), there way do ankhsvn or tortoisesvn in windows environment ? i believe closest can using tools using blame command. unfortunately, blame show last revision specific line has been modified only.

php - Recursion and passing by reference -

i have tree of categories of following structure: [6] => array ( [id] => 6 [name] => computers [productcount] => 0 [children] => array ( [91] => array ( [id] => 91 [name] => notebook [productcount] => 5 [children] => array ( ) ) [86] => array ( [id] => 86 [name] => desktop [productcount] => 0 [children] => array ( ) ) ) ) beside subcategory, each category may contain products (like folder may contain subfolders , files). i'm trying write recursive function

Is there a way to estimate the write bandwidth from java to an Oracle -

we have large volume of data , want know how fast can written oracle. there way estimate write bandwidth java oracle db? can use approach (not jdbc) if faster. example useful know x disk speed, y processor, can write z bytes/second. there way estimate such data rate? thanks! i don't think there's standard formula. among other things depends on schema (e.g whether have indexes on tables), file system, how many disks have, raid level using, how tables, indexes, logs etc spread out across disks... try , see way. if there way of estimating given that, i'd know too!

java - How do I deal with a character array in my homework? -

given 2 character arrays a[] , b[], remove b[] occurrences of characters occur in array a[]. need in-place i.e. without using array of characters. e.g.: input: a[] = [‘g’, ‘o’] input b[] = [‘g’, ’o’, ’o’, ’g’, ’l’, ’e’] output: b[] = [‘l’, ‘e’] code : public class replacecharacterarray{ public static void main(string args[]){ char a[] = [‘g’, ‘o’] char b[] = [‘g’, ’o’, ’o’, ’g’, ’l’, ’e’] //to replace occurences of characters of //a[] array in b[] array have below logic. for(int i=0;i<a.length;i++){ for(int j=0;j<b.length;j++){ if(b[j] == a[i]){ //im stuck here how proceed } } you can't remove elements "in place" in java arrays. have fixed length. is, in example you'll have return new array, since can't change length of b

performance - max mysql queries per minute -

how many queries slave can handle per minute? in case, used show status '%questions%' , found after interval of 1 minute, around 5,000 queries executed. is normal behavior or can improved? there many inter-related factors influence answer questions. include, not limited to the distribution of queries slave the timing , types of updates coming in via replication your dataset your hardware your mysql version , engines being employed having said that, stat of "5000 question s per minute" not sufficient raise flags in books. it might more worthwhile determine if application operating within acceptable range; e.g. application's average response time or worst case response time. it's worth noting question s counter includes more select s. can't find comprehensive list or reference, but, examples, believe " update s, delete s, show status , use $db, show tables " increment questions status variable.

Using a hash in view in rails -

hi , i using constant hash in model user as myuser = { :firstname => "first name", :lastname => "last name", :designation => "my designation" } now in views , have loop have field names (firstname,lastname,designation) so try send field name key in <% @userfields.sort.each |userfield| %> <tr> <td> <% @userkey=userfield%> <%= @userkey%> # gives exact field names <%= user::myuser[:@userkey]%> # doesnt gives <td></tr> <%end%> how rectify ?? give suggestions when use variable index hash, should not specify colon, correct syntax be: user::myuser[@userkey] or user::myuser[@userkey.to_sym] depending on value in @userkey. however, loop myuser constant directly this: <% user::myuser.keys.each |key| %> <tr> <td>key: <%= key %></td> <td>value: <%

php - How can I specify "any character" including double quotes, gt, lt, equal -

in php have next text: $text='<div id="my_date_div" year="2010" month="12" day="07" hour="00" minute="00" > <span id="my_span_days">dys</span> <span id="my_span_hours">hrs</span> </div>' i perform preg_replace() keep values of upper text, example year (2010) , hour(00). i perform lookup /year=\"/ , /hour=\"/, dont know how remove other text dont want since expresion [.+\s+]* not match characters " or < what have is $regex = "/[.+\s+]*year=\"(\d+)\"[.+\s+]*hour=\"(\d+)\"[.+\s+]*$/"; $regrep = "$1 $2"; echo preg_replace($regex, $regrep, $tex

version control - Multiple Developers on One Site (PHP) -

not direct relation php @ moment have 3 developers working on 1 site. using shared hosting cant svn or cvs installed. answered is there way can implement version control on shared hosting? unanswered on side note, have seen lot of developers have comment @ top of files, i.e. 1 invision power board have using few years ago /** * invision power services * ip.board v3.0.5 * wrapper interfacing stopforumspam.com * class written matt mecham * last updated: $date: 2009-02-04 20:05:25 +0000 (wed, 04 feb 2009) $ * * @author $author: bfarber $ * @copyright (c) 2001 - 2009 invision power services, inc * @license http://www.invisionpower.com/community/board/license.html * @package invision power services kernel * @link http://www.invisionpower.com * @since tuesday 22nd february 2005 (16:55) * @version $revision: 222 $ */ is there anyway automatically generate these files, updating "last

uibutton - Buttons in Iphone -

is possible manually assign image button in iphone sdk. wish assign plain card background button. when user clicks button picker appears user makes selection picker buttons image card selected? have cards saved in resources already. you can use image in image view on image use custom button , on click button ibaction call suppose -(ibaction)call { mypicker.hidden=no; } , in viewwillappear mypicker.hidden=yes; and use picker view delegate methods logic picker view.

email - zend framework gmail -

i'm trying use zend mail sending in 1 of application. i'm not sure basic requirement using zend_mail. $this->transport = new zend_mail_transport_smtp( 'smtp.gmail.com', array( 'ssl'=> 'tls', 'port'=> '587', 'auth'=> 'login', 'username'=> 'email@email.com', 'password'=> 'password' )); zend_mail::setdefaulttransport($this->transport); and while sending mail $mail->send($this->transport); and handled error using $e->getcode().$e->getmessage(); script gives me error 05.5.2 i'm not able understand issue. the port should 465!!!! works. me well!

What quality metrics shall I follow for a PHP project and are there any softwares available? -

what metrics should use measure quality of php project? have few in mind loc, functional changes, time spent, not sure if going right? recommend? also, there softwares available measure quality of product (based on metrics)? pointers. take at: http://pdepend.org/ , http://phpmd.org/

c# - Reflection usage for creating instance of a class into DLL -

i have following code: var type = typeof(plugininterface.imbddxplugininterface); var types = appdomain.currentdomain.getassemblies().tolist() .selectmany(s => s.gettypes()) .where(p => type.isassignablefrom(p)); type t = types.elementat(0); plugininterface.imbddxplugininterface instance = activator.createinstance(t) plugininterface.imbddxplugininterface; tabpage tp = new tabpage(); tp = instance.plugintabpage(); the class within dll implements plugininterface , type in code above, definately correct class/type, when try create instance through interface error message saying: object reference not assigned instance of object. anybody know why? thanks. anyway tabpage tp = new tabpage(); tp = instance.plugintabpage(); makes no sense. do: tabpage tp = instance.plugintabpage(); also next: type type = appdomain.currentdomain.getassemblies() .selectmany(s => s.gettypes()) .firstordefault(p => type.isassignablefrom(p)); if (

utilities - How can I perform fastload for a file which has only one column and 'n' rows? -

i have done fastload table has more 1 column (i did vartext format , delimiter). now want load file has 1 column (and 5 rows say). i'm unable , encountering below error: i/o error on file read: 16, text: unexpected data format my fastload script below: sessions 5; .logon dbc/dbc.dbc; begin loading mytable errorfiles table_flet, table_fluv ; define col1_mytable (char(2)) file = c:\fload\inpt.txt; insert mytable ( col1_mytable ) values ( :col1_mytable ); end loading; mytable structure below: create multiset table database.mytable ,no fallback , no before journal, no after journal, checksum = default ( col1_mytable char(2) character set latin not casespecific ) primary index ( col1_mytable ); the contents of input file below: aa bb cc dd ee how can fastload? done.. below script : .logon dbc/dbc,dbc; create multiset table database.mytable ,no fallback , no before journal, no after journal,

jquery - I cannot initially hide(); my span tag -

i have loader animated gif want hide , show during ajax request. this loader html code. <span id="loader"><img src="images/icons/ajax-loader.gif" alt="loader" /></span> i want hide this <script type="text/javascript"> $(document).ready(function() { $('#loader').hide() }); </script> however still shows until until ajax function run , hides it. want hide @ startup. <span id="loader" style="display: none">...</span>

Android Calling JavaScript functions in WebView -

i trying call javascript functions sitting in html page running inside android webview. pretty simple code tries below - android app, call javascript function test message, inturn calls java function in android app displays test message via toast. the javascript function looks like: function testecho(message){ window.jsinterface.doechotest(message); } from webview, have tried calling javascript following ways no luck: mywebview.loadurl("javascript:testecho(hello world!)"); mwebview.loadurl("javascript:(function () { " + "testecho(hello world!);" + "})()"); i did enable javascript on webview mywebview.getsettings().setjavascriptenabled(true); // register class containing methods exposed javascript mywebview.addjavascriptinterface(myjsinterface, "jsinterface"); and heres java class public class jsinterface{ private webview mappview; public jsinterface (webview appview) { this.mappview = appview; }

Use spring form tags or not? -

i working on new web project based on spring mvc 3. trying decide use spring form tags or not. don't use tags other html , jsp. takes time learn them , hard understand how rendered , error msgs when occur. there outstanding advantages use them? thank you! the spring mvc form tags basic indeed, they're better nothing. if you're trying render html forms, submissions, error messages, , resubmissions, take lot of annoyance away (especially <select> fields, huge pain handle otherwise). for more complex, they're pretty useless, forms, see no reason not use them.

c# - Using a ValueConverter after a DataContext switch -

i want try out small, custom valueconverter in class after being instantiated (via default constructor, calls initializecomponents() ), given datacontext , instance of viewmodel. using staticresource within binding not work @ (yields nullreferenceexception ), since datacontext has since been changed (is not this anymore). i've tried putting datacontext = this; before initializecomponents call, no change. should looking markupextension gizmo (as described in article ) ? i've tried creating instance of custom value converter within viewmodel (the current datacontext ), doesn't either. i can provide additional details @ times. thank in advance ! i'm trying display contextmenu within textblock. contextmenu contains sole menuitem. header of menuitem can "settings" instance. children (rendered menuitems well) of said menuitem stem enum, hence itemssource on menuitem. now getting displayed nicely, yet trying make 1 of children (e.g. member

frameworks - How to get code completion to work for PHP in Netbeans? -

Image
how code completion work php in netbeans 6.9.1? want netbeans suggest native php functions. edit: the auto complete works reserved vars , reserved keywords not native functions. looking @ example above, should suggest e.g str_replace, strlen, etc...that doesnt happen after ctrl + spc. just make sure have enabled php plugin, should trick. btw autocomplete might not work while netbeans checking project changes though...

oop - How to avoid to "fill" a generic class with attributes? -

i trying translate poker game correct oop model. basics : class hand { card cards[]; } class game { hand hands[]; } i games , hands text file. parse text file several times, several reasons: get somes infos (reason 1) compute stats (reason 2) ... for reason 1 need attributes (a1, b1) in class hand. reason 2, need other attributes (a2, b2). think dirty way : class hand { card cards[]; int a1,b1; int a2,b2; } i mean attributes useless of time. so, cleaner, do: class hand { card cards[]; } class handforreason1 extends hand { int a1,b1; } but feel using hammer... my question : there intermediate way ? or hammer solution 1 ? (in case, correct semantic ?) ps : design patterns welcome :-) ps2 : strategy pattern hammer, isn't it? * edit * here application : // parse file, read game infos (reason 1) // hand.a2 not needed here ! class parser_infos { game game; function parse() { game.hands[0].a1

Generate ER Diagram from existing MySQL database, created for CakePHP -

for cakephp application, created mysql database. which tool used create er diagram of database? fields , relations between tables created in way cakephp likes. thank in advance! try mysql workbench . packs in nice data modeling tools. check out screenshots eer diagrams (enhanced entity relationships, notch er diagrams). this isn't cakephp specific, can modify options foreign keys , join tables follow conventions cakephp uses. simplify data modeling process once you've put rules in place.

iPhone API - Bluetooth MAC addresses of surrounding devices? -

i registered iphone developer, did not me find answer questions. 1) how iphone bluetooth mac address via api? 2) possible (via iphone api) mac addresses of surrounding bluetooth devices (not iphones). can not use bonjour or gamekit, both used connect ios devices only. not want pair devices, or send data – need mac addresses. thanks lot answer (and sorry english). you cannot via public apis. this answer might you

mfc - Windows Menu: MF_HILITE flag does not cleared -

i have cmenu instance on add multiple items. 1 of items added in it, set mf_hilite flag. when show menu, appropriate item hi-lighted correctly, requested. problem stays hi-lighted until move mouse on , leave. want 1 item hi-lighted @ time. seems windows not un-light when item hi-lighed. how force un-lighted item hi-light? not find mouse-over callback or message menu, , not find invalidate either. you're using mf_hilite in weird way. item isn't highlighted, it's drawn is. if user presss enter, "highlighted" item won't selected. you're looking mf_default .

Open a .txt file into a richTextBox in C# -

i want able open .txt file richtextbox in c# , global variable have made called 'notes' don't know how this. code have @ moment: openfiledialog opentext = new openfiledialog(); if (opentext.showdialog() == dialogresult.ok) { richtextbox1.text = opentext.filename; globals.notes = opentext.filename; } only problem doesn't appear in neither richtextbox nor in global varibale, , global allows viewed in richtextbox in form. please can help, ideally .txt file going both, thanks do mean want have text displayed or filename? richtextbox1.text = file.readalltext(opentext.filename); globals.notes = richtextbox1.text; you want correct to: if (opentext.showdialog() == dialogresult.ok)

c# - When does a Gridview have a null DataSource? -

i've read multiple sources gridview's not persist gridview.datasource property on postback. understanding in term's of asp.net, postback page load not first pageload (see msdn ). i've got situation 2 similar gridviews. gvone.datasource null on postback. gvtwo.datasource not null on postback. the big difference outside of few differing columns gvone populated entity framework , linq. gvtwo populated datatable filled sqldataadapter. further, gvone , gvtwo have templatefield textbox use gather user input. both use same code pull textbox.text on postback: textbox tb = (textbox)gvone.rows[i].findcontrol("actualtxt"); gvone gathers tb.text. gvtwo always finds tb.text value 0 . basic gridview code: <asp:gridview id="gvone" runat="server" autogeneratecolumns="false"> <columns> <asp:templatefield headertext="return"> <itemtemplate> <asp:textbox id="

android - How can I show my contact phone numbers and get one of the phone numbers for use on my app? -

i have app has show phone contact list. user has select 1 phone number , have use phone number programmatically on app. how can it? code examples great. just wire button onbrowsefornumbersbuttonclicked() method... drop code in underneath formattedphonenumber line... , you're go. import android.app.activity; import android.content.intent; import android.database.cursor; import android.net.uri; import android.provider.contactscontract.commondatakinds.phone; import android.util.log; import android.view.view; public class testactivity extends activity { private static final int request_contact_number = 123456789; /** pops "select phone number" window */ public void onbrowsefornumbersbuttonclicked(view view) { intent contactpickerintent = new intent(intent.action_pick, phone.content_uri); startactivityforresult(contactpickerintent, request_contact_number); } protected void onactivityresult(int requestcode, int resultcode

winapi - win32 : display editbox with black color in text area on windows mobile 5 -

i writing simple ui application on windows mobile 5, want display editbox user color in whole edit box not successful approach........ whenever catch window event edit control , call setbkcolor(), display text area given color not entire edit box. i want given color displayed user when window presented user not when user enters data in edit box. please let me know solution , again native win32 application code not mfc regds suhail setbkcolor sets background colour text. change background of entire control, need process wm_ctlcoloredit message , return brush of choice. can in wndproc this: (assuming hedit handle of edit control) case wm_ctlcoloredit: if ((hwnd)lparam == hedit) { hdc hdc = (hdc)wparam; setbkmode(hdc, transparent); return (lresult)getstockobject(black_brush); // or other brush want } break; by setting background mode transparent, don't need separate setbkcolor call -- text painted transparently on background.

rendering - OpenGL 3.1-4.1 new and deprecated features -

i've been working opengl year now, , have learned lot of stuff. unfortunatly way learned old pre 3.x way, meaning immediate mode, default shaders, matrix stacks, etc. more or less have idea of has changed looking @ opengl specs, don't totally understand of new ways things. from understanding got rid of matrix stacks, meaning have keep track of own transformation matrices, doesn't seem complicated. got rid of immediate mode, meaning need use vbos or vaos (never know one, maybe both..) send pixel/normal/texture,etc. information shader program. don't way these objects works, think need put info them, , provide ofset of sort show separators between pixel,normal , texture coordinates. briefly explain how works (or send me link explains it)? tried wikipedia , googling it, found myself still not quite understanding them. another point know more shaders, i've never used them. i'm not going ask how code them or anything, needs go in there , opengl still you. more

javascript - How to prevent this regex that replaces hyphens with spaces from also replacing hyphens with additional hyphens? -

this regex: str.replace(/ +/g, '-').tolowercase(); will convert this: the dog jumped on lazy - chair into this: the-dog-jumped-over-the-lazy---chair how modify produces instead (only single hyphen): the-dog-jumped-over-the-lazy-chair i assume actual input "the dog jumped on lazy - chair", spaces around hyphen getting converted, since there's no other reason pattern should match there. try this: str.replace(/( +- *)|(- +)|( +)/g, '-').tolowercase(); that explicitly checks strings of spaces on either side of hyphens (the first pattern designed consume trailing space), consuming 1 hyphen in process. if hyphen exists surrounded spaces, hyphen included in match, when hyphen written, "replacement"; in case, spaces removed, , hyphen re-created replace operation because captured part of expression.

java - Is it possible to have destination view name configurable in spring mvc 3? -

code snippet this: @controller @requestmapping(value="/test") public class testcontroller { ........ @requestmapping(method=requestmethod.get) public string getcreateform(model model) { model.addattribute(new accountbean()); return "newtest"; } ......... "newtest" hard-coded view name. possible have configured in xml-style spring config file? thank you! i guess real question how configure properties of autodiscovered bean via xml. you can defining <bean> same name autodiscovered 1 have (when name of autodiscovered bean not specified, it's assumed classname first letter decapitalized): @controller @requestmapping(value="/test") public class testcontroller { private string viewname = "newtest"; public void setviewname(string viewname) { this.viewname = viewname; } @requestmapping(method=requestmethod.get) public string getcreateform(model

php - Magento: Adding a custom EAV attribute that autopopulates with its default value on entity creation -

is there way add custom eav attribute automatically gets set default value upon creation of new entity? i set eav_attribute.is_required 1 , eav_attribute.default_value 0 (the default value), it's not setting attribute automatically when create new object. by way, eav entity type shipment . i'm working on installation of 1.3.2.4, before sales data stored in flat tables. edit jonathan day asked "how adding attribute?" in moduledir\sql\module_setup\mysql4-install-0.1.0.php, have following code: $eav = new mage_eav_model_entity_setup('sales_setup'); $eav->addattribute('shipment', 'fieldname', array('type' => 'int')); i have code later versions of magento (after sales entities went eav flat tables): $w = $this->_conn; $table = $this->gettable('sales_flat_shipment'); $w->addcolumn($table, 'fieldname', 'int'); $w->addkey($table, 'fieldname', 'fieldname',

web services - Is it possible to search SharePoint metadata? -

when use search.asmx web service won't allow me search metadata. there way can this? below have come far query, errors out invalidpropertyexception every time run it. <?xml version="1.0" encoding="utf-8" ?> <querypacket xmlns="urn:microsoft.search.query" revision="1000"> <query domain="qdomain"> <supportedformats><format>urn:microsoft.search.response.document.document</format></supportedformats> <context> <querytext language="en-us" type="mssqlft"> <![cdata[ select title, rank, size, description, write, path portal..scope() "published" = 'yes' order "rank" desc ]]> </querytext> </context> <range><startat>1</startat><count>20</count></range> <enablestemming>false</enablestemming> <trimduplicates>true</trimduplicates> <ignore

rspec - Simple way to spec resources routes in rails -

is there short , dry way test routes generated resources :xxx ? as people have outlined before me, don't test routes. however, if have complex subdomain constraints in routes file want make damn sure going go right spot, i'd recommend (with touch of bias) reading article on testing rails requests .

Convert VBA in access to C# -

i have acces file forms create excel file multiple spreadsheets , have task converts c# application same thing vba code , has alot of code can convert vba code (e.g .dll file) enable me use vba methods in c# or anyway use vba code in c# instead of convert ? thanks, mohammed thabet zaky http://thabettech.blogspot.com/ if want yourself, possible reference com stuff. did application utilized vba (autocad). ended doing creating .net class referenced com interop , copied of code project. how created .dll file. refactored vba code c#. the copy , paste isn't seemless. need make adjustments. example thisworkbook, activesheet, , of items referenced automatically don't work automatically (because not out of excel's process). (at least us) better re-creating logic. here link reference material - http://au.autodesk.com/?nd=e_class&session_id=5084 . references autocad, doing in excel similar. hope helps.

c++ - algorithm moves the array elements -

i can not figure out algorithm task, maybe have idea? task: move array array in first half elements of odd lines , second elements of pair of lines. simplest option move elements array, make 1 using temp variable? input data array = {1,2,3,4,5,6,7,8} output data array = {2,4,6,8,1,3,5,7} is homework? if not, use std::stable_partition() : struct iseven { template<class t> bool operator()(const t& v) const { return v % 2 == 0; } }; int* arr = {1,2,3,4,5,6,7,8}; int* mid = std::stable_partition(arr, arr+8, iseven()); if homework, instructor expects write algorithm. if don't have maintain ordering in input sequence can rather efficiently: find first element doesn't satisfy predicate (i.e., odd ). find last element does satisfy predicate (i.e., even ) swap 2 elements. repeat, starting positions found, until 2 positions meet. the point 2 positions meet middle of partition, numbers stop , odd numbers begin. this how std::partition(

Javascript in list -

what's easiest way check see if number in comma delimited list? console.log(provider[cardtype]); //returns: object { name="visa", validlength="16,13", prefixregexp=} if (cclength == 0 || (cardtype > 0 && cclength < provider[cardtype].validlength)) { triggernotification('x', 'your credit card number isn\'t long enough'); return false; } else { if ($('.credit-card input[name="cc_cvv"]').val().length < 3) { triggernotification('x', 'you must provide ccv'); return false; } seems similar this question. just .split() csv , use inarray.

ASP.NET c# - RadioButtons not grouped -

i have gridview , in onrowdatabound callback adding new cell , cell i'm adding radiobutton. i've set groupname on radio button, can still select more 1 button @ time. how can make them grouped 1 radio button can selected within group. edit - code: // add radio button select if purchased address // set the home address of contact e.row.cells.addat(0, new tablecell()); radiobutton rbsetaddress = new radiobutton(); rbsetaddress.id = "rdsetaddress" + e.row.cells[2].text; rbsetaddress.groupname = "setaddress"; e.row.cells[0].controls.add(rbsetaddress); so i'm setting unique id , same groupname. asp.net not setting name attribute of input groupname. can select many radio buttons want. not want happen. want able select 1 , 1 in group identified groupname. http://www.codeproject.com/kb/webforms/how_group_rbuttons.aspx http://www.developer.com/net/asp/article.php/3623096/aspnet-tip-using-radiobutton-controls-in-

boost - How do you create a hash table in C++? -

i creating simple hash table in vs 2008 c++. #include <map> std::map <string, char> grade_list; grade_list["john"] = 'b'; i getting error: error c2057: expected constant expression what mean? boost library have better? thanks! #include <map> #include <iostream> #include <string> int main() { std::map<std::string, char> grade_list; grade_list["john"] = 'b'; std::cout << grade_list["john"] << std::endl; return 0; } this works great g++. should specify std:: before string in map declaration, did in code.

c++ - What happens when you bit shift beyond the end of a variable? -

if have variable (on stack) , left or right bit shift beyond end happens? i.e. byte x = 1; x >> n; what if x pointer memory cast byte , same thing? byte* x = obtain pointer somewhere; *x = 1; *x >> n; it not (necessarily) become zero. behavior undefined (c99 §6.5.7, "bitwise shift operators"): if value of right operand negative or greater or equal width of promoted left operand, behavior undefined. (c++0x §5.8, "shift operators"): the behavior undefined if right operand negative, or greater or equal length in bits of promoted left operand. the storage of value being shifted has no effect on of this.

JavaScript or C# -

i'm new development , want learn javascript , c#, 1 think best start with. want build web apps. they're not mutually exclusive. javascript client-side programming (dom manipulation, effects, ajax). c# server-side programming (database communication, oo, external services, etc). you should learn both. (and asp.net mvc while @ it).

What does script: do in powershell? -

i've seen syntax on variable before , not quite sure is: $script:foo = "bar" the syntax $script:foo commonly used modify script-level variable, in case $foo . when used read variable, $foo sufficient. example rather write this: verbose-script.ps1 $script:foo = '' function f { $script:foo } i write (less verbose , functionally equivalent): script.ps1 $foo = '' function f { $foo } where $script:foo crucial when want modify script-level variable within scope such function or anonymous scriptblock e.g.: ps> $f = 'hi' ps> & { $f; $f = 'bye';$f } hi bye ps> $f hi notice $f outside scriptblock did not change though modified bye within scriptblock. happened modified local copy of $f . when don't apply modifier script: (or global: ), powershell perform copy-on-write on higer-scoped variable local variable same name. given example above, if wanted make permanent change $f , use modifier script:

ReRender RichFaces element stored in a4j:included page -

i've got panelmenu in a4j:included xhtml page included in jsf page. when a4j:commandbutton hit in parent page, data changes in included file , i'd rerender element storing it. in example snippet below, controlpanel rerendered part of operation doesn't seem enough. when app first loads, looks rerender element in a4j:included page directly (if put in rerender attribute list) console warns it's not included yet. is there way round this? parent: <rich:toolbargroup location="right"> <h:panelgrid columns="1" id="controlpanel"> <a4j:region> <a4j:include viewid="#{mybacking.ctrlbox}"> <f:param name="targetidparam" value="controls" /> </a4j:include> </a4j:region> </h:panelgrid>

polyglot - What languages are used in 's 404 polygot?

currently, when user here gets 404, see following image: polygot-404.png http://sstatic.net/stackoverflow/img/polyglot-404.png which represents text: # define v putchar # define print(x) main(){v(4+v(v(52)-4));return 0;}/* #>+++++++4+[>++++++<-]> ++++.----.++++.*/ print(202*2);exit(); #define/*>.@*/exit() this looks suspiciously polyglottish . languages interesting in? side thought: me, or did find bug in prettify? line 4 print(202*2) valid in number of scripting languages perl, ruby, ecmascript (provided suitable implementation of print function) , python. line 2 there make line 4 valid in c , objective-c, maybe c++ , objective-c++. line 3 contains brainfuck, there seems else there. i have no idea line 1 v for. why not call putchar directly in line 2? so, suspect there's language somehow made valid through line. (at first thought whitespace, there's not enough whitespace in there valid whitespace program.) and line 5 contai

osx - Terminal in Mac: Put files in FTP Server -

i put files in ftp server using macintosh terminal. use command "put filename.txt" while doing text file utf-16 gets ftp server not retain doublebyte characters (e.g: japanese characters). believe because did not specify file format destination. what command used specify destination "file format" "type", "structure" etc. the default ftp type ascii. before put file, might first change type binary. here how looks @ prompt: ftp> binary 200 type set

javascript - Focus Input Box On Load -

how can cursor focus on specific input box on page load? is posible retain initial text value , place cursor @ end of input? <input type="text" size="25" id="myinputbox" class="input-text" name="input2" value = "initial text" /> there 2 parts question. 1) how focus input on page load? you can add autofocus attribute input. <input id="myinputbox" type="text" autofocus> however, might not supported in browsers, can use javascript. window.onload = function() { var input = document.getelementbyid("myinputbox").focus(); } 2) how place cursor @ end of input text? here's non-jquery solution borrowed code another answer . function placecursoratend() { if (this.setselectionrange) { // double length because opera inconsistent // whether carriage return 1 character or two. var len = this.value.length * 2; this.setselectionrange(len, l

sql - parse and replace in oracle -

i new sql/oracle, , wondering if there's easy way parse csv string , replace tokens string. for example, have string like param,value1,str1,param,value2,str3,param,value3 and want replace value after param constant so, string become param,constant,str1,param,constant,str3,param,constant thanks in advance. you can try regexp_replace select regexp_replace(regexp_replace(regexp_replace( str,'[^,]*','constant',1,3),'[^,]*','constant',1,9),'[^,]*','constant',1,15) (select 'param,value1,str1,param,value2,str3,param,value3' str dual); if have messy (like quoted values including commas) break. said regular expressions aren't strong point , should eb able better job. i presume know having rdbms oracle , storing data in such odd manner pretty poor idea. if not going convetional table/column structure, can use object relation features or xml.

iphone - How to use an IBOutlet from parent class? -

i'm working on ios , having trouble accessing iboutlet parent class, in case label life of character. my viewcontroller (parent) this: @interface opponentviewcontroller : uiviewcontroller { iboutlet uilabel *opponent_life; iboutlet opponentview *opponentview; } @end the opponentview (child) class character (image) reside , player touch interaction. when player touch opponentview label should refreshed. - (void)touchesbegan:(nsset *)touches withevent:(uievent *)event { } thanks. if i'm understanding question correctly update opponent_life when ever detect touch in opponentview . here 2 ways of assigning label view can used tocuhesbegan:withevent: 1. assigning label view in ib @interface opponentview : uiview { iboutlet uilabel *opponent_life; } in nib file opponentviewcontroller change type of view uiview opponentview , connect label outlet of view. 2. assigning label in viewdidload @interface opponentview : uiview { uilabel *opponent_l