Posts

Showing posts from August, 2011

Overriding Rails Error (Validation) Messages from Gems/Plugins -

is there accepted way of overriding error (validation) messages gem/plugin in rails? for example, i'm using activemerchant gem, , if puts in american express credit card number, selects 'mastercard', not-very-descriptive "type not correct card type" error. i can around doing this: def validate_card unless credit_card.valid? credit_card.errors.full_messages.each |message| if message =~ /is not correct card type/i errors.add_to_base "this credit card number invalid. please ensure selected correct type." else errors.add_to_base message end end end end but technique becomes unmaintainable , (at least in opinion) far 'best-practices'. similarly, unpack activemerchant gem , hack put in own custom error messages, seems unmaintainable require same hacks added future, unpacked, versions of activemerchant. in honesty, you're best bet either rewrite parts ...

Navigation menu with highlight in Asp.NET MVC? -

it's simple question. how did stackoverflow menu in asp.net mvc, highlight on page on . there no mvc special magic makes happen. i'm sure: if( httpcontext.current.request.path == "some menu url" ) or if( viewcontext_or_controllercontext.routedata.values["controller"] == "some value") is used someplace. you put code in 3 different locations ( view ( .aspx ), viewmodel, custom htmlhelper ) , require same bit of code.

c# - crystal-report problem + Oracle -

i have build c# program connect oracle , make report's using crystal-report. in computer work's excelent (when bind oracle) when run program on other computer - program work , see data on screen, when try see report crystal report error (problem connection oracle) why error ? connection , see data oracle on screen (in program) (my program in c# vs2008, oracle 11g) thank's in advance

c# - Webcam Capture Resolution issues -

i'm making own webcam timelapsing application, having issues webcams. 1 in particular advertises can take 5mp photos, runs native 320x240 (or horrible) feed i'm getting. i'm using code seems copy-and-pasted across web, incarnation i'm using access webcam here http://www.planet-source-code.com/vb/scripts/showcode.asp?txtcodeid=1339&lngwid=10 , uses avicap32 access webcam, call looking this mcaphwnd = capcreatecapturewindowa("webcap", 0, 0, 0, m_width, m_height, this.handle.toint32(), 0); sendmessage(mcaphwnd, wm_cap_connect, 0, 0); sendmessage(mcaphwnd, wm_cap_set_preview, 0, 0); i've tested 2 other webcams (one in built laptop, 1 oldie had kicking around) , both of seem respectable resolutions. i've modified webcam_capture code attempt take ridiculously high-res image //private int m_width = 320; //private int m_height = 240; private int m_width = 1600; private int m_height = 1200; //private int m_width = 3200; //private int m_heigh...

c# - DeviceAttached message never comes -

i trying develop c# application can communicate usb hid. have overriden wndproc method catches of wm_devicechange events , passes devicechange method method ondevicechange (this code borrowed jan axelson) looks this.... protected override void wndproc( ref message m ) { try { // ondevicechange routine processes wm_devicechange messages. if ( m.msg == devicemanagement.wm_devicechange ) { ondevicechange( m ); } // let base form process message. base.wndproc( ref m ); } catch ( exception ex ) { displayexception( this.name, ex ); throw ; } } for reason though, everytime plug in device, whether mouse or keyboard or device developing, hid's, value of wparam 0x7; i checked in dbt.h , value of 0x0007 ... #define dbt_devnodes_changed 0x0007 /* * message = wm_devicechange * wparam = dbt_querychangeconfig * ...

css - Float and margin -

i need know why following code: <!doctype html> <html> <head> <title></title> <style type="text/css"> * { margin:0px; padding:0px; } #right { float:right; } #content { margin-top:20px; } </style> </head> <body> <div id="right">a</div> <div id="content">b</div> </body> </html> applies 20px margin top @ #right div. two things missing: 1) clear:right; within #content. 2) widths need specified able apply clear:right without div's stacking. <html> <head> <title></title> <style type="text/css"> * { margin:0px; pad...

How to save R plot image to database? -

i'd save plot image directly database. is best way in r this: write plot image (png) filesystem read file written send file database via query (rodbc) ideally i'd combine steps 1 , 2 above write png image binary connection. r support this? no, graphics devices file-based, steps 1-3 correct. need fourth unlink temporary file it.

java - Max for Live vs. JVAP Tools -

i considering audio , midi application in max (or max live, really), totally comfortable in java, something seems attractive . have experience max? geared people not code, or goofy/friendly looking ui more efficient writing straight code in, say, java? also, has wrote vst plugin in java, , can share experiences there? max dataflow language. more familiar pd, same author. the advantage of dataflow programming style data dependencies explicit - can literally follow connections between subroutines visually, , displayed line on screen between them. difficulty order of operations less explicit, because 2 dimensional in layout, rather 1 dimensional textual code be. i of audio stuff in supercollider nowadays, quick sketch of audio idea, , building working rough model, pd works great. the main difficulty of programming in visual dataflow language comprehending order of operations. possible create multiple connections 1 outlet, behooves create explicit [trigger] object contro...

html - newbie question about anchor tag -

say have line in aspx file <li> <a href="../products/handout.pdf" target="_blank"> desktop , laptop installations </a> </li> my problem pdf file opened ie , how can force open in adobe acrobat ( associated app ) doable @ or decided ie , associated app somehow tia you can't. handled user's computer, not code.

jquery - Nested Each Criteria -

i have following timer periodically updates page: var refreshid = setinterval(function() { $(".content").each(function(i) { // stuff $(this).each(function(i) { // issue here }); }); }, 10000); within nested foreach loop, extract images, essentially, want match > .icons > .img, images inside of div of class "icons". the markup section following: <div class="content"> <div></div> <div class="icons"> <img id="dynamicimage12345" src="#"> </div> </div> how can accomplish this? you need line there: $("div.icons > .img", $(this)).each(function() { // code images }); it assumed using img class images can seen code. if not using class, can try instead: $("div.icons > img", $(this)).each(function() { // code images }); ...

xml - building an XDocument with a webclient downloaded string -

i using following methods download xml file private void loadxmlfile() { webclient xmlclient = new webclient(); xmlclient.downloadstringcompleted += new downloadstringcompletedeventhandler(xmlfileloaded); xmlclient.downloadstringasync(new uri("chart.xml", urikind.relativeorabsolute)); } void xmlfileloaded(object sender, downloadstringcompletedeventargs e) { if (e.error == null) { string xmldata = e.result; htmlpage.window.alert(xmldata); x2 = new xdocument(xmldata); } } i want use information inside xmldata build xdocument, trying in last line. not give errors program not work must not correctly making xdocument. assiging xml document directly x2 x2 = xdocument.load("chart.xml") works. but need through webclient. doing wrong here once you've got xmldata string, it's easy - use xdocument.parse : xdocument doc = xdocument.parse(xmldata); could elaborate why need use webclient rather xdocument.load though?...

C interview question---run-length coding of strings -

a friend of mine asked following question yahoo interview: given string of form "abbccc" print "a1b2c3". write function takes string , return string. take care of special cases. how experts code it? thanks lot there's more 1 way it, i'd run on input string twice: once count how many bytes required output, allocate output buffer , go again generate output. another possibility allocate front twice number of bytes in input string (plus one), , write output that. keeps code simpler, potentially wasteful of memory. since operation looks rudimentary compression (rle), perhaps it's best first implementation doesn't have output occupy double memory of input. another possibility take single pass, , reallocate output string necessary, perhaps increasing size exponentially ensure o(n) overall performance. quite fiddly in c, not initial implementation of function, in interview conditions. it's not faster first version. however it...

c# - Why Browsable attribute makes property not bindable? -

i'm trying use system.windows.forms.propertygrid . to make property not visible in grid 1 should use browsableattribute set false . adding attribute makes property not bindable. example: create new windows forms project, , drop textbox , propertygrid onto form1 . using code below, width of textbox not bound data.width : public partial class form1 : form { public form1() { initializecomponent(); data data = new data(); data.text = "qwe"; data.width = 500; bindingsource bindingsource = new bindingsource(); bindingsource.add(data); textbox1.databindings.add("text", bindingsource, "text", true, datasourceupdatemode.onpropertychanged); textbox1.databindings.add("width", bindingsource, "width", true, datasourceupdatemode.onpropertychanged); propertygrid1.selectedobject = data; } } the code data class is: publ...

security - How do I verify users of my PHP application? -

while installing application onto client's server, make sure client (or future developer them, etc) not copy application , place on other domains/servers/local servers. how can verify application running on server installed on? not want substantial lag in script every time runs, assume 'handshake' method not appropriate. i thinking script request php page on own server every time runs. send server server info , domain name, script can check against database of accepted clients. if request invalid, server handles work of emailing me details can follow up. should not slow down client's script isn't expecting response, , still operate on 'invalid' server until can investigate , follow them personally. if best method (or if there better), php call should making request server's script? file_get_contents , curl , similar seem retrieve response, don't need. update thank responses. understand php open source , should freely available edit. sh...

SQL Server 2008 VarChar To DateTime -

i have table unfortunately number of dates stored strings. i have number of reports cast them datetimes , filter them. working fine until today when of sudden i'm getting error "the conversion of varchar data type datetime data type resulted in out-of-range value." the dates stored in format of "yyyy-mm-dd" , valid. if run following sql statement select cast('2010-06-02' datetime) i expect "2010-06-02" of today i'm getting "2010-02-06" has changed way sql formats dates. i've had in regional settings on server , looks correct. what else causing this? an unambiguous way of getting conversion following: select cast(replace('2010-06-02', '-', '') datetime) and interpreted yyyymmdd, ignoring set dateformat ydm declaration or cultural settings database has.

How can I set flag CLIENT_MULTI_STATEMENTS for mysql2 ruby gem? -

or way run multiple queries in 1 function call in mysql2 gem? when setup new client can add flags client = mysql2::client.new(:host => 'localhost', :database => 'my_db', :username => "root", :password => "", :flags => mysql2::client::multi_statements)

iphone - OpenGLES 1.1 and 2.0, supporting both -

i have 2 separate renderers, 1 1.1 , 2.2 i have bunch of item s hold image information , texture handle generated whichever renderer using. items dumb objects , don't want introduce opengl specific functionality them. problem is, need store texture handle somewhere. store inside each item , handle of type gluint . if use gluint means including either gl.h es1/ or es2/. both typedef'd unsigned ints... ok use unsigned int? seems bad practice... example if opengl 3.0 came out , gluint different, item broken. any ideas? thanks reading. subsequent versions of opengl supersets of previous versions. opengl specific types meant hide underlying systems consistent across versions. example if have int 16 bit gluint might defined unsigned long . therefore say: go smallest common denominator (es1.1).

iphone - How to get each pixel position (Coordinate) of a Hollow Character drawn using Core Graphics? -

i using uiview subclass draw alphabet using core graphics.using code hollow characters drwan(by making stroke color- black color).here need each pixel(coordinate) position of character.please give me idea how each pixel point(only black point's pixel value) of hollow character. source code: /*uiview subclass method*/ - (void)drawrect:(cgrect)rect { //method draw alphabet [self drawchar:@"a" xcoord:5 ycoords:35]; } -(void)drawchar:(nsstring *)str xcoord: (cgfloat)x ycoord: (cgfloat)y { const char *text = [str utf8string];//getting alphabet cgcontextref ctx = uigraphicsgetcurrentcontext(); cgcontextselectfont(ctx, "helvetica", 40.0, kcgencodingmacroman); cgcontextsettextdrawingmode(ctx, kcgtextfillstroke); cgcontextsetstrokecolorwithcolor(ctx, [uicolor blackcolor].cgcolor);//to make character hollow-need these points cgcontextsetfillcolorwithcolor(ctx, [uicolor clearcolor].cgcolor);//fill color of character clear color...

php - Can't call static method from class as variable name? -

i'm using php 5.2.6. have strategy pattern, , strategies have static method. in class implements 1 of strategies, gets name of strategy class instantiate. however, wanted call 1 of static methods before instantiation, this: $strnameofstrategyclass::staticmethod(); but gives t_paamayim_nekudotayim . $> cat test.php <? interface strategyinterface { public function execute(); public function getlog(); public static function getformatstring(); } class strategya implements strategyinterface { public function execute() {} public function getlog() {} public static function getformatstring() {} } class strategyb implements strategyinterface { public function execute() {} public function getlog() {} public static function getformatstring() {} } class implementation { public function __construct( strategyinterface $strategy ) { $strformat = $strategy::getformatstring(); ...

c++ - Checking if an iterator is valid -

is there way check if iterator (whether vector, list, deque...) (still) dereferencable, i.e. has not been invalidated? i have been using try - catch , there more direct way this? example: (which doesn't work) list<int> l; (i = 1; i<10; i++) { l.push_back(i * 10); } itd = l.begin(); itd++; if (something) { l.erase(itd); } /* now, in other place.. check if itd points somewhere meaningful */ if (itd != l.end()) { // blablabla } i assume mean "is iterator valid," hasn't been invalidated due changes container (e.g., inserting/erasing to/from vector). in case, no, cannot determine if iterator (safely) dereferencable.

visual studio 2010 - VS2010 Publish Project -

i having trouble publishing windows 2003 server in vs2010. in past (with vs2008) had include address of server - there new publish options such "web deploy" , not settings not aware of. how publish working again? publish web deploy stopped working me also. server local use publish method: "file system" then have type target of windows 2003 server " target location box. i.e. \servername\wwwroot\project

java - EasyMock methods with parameters returning void -

my unit test framework replaces business service components mock objects using easymock.createmock(interace). these components accessed several layers down in class under test don't wish modify either interface definition nor class undertest. i use easymock.expect(...) drive behavoir of collaborating objects. works great long methods don't return void. how can drive behavior when there void results. ie. easymock.expect(object.method( easymock.isa(arg1) ).andanswer( new ianswer()){ public void anser(){ ... seomething meaningful arg1... }).anytimes(); you can use expectlastcall().andreturn("something"); . you don't mention version of easymock you're using, think feature has been around while anyway. read more in documentation .

algorithm - Generate a list of primes up to a certain number -

i'm trying generate list of primes below 1 billion. i'm trying this, kind of structure pretty shitty. suggestions? a <- 1:1000000000 d <- 0 b <- (i in a) {for (j in 1:i) {if (i %% j !=0) {d <- c(d,i)}}} this implementation of sieve of eratosthenes algorithm in r. sieve <- function(n) { n <- as.integer(n) if(n > 1e6) stop("n large") primes <- rep(true, n) primes[1] <- false last.prime <- 2l for(i in last.prime:floor(sqrt(n))) { primes[seq.int(2l*last.prime, n, last.prime)] <- false last.prime <- last.prime + min(which(primes[(last.prime+1):n])) } which(primes) } sieve(1000000)

tortoisesvn - Any way to get Tortoise Columns in Windows 7 or Vista -

i know explorer in vista , windows 7 no longer supports extensible column views, there way columns in windows 7 or vista. don't mind using alternate file explorer, not knowing things tag or branch on becoming more , more annoying (having switched xp windows 7). i don't think it's going implemented in foreseeable future. idea of using third-party file explorer not bad tortoisesvn windows shell extension , don't think they'll take path of writing plugins alternative file browsers. the subversion site lists a number of clients . of them gui tools , implement own file browsers (for instance, rapidsvn). can alternative and, of course, don't need replace tortoisesvn.

c# - Custom Indicator Control -

control (c# code): public partial class redgreenstatusindicator : usercontrol, inotifypropertychanged { public redgreenstatusindicator() { this.initializecomponent(); dependencypropertydescriptor dpd = dependencypropertydescriptor.fromproperty (archiverdetails.ardetailsproperty, typeof(archiverdetails)); dpd.addvaluechanged(this, delegate { this.objectvaluechanged(); }); status = false; } void redgreenstatusindicator_loaded(object sender, routedeventargs e) { } public bool status { { return (bool)getvalue(statusproperty); } set { bool old_value = status; setvalue(statusproperty, value); if ((old_value == true) && (status == false)) { hide_green(); show_red(); } if((old_value == false) && (status == true)) { hide_red(...

Which Eclipse version should I use for an Android app? -

i starting develop android applications. version of eclipse should use? i see there 11 versions. confused these: eclipse ide java developers eclipse classic 3.6.1 eclipse ide java ee developers pulsar mobile developers update july 2017: from adt plugin page , question must unasked: the eclipse adt plugin no longer supported, per this announcement in june 2015 . the eclipse adt plugin has many known bugs , potential security bugs not fixed. you should switch use android studio , official ide android. transitioning projects, read migrate android studio.

u2 - UniVerse RetrieVe how do I query a file for all of its columns' values? -

kind of follow my self-answered question finding column names. in universe can't query file of columns unless @ phrase in file's dictionary set of tables columns. if isn't, how query table of columns' values? so can total column listing (column name & display name) using: list dict file name this return listing of columns , display names. how query table of columns has? list file will query list file @id (@id thing in @). update found a blog -- living breathing person id using version of universe older mine!! complains same thing, says there no solution shy of updating @ of columns, please god prove him (dan watts) wrong. what if have 200 column table , want select * return 200 columns? sorry, you’ll have enter 200 column names in "@" record. , if add, delete or rename column, you’ll have remember edit "@" record. feel pain! cumbersome approach dates universe’s odbc driver, , suppose can’t change...

does fluent nhibernate support lazy loading of properties -

i have person class photo property , want load 1 property in lazy fashion. see regular nhibernate supports here . possible in fluent nhibernate use feature yes, add .lazy() fluent mapping.

r - Change the class from numeric to factor of many columns in a data frame -

what quickest/best way change large number of columns numeric factor? i used following code appears have re-ordered data. > head(stats[,1:2]) rk team 1 1 washington capitals* 2 2 san jose sharks* 3 3 chicago blackhawks* 4 4 phoenix coyotes* 5 5 new jersey devils* 6 6 vancouver canucks* for(i in c(1,3:ncol(stats))) { stats[,i] <- as.numeric(stats[,i]) } > head(stats[,1:2]) rk team 1 2 washington capitals* 2 13 san jose sharks* 3 24 chicago blackhawks* 4 26 phoenix coyotes* 5 27 new jersey devils* 6 28 vancouver canucks* what best way, short of naming every column in: df$colname <- as.numeric(ds$colname) further ramnath's answer, behaviour experiencing due as.numeric(x) returning internal, numeric representation of factor x @ r level. if want preserve numbers levels of factor (rather internal representation), need convert character via as.character() first per ramnath's ...

iphone - How to copy a XIB to another project? -

simple. have 2 projects in xcode. in 1 of them made .xib file , want copy project, save time redoing it. i can't drag other project, nor copy/paste command, nor copy/paste edit menu. any suggestions? go finder, find .xib file , copy directory of second project. uses add existing files add second project.

asp.net MVC: reroute to action in custom action attribute -

i'm trying create attribute can set on controllers action in can check if user in kind of role. know standard asp.net authentication possible, i'm not using that. so want accomplish this: [role("admin", "superuser")] public actionresult safecourse() i've constructed this: public class adminattribute : actionfilterattribute { public override void onactionexecuting(actionexecutingcontext filtercontext) { ans now..... want redirect user controller/action or if isn't possible view when / not in right role. i'm not in usual context (= controller) , i'm lost :) michel if make action filter implement iauthorizationfilter execute before other types ... in onauthorization(authorizationcontext filtercontext) set result. something like filtercontext.result = new redirectresult("/controller/actionyouwanttodirectto"); kindness, dan

keypress - Java while ( keyispressed ) -

how write code loops while left or right arrow key pressed? add keylistener swing component (assuming you're using swing), , mark keydown , keyup event. specifically, on keydown set boolean movingleft, , on keyup unset boolean. a better solution might use map of enumerations of directions booleans, make code cleaner. example: map<movedirection, boolean> movemap = new hashmap<movedirection,boolean>(); movemap.put( movedirection.left, false ); movemap.put( movedirection.right, false ); movemap.put( movedirection.up, false ); movemap.put( movedirection.down, false ); then put , get necessary.

caching - Prevent IIS from flushing cache -

i'm trying iis not flush cached data, loading of pages after period without requests can faster. far i've tried this, success: define infinite time "object cache ttl" property; unchecked on iis (version 6.0) option "recycle worker processes"; unchecked on iis option "shutdown worker processes after being idle.."; set cache activityperiod "0". what missing? there forcing cache flushed after time idle? if using asp.net, can control caching web.config settings or programatically. look here: http://www.15seconds.com/issue/040518.htm

scipy - Numpy: convert index in one dimension into many dimensions -

many array methods return single index despite fact array multidimensional. example: a = rand(2,3) z = a.argmax() for 2 dimensions, easy find matrix indices of maximum element: a[z/3, z%3] but more dimensions, can become annoying. numpy/scipy have simple way of returning indices in multiple dimensions given index in 1 (collapsed) dimension? thanks. got it! a = x.argmax() (i,j) = unravel_index(a, x.shape)

php - How to make a page for Custom Post Types in Wordpress 3.0? -

i have custom post types, such 'review'. can't seem find out how make section (e.g., www.mysite.com/reviews/) works blog home page, lists reviews instead of posts (with pagination , everything). i'd use separate template too. create page called reviews , create new template in theme folder called page-reviews.php. add necessary elements template , include query_posts in front of post loop. should this: <?php query_posts("post_type=reviews"); ?> <?php if (have_posts()) :?> <?php while (have_posts()) : the_post(); ?> <div class="post" > <h2><a href="<?php the_permalink() ?>" ><?php the_title(); ?></a></h2> <?php the_content(); ?> </div><!-- post ends --> <?php endwhile; ?> <?php else: ?> <p>sorry, not find looking for</p> <?php ...

web services - WCF calling webservice taking a long time -

i have wcf service (wcf_a ) calls wcf service (wcf_b) (currently hosting wcf_b on local machine credentials – windows service), wcf_b internally makes call webservice (ws01) hosted on iis. have created test client , call wcf_a -> wcf_b -> ws01. before making call (ws01) start timer , stop timer when webservice call comes , result assigned variable, flow below wcf_b 1) debug.writeline(“call webservice”) 2) starttimer 3) var result = ws01.function(xxxx) 4) stop timer 5) debug.writeline (timetaken) 6) debug.writeline(“call webservice came back”) the first time make webservice function call find between step (2) , step (5) takes long time. my initial thought proxy creation taking long time, running fiddler find call webservice made , comes expected results instantly. after not sure happens , process seems wait. (it takes close 2.5 minutes hit step (5). once call made if turn around , make same call different parameters webservice step (5) hit in around 1.1 sec (...

Options, Settings, Properties, Configuration, Preferences — when and why? -

there several words similar (in sense) meaning: options, settings, properties, configuration, preferences english not native language. explain difference in simple english please? think following template useful: use xxx in gui in order let people change behaviour of application (maybe preferences or settings?) use yyy in gui in order let people change parts of object (perhaps properties or options?) use zzz in code ... what best practices? tricky, this, there's no 1 single consistent style followed applications. (broadly) synonyms. in truth doesn't matter long expected audience understands mean. the biggest difference between properties, affect component or object, , others, affect whole application. following approximate lead visual studio , other microsoft products: properties represent characteristics of single component or object in application. options alter global ways application works. microsoft products use custo...

Java generics question - Class<T> vs. T? -

i'm using hibernate validator , trying create little util class: public class datarecordvalidator<t> { public void validate(class<t> clazz, t validateme) { classvalidator<t> validator = new classvalidator<t>(clazz); invalidvalue[] errors = validator.getinvalidvalues(validateme); [...] } } question is, why need supply class<t> clazz parameter when executing new classvalidator<t>(clazz) ? why can't specify: t in classvalidator<t>(t) ? validateme.getclass() in classvalidator<t>(validateme.getclass()) i errors when try both options. edit : understand why #1 doesn't work. don't why #2 doesn't work. error #2: cannot find symbol symbol : constructor classvalidator(java.lang.class<capture#279 of ? extends java.lang.object>) location: class org.hibernate.validator.classvalidator<t> note: hibernate api method ( here ) if validate method yours, can...

.net - What possible errors could I expect to recieve in System.Net.Mail.SendCompletedEventHandler? -

i using sendasync method send emails out. different errors possibly returned in asynccompletedeventargs in sendcompletedeventhandler? there recommended practices handling these? anything possible here, might trying talk particularly cranky smtp server. can't handle errors in code, code can't change way server works. takes human figure out why server doesn't message. error codes can returned smtp server otherwise documented, review smtpstatuscode enum .

json - UTF-8 to Unicode using C# -

help me please. have problem encoding response string after request: var m_refwebclient = new webclient(); var m_refstream = m_refwebclient.openread(this.m_refuri); var m_refstreamreader = new streamreader(this.m_refstream, encoding.utf8); var m_refresponse = m_refstreamreader.readtoend(); after calling code string m_refresponse json source substrings \u041c\u043e\u0439 . it? how encode cyrillic? tired after lot of attempts. corrected am missing here? what it? "\u041c\u043e\u0439" string literal representation of Мой . don't have more, strings unicode, you've got cyrillic already. (unless mean literally have sequence \u041c\u043e\u0439 , ie. value "\\u041c\\u043e\\u0439" . wouldn't result of encoding error, happening @ server, example returning json string, since json , c# use same \u escapes. if that's what's happening use json parser.)

asp.net mvc - Keeping a controller thin (too many action methods) -

i'm working on first real asp.net mvc project , i've noticed controller i've been working in getting rather large. seemingly goes against best practice of keeping controllers thin. i've done job keeping business logic out of controllers. use separate layer that. each action calls method in business layer , coordinates end result based on whether or not modelstate valid. that said, controller has large number of action methods. intuitively, break controller down sub-controllers don't see easy way that. break controller down separate controllers loose hierarchy , feels bit dirty. is necessary refactor controller large number of thin actions? if so, best way this? first, when hear it's keep controller code minimum, refers keeping each action method thin possible (put logic instead business classes, not views , viewmodels.) seems you're doing this, great. as having "too many" action methods, judgment call. sign of organiz...

testing - Ruby on Rails - Accessing data in :has_many => :through association -

i'm trying grips type of association in rails i have following 3 models: user has_many: 'memberships' has_many: groups, :through => 'memberships' membership belongs_to: 'user' belongs_to 'group' group has_many: 'memberships' has_many: 'users', :through => 'memberships' i have before_create method adds new user default user group. user.rb attr_accessor :group_ids before_create :add_user_to_default_group after_save :update_groups def add_user_to_default_group self.group_ids = [1] end #after_save callback handle group_ids def update_groups unless group_ids.nil? self.memberships.each |m| m.destroy unless group_ids.include?(m.group_id.to_s) group_ids.delete(m.group_id.to_s) end group_ids.each |g| self.memberships.create(:group_id => g) unless g.blank? end reload self.group_ids = nil end end i'm trying wri...

Dictionary(string -> tuple) in .NET 3.5? -

i wondering if there's way create dictionary using anonymous type values. { { "first", {1, true} }, { "second", {2, false} }, } i want use in .net 3.5, there's no vanilla implementation of tuple<...> available. any suggestions? what use (though ugly , assumptive) is: dim dict dictionary(of string, object()) dict.add("first", new object() {1, true}) dict.add("second", new object() {2, false}) obviously, doesn't provide compiler support type- , bounds-checking tuples, in pinch works.

php - Automatic update of MYSQL table according to date -

i have mysql table holds events information. need mechanism updates status of each event according date ("over" if past date). what´s best way such thing? update status of event when user logs in (useless routine users), create sort of internal task (like cron job?), or other way. right now, status of event updated when creator logs in. works user see event "scheduled" until creator logs in, if date past. im using php way. thanks i recommend updating status time status requested. or better yet, don't store status in database @ all, compute each time it's requested based on other variables. way whenever have table list status or request status, take event date, compare today's date, , send them "not started", "ongoing", or "over". unless of course need more possible statuses ("planning", "preparing", "setting up", etc). either need scheduled dates/times each of these statuses or ...

objective c - Location-based features in iOS -

not sure if possible, wanted check out. i want access gps features in ios, on ipad through app. goal able see else nearby running app well. @ possible or practical implement? entirely. check out documentation on core location. typically way app yours works devices running app submit location script on server, query script other devices nearby.

objective c - How do I model relative scores between entities in CoreData -

i new coredata , struggling work out correct way model particular relationship. have entity called 'friend' few attributes such 'name', 'age', 'sex' etc. i able model score between 2 instances of friend , having trouble getting head around best way this. for example 3 friends called a, b , c, there may scores so: a <-> b: 3 <-> c: 2 b <-> c: 4 or in matrix form: b c 0 3 2 b 3 0 4 c 2 4 0 the best have come have 'score' entity 'value' integer attribute , 2 relationships 'frienda' , 'friendb' - if correct approach how should model inverse relationships on friend entity? many in advance help! your idea of score entity best can think of without more detail entire design. inverse relationship simple enough. create many-to-many relationship between friend , score. on score side set min , max count 2. set friend side no min , no max. this assuming order of friends in rela...

jmeter : while controller and csv -

i unable execute requests list of url given in csv file. the sequence of execution follows: thread group http authorization manager while controller csv reader http sampler summary results the questions specify in while controller list of url's specified in while controller invoked? i tried both javascript , beanshell evaluation: ${__beanshell(!"${url}".equals("end"))} and ${url} - yet not records processed - idea how debug issue? the issue related firewall authentication. there firewall authentication done prior accessing pages - 1 time activity. however, jmeter, authentication has part of script otherwise pages not accessible after period of time. so work around first have firewall authentication done part of jmeter script , proceed page access.

java - How does one automate configuration of Eclipse? -

a team working on project tend need common configuration of eclipse. includes general configuration , project specific configuration. example, generally, might wish share indentation, installation of plugins (say m2eclipse, testng, egit, spring support). further, project, might want specific plug-in configurations (e.g., m2eclipse, setting custom maven settings file, configuring maven targets eclipse build events), or custom eclipse target platform, or set-up custom launchers. currently, team executes series of manual steps try , configured correctly. tedious, error-prone , difficult new developers follow. instructions tend out-dated. to extent can sort of configuration automated? how should done? the simplest thing available without modifications have common preferences file (export->general->preferences), can load. works best same java installations present. it possible drop in plugins these days have not worked it. might beneficial create local reposi...

xml - in regards of finding all nodes that have an attribute that matches a certain value with scala -

i saw following example disccussed here previously, goal return nodes contain attribute id of x contains value y: //find nodes attribute "class" contains value "test" val xml = xml.loadstring( """<div> <span class="test">hello</span> <div class="test"><p>hello</p></div> </div>""" ) def attributeequals(name: string, value: string)(node: node) = { node.attribute(name).filter(_==value).isdefined } val testresults = (xml \\ "_").filter(attributeequals("class","test")) //prints: arraybuffer( //<span class="test">hello</span>, //<div class="test"><p>hello</p></div> //) println("testresults: " + testresults) i using scala 2.7 , everytime return printed value empty. on ? sorry if copying thread... thought more visible if posted new 1 ? a...

sql - MySQL: Average and join two queries -

i have 2 queries: select s.id id, g.id group_id, g.nazwa group_name, s.nazwa station_name, s.szerokosc szerokosc, s.dlugosc dlugosc, s.95 p95, s.98 p98, s.diesel diesel, s.dieseltir dieseltir, s.super98 s98, s.superdiesel sdiesel, s.lpg lpg, s.ulica ulica, s.kodpocztowy kod_pocztowy, s.miasto miasto, w.id wojewodztwo_id, w.nazwa wojewodzto_nazwa, k.id kraj_id, k.kod kraj_kod, k.nazwa kraj_nazwa, s.data date_mod, s.active active stacje_main s join stacje_grups g on (s.grupa=g.id) join wojewodztwa w on (s.wojewodztwo=w.id) join kraje k on (w.kraj=k.id) s.data > 0; and select avg(rr.vote) average, count(rr.station_id) counter stacje_ratings rr group rr.station_id; in second query not id (station_id) present, , doubled. join station_id id, , give average value of rate each id. the problem when no rate, value in question in average , counter have 0. when combined these queries see id, has present station_id. want see all....

java - Required to solve this regex issue -

i need characters between particular expression. example below sample document sample document. $condtion first text can repeated many times until while called. $endcondition i need characters between $condtion , $endcondition while(matcher.find()) loop getting called 3 times. possible handle in regular expression. 1 condition must satisfied. if condition satisfied other conditions need not called. your expression matches either \\#if\\s*\\((.*?)\\)(.*?)\\#elseif or #else or #endif . if want or around closing statement of if block have put group (?:elseif|else|endif) .

registry - Windows Context menu shell icon -

i have created new windows shell context menu item using registry , keys hklm\software\classes\folder\shell\appname hklm\software\classes\folder\shell\appname\command now want add icon command. how that? windows 7 added support icons (and submenus) static (registry) verbs, add reg_sz value named "icon" under hkcr\%progid%\shell\%verb% on <= vista need shell extension implements icontextmenu , see this blog entry information icon/bitmap formats can use...

Why can't Python decorators be chained across definitions? -

why arn't following 2 scripts equivalent? (taken question: understanding python decorators ) def makebold(fn): def wrapped(): return "<b>" + fn() + "</b>" return wrapped def makeitalic(fn): def wrapped(): return "<i>" + fn() + "</i>" return wrapped @makebold @makeitalic def hello(): return "hello world" print hello() ## returns <b><i>hello world</i></b> and decorated decorator: def makebold(fn): def wrapped(): return "<b>" + fn() + "</b>" return wrapped @makebold def makeitalic(fn): def wrapped(): return "<i>" + fn() + "</i>" return wrapped @makeitalic def hello(): return "hello world" print hello() ## typeerror: wrapped() takes no arguments (1 given) why want know? i've written retry decorator catch mysqldb exception...

Android: Bitmap recycle() how does it work? -

lets have loaded image in bitmap object like bitmap mybitmap = bitmapfactory.decodefile(myfile); now happen if load bitmap like mybitmap = bitmapfactory.decodefile(myfile2); what happens first mybitmap garbage collected or have manually garbage collect before loading bitmap , eg. mybitmap.recycle() also there better way load large images , display them 1 after recycling on way the first bitmap not gc'ed when decode second one. gc later whenever decides. if want free memory asap should call recycle() before decoding second bitmap. if want load big image should resample it. here's example strange out of memory issue while loading image bitmap object .

PHP session_cache_limiter() private and nocache HTTP Expires date question -

if @ php doc function session_cache_limiter() , see if cache_limiter parameter set private or nocache expires http header set const date (thu, 19 nov 1981 08:52:00 gmt). understand date in past avoid caching, why date/time in particular? it's not 0 date, guess kind of easter egg. if it's kind of dummy value in past, can change else (still in past) , still have private/nocache mechanism still working? it birthday of person contributed code: diffs: http://cvs.php.net/viewvc.cgi/php-src/ext/session/session.c?r1=1.80&r2=1.81 http://www.phpbuilder.com/lists/php3-list/199911/3159.php to change it, preferable set headers manually, example nocache sets this: expires: thu, 19 nov 1981 08:52:00 gmt cache-control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 pragma: no-cache but still do: session_cache_limiter('nocache') header('expires: thu, 1 jan 2000 00:00:00 gmt'); header replace existing header same name (by default). ...

JavaScript constructors -

i not understand quite how apply constructors on object creation method: var myobject = { ... }; i know can do: var myobject = new object(); myobject.prototype.constructor = function(props) { ... } or... function myobject(prop1, prop2) { this.prop1 = prop1; ... } can this? var myobject = { myobject: function(prop1, prop2) { ... } } no, can't, create (static) method on myobject -- myobject.myobject . in javascript, constructor is class. class methods , properties created either inside constructor using this. or adding prototype (outside of constructor) using myclass.prototype. . can think of "objects" in javascript static classes.

rails how to display data or retrieve values after find -

i did find on model , got following >> @addy => [#<address id: 3, street: "some street", housenumber: nil, created_at: "2010-01-20 06:09:52", updated_at: "2010-01-20 06:09:52", address_id: 16>] now how retrieve values? if want street? @addy.street not work netiher @addy[:street] what if had list of @addy's , wanted loop through them show street each? @addy.first.street should work, list of adress classes containing 1 member. for displaying each street more adresses in list: @addy.each |address| puts address.street end or list_of_streets = @addy.map { |address| address.street } edit: when have problem identifying class have, check object.class . when use object in irb, see output object.inspect , doesn't have show class name or can spoof informations. can call object.methods , object.public_methods . and remember in ruby class instance (of class class). can call @addr.methods instance methods ,...

html - jQuery ui.datepicker on 'select' element -

i have select element couple of dates want give possibility of picking date datepicker have following code displays calendar icon next select field. <select name="birthday" > <option value="${merge0.birthday}">${merge0.birthday}</option> <option value="${merge1.birthday}">${merge1.birthday}</option> </select> <input type="hidden" id="bday_icon" /> then, datepicker script $("#bday_icon").datepicker( { changemonth: true, changeyear: true, showon: 'button', buttonimage: 'cal/images/calendar.gif', buttonimageonly: true, onselect: function(datetext, inst) { var field = document.getelementsbynamebyname("birthday"); var opt = document.createelement('option'); ...

css - Match width of different elements on web page. HTML IE7 & IE8 -

in following code need match width when shrinking window : <div style="background-color:blue;">the title</div> <table> <tr> <td> column title </td> <td>content</td> <td>column title2</td> <td>content 2</td> </tr> </table> this little example of page, involve more divs , tables. when shrink window table , div shrink need div shrink more table, , make page ugly. is there way stop div shrinking when table can't shrink more? i tried min-with , not work, , asked similar apparently there isn't apart of javascript. could of give me solution other javascript? thanks in advance. cesar. i not have ie7+ test this, in opera works when put html in outer div block. outer div block same table. @ point not fit browser window more, outer block has width , in title div keeps same width outer block. <div style="background-color:red;"> ...

android - Child headers for ExpandableListView using CursorTreeAdapter -

how create header every expanded childview without affecting underlying data , onclick / onlongclick events on childview . below skeleton implementation of expandablelistview adapter: private class eadapter extends cursortreeadapter { public eadapter(cursor cursor, context context) { super(cursor, context); } @override protected void bindchildview(view view, context context, cursor cursor, boolean islastchild) { } @override protected void bindgroupview(view view, context context, cursor cursor, boolean isexpanded) { } childholder childholder; @override protected view newchildview(context context, cursor cursor, boolean islastchild, viewgroup parent) { view.settag(childholder); registerforcontextmenu(view); return view; } groupholder groupholder; @override protected view newgroupview(context context, final cursor cursor, boolean isexpanded, viewgroup parent) { view.settag(groupholder); return view; } @overr...

winapi - The biggest size of Windows Cursor -

i have cursor size size 128x128, when used loadcursor load , show it, has 32x32. api can make correctly? seems ms resize it. thanks. windows xp not include system cursors larger 32x32. (if larger cursors included, stretched down 32x32 when standard apis load cursors.) for high-dpi systems, windows xp has adjusted sm_cxcursor , sm_cycursor values 64x64 pixels. size adjustment prevent mouse pointer virtually disappearing because small used. although other aspects of system scale dpi, mouse pointer not scale. microsoft not try enforce dpi-independent size mouse pointer. the system provides setsystemcursor api function can use change system cursor specific categories. can use function set cursor of size. however, must call function programmatically, , can use set cursor specific category. cannot use make cursors on system same size. http://support.microsoft.com/kb/307213

jquery - assign value to global variable in javascript -

i want assign value global variable in javascript jquery ajax function. var truefalse; $.ajax({ type: "get", url: "url", data: "text=" + $("#text").val(), success: function(msg) { if(msg.match(/ok/) != null) { truefalse = "true"; } else { truefalse = "false"; } } }); return truefalse; here need value of truefalse success function. thanks v.srinath if can't change application logic, have create "synchronous" ajax request (by setting async:false in $.ajax options), wait until "get" has executed , return value caller. otherwise, should rewrite code success function calls callback function can proceed whatever has done.

multithreading - Kill child process from main app -

i have delphi server run python scripts in background (they run similar " python sync.py **params** "). this scripts can things connect external servers, open ssh connections , scary stuff can hang. i need detect if hang, , kill it. also, if server closed, , want kill process (if not, delphi server hang, disappear desktop invisible in background. cause issues later if server executed again). by first try not work. process killed if close app, server hang. so question if exist more reliable/better way kill child process. now, save handle , gettickcount , this: "handle=tickcount", running ttimer each 4 seconds , see if process timeout: procedure tfrmmain.checkprocess(sender: tobject); var i: integer; fecha:tdatetime; start, stop, elapsed,handle : cardinal; begin stop := gettickcount; := (fprocesos.count - 1) downto 0 begin start := strtoint( fprocesos.valuefromindex[i] ); elapsed := stop - start; //milliseconds //esta mue...

building a 'simple' php url proxy -

i need implement simple php proxy in web application building (its flash based , destination service provider doesn't allow edits crossdomain.xml file) can php gurus offer advice on following 2 options? also, think, not sure, need include header info well. thanks feedback! option1 $url = $_get['path']; readfile($path); option2 $content .= file_get_contents($_get['path']); if ($content !== false) { echo($content); } else { // there error } first of all, never ever ever include file based on user input. imagine happen if call script this: http://example.com/proxy.php?path=/etc/passwd then onto issue: kind of data proxying? if kind @ all, need detect content type content, , pass on receiving end knows it's getting. suggest using http_request2 or similar pear (see: http://pear.php.net/package/http_request2 ) if @ possible. if have access it, this: // first validate request actual web address if(!preg_match(...