Posts

Showing posts from May, 2014

iphone - Problem with memory manament in Objective-C -

i have method: -(nsarray *)dosomething{ nsarray *array = [[nsarray alloc] initwithobjects:@"huy 1",@"huy 2",@"huy 3",nil]; [array release]; return array; } and - (void)viewdidload { [super viewdidload]; nsarray *array = [self dosomething]; if(array&&array.count>0){ nslog([nsstring stringwithformat:@"%@\n",[array objectatindex:1]]); } else{ nslog(@"null"); } } i thinks released array on dosomething() won't return nsarray created on dosomething(). don't know still print "huy 2"? can tell me why? -(nsarray *)dosomething { nsarray *array = [[nsarray alloc] initwithobjects:@"huy 1",@"huy 2",@"huy 3",nil]; return [array autorelease]; } memory management programming guide - (void)viewdidload { [super viewdidload]; nsarray *array = [self dosomething]; if([array co

Encryption message in java -

i project using java's bouncycastle encryption. however, when encrypt message, throws exception me. javax.crypto.illegalblocksizeexception: data not block size aligned i using blowfish/ecb/nopadding, , message xml. public static void main(string args[]){ string message = "<abc>abcdefg</abc>"; string key = "key"; byte[] b = encrypt(message.getbytes(), key.getbytes()); } public byte[] encrypt(byte encrypt[], byte en_key[]) { try { secretkeyspec key = new secretkeyspec(en_key, "blowfish"); cipher cipher = cipher.getinstance("blowfish/ecb/nopadding"); cipher.init(cipher.encrypt_mode, en_key); return cipher.dofinal(encrypt); } catch (exception e) { e.printstacktrace(); return null; } } could can me? thank you you using nopadding , size of input data must not match block size of cipher, illegalblock

c# - GetScrollInfo only works when visual styles are activated -

in current project on winforms .net3.5 imported user32.dll functions scrolling programmatically. extended tablelayoutpanel - ought scrolled. everything worked fine after bit of work, found out function getscrollinfo(this.handle, sb_vert, ref _si); always returns false when visual styles on windows xp deactivated. if visual styles activated (everything else "classic" ok), above mentioned function returns true , correct values. how avoid this, or how correct scrollvalues without activating visual styles? ps: _si struct called scrollinfo described in msdn (i not allowed link more 1 page sorry) , getscrollinfo described here . this.handle handle of base tablelayoutpanel. after little playing around scrollinfo struct found out on own. for having same problem, had set cbsize of scrollinfo struct sizeof(scrollinfo). something like public scrollableexampleconstructor() { _si = new scrollinfo(); _si.fmask = (uint) scrollinfomask

flex - actionscript: embed glyphs by code -

you can embed glyphs of font via flash ide. is possible code only? (without ide) [embed(source='fonts/arial.swf' ,fontname='arial' )] public static var font:class; it's possible, see using embedded fonts (look 'unicoderange').

c# - Improving access time on SortedDictionary -

i have 2 millions items in sorteddictionary<string, myclass> i've done following , takes ages, ideas? for(int = 0; i<dic.count-1; i++) { debug.writeline(dic.elementat(i).value.tostring()); } the sorteddictionary<tkey, tvalue> class not directly support (fast) retrieval index; internally implemented binary search tree. consequently, every call linq enumerable.elementat method you've got there creates new enumerator iterates each value of sequence represented key-value pairs in collection (sorted key) from beginning until reaches desired index. means loop going have pull 1 + 2 + 3 + ... + count (roughly 2 trillion) elements before completes, making (atleast) quadratic in time-complexity. try instead, should run in linear time: foreach(var myclass in dic.values) debug.writeline(myclass); if want fast access index (from provided code, there doesn't seem reason indicate this), consider using sortedlist<tkey, tvalue> inste

javascript - How can I react when a user touches an HTML element on an iPhone? -

i'm displaying html content in iphone app using uiwebview. have image link, , want change when user touches - @ moment user puts finger on screen, rather waiting until lift finger off. what css or javascript concept accomplish this? i've looked @ hover , active states in css, don't seem i'm after: hover relates touch-up rather touch-down, while active seems have no effect @ all. you try this. i think should looking for! http://articles.sitepoint.com/article/iphone-development-12-tips/2 8: touch events of course, use iphone finger instead of mouse; rather clicking, tap. what’s more, can use several fingers touch , tap. on iphone, mouse events replaced touch events. are: touchstart touchend touchmove touchcancel (when system cancels touch) when subscribe of events, event listener receive event object. event object has important properties, such as: touches — collection of touch obj

Good library for Google Maps? -

in project need use google maps api place users on map. there libraries enhance user experience working google maps? i noticed flutster . do try http://code.google.com/p/gmaps-utility-library/

Difference between android sha224 and python sha224 -

for application prototype i'm creating simple user login. password of user hashed using sha224 , transferred back-end. problem facing right following. password stored in db (also hashed using sha224) seems little different hash sending. use following code create hashes. given password == test python from hashlib import sha224 sha224("test").hexdigest() android messagedigest sha224 = messagedigest.getinstance("sha-224"); sha224.update(key.getbytes()); byte[] digest = sha224.digest(); stringbuffer buffer = new stringbuffer(); for(int = 0; < digest.length; i++) { buffer.append(string.valueof(integer.tohexstring(0xff & digest[i]))); } return buffer.tostring(); what produced looks , post 2 hashes directly underneath each other. (the first 1 python , second android) 90a3ed9e32b2aaf4c61c410eb925426119e1a9dc53d4286ade99a809 90a3ed9e32b2aaf4c61c41eb925426119e1a9dc53d4286ade99a89 they same python hash has 2 0s more. guys have idea why?

convert a C Enum to the delphi? -

i wrote delphi numeric c enum can answer me , can may had mistake? there wrong? c: typedef enum { attributestandardinformation = 0x10, attributeattributelist = 0x20, attributefilename = 0x30, attributeobjectid = 0x40, attributesecuritydescriptor = 0x50, attributevolumename = 0x60, attributevolumeinformation = 0x70, attributedata = 0x80, attributeindexroot = 0x90, attributeindexallocation = 0xa0, attributebitmap = 0xb0, attributereparsepoint = 0xc0, attributeeainformation = 0xd0, attributeea = 0xe0, attributepropertyset = 0xf0, attributeloggedutilitystream = 0x100 } attribute_type and converted delphi enum: attribute_type=( attributestandardinformation = $10, attributeattributelist = $20, attributefilename = $30, attributeobjectid = $40, attributesecuritydescriptor = $50, attributevolumename = $60, attributevolumeinformation = $70, attributedata = $80, //attributedata1 = $0, // has problem attr

ios - Reprinted Cell Text into an UITableViewCell -

into cellforrowatindexpath: method of uitableviewcontroller class using next code show cell contains uitextview . sometimes when scroll table contains cell , scroll cell uitextview , shows cell text reprinted (as if there 2 uitextview objects, instead of one, cell). what can solve problem? static nsstring *cellidentifier = @"cell"; uitableviewcell *cell = [tableview dequeuereusablecellwithidentifier:cellidentifier]; if (cell == nil) { cell = [[[uitableviewcell alloc] initwithstyle:uitableviewcellstyledefault reuseidentifier:cellidentifier] autorelease]; } cell.contentview.bounds = cgrectmake(0, 0, cell.frame.size.width, cell.frame.size.height); cell.selectionstyle = uitableviewcellselectionstylenone; uitextview *textview = [[uitextview alloc] initwithframe:cell.contentview.bounds]; textview.autoresizingmask = uiviewautoresizingflexiblewidth | uiviewautoresizingflexibleheight; textview.editable = no; textview.scrollenabled = yes; tex

sql server 2008 - Join query with flattened result -

Image
i have following entities addresstype enum field define if email personal/work/other. is possible query returns flattened result 1 in following sample? customerid full name personal email work email ----------- -------------- ----------------- ----------------------- 1 john doe johndoe@hotmail.com john.doe@company.com two main choices: 1) select typical (with 2 rows, 1 each email), use pivot operator flatten. example of pivot (i call example wrote in notepad. may wrong, should point right way): select customerid, fullname [1] workemail, [2] homeemail (select c.customerid, c.fullname, e.addresstext, e.addresstype customer c join emails e on e.customerid = c.customerid) source pivot ( addresstext addresstype in ([1], [2]) ) 2) join email table twice, once each type of address. suggest outer joins if 1 missing still other.

Twitter API refuses my credentials -

the twitter api keeps refusing credentials, no matter shared library use. there reason this? twitter no longer allows basic authentication on api. need oauth authentication. problem having. if need further help, need post code, library using, , part of api trying access.

iphone - -[NSPathStore2 objectForKey:]: unrecognized selector sent to instance 0x6a3fc60' -

i preparing customcellview in tableview. according me, perfect in .xib , methods. getting exception in configuring cell. int listindex = [indexpath indexatposition:[indexpath length] - 1]; nslog(@"outside"); cell.lblname.text = (nsstring *) [[directorycontent objectatindex:listindex] objectforkey:@"filesname"]; cell.lblsize.text = (nsstring *) [[directorycontent objectatindex:listindex] objectforkey:@"filessize"]; cell.lbltype.text = (nsstring *) [[directorycontent objectatindex:listindex] objectforkey:@"filestype"]; return cell; the compiler works till nslog(@"outside"); . not proceeds next line. terminated error 2010-11-15 20:32:28.623 idatatraveller[5346:207] outside 2010-11-15 20:32:28.625 idatatraveller[5346:207] -[nspathstore2 objectforkey:]: unrecognized selector sent instance 0x5f19cf0 2010-11-15 20:32:28.627 idatatraveller[5346:207] *** terminating app due uncaught exception 'nsinvali

python - How to display database query results of 100,000 rows or more with HTML? -

we're rewriting website used 1 of our clients. user traffic on low, less 100 unique visitors week. it's nice interface data in our databases. allows them query , filter on different sets of data of theirs. we're rewriting site in python, re-using same oracle database data on. current version written in old, old version of coldfusion. 1 of things coldfusion though displays tons of database records on single page. it's capable of displaying hundreds of thousands of rows @ once without crashing browser. uses java applet, , looks contents of rows perhaps compressed , passed in through html or something. there large block of data in html it's not displayed - it's rendered java applet. i've tried several javascript solutions hinge on fact data present in html table or along lines. causes browsers freeze , run out of memory. does know of solutions situation? our client loves ability scroll through of data without clicking "next page" link. tha

asp.net - MVC3 RC app deployed on IIS 6 giving "403 forbidden" error -

i've deployed simple mvc3 rc app iis 6 + windows 2003 server. i'm getting "403 forbidden" error when trying accesss root. right app 1 page, there no others try out. i noticed there no longer default.aspx in root handle default requests, maybe problem? or there special config needed iis 6? it depends. if using extensionless routes yes there's special config .

Twisted C++ code -

possible duplicate: undefined behavior , sequence points #include< iostream.h> int main() { int i=7,j=i; j=(i++,++i,j++*i); cout <<j; return 0; } what output of c++ code? it's homework professor gave me. it helps convince people don't believe undefined compiling program several compilers , observing results: after fixing iostream.h error, g++ 4.5.2 prints 64 clang++ 2.8 prints 63 sun c++ 5.8 prints 63 msvc 2010 prints 64 (oh, and, re-written use c i/o, original k&r c compiler on unix 7 prints 63)

Move all sharepoint 2007 databases to a new Sql Server -

in our organization have microsoft sharepoint 2007 installed , configured on windows server 2003 standard edition (32 bit). database had been installed , configured on sql server 2000 (windows 2000 server 32 bit). in process move databases sql server 2000 new windows 2008 server r2 enterprise (64bit). new server has been installed , doesn't have same name of sql server 2000. upgrade sharepoint 2007 database rdbms can dismiss old, slow sql server 2000. has tried similar? you should following steps: backup content , configuration databases. backup ssp databases. prepare content databases moving. delete content databases. stop sharepoint farm stopping timer, tracing, administration service copy mdf files of old config database new sql server attach sharepoint_config database on new server copied mdf files. run stsadm -o renameserver -oldservername oldserver -newservername newserver start sharepoint services stopped in 4. copy mdf files of content database

c++ - packet fragmentation for raw sockets -

if using raw sockets send udp packet of size 3000bytes, need handle packet fragmentation myself in code, or should raw socket handle fragmentation similar dgram socket? well, if using udp, aren't sending raw. raw no ip @ all, in case yes have handle fragmentation yourself. with udp ip's fragmentation support, imho plenty enough short-haul networks collisions should minimal. make link between 2 systems dedicated subnet, , isn't issue @ all. what tcp buys on udp (among other things) stack's ability have resend 1 fragment if gets lost or hosed somehow. udp if happens entire message must discarded. there's overhead though, , modern networks can live trade-off.

java - Why doesn't this method of getting user input work? -

i have following code i'm using user input integer, check make sure input valid, , if not, ask input again. when code run, works fine until invalid input given, @ point code loops without pausing ask input again until stack overflow occurs, , have no idea why. code: //create scanner object private static scanner in = new scanner(system.in); //function input in integer form, complete exception handling //a value of -1 means user done inputing public static int getint() { int num; //begin try block try { //get user input integer num = in.nextint(); //make sure integer positive. throw exception otherwise if (num < -1) throw new inputmismatchexception(); } //if exception occurred during inputting process, recursively call function catch (inputmismatchexception e) { system.out.println("error: input must positive integer, or -1."); system.out.print("enter score: ")

plugins - Eclipse PluginDevelopment: How to set ProblemMarker for IFolder? -

when developing eclipse plugin, best way set problemmarker empty ifolders? trying achieve following: im using own project type, , want folders in package explorer marked , decorated warning when empty. what can add markers when opening eclipse. dont know how update markers when changes occur. i tried way: using method : public void resourcechanged(iresourcechangeevent event) (is called whenever in workspace changed) i checking folders if empty (works) then adding problemmarker on ifile instances. (does not work, because adding problemmarker locked while being in method resourcechanged) because changing markers fires resourcechanged event. so usual way solve problem? guess there 1 because in eclipse whenever change in package explorer decorators updated instantly. you try create builder checks problems , creates markers needed. this article you

sql - Grouping and summing items in a table using SSRS -

i have ssrs report, , i'm trying sum rows conditionally. have: 11/15/2010 12:14:43 | current rate | current speed | amount used in minute (speed*rate/60) etc etc etc i trying add rows happened in hour, report show: 11/15/2010 | 12 - 1 | amount used hour (say, 7 gallons) i cannot find anywhere how conditionally sum row per hour, or how report above. thank in advance! using following table testing: create table `log` ( `entry_date` datetime default null, `amount_used` int(11) default null ) with test data: entry_date amount_used 2010-11-01 10:00:00, 3 2010-11-01 10:30:00, 1 2010-11-01 11:00:00, 6 use query date, hour range , total amount used: select date(entry_date) entry_date, concat_ws('-',convert(min(hour(entry_date)), char(2)), convert(max(hour(entry_date)),char(2))) hours, sum(amount_used) amount_used ( select entry_date, sum(amount_used) amount_used log group date(entry_date), hour(entry_date) )

ruby on rails - Redis and Memcache or just Redis? -

i'm using memcached caching in rails 3 app through simple rails.cache interface , i'd background job processing redis , resque. i think they're different enough warrant using both. on heroku though, there separate fees use both memcached , redis. make sense use both or should migrate using redis? i using memcached caching because least used keys automatically pushed out of cache , don't need cache data persist. redis new me, understand it's persistent default , keys not expire out of cache automatically. edit: wanted more clear question. know it's feasible use redis instead of both. guess want know if there specific disadvantages in doing so? considering both implementation , infrastructure, there reasons why shouldn't use redis? (i.e., memcached faster simple caching?) haven't found definitive either way. assuming migrating memcached redis caching easy enough, i'd go redis keep things simple. in redis persistence optional, can

SQL Server code to duplicate Excel calculation that includes circular reference -

is there way duplicate formula circular reference excel file sql server? client uses excel file calculate selling price. selling price field (costs/1-projected margin)) = 6.5224 (1-.6) = 16.3060. 1 of numbers goes costs commission defined sellingprice times commission rate. costs = 6.5224 projected margin = 60% commissions = 16.3060(selling price) * .10(commission rate) = 1.6306 (which part of 6.5224) they around circular reference issue in excel because excel allows them check enable iterative calculation option , stops iterations after 100 times. is possible using sql server 2005? thanks don this business problem, not one, follows need business solution, not one. doesn't sound you're working particularly astute customer. essentially, you're feeding commission costs , recalculating commission 100 times. salesman earning commission based on commission?!? seriously? :-) i try persuading them calculate costs , commissions separately. in profe

css - How to make a:hover, hyperlinked color gradient? -

i want make effection: a{color:#000;} , when make a:hover, hyperlinked color gradient #00c #000 , gradient time maybe 1 second. make css? no, cannot done in css. except maybe behaviour, ie , pretty shady. you'll need bit of javascript register onmouseover , onmouseout events, handle fade.

asp.net - How can i diagnose IIS pushing the CPU to 100% usage? -

i have web server more few asp.net sites running on it. every often, notice iis pushing server's cpu 100%. sites share application pools, per .net version running. what i'm looking way able pinpoint site is doing this, using tool. if tool happened down code show it, nice. if not, i'm happy knowing site causing issue. i've tried using ants. however, ants need know site is, , have running , waiting on said cpu-crashing web app. not ideal. any experience/ideas? use task manager pid of process taking of cpu, use answers this question match pid web site.

python - What does [:] do? -

return self.var[:] what return? python permits "slice" various container types; shorthand notation taking subcollection of ordered collection. instance, if have list foo = [1,2,3,4,5] and want second, third, , fourth elements, can do: foo[1:4] if omit 1 of numbers in slice, defaults start of list. instance foo[1:] == [2,3,4,5] foo[:4] == [1,2,3,4] naturally, if omit both numbers in slice entire list back! however, copy of list instead of original; in fact, standard notation copying list. note difference: >>> = [1,2,3,4] >>> b = >>> b.append(5) >>> [1, 2, 3, 4, 5] >>> >>> = [1,2,3,4] >>> b = a[:] >>> b.append(5) >>> [1, 2, 3, 4] this occurs because b = a tells b point same object a , appending b same appending a . copying list a avoids this. notice runs 1 level of indirection deep -- if a contained list, say, , appended list in b , still change a . by way, the

MPMoviePlayerController wont play movie on iPhone 3G when in release mode but will in debug mode -

ok, i've got weird 1 here... have issue mpmovieplayercontroller , playing m4v movie on old iphone 3g. when connect device mac, , run through xcode build set device|debug - movie plays fine . when change build device|release, mpmovieplayerplaybackdidfinishnotification called error of "this movie format not supported" , movie not shown. running 4.1 on device, , have 4.1 set base sdk. do have ideas? thanks chris maybe problem video encoding. try example video provided in tutorial: http://mobiledevelopertips.com/video/getting-mpmovieplayercontroller-to-cooperate-with-ios4-3-2-ipad-and-earlier-versions-of-iphone-sdk.html if problem still occurs, let me know.

c# - Why is calling Dispose() in a finalizer causing an ObjectDisposedException? -

i have nhibernate repository looks this: public class nhibrepository : idisposable { public isession session { get; set; } public itransaction transaction { get; set; } // constructor public nhibrepository() { session = database.opensession(); } public iqueryable<t> getall<t>() { transaction = session.begintransaction(); return session.query<t>(); } public void dispose() { if (transaction != null && transaction.isactive) { transaction.rollback(); // objectdisposedexception on line } session.close(); session.dispose(); } ~nhibrepository() { dispose(); } } when use repository this, runs fine: using (var repo = new nhibrepository()) { console.writeline(repo.getall<product>().count()); } but when use this, throw objectdisposedexception : var repo = new nhibrepository(); console.writeline(repo.g

Python SQL DB string literals and escaping -

anyone know if mysqldb automatically escape string literals sql statements? for instance trying execute following: cursor.execute("""select * `accounts` `account_name` = 'blah'""") will escape account name automatically? or escape if following?: x = 'blah' cursor.execute("""select * `accounts` `account_name` = %s""", (x)) or both? can clarify can't find information on it. there no escaping in first example, raw sql query. it's valid, it'll work, makes sense if want search account blah . when need account name in variable, need parameterised version. example may not work expected (x) isn't tuple, it's value x . x in tuple sequence (x,) . avoid confusion may prefer use list [x] .

asp.net - .ASPXROLES membership roles cookie expiry -

using asp.net 2.0, forms authentication. test, configured roles cookie in web.config : <rolemanager enabled="true" cacherolesincookie="true" cookiename=".aspxroles" cookietimeout="2"></rolemanager> i wanted see happen when cached role cookie expired. using fiddler, after 2 minutes had elapsed, see raw value of role cookie had changed. i expecting on expiry, asp.net re-read roles information database, , repopulate cookie same value. question is, why raw value of cookie change after expiry ? cookie value not human-readable (base 64 encoded and/or encrypted ?), can't tell if information in same, although application still seems work fine. edit : it looks each time roles encrypted , cached in cookie, gets different raw value. e.g. if run following code : roleprincipal rp = (roleprincipal) user; string str = rp.toencryptedticket(); label1.text = str; you different value each time. behavior seems normal.

dotnetnuke - export data from dot net nuke -

i'm migrating data dnn platform, , need way extract database tables 1 one in useful format xml, csv etc. is there way dump , export whole database or few tables @ time? cheers it sql server database, standard sql server tools work (e.g. bcp ). also many dnn modules explicitly support import/export of content.

iphone - SubTitle for Navigation Bar -

does know how subtitle bar in navigation bar, nytimes (where latest news). part of navigation bar since stays still. here looks @ nytimes (but whole lot of other apps same). http://cl.ly/362d181q3l2i111q2q46 the top part of highlighted area (where says "latest news updated moments ago") custom view have created , assigned table view's tableheaderview property. the bottom part of highlighted area (where says "today") table section header. each section in table gets optional header. made theirs implementing – tableview:titleforheaderinsection: in class implementing uitableviewdatasource protocol , returning string @"today" section.

linux - detect automatic key-repeats in curses -

i'm writing little text mode application using curses on linux. for keyboard input use curses functions. key auto-repeats work, e.g. if hold key down multiple key events until release key again. is possible distinguish between real key events , generated key repeat logic? background: application little data-entry front-end user can modify integer numbers of parameters. in long run application work without standard keyboard. have 4 buttons data-entry: 'increase', 'decrease', 'ok' , 'cancel'. since number ranges large i'd know if user holds down key. if can scan faster through numeric range not incrementing number 1 10 or maybe 100. if user otoh taps key input method should precise again , increase/decrease numbers one. is possible keyboard input functions of curses? no - curses receives keys terminal. if need try find out if key repeats automated or not looking @ delay between each keypress. however, on remote connections,

salesforce - How to handle error in Messaging.sendEmail()? -

i wrote code send email. works fine goal is: when sent non-existing email address, want log result 'false' or 'failure' etc (and when email address valid, 'success') i've tried 2 things code below. provided non-email string 'foo@!' provided non-existing email address 'thisdoesnotexistignsdfkjsdf@gmail.com' result: execute case 1 caused code go catch block outputting error message on html page expected. execute case 2 caused code return 'ok sent!' and after few minutes received email delivery failed. my guess sendemailresult object's issuccess() not responsible non-existing email address check. cares if email fired??? is there way log if email account not exist can log such occasion in apex code? try { messaging.sendemailresult[] resultmail = messaging.sendemail(new messaging.singleemailmessage[] { mail }); resultmail[0].geterrors(); //display success or error message if (re

wolfram mathematica - Custom Notation question -

Image
i need extract restrict value lists sublists, ie if vals gives values of vars={x1,x2,x3,x4} , , need values of svars={x2,x4} restrict[list,vars,svars] where restrict[vars_, svars_, vals_] := extract[vals, flatten[position[vars, #] & /@ svars, 1]] i'd improve code readability, perhaps defining following custom notation restrict[vars,svars,vals] http://yaroslavvb.com/upload/custom-notation.png my questions are what way implement this? is idea altogether? good notations can useful - i'm not sure particular 1 needed... that said, notation package makes pretty easy. there many hidden boxes when use notation palette, i'll use screenshot: you can see underlying notationmake* downvalues construct using action -> printnotationrules option. in[4] in screenshot generates notationmakeexpression[ subscriptbox[vals_, rowbox[{vars_, "|", svars_}]], standardform] := makeexpression[ rowbox[{"restrict", "[", ro

Ruby on Rails -- Saving and updating an attribute in a join table with has many => through -

to simplify things, have 3 tables : person has_many :abilities, through => :stats ability has_many :people, through => :stats stats belongs_to :people belongs_to :abilities stats has attribute called 'rating'. what i'd make edit person form lists abilities in database, , lets me assign each 1 rating. for life of me, can't figure out how this. managed work when creating new user this: (from people controller) def new @character = character.new @abilities = ability.all @abilities.each |ability| @person.stats.build(:ability_id => ability.id ) end end people form: <% @ability in @abilities %> <%= fields_for "person[stats_attributes]" |t| %> <div class="field"> <%= t.label @ability.name %> <%= t.hidden_field :ability_id, :value => @ability.id, :index => nil %> <%= t.text_field :rating, :index => nil %> </div> <% end %>

Using jQuery to change hover colour (from array)? -

i wondering if possible use jquery change colour of link when hovered, getting colour randomly array? have following not sure how grab random colour.. might super easy can't seem work out.. var colors = array("#fb2900", "#ff7800", "#fff43b", "#8dfa30", "#01c86a", "#00d7b2", "#0092e3", "#002f7e", "#390e73"); $("ul.menu li a").hover(function(){ $(this).css("color","#f0f"); //random colour going here }, function() { $(this).css("color","#ffffff"); }); why not try like: var colors = array("#fb2900", "#ff7800", "#fff43b", "#8dfa30", "#01c86a", "#00d7b2", "#0092e3", "#002f7e", "#390e73"), idx; $("ul.menu li a").hover(function(){ idx = math.floor(math.random() * colors.length); // pick random index $(this).css("color",

java - Reading from a CSV file -

try { bufferedreader br = new bufferedreader(new inputstreamreader(item.getinputstream())); string strline = ""; stringtokenizer st = null; while ((strline = br.readline()) != null) { st = new stringtokenizer(strline, "\t"); while (st.hasmoretokens()) { urlcnt = st.nexttoken(); srccnt = st.nexttoken(); contenttype = st.nexttoken(); verticle = st.nexttoken(); timeframe = st.nexttoken(); } if (con == null) { sqlconnection.seturl("jdbc:sqlserver://192.168.2.53\\sql2005;user=sa;password=365media;databasename=ln_adweek"); con = sqlconnection.getnewconnection(); stmt = con.createstatement(); } try { resultset rs; boolean hasrows = false; rs = stmt.executequery("select url urls_temp url='"+urlcnt+"'"); while (rs.next()) {

user interface - Add buttons to a ListField in BlackBerry -

i using listfield in blackberry , want include button 2 text fields in row like: button text1 text2 but not able add buttons. i've found adding images. take @ how customize list field in blackberry , blackberry - how add fields listfield

selenium rc - not able to run in chrome -

iam not able run selenium rc chrome.it runs fine in firefox.any 1 sucessful in running in chrome browser? these links help: sauce labs: available browsers google groups: selenium users > browser strings these browser strings available: *firefox *mock *firefoxproxy *pifirefox *chrome *iexploreproxy *iexplore *firefox3 *safariproxy *googlechrome *konqueror *firefox2 *safari *piiexplore *firefoxchrome *opera *iehta *custom *googlechrome this google chrome , not confused *chrome firefox. *chrome this 1 little confusing. 'chrome' of web browser usable space web page. is, if display 1024x768, chrome smaller. title, menu, toolbars, status bar, etc. reduce usable space, i.e. chrome. google chrome called chrome because 1 of main goals maximize chrome. selenium using keyword *chrome before google chrome , using firefox.

Java web framework to design UI easily -

i new java web. can recommend useful , efficient web framework create ui , develop code using java? core java developer. updated thank guidance guys planning go gwt ..and once again thankyou... java web frameworks might not in designing ui, in real sense. might need @ javascript frameworks that, i.e. yui, jquery, scriptaculous, extjs etc.. however, wicket , stripes, among java web frameworks rapid development. found related thread used java web frameworks.

asp.net - Using SELECT DISTINCT on an already created DataTable object? -

i have created datatable object using girdview (asp.net) need bind column of object dropdownlist. datatable has correct details in column column contains more 1 of same name in column - hence love kind of select distinct on datatable , copy new datatable use binding dropdown. this allow me save resources making trip database. here example, current datatable has column called items , in column has following entries 1 1 1 1 5 5 6 and of course need unique items binding dropdown, hence need following data 1 5 6 of course don't want change original datatable object rather make copy of new details any ideas if possible ? or need make trip db? thanks in advance datatable dt = new datatable(); dt = dsmobileinfo.tables[0].defaultview.totable(true, "columnname"); //applying dvresult data set grid for(int i=0;i hope work you.

SVN different update and commit sources -

i'm going check out repository source can't commit changes there. i'm gonna change code , submit own svn server. problem want keep code update-able original svn server, changes saved own server. is possible using externals? or try commit changes original server? if know way, possible done using tortoisesvn? sounds looking vendor branches

mvvm - WPF: Hiding ContextMenu when empty -

i have context menu gets menu items through databinding (i'm using mvvm pattern): <contextmenu itemssource="{binding path=contextmenuitems}" /> this works fine. however, in cases when there no menu items show, don't want context menu show @ all. there way accomplish this? kind of xaml trigger maybe? i've tried catching opened event och closing context menu when there no children. works context menu still flashes by... maybe bind menu items collections count property , use converter set context menu's visibility. <contextmenu itemssource="{binding path=contextmenuitems}" visibility="{binding path=contextmenuitems.count,converter={staticresource zerotohiddenconverter}}"> public class zerotohiddenconverter:ivalueconverter { public object convert(object value, type targettype, object parameter, system.globalization.cultureinfo culture) { int count = (int) value; if (

asp.net mvc - Getting Posted Data from a Dynamic Form with MVC -

i have page contains form, part of dynamically generated based off of sku's on order. <% each in viewdata.model %> <script type="text/javascript"> $(function () { $('#return_<%=i.skun%>').change(function () { if ($('#return_<%=i.skun%>').val() > $('#qty_<%=i.skun%>').val()) { $('#discrepancy').val("yes"); } else { $('#discrepancy').val(""); } }); }); </script> <tr> <td style="text-align: left"><%= i.skun%></td> <td style="text-align: left; width: 360px&qu

Algorithm to find duplicate in an array -

i have assignment create algorithm find duplicates in array includes number values. has not said kind of numbers, integers or floats. have written following pseudocode: findingduplicatealgorithm(a) // array mergesort(a); int <- 0 i<a.length if a[i] == a[i+1] i++ return a[i] else i++ have created efficient algorithm? think there problem in algorithm, returns duplicate numbers several time. example if array include 2 in 2 two indexes have ...2, 2,... in output. how can change return each duplicat 1 time? think algorithm integers, work float numbers too? to handle duplicates, can following: if a[i] == a[i+1]: result.append(a[i]) # collect found duplicates in list while a[i] == a[i+1]: # skip entire range of duplicates i++ # until new value found

What is the best way to let users upload pictures to my WPF application -

i have wpf intranet app running in trusted mode (local only). users able upload image , attach article on newsletters section. having trouble deciding these images stored. please provide me opinions. @ present have few ideas myself; have aspx page runs parallel app, , run inside browser(i-frame). page handle upload , display of image. also, have users copy directly network share. seems there should more elegant sollution not aware of. ideas? don't force solution towards aspx because know how there. it's unnatural build page, host browser show page etc, upload image. it's quite simpler in desktop client on web page. have "load file dialog" - use filepath user wants upload, , when have can either: copy (inside application) share, or if have service - send through method call, or can store inside database (recommended if files small) there's lots of options here... depends if client has connection db, have service in between, etc...

regex - Vim search and replace, adding a constant -

i know long shot, have huge text file , need add given number other numbers matching criteria. eg. identifying text 1.1200 identifying text 1.1400 and i'd transform (by adding 1.15) to identifying text 2.2700 identifying text 2.2900 normally i'd in python, it's on windows machine can't install many things. i've got vim though :) here simplification , fix on hobbs' solution: :%s/identifying text \zs\d\+\(.\d\+\)\=/\=(1.15+str2float(submatch(0)))/ thanks \zs , there no need recall leading text. str2float() single addition done on whole number (in other words, 1.15 + 2.87 give expected result, 4.02, , not 3.102). of course solution requires recent version of vim (7.3?)

Multi platform (android/iphone) chat -

i add chat feature application, runs on both iphone , android platform. have idea on how make ? i have seen tutorial : http://mobileorchard.com/tutorial-networking-and-bonjour-on-iphone/ , don't know if work using android ndk i have think writing architecture client/server in c i'm not sure if it's solution .. do have idea ? thanks i use xmpp standard: http://xmpp.org/ you can set existing xmpp server: http://xmpp.org/xmpp-software/servers/ and use existing libraries iphone / android applications: http://xmpp.org/xmpp-software/libraries/

.net - How can i see the total size of the ViewState by using Fiddler? -

where can see total size of viewstate out of total size of response (value in bytes in body column) in fiddler 2? thanks! you copy-paste value of __viewstate hidden-field (using "view source" in browser, works without fiddler) new text-file , check size of file.

hibernate - a different object with the same identifier value was already associated with the session error on save -

possible duplicate: spring + hibernate : different object same identifier value associated session i've been having problems hibernate annotations. have bidirectional relationship between 2 classes. here's mapping(thanks axtavt ): @entity public class receipt implements serializable { @id @generatedvalue(strategy=generationtype.auto) private long id; @onetomany(cascade = cascadetype.all, mappedby = "receipt") private list<collection> collections; ... } @entity public class collection implements serializable { @id @generatedvalue(strategy=generationtype.auto) private long id; @manytoone @joincolumn(name="receiptid") private receipt receipt; ... } but when try save receipt list of collections using: receipt r = new receipt(); list<collection> cols = new arraylist<collection>(); cols.add(new collection()); r.setcollections(cols); gethibernatetemplate().sa

c++ - Replace vector and hash table with Boost.Bimap -

i'm looking replace vector<string> , boost::unordered_map<string, size_t> mapping string indices in former boost::bimap . what instantiation of bimap should use? far, i've come with typedef bimap< unordered_set_of<size_t>, vector_of<string> > stringmap; but i'm not sure if i've reversed collection types now. also, wonder if should change collection of relations type . vector_of_relation best choice, or set_of_relation , or go default? to bimap between size_t , std::string have ~constant (up cost of hashing , potential clashes) need use unordered_set_of: #include <boost/bimap.hpp> #include <boost/bimap/unordered_set_of.hpp> #include <string> #include <iostream> #include <typeinfo> int main(int argc, char* argv[]) { typedef boost::bimap< boost::bimaps::unordered_set_of<size_t>, boost::bimaps::unordered_set_of<std::string> > stringmap; stringmap map; map

wpf - Where should I put list of UserControls and not break MVVM? -

i have tab control each tabitem usercontrol. i'd hold usercontrols in tabcontrol's itemssource. itemssource list go in window's viewmodel? if so, feel it's breaking mvvm since viewmodel have gui controls within it. or put list in codebehind of window holds tab control? any suggestions great! with tab controls, more not individual tabs created statically in xaml rather @ run time data binding. there no reason why shouldn't this. if have collection of views, should stored in view. bear in mind bind itemssource list of viewmodels objects , wpf generate view itemtemplate, viewmodel object set datacontext. collection of viewmodels should stored in view model, although @ point view model have stored in view.

google chrome - jQuery: HTML is not updated after manipulating <img src> paths -

i loading external content via jquery method load , manipulate src attribute of img elements loaded follows: <div id="content"></div> <script> $("#content").load("additional_content.html #content table", function() { $("#content").find("img").each(function() { $(this).attr("src", "new_path/" + $(this).attr("src")); }); }); </script> while inspecting parent html via firebug, source code changed , reflects new image paths. however, html rendered within browser not updated , points old path. in addition, getting following error within chrome: xmlhttprequest cannot load file:///.../additional_content.html. origin null not allowed access-control-allow-origin. can me, please? the 'origin null not allowed access-control-allow-origin.' happening because opening page locally on machine , not via web address. chrome checking not making cross-

Android Inline Images in Email -

any 1 can suggest how add images in email body ? tried it, no answer. here code: intent sendintent = new intent(intent.action_send); sendintent.settype("image/jpeg"); sendintent.putextra(intent.extra_email, new string[] { "gmail@gmail.com" }); sendintent.putextra(intent.extra_subject, "photo"); sendintent.putextra(intent.extra_stream, uri.parse("file://" + _path)); sendintent.settype("image/png;text/html"); string htmlecode = "<html><b>bold text works perfectly</b>" + "<img width='48' height='48' alt='' " + "src='http://upload.wikimedia.org/wikipedia/commons/7/7a/basketball.png' />" + "</html>"; sendintent.putextra(intent.extra_text, html.fromhtml(htmlecode, imggetter, null)); startactivity(intent.createchooser(sendintent, "email:")); wat's wrong in code ? there similar post here . su

asp.net mvc - Supporting custom compression algorithm for IIS served content -

i have bunch of internet devices communicate mvc app on iis 7.5. i'm using built-in dynamic transparent compression (gzip/deflate). i'd able support different compression algorithm, lot better gzip (7zip) content i'm sending/receiving. in other words, on client add header: accepts: gzip, deflate, 7zip (or similar), , server recognize this, , apply best choice when sending content. what's best way go hooking together? (i know how implement actual 7zip encode/decode aspect) thanks. on server side, can compress responses using httpmodule . httpmodule similar global.asax in exposes request , response lifecycle events beginrequest, releaserequeststate, , endrequest. can alter contents of response handling appropriate event , changing output stream. typically alter response attaching output filter . example, the blowery httpcompress module(no longer updated) attaches compression filters in releaserequeststate or presendrequestheaders events: http://

regex - C#: Read data from txt file -

i have .edf (text) file. file's contents follows: configfile.sample, software v0.32, cp version 0.32 [123_float][2] [127_number][0] [039_code][70] i wnat read these items , parse them this: 123_float - 2 127_number - 0 039_code - 70 how can using c#? well, might start file.readalllines() method. then, iterate through lines in file, checking see if match pattern. if do, extract necessary text , whatever want it. here's example assumes want lines in format [(field 1)][(field 2)] : // or wherever file located string path = @"c:\myfile.edf"; // pattern check each line regex pattern = new regex(@"\[([^\]]*?)\]"); // read in lines string[] lines = file.readalllines(path); // iterate through lines foreach (string line in lines) { // check if line matches format here var matches = pattern.matches(line); if (matches.count == 2) { string value1 = matches[0].groups[1].value; string value2

has and belongs to many - How can I join the same 2 models twice in Rails? -

i have app country preferences. user have 2 types of country preferences - event , research. in future there may more. leaning more towards having 2 tables represent on using sti. i'm having bit of trouble configuring rails elegantly this. hack rather rails convention. want this: class user < activerecord::base has_many event_countries, :through => :event_countries, :class_name => 'country' has_many research_countries, :through => :research_countries, :class_name => 'country' end class eventcountry < activerecord::base belongs_to :country belongs_to :user end class researchcountry < activerecord::base belongs_to :country belongs_to :user end class country < activerecord::base ... end this doesn't work though. given "pseudo code" know how implement in rails? i think you're going declaring them wrong, because should work properly. that's :through directive for: class user < acti

Objective-C: NSMutableString error -

i keep getting error code, app telling me trying mutate object not mutable. can take , explain doing wrong? thanks. thisrow = [nsstring stringwithformat:@"%i", startpointx2]; nsmutablestring* setcoordstr = [[nsmutablestring alloc] init]; [setcoordstr appendformat: thisrow]; if(w==1) { thiscol = [nsstring stringwithformat:@"%i", endpointy]; [setcoordstr insertstring:thiscol atindex:[setcoordstr length]]; } else { for(startpointy; startpointy<endpointy+1; startpointy++) { thiscol = [nsstring stringwithformat:@"%i", startpointy]; [setcoordstr insertstring:thiscol atindex:[setcoordstr length]]; } } nslog(@"%@ ", setcoordstr); you used appendstring: instead of first appendformat: and insertstring:atindex:

Django, need some specified groups of users -

i need let's instructors, students , on. both groups users, login etc. example instructor need many many relationship model subjects. how achieve that? create class instructors inherit users. within class provide many-to-many relationship. use profile module identify separation. there good examples of both here . edit: there good post james bennett here .

Using Javascript's typeof on DOM elements to check undefined (IE problem) -

i want iterate on list of dom elements (check boxes) , keep going long list defined. elements 'c1r1', 'c1r2', 'c1r3', etc. once hit undefined one, stop. problem seems using typeof dom elements. here's offending code: function domisdefined(idstring){ alert(idstring); var isitdefined = (typeof $(idstring) != 'undefined'); alert(isitdefined); return isitdefined; } ... for(i=1; domisdefined('c1r' + i); i++){ if($('c1r' + i).checked==true){ // stuff } } the crux of problem line: var isitdefined = (typeof $(idstring) != 'undefined'); the problem, found out, typeof $(idstring) returns object, whether defined or not. there way sort of thing? guess i'll put in try catch , check .checked property early, feels disgusting. function domisdefined(idstring){ return !!document.getelementbyid(idstring); }

jquery - Calling .NET 4.0 web service from ASP.NET 4.0 application generates a 403.1 error due to execute permissions -

i have created web service in .net 4.0 framework asp.net 4.0 site. both hosted on same server different sites. can access both sites no issues , invoke web service methods no problem itself. when try call web service asp.net page using jquery's ajax function generates error 403.1 execute permissions denied. confused cause this. running in iis 6 on server 2003. debugging calls fiddler2. appreciated issue due cross domain access, primary domain name same however, sub domain name different. jquery's ajax function not cross domain calls.

webkit - Disable XSS filter in Safari/WebView -

i'm developing tool xss checking, using webkit webview , macruby. works great, except safari's xss filter catches urls , refuses execute evil scripts. there way disable functionality, preferably programatically? so after digging found solution. there's undocumented, private method called 'setxssauditorenabled' on webpreferences. in case, did view.preferences.xssauditorenabled = false make work.

python - PyBluez does not detect the built-in bluetooth adapter -

i want start developing tools let me communicate between phone , computer via bluetooth, , want use python it. installed python bluetooth module (pybluez), not detect built in bt adapter (i'm on toshiba satellite a300). import bluetooth nearby_devices = bluetooth.discover_devices() print(nearby_devices) returns following error: traceback (most recent call last): file "c:/python26/bt.py", line 3, in <module> nearby_devices = bluetooth.discover_devices() file "c:\python26\lib\site-packages\bluetooth\msbt.py", line 9, in discover_devices return bt.discover_devices (flush_cache, lookup_names) ioerror: no bluetooth adapter detected any help? pybluez uses ms bluetooth driver stack , widcom windows, linux uses bluez. if laptop has different stack normal not work.

php - $.ajax trying to get $_GET query variables inside newly loaded ajax page -

alright have div #pagecontainer loads php page page_$var.php , $var page number, need url query string variables cant seem retrieve them newly page. example: loc=3&option=5 i cant grab inside new page 1) make sure page loading - output static value regardless of loc , option 2) print out $_server['query_string'] make sure parameters getting passed 3) print out dump of _get via var_dump($_get) good luck!

iphone - How can I avoid redundancy while declaring new class attributes in Objective-C? -

in code, every time need new object attribute class, typically copy/paste name in 4 different places! the declaration in header file ( nsobject * myobject; ) the @property() line the @synthesize() line in implementation releasing under dealloc: (only objects of course) i because works, not because understand what's going on. know declaration in header file allows other classes see attributes, property specifier determines how getter/setter methods constructed. , synthesize line builds getter/setter methods. know primitive types should use ( nonatomic,assign ) instead of ( nonatomic,retain ), have no clue when should omit nonatomic. what can avoid redundancy in code. if change or add variable in class have check 4 different places, , gets old fast. there key strokes make process faster? there lines of code can simplify or combine obtain same result? accessorizer automate lot of you.

asp.net - 2 update panels always posting back -

i have below page , racking brain why when have 2 update panels both post backs. can tell cause have 2 user controls- 1 in each panel , both fire page load events when left panel should posing , updating itself... or else whats point of update panels if in reality entire page posting back!!! what missing here? <asp:content id="stylecontent" contentplaceholderid="style" runat="server"> <link href="../styles/reportwizard.css" rel="stylesheet" type="text/css" /> <div class="clearfix"></div> <div class="wizardcontainer"> <asp:updatepanel runat="server" id="pnlwizard"> <contenttemplate> <table> <tr> <td> <asp:panel runat="

Java - ArrayList - Get a value from an Array of array -

i save values database using function (i've been replaced vector, because deprecated) : // database function public arraylist<string[]> selectquery(string query) { arraylist<string[]> v = null; string [] record; int colonne = 0; try { statement stmt = db.createstatement(); resultset rs = stmt.executequery(query); v = new arraylist<string[]>(); resultsetmetadata rsmd = rs.getmetadata(); colonne = rsmd.getcolumncount(); while(rs.next()) { record=new string[colonne]; (int i=0; i<colonne; i++) record[i] = rs.getstring(i+1); v.add((string[])record); } rs.close(); stmt.close(); } catch (exception e) { e.printstacktrace(); errore = e.getmessage(); } return v; } // here print result, after call function arraylist db_result=null; db_result=mydb.selectquery("select titolo, user, date articles category='1' order id asc&q