Posts

Showing posts from February, 2011

variables - Where should I store calculated values I use throughout my application in Rails? -

i have following variable definition: @monday = (time.now).at_beginning_of_week i use in different models, controllers, , views. where can define (and how should define -- @@? ) can define once , use throughout rails application? should in environment.rb? should @@? i add application controller: before_filter :load_date def load_date @monday = (time.now).at_beginning_of_week end so accessible in of yours controllers , views. if want use in models, need param, on example scopes. controller place should pass variable model: @models = mymodel.before_date(@monday) i don't think need have 1 instance of variable whole application. initializing quite simple. not when initialize , don't use it. me hard imagine need in of controllers , actions. the other way can define class: class mydate def self.get_monday time.now.at_beginning_of_week end end and put in config/initializers (probably there better place put it). can access anywhere in a...

Finding the longest down sequence in a Java array -

given array int [] myarray = {5,-11,2,3,14,5,-14,2}; i must able return 3 because longest down sequence 14,5,-14. what's fastest way this? ps: down sequence series of non-increasing numbers. just make 1 pass through list of numbers. pseudocode: bestindex = 0 bestlength = 0 curindex = 0 curlength = 1 index = 1..length-1 if a[index] less or equal a[index-1] curlength++ else //restart @ index since it's new possible starting point curlength = 1 curindex = index if curlength better bestlength bestindex = curindex bestlength = curlength next note: can ditch line containing bestindex or curindex if don't care knowing subsequence occurs, seen in gary's implementation.

objective c - Reducing the memory footprint of a function with a lot of autoreleased variables? -

i'm still wrapping head around of nuances of memory management in objective-c, , came following case i'm unsure about: + (nsdecimalnumber*)factorial: (nsdecimalnumber *)l { nsdecimalnumber *index = l; nsdecimalnumber *running = [nsdecimalnumber one]; (; [index intvalue] > 1; index = [index decimalnumberbysubtracting:[nsdecimalnumber one]]) { running = [running decimalnumberbymultiplyingby: index]; } return running; } here decimalnumberbymultiplyingby , decimalnumberbysubtracting creating lot of nsdecimalnumbers, autoreleased understand it, worry until time containing program hanging unto awful lot of memory. should introducing autorelease pool somewhere? (if where?) going have noticeable effect on performance (when compared side effect of memory in use)? is autoreleasing right mechanism use here? should @ breaking loop apart , manually releasing memory i'm done it? it's n00b question, i'm trying flavour best practice...

will paginate - paginate_by_sql, next page error -

i'm using will_paginate (3.0.pre2) rails 3.0.0.rc. first page pulls fine when go page 2, returns nothing because query page 2 not being set correctly will_paginate. controller: page = params['page'].blank? ? 1 : params['page'] @posts = post.paginate_by_sql (['select * foo_table ids = ?', params[:ids]], :page=>page, :per_page=>50) @pag_params = {:ids=>params[:ids]} view: <%= will_paginate @posts, :params=>@pag_params %> link page 2 is: http://localhost:3000/posts/search?page=2&ids=1 logs show clause show incorrect (ids = 'search') when should (ids = '1') select * `foo_table` (ids = 'search') what missing query page 2 can corrected? talked developer of of will_paginate , found out best way attack using scoped_by_column_name(...column_value...).paginate(...conditions...) hope helps someone. :)

cryptography - CryptHashData equivalent for C#? -

i trying translate existing c++ code c#. have code calls crypthashdata 3 times on same hcrypthash . documentation says "this function , crypthashsessionkey can called multiple times compute hash of long or discontinuous data streams." which want achieve in c#. unfortunately, md5.computehash() doesn't appear have way build on existing hash. am missing something, there c# api achieve this? instantiate instance of hash class , use transformblock , transformfinalblock : byte[] part1 = //... byte[] part2 = //... byte[] part3 = //... var hash = new md5cryptoserviceprovider(); hash.transformblock(part1, 0, part1.length, null, 0); hash.transformblock(part2, 0, part2.length, null, 0); hash.transformfinalblock(part3, 0, part3.length); byte[] res = hash.hash;

database - Improve the speed of locating a row (integer columns) -

i have 15 integer column 5,000,000 rows in table. given input record containing 15 integers need compare input record 5,000,000 record table , obtain matching rows. note1: integers within row unique note2: order of columns matching , input record not important. example: 1, 10, 15, 23, 9, 22, 99, 11, 19, 32, 45, 21, 76, 12, 33 , 33, 10, 15, 99, 11, 19, 32, 45, 21, 23, 9, 22, 76, 12, 1 should yield match result is possible implement hashing function / bitwise operation generate unique index each row. function can return same index 2 rows if values in records same this isn't much, should started. you want hash function generates few collisions possible; has commutative (ie: order in add numbers hash irrelevant). can accomplish using combination of xor's , bit shifts (see page ). you might want store hash in column. can hash input looking , lookup hash on database. note hashes allow false positives, you'd still need check if candidate rows want (ie: sor...

apache - Handle HTTP POST with PHP -

i struggled half day , came conclusion can't done. threw away php scripts , rewrote in perl , worked right start way wanted work. still, want find out if such trivial task can done correctly in php. question: have arbitrarily long (in size , time) file upload (via raw data post) , need save file php. way works php fist processes posted data, saves file , execution of script begins (my file upload lasts 30 minutes). if tried fopen("php:/stdin" or php://input) still worked retarded way. need able process incoming posted data in chunks sequentially. tried: 1) modphp, 2) php-cgi, 3) php-cli run cgi executable. though php-cgi meant used cgi, still preprocesses posted data (so $_post becomes available) , doesn't work same way regular momphp. cli version run cgi script doens't work, can't read php://stdin or php://input @ all! whatever tried, nothing worked me , came conclusion can't done php... or can? thanks of course php can it. uploaded files s...

Channels for Java, Java EE, C#, asp.net and SOA -

what freenode irc channels java, java ee, c#, asp.net , soa? available servers: freenode servers java: ##java c#: ##csharp asp.net: ##asp.net looks bit more tricky find soa-channel though. search irc way search channels on either global or specific networks. google works quick search keywords, example; "java irc freenode".

python - How to use thread search method in imaplib? -

i want create gmail client ability view emails conversations (threads). in imaplib, there method: imap4.thread(threading_algorithm, charset, search_criterion[, ...]) think solution. has experience using it? please give example. thanks. that method wrapper imap4rev1 extension thread command. have @ link describes how imap command works: http://tools.ietf.org/search/rfc5256 however, i'm not sure gmail implements thread command. if does, should list 'thread=' among capabilities.

c# - converting/Casting ISingleResult - List values to DataTable without Looping -

i using linq sql . when storedprocedure executing result ll returned in form of imultipleresults . i converting isingleresults , can casted list . so need convert datatable can bind dataset , pass values ui. but want such method can convert without loop . please body me. for clarification contact me. thanking you. first might want see if cast list bindinglist, or this: bindinglistx = new bindinglist(of elementx)(queryresult.tolist()) you might able bind that. if doesn't work though here's question: want not use loop in code @ all, or not see loop in code? possible create extension function conversion: public static class helperfunctions { public static void map<t>(this ienumerable<t> source, action<t> func) { foreach (t in source) func(i); } public static datatable todatatable<t>(this ienumerable<t> source) { var dt = new datat...

c# - Size of a subversion directory -

i have project takes checkout in directory under subversion sharpsvn. want show checkout process in progress bar, need know size of board, property or decision of library return size of directory? thanks in advance! i managed size of download directory subversion through checkout, variable "total_size" overall size of download. display download process in progressbar should capture bits downloaded compare total , assign them progressbar, not how data ... has done similar? show me property , has used code? //this collection contain property collections each node system.collections.objectmodel.collection<svnpropertylisteventargs> proplist; //this can specify arguments svn proplist svnpropertylistargs args = new svnpropertylistargs(); args.depth = svndepth.infinity; //this method executes svn proplist client.getpropertylist(targetsource, args, out proplist)...

javascript - "var variable" returns undefined? -

when run "var variable = true;" in chrome console "undefined" returned: > var variable = true; undefined but when run without "var" returns true: > variable = true; true why returning "undefined" "var"? it's confusing cause expected return true. the first statement, while second expression. while not quite same, similar c's rules: // statement has no value. int x = 5; // expression... x = 10; // ...that can passed around. printf("%d\n", x = 15);

tsql - T-Sql Algorithm Question -

i have t-sql statement follows; insert table1 select * table2 i want know running sequence. insert waits select statement finish before starting or starts asap select statement starts returning values , expects new records select statement continue. this plain stored procedure , no transactions used. to echo @codebymoonlight's answer, , address comment there: physical considerations (including specifics of locking) subordinate logical instructions specified query. in processing of insert ... select statement, logically speaking select carried out produce resultset, , rows of resultset insert ed. fact in case source table , target table same table irrelevant. i'm sure specifying nolock or tablock in case apply select , if that's position them. consider example statement, makes no sense if read in 'imperative' way: update sometable set column1 = column2, column2 = column1 with imperative, rather set-based, understanding, statement mig...

python - Add repository url to install_requires in project's setup.py -

i'm developing django app depends on app in private bitbucket repository, example ssh:/...@bitbucket.org/username/my-django-app. possible add url list of install_requires in setup.py? tried various possibilities, none worked. i don't know if can setuptools, it's possible distribute (wich can consider new setuptools). check dependencies aren’t in pypi sections in distribute documentation .

Drupal Views and Content Taxonomy -

i have been searching morning , have yet come across solution problem.. problem is: have created cck content type using content taxonomy module (which allows me use vocabulary content). user asked select his/her preferred cultures. in simple terms form holding series of checkboxes user merely selects preferred cultures. problem comes when wish display selected cultures user them sort top 5 cultures. the sorting bit can using draggable views. displaying users selected cultures im finding difficult. sorry novice of question.. been 1 of days. you should use relationships. howto: views 2 relationships : http://drewish.com/node/127 user relationships module: http://drupal.org/project/user_relationships http://www.drupalforusers.com/content/using-views-2-relationships using drupal's views relationships : http://www.drupalove.com/drupal-video/using-drupals-views-relationships also may need patch: http://drupal.org/node/241078 . or module allows make backre...

regex - php regular expression help -

i have string. there need 1 word. word between space , point. example ' 'word. if find many same pattern words, need first word. as far understand, try : /\s(\w+)\./ preg_match('/\s(\w+)\./', 'abc. def. ghi.', $m); echo $m[1],"\n"; output: def

database - "if, then, else" in SQLite -

without using custom functions, possible in sqlite following. have 2 tables, linked via common id numbers. in second table, there 2 variables. able return list of results, consisting of: row id, , null if instances of 2 variables (and there may more two) null, 1 if 0 , 2 if 1 or more 1. what have right follows: select a.aid, (select count(*) w3s19 b a.aid=b.aid) num, (select count(*) w3s19 c a.aid=c.aid , h110 null , h112 null) num_null, (select count(*) w3s19 d a.aid=d.aid , (h110=1 or h112=1)) num_yes w3 so requires step through each result follows (rough python pseudocode): if row['num_yes'] > 0: out[aid] = 2 elif row['num_null'] == row['num']: out[aid] = 'null' else: out[aid] = 1 is there easier way? thanks! use case...when , e.g. case x when w1 r1 when w2 r2 else r3 end read more sqlite syntax manual (go section "the case expression").

java - How to setup root url for Restlet -

at root of restlet web service, this: http://localhost:8080/foobarwebservice/ my page blank... i suspect when user/programmer wants find out resources available on webservice , how should accessed e.g. url format , parameters pass. should here - rest form of wsdl think??? called wadl what do? there way of auto generating root resource based on resources publishing? don't think having blank page right. making sense anyone???? :) please bear me it's been on year since looked @ stuff. restlet doesn't enforce conventions, general rest principles, , http spec. so if want have resource @ url, , make representation of resource available, that's cool, it's you. need implement , wire other resource @ other url. that said, restlet include wadl extension can automatically generate wadl representation of application , make available clients representation of resource — typically "base resource" of app, typically using options method, b...

How to Change color of Button in Android when Clicked? -

i working on android application. want have 4 buttons placed horizontally @ bottom of screen. in these 4 buttons 2 buttons having images on them. border of buttons should black color , border should thin possible. when click button, want background of button should changed blue color without color of border changed , should remained in color time. how can achieve scenario in android? one approach create xml file in drawable , called whatever.xml: <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/bgalt" /> <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/bgalt" /> <item android:drawable="@drawable...

How to know MS SQL Server Database version? 2005 or 2008, for example? -

i want know version of "mdf" ms sql server database file. i have "sql server management studio" tool if it's needed. in "properties" of mdf file, i've found: "version -> 10.xxx" regards..... version 10 sql server 2008

objective c - Garbage Collector and Core Foundation -

i wrote method load image calayer. code: - (cgimageref)loadimage:(nsstring*)path { // data image cgimageref image = null; nsdata *data = [nsdata datawithcontentsoffile:path]; cfdataref imgdata = (cfdataref)data; cgdataproviderref imgdataprovider = cgdataprovidercreatewithcfdata (imgdata); // cgimage cfdataref image = cgimagecreatewithjpegdataprovider(imgdataprovider, null, true, kcgrenderingintentdefault); // if image isn't jpg image, png file if (!image) image = cgimagecreatewithpngdataprovider(imgdataprovider, null, true, kcgrenderingintentdefault); return image; } i use method in calayer: nsstring *pathstring = // image path; alayer = [calayer layer]; alayer.contents = [self loadimage:pathstring]; it's work. finalize view (using garbage collector) application has leaks. should release cfdataref imgdata? read garbage collector not work in core foun...

Dealing with code indentation in Vim? -

i work on engineering team of 4 people, writing javascript while dabbling in ruby , python. so, team, share code time, , programmers do, each member of team has favorite level of indentation & related settings. 1 of 2 members of team use , love vim primary code editor. love team love my indentation , happens use 4-space tab characters. more context, here's use in .vimrc: set ts = 4 sts = 4 sw = 4 expandtab " 4 space tabs with code-sharing , collaborative editing going on in team, main code files start appear mass of mixed tab & space mayhem, classic vim trick of selecting , pressing = smart indent doesn't have effect. anyway, question this: in vim (macvim specifically) there better (more reliable) way of converting code file messy, mixed indentation preferred indentation? whether .vimrc setting or command enter while editing file, don't care. thanks suggestions in advance! use :retab . having said that, suggest you, team, agree on , use...

asp.net mvc - Why is EF4 trying to re-create my database even though the model hasn't changed? -

i have asp.net mvc 3 beta website using sql server ce 4.0. both scottgu's nerddinner example , own code, following exception try access database: file exists. try using different database name. [ file name = d:\sourcecode\nerddinner\nerddinner\app_data\nerddinners.sdf ] line 17: public actionresult index() line 18: { line 19: var dinners = d in nerddinners.dinners line 20: d.eventdate > datetime.now line 21: select d; [sqlceexception (0x80004005): file exists. try using different database name. [ file name = d:\sourcecode\nerddinner\nerddinner\app_data\nerddinners.sdf ]] system.data.sqlserverce.sqlceengine.processresults(intptr perror, int32 hr) +92 system.data.sqlserverce.sqlceengine.createdatabase() +1584 system.data.sqlserverce.sqlceproviderservices.dbcreatedatabase(dbconnection connection, nullable`1 timeout, storeitemcollection storeitemcollection) +287 system.data.objects...

How to send SMS in C# -

i want integrate sms service software developing, users send sms clients. perhaps can actual sms integration sending email ('[phonenumber]@[carrierdomainname]') . how integrated paging eventlog in past. cellphone domain name each carrier shouldn't hard determine. verizon's vtext.com .

latex - Draw chemical laboratory equipment -

i need draw chemical laboratory equiment setups. include erlenmeyer flask, bunsen burner , on. does tikz provide support such drawings? you can draw pretty want: http://www.texample.net/tikz/examples/ but doesn't tikz includes premade versions of lab equipment. i'd try asking question on @ https://tex.stackexchange.com/ .

Is it possible to create a SOAP API using C# and JavaScript -

i looking create soap api using c# can call using javascript. use c# regularly not have experience creating api's. call api using javascript used submit form data multiple websites not maintained us. if there better solution soap open suggestions. if can point me examples or has examples can share appreciate it. tia brianke edit: should have mentioned deploy solution allow form data multiple websites, not under our domain, submit data directly our database, hence api. perhaps there different way handle other api not aware of. if there better solution soap? if going consume api javascript json preferred. may checkout this example illustrates how expose json enabled wcf service consumption jquery ajax.

passwords - How do I setpassword to compressed zip files in Python -

i error when try set password zip file. below code/error get. please give me example of correct way it. this password part of script... entire script long post. code: password = "dog" password = zipfile.setpassword(pwd) error received when hitting password part of script. ------------------------------------------- traceback (most recent call last): file "c:\users\owner\desktop\zip-it\zip it.py", line 86, in <module> start() file "c:\users\owner\desktop\zip-it\zip it.py", line 54, in start compress() file "c:\users\owner\desktop\zip-it\zip it.py", line 70, in compress password = zipfile.setpassword(pwd) attributeerror: 'module' object has no attribute 'setpassword' are running python 2.6+? zipfile.setpassword(pwd) set pwd default password extract encrypted files. new in version 2.6. the python zipfile docs @ top "[support] decryption of encrypted files in zip archiv...

Interface, Abstract or Inheritance? C# Design Question -

i have table houses 2 entities, staticprogram , dynamicprogram . there 1 column in table called programtype determines if program of type "static" or "dynamic". though these 2 entities stored in 1 table (i guessing because primitive fields static , dynamic programs same) business point of view these 2 different entities. so, created 2 classes staticprogram , dynamicprogram . however, donot want create 2 seperate data access classes because going exact same code replicated twice. tried creating "program" class base class , inherited staticprogram , dynamicprogram classes down casting not supported can't return "program" object data access class , cast "staticprogram" class etc. so, options? can create iprogram interface , have staticprogram , dynamicprogram implement interface , have data access class return iprogram ? or making data access method generic method (if possible , recommended approach need not have expreienc...

django - CMS for Multilingual Localization and Translation Workflow -

i'm helping build multilingual website in english, chinese , french (after in spanish, korean , arabic). i've collected database of on 2000+ entries. huge product catalog (specifically travel packages) more or less info same (prices, sizes, numbers, etc.) labels change (of course excluding intro texts must written manually). want avoid having translate piece piece manually. there needs way users save things interested in , rate favorites. also, need e-commerce shopping cart. search functionality must since people tend start general (one or 2 categories or wants) , work towards specifics. need localization , internationalization. other need specific workflow system content updated , new additions made, editors can notified , translators can translate needs done. work flow key since project involve dozens of non-technical people around world. i tried work-around solution in drupal seemed ill-equipped , clunky. tried self-built php cms project seems big purely manual. i...

java - calling one JApplet form from another -

i have created project files swing applications, i.e files extending japplet, how call 1 japplet file another? kow set visible methods there jframe dont have time convert convert, please possible basically, can't. or, rather, it's difficult. running applet requires construction of appletcontext , management of applet life cycle. a better approach move of code have in applet jpanel. have simple applet creates panel. then, when want open panel, create jframe , populate appropriate panel.

encryption - What does this PHP do? Is it an encoder/decoder? -

i don't know php @ all; more of question of curiosity. following php function below in text file few thousand characters of text, such as: xnefstuhsnwgsx5ztq4x/auw/rtism+klrbetwg0xe1uwb49rnrxrgrgy5eep3y0uvtcvlqhufop 4n7ldlqpq9uactyuujgbkmuscqcylcp08u06t0k3nwtnim7q6bqmk/izbe+uk1ywbvc1lzr9ooek does php function encode random-looking text php? can encryption scheme figured out this? edit: client says has full ownership , rights code, developed else. how decoded? require password? <?php //003ac if (!extension_loaded('ioncube loader')) { $__oc = strtolower(substr(php_uname(), 0, 3)); $__ln = 'ioncube_loader_' . $__oc . '_' . substr(phpversion(), 0, 3) . (($__oc == 'win') ? '.dll' : '.so'); @dl($__ln); if (function_exists('_il_exec')) { return _il_exec(); } $__ln = '/ioncube/' . $__ln; $__oid = $__id = realpath(ini_get('extension_dir')); $__here = dirname(_...

asp.net - call stack missing info on mono with apache and mod_mono -

how enable debugging/stacktrace filenames , numbers apache2/mod_mono? instead of filenames , numbers this at system.web.staticfilehandler.processrequest (system.web.httpcontext context) [0x00000] in <filename unknown>:0 i tried using monodebug true in apache , recompile mod_mono --enable-debug , have <compilation debug="true"> inside of configuration>system.web>httpruntime in web.config. i using debian lenny , tried installing mono-debugger, restart apache , still no luck. used configuration tool no luck. many supported on suse? http://go-mono.com/config-mod-mono/ i had same problem. there quite few solutions. first of all, must install mono-core-debuginfo package, or might not work. second, must run mono in debug mode *solution 1: add virtual host section/httpd.conf monosetenv monodebug true *solution 2: start xsp/mod-mono-server debug $ mono_options=--debug xsp2

python - Parse dict of dicts to string -

i have dictionary following structure : {1: {'message': u'test', 'user': u'user1'}, 2: {'message': u'test2', 'user': u'user2'}} i'd create string containing values inner dictionary in form : string = "<span>test1</span><span>user1</span><br /> <span>test2</span>..." i've tried dict.keys() , dict.values() , (k,v) k, v in dict cannot make work. proper way ? >>> d={1: {'message': u'test', 'user': u'user1'}, 2: {'message': u'test2', 'user': u'user2'}} >>> ''.join('<span>%(message)s</span><span>%(user)s</span><br/>' % v k,v in sorted(d.items())) u'<span>test</span><span>user1</span><br/><span>test2</span><span>user2</span><br/>'

ruby - unix utility that reads files into memory? -

i using ruby's net-ssh library remotely execute shell commands. read few files memory rather transfer them via scp/sftp. can can this? if use wc or ls find size, can use cat data out, read right number of bytes.

Inverted-colors text on top of an OpenGL scene -

i have font texture use in order draw text on top of opengl scene. problem scene's colors vary solid color use hard read. possible draw font texture inverted colors? a call glblendfunc(gl_src_alpha, gl_one_minus_src_alpha); draw solid color, call glblendfunc(gl_one_minus_dst_color, gl_zero); draw inverted, disregard alpha values of texture you'd see inverted rectangle instead of letters. what need equivalent glblendfunc(gl_src_alpha * gl_one_minus_dst_color, gl_one_minus_src_alpha); can achieved somehow without using shaders ? problem solved. following dave's comment original post: instead of using gl_alpha texture generate gl_rgba texture each pixel equal: (alpha, alpha, alpha, 0xff) (this greyscale image instead of luminance image). use texture with: glblendfunc(gl_one_minus_dst_color, gl_one_minus_src_color); the result is: (1 - dest_color) x "src_alpha" + dest_color x (1 - "src_alpha") needed. thank you! ron

Any experience in writing greasemonkey script for gmail? -

i've had idea year or , find hard believe 1 have ever of thought of this. feature not available in web-based or email client know of. love see gmail. posted topic on gmail forums never received meaningful replies. a lot of people forward on emails groups of other people, of fun or joke variety. don't want guy forwards on email "fun" group of addresses send right person sent me or may have received in thread of messages. find myself hitting "forward" button, adding group recipients list, having go through list , remove people received email me. so, why not have "forward without duplicates" button parses through message body , remove address found recipients list. way, has been included in email thread not receive message again. don't forward on emails anymore b/c of annoyance of having add group of addresses , , painfully go through , remove each 1 not need on it. i have tried using firebug isolate needs parsed through, tough. ...

Liferay authentication and authorization (Siteminder and Custom Tomcat Authorization) -

i new liferay portal. afraid, questions being raised might simple, not aware. please clarify. we trying build portal using liferay on tomcat. portal should authenticated netegrity siteminder , have our internal authorization mechanism built on tomcat security . have questions on 2 areas have listed below question on enabling siteminder in liferay when siteminder enabled within liferay, necessary still configure user in liferay portal have siteminder authenticated user portal page. authorizations - objective avoid configuring user , roles , associations in liferay. because portal want built should rely on tomcat security customized framework in place. i deployed portlet has set of links available , these links should available based on user permissions. configured users , set of roles in tomcat-users.xml , defined role-mapping in liferay-portlet.xml,portlet.xml,web.xml , deployed portlet , changed realm configuration in liferay.xml below appname="portalrealm" u...

A potentially dangerous Request.QueryString value was detected from the client when sending html markup from jquery post call to asp.net page -

i m making ajax call using jquery asp.net page acts ajax server page save data sending in query string. in asp.net page when trying read querystring getting error: a potentially dangerous request.querystring value detected client... i have set validaterequest="false" in page. dont want set pages. did in page level instead of config level: var content = "<h3>sample header</h3><p>sample para</p>" content = encodeuricomponent(content); var url = "../lib/ajaxhandler.aspx?mode=savecontent&page=home&ltxt=" + content; $.post(url, function (data) { //check return value , }); and in asp.net page: <%@ page language="c#" autoeventwireup="true" codebehind="ajaxhandler.aspx.cs" validaterequest="false" inherits="myproject.lib.ajaxhandler" %> but when sending plain text instead of html markup, works fine. if asp.net 4, there breaking ...

objective c - Globally hiding cursor (from background app) -

i want hide cursor statusbar app , i've done research. seems though solution problem found while ago: globally hide mouse cursor in cocoa/carbon? or http://lists.apple.com/archives/carbon-dev/2006/jan/msg00555.html but code referred not compile. of guys know either how make code compile (by importing old api or something) or way of achieving (some kind of hack)? (i know bad idea hide cursor background app, making app functionality pretty essential) edit: here's old hack, doesn't work anymore. long sysvers = getsystemversion(); // trick doesn't work on 10.1 if (sysvers >= 0x1020) { void cgssetconnectionproperty(int, int, int, int); int cgscreatecstring(char *); int cgscreateboolean(bool); int _cgsdefaultconnection(); void cgsreleaseobj(int); int propertystring, boolval; // hack make background cursor setting work propertystring = cgscreatecstring("setscursorinbackground"); boolval = cgscreateboolean(tru...

html - CSS page-break-after and float not playing nicely? -

if have following html code: <!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"/> <title>test</title> </head> <body> <div style="page-break-after: always; float: left;">hello</div> <div style="page-break-after: always; float: left;">there</div> <div style="page-break-after: always; float: left;">bilbo</div> <div style="page-break-after: always; float: left;">baggins</div> </body> </html> i want 1 word printed on each page, page break after each one. (this simplified code - in actual web page, floats important.) firefox prints fine, both ie , ...

spring - Where should "@Transactional" be place Service Layer or DAO -

firstly possible asking has been asked , answered before not search result . okay (or far:) ) define transactional annotations on service layer typical spring hibernate crud usually controller->manager->dao->orm . i have situation need choose between domain model based on client site . client using domain model other client site give me web service , not using our domain model . which layer should replacing . believe has dao getting me data web service , sending back.i.e 2 separately written dao layers , plugged in based on scenario . i have realized have been doing tight coupling (if there such thing or not having loose coupling) when put @transactional in service layer . many brains can not wrong or (i doubt it). so question "where should "@transactional" place service layer or dao ?" , service layer downwards should replacing . ideally, service layer(manager) represents business logic , hence should annotated @transactional. ser...

iphone - C++ Struct in array, help! -

i have iphone app used use array of several thousand small objects data source. now, trying make use c++ structs, improve performance. have written struct, , put in "particle.h": typedef struct{ double changex; double changey; double x; double y; }particlestruct; then, imported "particle.h", , attempted define array: #import "particle.h" @implementation particledisplay struct particlestruct particles[]; ///size determined later, declaration make ////the declaration visible entire class... on line, however, error: "array type has incomplete element type". else compiles fine, far can tell, , sure "particle.h" has been imported before declaration. ideas? since have typedef ed in particle.h, drop word struct array declaration line (the line error is). however, in c++, not need typedef it, write struct particle { /* members */ }; why declaring array without length? consider using std::vector ( t...

iphone - UIView in UIView issue -

perhaps i'm missing property or misunderstanding having issues simple. i have uiview frame lets of 100px high in have uiview lets 50px high. if set main uiview 20px high 50px high 1 visible. thought might of been bounds set , no different. sorry if answered somewhere else couldn't find relating this. on "parent" view, set clipstobounds property yes.

Puzzle : finding out repeated element in an Array -

size of array n.all elements in array distinct in range of [0 , n-1] except 2 elements.find out repeated element without using temporary array constant time complexity. i tried o(n) this. a[]={1,0,0,2,3}; b[]={-1,-1,-1,-1,-1}; i=0; int required; while(i<n) { b[a[i]]++; if(b[a[i]==1) required=a[i]; } print required; if there no constraint on range of numbers i.e allowing out of range also.is possible o(n) solution without temporary array. look first , last number calculate sum(1) of array elements without duplicate (like know sum of 1...5 = 1+2+3+4+5 = 15. call sum(1)). aaronmcsmooth pointed out, formula sum(1, n) = (n+1)n/2 . calculate sum(2) of elements in array given you. subtract sum(2) - sum(1). whoa! result duplicate number (like if given array 1, 2, 3, 4, 5, 3, sum(2) 18. 18 - 15 = 3. 3 duplicate). good luck coding!

comparison - Advantages of Erlang over (something like) node.js? -

i realize different beast used solve different problems, ask enumerated list of advantages of erlang on node.js (and vice-versa). when use 1 on other? erlang language , runtime. i'm assuming wish comparison of erlang runtime node.js first i'll list similarities: both lend event driven programming. both focus on highly asynchronous programming. and then advantages erlang has: erlangs message passing abstracts differences between local , distributed processes making distributed programming easier. erlangs hot code loading allows in place releases on running services without disrupting current activity. erlang has superior tools packaging , deployment. erlangs supervisor , gen_server behviors provide superior framework building extremely robust , fault tolerant systems.

asp.net - How to focus in div tag in javascript -

i have created tabs using div tag in javascript. have asp.net button on each tab. whenever clicked on button focus set first tab. i using following code in page load event. htmlgenericcontrol content_1 = new htmlgenericcontrol("content_1"); htmlgenericcontrol content_2 = new htmlgenericcontrol("content_2"); htmlgenericcontrol content_3 = new htmlgenericcontrol("content_3"); htmlgenericcontrol content_4 = new htmlgenericcontrol("content_4"); htmlgenericcontrol content_5 = new htmlgenericcontrol("content_5"); htmlgenericcontrol selectedpage = new htmlgenericcontrol(pagename); content_1.style["display"] = "none"; content_2.style["display"] = "none"; content_3.style["display"] = "none"; content_4.style["display"] = "none"; content_5.style["display"] = "none"; selectedpage.style["display"] = "block"; selectedpage....

iphone - Top row fixed in UITableView -

Image
is possible ? i used 3 label in cell of uitableview. want make first row header , fixed position when scroll. section header can't show right position of label. lost angeles, u.s.a should show on second column first columns text long. you can place uiview content of first cell on top of uitableview. when fill cells should leave first cell empty (it covered fixed uiview in initial position).

keyword - Swap two variables without using ref/out in C# -

is possible swap 2 variables without using ref/out keyword in c#(i.e. using unsafe)? for ex, swap(ref x,ref y);//it possbile passing reference but, there other way of doing same thing. in swap function can use temp variable. but, how swap variables without using ref/out keywords in c#? a (very!) contrived example using delegates: class program { static void funkyswap<t>(t a, t b, action<t> seta, action<t> setb) { t tempa = a; seta(b); setb(tempa); } static void main(string[] args) { string s1 = "big"; string s2 = "apples"; console.writeline("before, s1: {0}, s2: {1}", s1, s2); funkyswap(s1, s2, => s1 = a, b => s2 = b); console.writeline("after, s1: {0}, s2: {1}", s1, s2); } } while above pretty silly, using delegate setter method can useful in other situations; i've used technique implementing undo/re...

Configure an Android application using property file -

i have android application need install on diffferent devices different configurations. kept in res/raw folder, data stored in key=value format. can access value passing key? can change .properties file outside application? suggestions? i'd go sharedpreferences . can predefine sharedpreference file , ship application it. need implement way alter preferences desired extent. it xml file using key:value pairs.

ajax - How to use jQuery with in xhtml? -

i using facelets,richfaces,and ajax, in xhtml facing error while creating datepicker! solution problem? the code is: <?xml version="1.0" encoding="iso-8859-1" ?> <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:a4j="https://ajax4jsf.dev.java.net/ajax" xmlns:rich="http://richfaces.ajax4jsf.org/rich"> <head> <a4j:loadscript src="jquery/jquery-1.4.2.min.js" /> <a4j:loadscript src="jquery/jquery-ui-1.8.5.custom.min.js" /> </head> <body> <h:form> <rich:panel> <h:inputtext id="mydate" value="" ...

ruby on rails - Cucumber and Seed data -

can load seed data when start cucumber? please support me way. you use factory girl in cucumber tests setup 'stuff' background: car exists scenario: drive car given in car , have keys in ignition when turn keys ... then you'll create car in step definitions, like @car = factory.create(:car)

.net - How to change the Public token of the assembly -

i have 2 assemblies. 1 assembly referring one. checked manifest of first assembly , found referencing second 1 specific token key. but checked token of second assembly , found has different public token. somehow missed correct second assembly. want know there way can change second assembly's public token 1 first assembly needs. also have second assembly has public token = null. sounds want rebuild second assembly , sign different key, easy if had source guess don't? i think easier rebuild first assembly references second assembly have, using public key token present on second assembly. easier, not entirely straightforward. i think should able achieve running first assembly through ildasm.exe , change public key token on reference second assembly, , run result through ilasm.exe , produce new version of first assembly. a rough outline of steps involved... run ildasm.exe /out=first.il first.dll (or first.exe ) edit first.il , find .assembly extern bl...

activerecord - how to modify complex sql query w/ join into rails 3 -

i'm working on car pooling application users can add lifts , able select multiple stops each lift ( b via c, d, e). when user searches database lift results should include lifts 'a d', 'c b' or 'c e' , on. got working rails 2.3.5 using below code struggle moving on rails 3. i'm sure there must cleaner way achieve i'm trying , move code model. it great if me on one. class lift < activerecord::base has_many :stops end class stop < activerecord::base belongs_to :lift belongs_to :city end class city < activerecord::base has_one :stop end @lifts = lift.find( :select => "lifts.id, bs.city_id start_city_id, bs2.city_id destination_city_id", :from => "lifts", :joins => "left join stops bs on lifts.id = bs.lift_id left join stops bs2 on lifts.id = bs2.lift_id join cities bc on bs.city_id = bc.id join cities bc...

generics - How can I use Scala's Manifest class to instantiate the erased class at runtime? -

i'm doing webdriver+pageobject stuff. (if not familiar pageobjects, pattern have class representing each page on site exposes functions of page using domain language, hiding html stuff test.) i want lazy , have 1 'submit' method in abstract page class other pages extend from. want method new next page subclass , return it. here have in page class: def submitexpecting[p <: page[p]](implicit m: manifest[_]): p = { driver.findelement(by.xpath("//input[@type='submit']")).click m.erasure.getconstructor(classof[webdriver]).newinstance(driver).asinstanceof[p] } and here's how i'm calling it: val userhomepage = usersignuppage .login("graham") .accepttermsandconditions .submitexpecting[userhomepage] compiling this, get: error: not find implicit value parameter m: manifest[_] .submitexpecting[userhomepage] i thought being smart, i'm not. ;) doing wrong? you need make manifest related type...

database - creating Models with sqlite3 + datamapper + ruby -

how build model following associations (i tried couldn't work): each order has: customer, salesrep, many orderline each has item . i tried: when do: customer.all(customer.orders.order_lines.item.sku.like => "%blue%") output :[] instead of: '[#<"customer @id=1 @name="dan kubb">]' when delete salesrep: works. customer has n, :orders has n, :items, :through => :order salesrep has n, :orders has n, :items, :through => :order order belongs_to :customer belongs_to :technician has n, :order_lines has n, :items, :through => :order_line orderline belongs_to :order belongs_to :item item has n, :order_lines since output isn't error, don't have data in database. try following irb -r your_models_file.rb : - c = customer.create(:name => "dan kubb") o = order.new(:customer => c) # create , add technician unless it's :required => false i = item.create(:...

opengl es - Android memory mapped file with vertices -

i trying render vertices stored in big file (approx 50mb). file layout optimized can take slice , give opengl render triangel strip directly. this works in emulator, when run same code in magic (android 1.5) crashes sigbus in libhgl.so. sounds driver issue? i have tried manually copy vertices local buffer (non mem mapped), works takes eons of time, 300-600 ms. anyone have experience?

css - Incorrect vertical alignment in IE8 -

the default text in search box looks fine in chrome, ff, , safari (vertical-align: middle). however, default text rises top of search box in ie 8 . is there workaround ie? help. html: <input type="text" class="text" value="search" title="search" /> css: .text { height: 47px; font-size: 18px; margin: 0; padding: 0 5px 0 45px; } have tried setting line height match height of text box? text should automatically appear in middle of line

html - How to add vertical gradient using css? -

i have vertical submenu under: <div id="dropdown_menu" class="menu"> <ul> <li> <a>first link</a></li> <li> <a>second link</a></li> </ul> </div> i putting bottom piece of background in css class 'menu'., top slice of background in .menu ul. now, have 1 vertical gradient changes color top down (in whole vertical menu) , therefore cannot put in .menu ul li. possible add vertical gradient without making change html? #dropdown_menu { filter: progid:dximagetransform.microsoft.gradient(startcolorstr='#ff280c00', endcolorstr='#004a1d00'); /* ie */ background: -webkit-gradient(linear, left top, left bottom, from(#280c00), to(rgba(75, 30, 0, 0))); /* webkit browsers */ background: -moz-linear-gradient(top, #280c00, rgba(75, 30, 0, 0)); /* firefox 3.6+ */ } see actual implementation here: http://www.salonbelledesoir.com (the gradients around edge cs...

android - How many ViewStubs is too many for a single layout XML file? -

i have layout defined in xml file( base_layout.xml ) may contain 20+ viewstub definitions in addition 3-5 other views such imageview , linearlayout containing 3-5 imagebutton views. should concerned how many viewstub views place in layout file? i read on developer.android site: a viewstub dumb , lightweight view. has no dimension, not draw , not participate in layout in way. means viewstub cheap inflate , cheap keep in view hierarchy is cheap enough have 20+ of them? not being inflated of course, 1-2 @ time. when cheap enough or talk of being concerned , regarding performance of ui edit: trying accomplish: create layout xml file can skeleton of activities. in each activity , inflate correct viewstub activity's layout. since have many activities requiring same skeleton, wish re-use as possible i have activity class parent of of activities. parent class calls setcontentview(r.layout.base_layout); . each child activity, doing inflating co...

Demonstrating package names collision in java -

i got question assignment: packages/naming we have created lot of packages , defined classes , interfaces in them. have discussed point have remember while naming them. in assignment see how important naming is. please change package names in previous assignment such 2 packages have same name , analyze result/errors thrown. my doubt: i unable think of way(scenario) demonstrate has been asked. since java imports absolute, situation described in question seem impossible produce (imo). please me demonstrate thing. thanks in advance :) that depend heavily on code you're running. the way cause package name conflict put 2 separate jars on classpath both contain classes in same package. if none of class names conflict, there no conflict. if class names conflict, jvm try load them jar comes earlier in classpath. errors occur when classes in later jar, , classes in later jar use classes names used in earlier jar. nature of error depends on type of u...

excel - Is RExcel useful? or should I look for alternatives -

also, illadvised use rexcel corporate work? also, advantages / disadvantages of using it? how small files need rexcel? i have used in past, not using it. here's personal list of pros/cons: pro: easy access r functions excel allows slipping r logic existing excel spreadsheet fairly easy use syntax con: in instances can slow. if have 5000 calls r in spreadsheet can eat lunch while refreshes to share spreadsheet rexcel embedded, other users must have rexcel installed sometimes connection r drops , have reconnect it in opinion rexcel can useful hack, not make critical path along workflow. if need 1 or 2 functions r rexcel can lifesaver. i used rexcel speed slow excel spreadsheet replacing slow vba function fast 1 r. bought me time migrate whole process r made easier maintain , track. i'm not sure you're asking when asked "how small files need rexcel?" rexcel excel add-on, if data fits in excel can operate on it. if huge excel file...

html - SEO title vs alt vs text -

does title attribute in link job of real text in link seo? i.e <a href="..." title="web design">web design</a> is same as: <a href="..." title="web design">click here</a> when trying page rank keywords "web design"? alt attribute in image tag? or useless in seo? is same as: <a href="..." alt="web design">click here</a> what's difference between above? thank in advance! alt not valid attribute <a> elements. use alt describe images use title describe link going. the textvalue (click here) important part title attribute gets more , more ignored. google looks far more on link text title attribute. google title tag meta tag not important compared content. image alt tags still important (especially image search) the main feature of tags provide usability users, not feed informatino search engines.

.net - entity framework linq - which should I learn, method-based on query-based? -

just starting getting entity framework , linq ef. i'm not sure of 2 query methods should concentrate on, method-based or query-based? is there obvious choice 1 easier use, both simple , more complex queries, hence should 1 concentrate on? assuming i'm using vs2010 method based have advantage in terms of having more design time checks/prompts ide make easier things right prior running application? thanks the method syntax more complete; there things can't query syntax without plugging in method here or there inline. also, queries, method syntax can seem more concise, imo. on other hand, query syntax can appear describe query more naturally familiar sql. i figured use method syntax exclusively when started learning linq in general. find myself pounding out query syntax queries sort of automatically @ times, too. perhaps concentrate on method syntax due completeness , familiarity factor (if @ valuable you), , maybe you'll find query syntax sort of ...

multithreading - WPF: Problems with CurrentDispatcher.CheckAccess and CanExecuteChanged -

sometimes when call raiseevent canexecutechanged(sender, eventargs.empty) ground thread give me exception stating "the calling thread cannot access object because different thread owns it." however, if call system.windows.threading.dispatcher.currentdispatcher.checkaccess returns true. what doing wrong? private sub m_parent_propertychanged(byval sender object, byval e propertychangedeventargs) handles m_parent.propertychanged if system.windows.threading.dispatcher.currentdispatcher.checkaccess raiseevent canexecutechanged(sender, eventargs.empty) else end if end sub application.current.dispatcher.checkaccess() see : ensuring things run on ui thread in wpf

facebook - Display .txt file in html (without php or javascript) (UPDATE) -

i want display context of .txt file in html file. i know easy php or javascript, but, put in context, building content administrator facebook page (not app). facebook fbml static , doest allow php , limited javascript. the first question if possible (couldn´t find decent answers googling), , second obvious how. edit: saw question is possible use javascript or php in static fbml? does change mattbasta´s answer? it sure is! can use fbml create ajax request server , pull txt file in. can load on ajax otherwise able load polling url. check out: http://developers.facebook.com/docs/fbjs#ajax once pull in txt file string in fbjs, assign string element , you're gold. that should going. luck! edit also, record, can output fbml php (or other language, matter) create dynamic fbml page. write fbml in same way write html php script , it'll work how expect to! edit 2 you can create fbml page: <!-- fbml code here --> <?php echo file_get_contents...

javascript - Started Playing with node.js. I have a question -

i created http server using code fro documentation: var sys = require("sys"), http = require("http"); http.createserver(function(request, response) { response.writehead(200, {"content-type": "text/plain"}); response.end("hello world!"); sys.puts('connection'); }).listen(8080); sys.puts("server running @ http://localhost:8080/");** my question is, why when go localhost:8080 got "connection" printed twice? bug? your browser may requesting url twice, once head request , once request. try using simple interface, telnet : $ telnet localhost 8080 / http/1.0 ^]q leave blank line after get , , press ctrl+] q enter out.

objective c - XCode - nested functions are disabled ! -

i used able foreach loops in xcode, after installing sdk 4 errors error: nested functions disabled, use -fnested-functions re-enable how can enable nested functions says "use -fnested-", use where? how? for (myobject *obj : array) { } i think mean: for (myobject * obj in array) { ... } (note use in , not : .

networking - Good article on sockets? -

i wondering find article on sockets. don't want indepth code. want understand structures , other stuff how buffers work. i found beej's guide network programming pretty informative.

perl - How Can I Remove Magic Number when using XML::Simple? -

i did exercise this, how calculate # of xml elements collapsed array xml::simple don't have hard-code # of elements? plan use code parse bigger xml file. don't want cout elements manual. can use count replace magic numbers, little person.count or hobbie.length etc. know, can use kind of statement in c# conveniently. #!/usr/bin/perl -w use strict; use xml::simple; use data::dumper; $tree = xmlin('./t1.xml'); print dumper($tree); print "\n"; (my $i = 0; $i < 2; $i++) # magic number '2' { print "$tree->{person}->[$i]->{first_name} $tree->{person}->[$i]->{last_name}\n"; print "\n"; (my $j = 0; $j < 3; $j++) # magic number '3' { print $tree->{person}->[$i]->{hobbie}->[$j], "\n"; } print "\n"; } out put: could not find parserdetails.ini in c:/perl/site/lib/xml/sax $var1 = { 'person' => [ ...