Posts

Showing posts from August, 2011

Do Android controls/widgets have choice of styles? -

i have column of checkboxes , associated edittexts , want 1 pair of these have distinct appearance because has distinct significance. short of writing custom controls, or using custom drawables, android have way style or alter appearance of basic controls buttons, checkboxes, etc, in xml control declared? or there 1 native style or appearance android checkboxes, buttons, edittexts, etc? thanks in advance. you can custom related style: http://developer.android.com/guide/topics/ui/themes.html in fact, android button textview different style. in source code, button extend textview no overriding.

geospatial - Problem with a column name contains a colon in PostgreSQL -

i downloaded shape data osm. have imported data shapefile postgresql without problem got error when select statement. select addr:city location; error: syntax error @ or near ":" the problem because of column name contains colon. me issue? should reject shapefile in importing process? shapefile normal? if enclose addr:city quotes should work: select "addr:city" "location"; and if want use openstreetmap data, don't have import shapefiles. instead, can import planet.osm (or regional subset) directly osm2pgsql .

flash - FlashDevelop - change default choice for autocompleted classes -

sometimes there name conflict between classes in 2 different libraries, exclusively use 1 on other. unfortunately, 1 using not showing first entry , have press down arrow pick it. how can change 1 shows first default? this not possible using flashdevelop. can see response developer in forum post similar question here: sorting types in codecompletion

Specifying relationships with YAML for Doctrine -

just trying specify tables structures , models doctrine in yaml file. i'm going through documentation on page: http://www.doctrine-project.org/projects/orm/1.2/docs/manual/yaml-schema-files/en i haven't quite got grasp on each line in relations section doing. here's sample yaml page: user: columns: username: type: string(255) password: type: string(255) contact_id: type: integer relations: contact: class: contact local: contact_id foreign: id foreignalias: user foreigntype: 1 type: 1 specifically, relations , in order: contact is.. guessing name of other corresponding table pertaining relationship? class: contact is.. exactly? name of model created yaml? local: contact_id local key, understand this. foreign: id field name of foreign key, understand this foreignalias: user line doing? foreigntype: one type: one: guessing these 2 lines specify type of relationship, eg,

.net - Cannot find System.Runtime.Serialization.Json in MonoTouch -

i beginner in monotouch. deserialize json data using datacontractjsonserializer. cannot reference system.runtime.serialization.json(only .formatters under system.runtime.serialization) in monodevelop. have referenced system.runtime.serialization. config , installation sequences are: 1. iphone sdk 4.2 2. mono 2.8.2 (not csdk version) 3. monotouch 3.2.4 eval 4. monodevelop 2.4 what problem? monotouch not ship datacontractjsonserializer simple serializer looks, brings in large set of libraries. you can use either system.json api or can try newtonsoft's json library.

c# - Getting "IErrorInfo.GetDescription failed with E_FAIL(0x80004005)" when querying "select * from open" -

i have c# app connected jet 4.0 engine. when run query "select * open" (i think "open" keyword , why i'm getting exception, but...) exception: "ierrorinfo.getdescription failed e_fail(0x80004005)". more human readable exceptions telling me wrong query. 1 looks more bug in jet engine. tested in microsoft access 2002 run same query , treats "open" valid name. can create table named "open" , whatever want it. need know if it's bug in jet engine can go ahead , replace weired looking message human readable 1 , show user, or if there problem code. i have been through same problem, try enclosing reserved word in square brackets i.e.: "select * [open]"

Is there a math nCr function in python? -

Image
possible duplicates: statistics: combinations in python counting combinations , permutations efficiently project euler problem in python (problem 53) i'm looking see if built in math library in python ncr (n choose r) function: i understand can programmed thought i'd check see if it's built in before do. the following program calculates ncr in efficient manner (compared calculating factorials etc.) import operator op def ncr(n, r): r = min(r, n-r) if r == 0: return 1 numer = reduce(op.mul, xrange(n, n-r, -1)) denom = reduce(op.mul, xrange(1, r+1)) return numer//denom

linker - undefined references with debgging symbols on android -

i trying compile app debug options set. have included android/bitmap.h file. compiles methods in android/bitmap.h file, linker has problems says /home/user5432/workspace/bitmapproj/obj/local/armeabi/objs-debug/mybitmap.o : in function java_com_example_plasma_plasmaview_renderplasma "undefined reference androidbitmap_getinfo" "undefined reference androidbitmap_lockpixels" "undefined reference androidbitmap_unlockpixels" can tell me what's problem? needed add local_ldflags +=-ljnigraphics in android.mk file

jsp - Error : Body could not be parsed as valid XML/AMF/JSON -

i calling jsp page flex using http request, getting error, "body not parsed valid xml/amf/json." in network monitor response tab getting whole jsp file, calling through http request. how can solve this? thanks. i had error turned out had different variable names , variable quantity in value object in flash builder compared mysql database after correcting this, error went away if read error few times kinda make sense

java - Inserting enum values into HashMap -

i doing program in need insert enum values hashmap. can that? tried out in many ways, failed. can please me? through program need implement hashmap containing 4 threadpools (whose names act key) corresponding have threapoolexcecutor object. below given code : public class mythreadpoolexcecutorpgm { enum threadpoolname { dr, pq, event, miscelleneous; } private static string threadname; private static hashmap<string, threadpoolexecutor> threadpoolexecutorhash; public mythreadpoolexcecutorpgm(string p_threadname) { threadname = p_threadname; } public static void fillthreadpoolexecutorhash() { int poolsize = 3; int maxpoolsize = 3; long keepalivetime = 10; threadpoolexecutor tp = null; threadpoolexecutorhash = new hashmap<string, threadpoolexecutor>(); threadpoolname poolname ; tp = new threadpoolexecutor(poolsize, maxpoolsize, keepalivet

.net - Use svcutil.exe with a webproxy -

i have scenario need consume service using svcutil.exe wsdl of service contains following sections <xsd:schema targetnamespace="http://tempuri.org/imports"> <xsd:import schemalocation="http://mysite/service.svc?xsd=xsd0" namespace="http://tempuri.org/"/> <xsd:import schemalocation="http://mysite/service.svc?xsd=xsd1" namespace="http://schemas.microsoft.com/2003/10/serialization/"/> <xsd:import schemalocation="http://mysite/service.svc?xsd=xsd2" namespace="http://schemas.datacontract.org/2004/07/pensjonskalkulator"/> <xsd:import schemalocation="http://mysite/service.svc?xsd=xsd3" namespace="http://schemas.microsoft.com/2003/10/serialization/arrays"/> </xsd:schema> problem these schema locations accessible through webproxy. if setup proxy in ie settings can browse schema locations in ie. looks svcutil.exe ignores these settings when downloading the

flex - how to stop objects go out of the container bounds when using move effect in flex4 -

the setup have container (tested group, panel, bordercontainer) size 500x100 inside container have 5 images 100x100 when apply move effect on images , move of them 100px right or left move ignoring bounds of parent container sit on top of it. move effect works ok when pictures go beyond application borders manage find solution put in mx:canvas smaller original container if want move staff in container size 500x100 create 1 499x99 , moving objects disappear when move effect reach end of container

ios - Any tutorial for UI Automation of iPhone using Java Scripting? -

i want automate ui testing of app. please tell me how use javascripting automate process. dint information after searching on google. the main resource on apple's site ui automation reference collection lists various interfaces, etc. available. if click "more" link @ top of above link brief overview provided, although i'd recommend @ least quick read of blog such " how perform ui automation testing in ios 4 " on over the code project .

SQL Server 2008 R2 First Time Login -

i've started work on new computer in had download software fresh. i've download copy of sql server 2008 r2, , i'm trying connect sql server management studio without success. vaguely remember last time installed this, asked me choose between windows, or sql server authentication, didn't happen installation. if try login via windows authentication (where username , password fields greyed out, localhost server name) gives following error: "a network-related or instance specific error occured while establishing connection sql server. server not found or not accessible. verify instance name correct , sql server configured allow remote connections. (provider: named pipes provider, error: 40 - not open connection sql server) (microsoft sql server, error: 2)" i have checked in sql server configuration manager, , bar via enabled. if try sql server authentication, asks me username , password definiately have not set yet. also, unde

c# - Approach for performing XSLT transformation on SQL Server -

i trying perform xslt transformation converting xml different xml format. using xslt extension objects perform data mapping operations during transformation. i have mentioned cut down version of xml formats below. there mapping table maps supplier product code productid in system. while transforming use extension objects such mapping operations. this works till time big xml document couple of 1000's of detail nodes in it. in such scenario extension object have performance impact. i wondering whether can shift xslt transformation sql server , handle data mapping operation @ db level rather making individual db call extension objects? source xml document <suppliersdocument> <supplierproducts> <product> <productcode>a001</productcode> <uom>kg</uom> </product> <product> <productcode>a002</productcode> <uom>ml</uom> </product> <product>

java - Draw nodes in e.g. a Chord ring -

i have set of nodes put ring. have numeric property use reference when putting ring. e.g, node param 32 comes after node para 22. what need library (or that) can make possible have correct "distance" between nodes, e.g: between 22 , 32 10 "units", , between 32 , 35 3 "units" "units" may empty numeric slot. sounds need sorted list end links start. know of no standard implementation, pretty easy implement 1 yourself. something doubly linked list head , tail connected work. add operations have traverse list find appropriate position insert into, making insert o(n) operation. make list perform realtivly poorly, pretty all standard list operations being o(n). you implement distancetonext and/or distancetoprevious pretty getting values of current , next/previous nodes , returning difference. edit: realised question title looking gui library draw these , hinted @ model might use. i'll have think gui. edit 2: problem boi

Vim: insert text from a file at current cursor position -

to insert text file in current vim buffer use :r filename insert text below cursor or :0r filename insert in first line. how insert contents of file [cursor] located? actual line coding [cursor] // todo later version line below actual line ... insert line break, read file, , take out line break...

html - textile - how do I add a class to a definition list? -

i'm using redcloth convert textile text html. one particular scenario seems particularly apt using definition lists . with redcloth, definition lists have syntax ( source ): - coffee := hot , black - tea := hot, little less black - milk := nourishing beverage baby cows. cold drink goes great cookies. =: i want add class "beverages" list (so generated code looks <dl class="beverages">... ). i've tried this: (beverages)- coffee := hot , black ... i tried: -(beverage) coffee := hot , black -(beverage) tea := hot, little less black ... this way style other lists ( ul s , ol s) in textile, didn't work dl s. text rendered literal paragraph ( <p>-(beverage) coffee := hot , black</p> ) is there syntax adding classes definition lists in textile, or must use raw html instead? the old - :- syntax not allow adding classes/ids, following work: ;(defclass#defid) lorem : lorem ipsum dolor sit amet will produce &

sql - xQuery LIKE-operator? -

is there way perform operation xquery in same way sql? i wan't construct "startswith", "endswith" , "contains"-expressions. example of want achieve: for $x in /user $x/firstname '%xxx' return $x $x in /user $x/middlename 'xxx%' return $x $x in /user $x/lastname '%xxx%' return $x is there way achieve in xquery? edit: got answer question above. new problem: would there way opposite way around? run queries sql equivalent not operator. possible? has in flwor-expression edit2: solved problem. can run fn:not(starts-with('123', '1')) , returns false. xpath 2.0 , xquery 1.0 (as standardized w3c) have regular expression support matches function http://www.w3.org/tr/xpath-functions/#func-matches : /user[matches(firstname, 'xxx$')] and of course there functions starts-with , contains (both in xpath 1.0/2.0), , ends-with (only in xpath 2.0) might suffice.

php - str_replace in Twig -

i want simple str_replace in twig template. i'm new twig , need add new filter or sth or use existing. how can this? can find list of filters available? to replace string stored in twig variables: {% set twig_content_variable= 'testing replace content'%} {% set replace_value_var= 'testing' %} {% set replace_with_value_var = 'testing complete' %} {{ twig_content_variable|replace({ (replace_value_var): replace_with_value_var }) }}

localization - php how to get the current decimal/thousand separator for a given locale -

i've set locale using setlocale() function let's "en_us". now i'm trying format currency without thousand separator this: $currency = number_format($value, 2, '.', ''); that works, have other currencies , want number_format use correct decimal separator according use locale. is there way current decimal separator somehow, based on locale has been set? localeconv() should it. manual: returns associative array containing localized numeric , monetary formatting information. here list of language strings recognized setlocale() on windows.

Glassfish Java App Class cast exception -

getting following exception when casting fqe.datahandler.liveupdatemessage cannot cast fqe.datahandler.liveupdatemessage sometimes happens, doesn't. object can never other class. if helps when getting object grizzly-comet's cometevent.message() function on glassfish 3. thanks in advance help. this due in servlet engine when have 2 instances of jar file being loaded different classloaders. maybe 1 in war , in classpath of engine ?

c# - building flexible and reusable class hierarchy -

let's review entities: company ; collaborator ; chief ; subordinate workers . there rules: collaborator 1 of these: sales , manager , employee ; sales , manager have subordinate workers (of type decribed in 1st rule); sales, manager, employee have chief; each role has own salary calculation method. so target create flexible & reusable class hierarchy. first thing confuses me "can have" phrase. should implemented composition? if said "can have many" should composition list of objects? should create abstract class collaborator , inherit 3 other types or there more smart way? what best way tie entities , have reusable assembly? "can have" , fact followed "workers" , tells me "has a" relationship (composition) 0 many relationship (so list mention empty) an abstract class collaborator seems reasonable.

java - String to ArrayList<String> -

i implementing spring mvc. different string values displayed on jsp page. help me move string values arraylist reduce bulky code. @controller("control") public class controller{ ... @requestmapping() public string init(renderrequest request, renderresponse response, model model) { try { string auth = request.getauthtype(); //all these strings moved arraylist<string> string context = request.getcontextpath(); string etags = request.getetag(); string remoteuser = request.getremoteuser(); string sessionid = request.getrequestedsessionid(); string rescontent = request.getresponsecontenttype(); string scheme = request.getscheme(); string getservername = request.getservername(); string getwindowid = request.getwindowid(); portletmode getportletmode = request.getportletmode(); //if these different types moved <?> portalcontext pcontext = request.getportalcon

Select something with location unkown from all tables in database in mysql -

i have varchar value of foo somewhere in database , don't know exactly. is possible create query search tables , columns content? similar grep there isn't easy way this, use information schema find varchar columns. select table_name, column_name information_schema.columns data_type = 'varchar'; you write query produce list of queries need run search term. select concat( 'select ', column_name, ' ', table_name, ' ', column_name, ' \'%foo%\'' ) stmt information_schema.columns data_type = 'varchar'; a more advanced example might insert matches results table along table , column names.

Retrieving the field names from sitecore item -

while searching keyword in sitecore using sitecore.seach returns item name(where located) search keyword. there option field name along item? i use following code: using (indexsearchcontext context = searchindex.createsearchcontext()) { searchhits hits = context.search(searchstring, new searchcontext(siteroot)); var results = hits.fetchresults(0, 100); foreach (searchresult result in results) { try { item item = result.getobject<item>(); if (item != null) { results.addresulttocategory(result, categoryname); } } ... } } if understand goal correctly, want find out exact fields (field names) search string found, right? if that's case, should collection of item fields ( item.fields ), , iterate through checking search string in field value. as far know, sitecore search shell application works same way when displaying results: item taken form searchresult , , field collecti

Folder access PHP on dedicated server -

can access folder on different account on same dedicated server via php? probably folders in server in */home/_folder_you_want_* (if host uses linux), , can define constant define('home', '/home/'), , include (like: include( home . ' folder ');) files want.

jquery javascript checkbox radio calculate sum of values complex form objects -

how calculate sum of values checkboxes, radios input type=text name=totalsum <script type="text/javascript"> $(function(){ $("table input:checkbox").click(function(){ if ( $(this).is(":checked") ){ $(this).parents("tbody").find("input:radio").attr("disabled",null); } else{ $(this).parents("tbody").find("input:radio").attr("disabled",true); } }); }); </script> <form method=post name=memform><table align=center> <tbody> <tr><td colspan=3><input type=checkbox name=serv1 value=1>ВъездАвто</td></tr> <tr><td><input type=radio price=6000 name=servch1 value=6000 ><a>г/п 10Т</a></td><td><a>Сумма:&nbsp;6000</a></td><td><a>НДС:&nbsp;1200</a></td></tr> <tr><td><input type=radio price=4200 name=

php - Apache configuration question about uri -

i have question i'm positive i'm missing vocabulary on it. basically, configuration in apache ignores past uri? for example: www.mydomain.com/my-page www.mydomain.com/this-is-some-page/somepage.html i want write url, have random text in it, @ same time load whatever page needs loaded. i'm thinking it's mod_rewrite can't find example ignore things past valid page. i'm thinking it's within php code i'm unsure on too. thanks help. yes, mod_rewrite let this, need more define how should determine part of uri matters , part should throw out. if that's determined files exist on disk may match part of uri, you'll have write php code figure out. is, you'd create rewrite rule send requests php script, looks @ $_server['request_uri'] , compares list of files determine 1 run or redirect to.

sql - Should I use a code in my lookup table -

i woking on orable database , adding couple of lookup tables. the general question should lookup table contain code , description , code fk main table, or should lookup table contain description , fk main table. i arguing code/description pair. feel if have type = contractor , code = cn stored proc should where type='cn' rather having type=contractor , no code , saying in stored proc: where type='contractor' because if want display: general contractor user rather contractor . have change stored proc. feel should not have this. (changing stored proc requires recompilation in dev, migration test, retesting clients, , migrating prod requires going through change control proccess involves 2 week waiting period; whereas modifying record in table not require of this) my data modeler wants use description. main argument require unnessesary join. which way should done? , if if should done code/description way how convince data modeler? thanks! type_cd t

How do I deal with a forced close message on Android? -

i having trouble debugging app causes pop-up "forced close" message every time try use android app. how can go around ? usually "force close" means getting exception not handling / expecting. use logcat check happing app , try fix it. you can use log cat this: .\adb.exe logcat if seeing info in log can filter log this: .\adb.exe logcat activitymanager:i your_app_tag:d *:s i don't use eclipse don't know if default eclipse console show happening application. hope helps, luck

System.Net.Mail send anonymous emails from ASP.NET 3.5 -

i'm needing send anonymous emails asp.net 3.5 app. website using active directory authentication, thing cannot use of user & pass send emails. is there way send anonymous emails asp.net?, heard there way in sql (i'm using 2005) stored procedure, prefer sure cannot website first. i have implemented using system.net.mail smtpclient class if don't specify host, user & pass doesn't work. thanks

ruby - Match as to the right as possible using =~ (regex) -

i'm trying work: data = "testing: download complete (this string) - priority 0 random value testing: download complete (this to) - priority 0 random value" puts $1 if data =~ /testing: download complete \((.*?)\) - priority.*?$/i i want print this to , right this string being printed. the idea value far right possible. use puts $1 if data =~ /.*testing: download complete \((.*?)\) - priority/i the initial .* match until end of line, , rest of regex backtrack as needed match. therefore, last possible match found.

Task execute well with Msbuild but not in visual studio -

i strange behaviour in visual studio vs executing msbuild in command line. a solution (s1) contains 3 project (p1,p2,pb). p1 , p2 "normal" vs project while pb xml msbuild file wrote myself. purpose of task pb contains modifying part of source code. i did configure dependencies p1 , p2 depends on pb sure pb first project execute. when compilation (pressing f6 key) in visual studio, files modified seems p1 , p2 start before modification result not expended. also, when in build console seems ok. and when launch compilation via "msbuild s1", perfected ! how can have same behaviour between vs2010 , msbuild ? thx everytime build vs solution creates .sln.cache file wich quite csproj file every project have in solution. thus modifying csproj files during build have no effect in current build (which uses .sln.cache file).

Python List Variable - Is it using the memory location or something? -

i'm trying pop off values i'm appending list m each time i've evaluated difference between them , expected values. i'm printing result of list before , after use m.pop() . using location in memory , messing list inside of deltal? m=[] delta = 3 while abs(delta) > 0.3: num1 in range(450,800,20): best_config_per_numl = [] delta_ml = [] config in ['fff','ffs','fsf','fss','sff','sfs','ssf','sss']: m.append(gen(num1,config[0])) m.append(gen(num1,config[1])) m.append(gen(num1,config[2])) xyl = [] xl = range(400,801,1) in xl: xyl.append([geny(m,i),i]) deltal = [] yl = range(400,801,1) in range(len(yl)): expected = yl[i] actual = xyl[i][0].real deltal.append(abs(expected - actual)) delta_ml.appe

ajax - JQuery - which form was submitted? -

i have page of products , each of them, want have form uses ajax update session. i've done bit - providing background. i use product's id create different form class , name each form, each form called this_form_name_567 , next this_form_name_568 , on. there submit button per form. i'm having trouble figuring out which event best use correct form identified when submit button clicked? once clicked, how make sure correct value taken hidden field (unique id) within submitted form can populate line of code such as: $.post("compare_response.php", {compare_this: $("#compare_this").val()}, function(data){ } you can use .closest tree traversal method form in button of interest nested: $("input[type=submit]").click(function() { alert($(this).closest("form").attr("id")); }); or simpler, element's form property :) $("input[type=submit]").click(function() { alert(this.form.id); }

css - JavaScript or JQuery Problem Div doesnt toggle -

i think im missing pieces this. im new javascript , jquery, , tried before, solution doesnt work either. i need sort-of drop down navigation effect similar on site: professional-painters.com click "quick contact" for reason contact isnt toggling. <%@ page language="c#" autoeventwireup="true" codebehind="webform2.aspx.cs" inherits="davincisapp1.webform2" %> <!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"> <head runat="server"> <title></title> <link href="~/styles/stylesheet1.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="scripts/jquery-1.4.1.min.js"></script> <%--<script type="text/javascript" src="scripts/motion.js&qu

ruby on rails - Problem: Cannot create mulitple table entries in an each-loop -

i'm trying loop through array in controller create new users array of email-adresses @emails.each |email| @user = user.new(:email => email) @user.save end now creates 1 user , not several array contains. i suspect, somehow have reinitialize new user differently controller handle on instance of it. doing wrong? are sure it's creating 1 user in db? code looks ok, @user ever refer single instance because re-set on each iteration through array. if you're wanting array of users @ end, better way of doing add them array (you use inject this): @users = [] @emails.each |email| @users << user.create(:email => email) end another reason due validations making record invalid. have validations on email? if want make blow if record invalid, use save or create bang (!)... @emails.each |email| user.create!(:email => email) end

javascript - Global variable doesn't get assigned the value -

i can't figure out. i have global variable named id. when call function below id doesn't return value of msg in less use bottom alert('inside bottom4 (id) =' + id) . if comment out alert, id value of global variable before calling function. oh btw, alert('after assignment=' + id); has correct return value. var id = 0; savetodb(obj); alert(id) function savetodb(lcalevent) { var thingid = parseint(lcalevent.userid); $.ajax({ type: "get", url: "res_update.asp", data: "id=" + lcalevent.id, success: function (msg) { if (msg.indexof('following') > 0) { notices.show('error', msg, { duration: 1000 }); $("#calendar").weekcalendar("refresh"); } else { if (msg != '0') { id = msg++; alert('after assignment=' + id); }

cocoa - How to stop the animation on a determinate NSProgressIndicator? -

nsprogressindicator allows stopanimation: when isindeterminate == yes , how 1 stop animation determinate progress bars? for context, progress bar trying child of nsview, view property of nsmenuitem. sending ridiculously high numbers setanimationdelay: want, temporarily -- when parent menu closed , re-opened, progress bar animated again. (possibly unnecessary disclaimer: swear legit use case; have able visually (i.e.: without using text) display progress of very-long-running tasks may pause , re-start needed backend. answers boil down "ui design: ur doin rong" not accepted unless accompanied brilliant alternative suggestion. ;) ) subclass nsprogressindicator this, works lion: @interface unanimatedprogressindicator : nsprogressindicator { @private bool isanimating; } @end @interface nsprogressindicator (heartbeat) - (void) heartbeat:(id)sender; // apple internal method animation @end @implementation unanimatedprogressindicator - (void) st

Grails/GORM saves in the wrong order -

i using grails 1.3.6 , having problems getting saves cascade properly. problem classes have 2 parent classes. simplified version of attempting this: class location { string city static hasmany = [authors: author, publishers: publisher] } class author { string name static belongsto = [location: location] static hasmany = [books: book] } class publisher { string name static belongsto = [location: location] static hasmany = [books: book] } class book { string title static belongsto = [author: author, publisher: publisher] } class srv1service { static transactional = true def loaddata() { def l1 = new location(city: "london") def a1 = new author(name: "graham greene") l1.addtoauthors(a1) def p1 = new publisher(name: "some press") l1.addtopublishers(p1) def b1 = new book(title: "the comedians") a1.addtobooks(b1) p1.addtobook

iphone - Pass a UImage to a UIImageView -

i trying pass image loaded uiimage instance uiimageview in detailviewcontroller. can see getting pulling image path successfully, , accessing .gif file seen in nslogs () : 2011-02-09 10:52:13.404 worldgovernments[31443:207] pathtomap = af-map.gif 2011-02-09 10:52:13.406 worldgovernments[31443:207] detail map is: <uiimage: 0x4e44a80> i uncertain on how pass image mapdetailsviewcontroller in following method? - (void)tableview:(uitableview *)tableview didselectrowatindexpath:(nsindexpath *)indexpath { mapdetailsviewcontroller *dvcontroller = [[mapdetailsviewcontroller alloc] initwithnibname:@"mapdetailsview" bundle:[nsbundle mainbundle]]; nsdictionary* tempdict=[sortedcountries objectatindex:indexpath.row]; nsstring *pathtomap = [tempdict objectforkey:@"map"]; nslog(@"pathtomap = %@",pathtomap); uiimage *detailmap = [uiimage imagenamed:pathtomap]; nslog(@"detail map is: %@",detailmap); mapdetailsviewcontroller.selectedimagev

Serial joins in a Rails 3 model; how to associate through a many-to-many relationship? -

i have model x , model y associated through has_and_belongs_to_many macro. there's table in database retains data on many-to-many relationships between model x , model y. i have model a, associated through has_many macro model x. want able run simple command reach model y objects associated model a. so, in other words, let's have following objects: objecta.kind_of? modela = true objectx.kind_of? modelx = true objecty.kind_of? modely = true i want able run objecta.objectys , have returned me [objecty]. what must put in model definitions able this? (i have tried placing in model a: (1) has_many :modely ; , (2) has_many :modely, :through => :modelx . neither right.) caveat: 1 wouldn't use such perverse model names. assuming models this: class modela < activerecord::base has_many :model_xes end class modelx < activerecord::base belongs_to :model_a has_and_belongs_to_many :model_ies, :class_name => 'modely', :join_t

osx - Mac keyboard shortcut to strip special characters and search selected text in youtube -

often @ podcasts tracklist , identify songs download. process looks this: go tracklist page select song name (which on occassion has underscores / hyphens instead of spaces) switch youtube tab paste text remove special characters such underscores and/or hyphens search i create keyboard shortcut take selected text, strip out special characters (mostly concerned hyphens , underscores), , create youtube search in new tab. on mac os x 10.6 , use firefox part. ideas? greasemonkey might able out here, or may use bookmarklet: javascript:void(window.open("http://www.youtube.com/results?aq=f&oq=&search_query="+window.getselection().tostring().replace(/\w+/g,'+')));

dynamic progress bar in android web view -

hello how can add page loading progress in . when page load prgress bar should .i want put code in case statement . in advance . here code package com.menu; import android.app.activity; import android.os.bundle; import android.view.menu; import android.view.menuinflater; import android.view.menuitem; import android.webkit.webview; import android.webkit.webviewclient; import android.widget.toast; public class menuactivity extends activity { webview mwebview; /** called when activity first created. */ @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); mwebview = (webview) findviewbyid(r.id.webview); mwebview.getsettings().setjavascriptenabled(true); mwebview.loadurl("http://www.google.com"); mwebview.setwebviewclient(new webviewclient()); } public boolean oncreateoptionsmenu(menu menu) { new menuinflater(getapplication()) .inflate(r.layout.menu, menu);

How to fetch output of page as string in ASP.net -

i want fetch output string. want run webpage code www.example.com after running want keep whole values in string , again in next step want search anchor href values string. how domain ouput string asp.net. it sounds you're trying scrape website. may help: http://www.beansoftware.com/asp.net-tutorials/screen-scraping-web-fetching.aspx

asp.net - Accessing user control properties defined in code behind in markup -

i have public property defined in code behind of user control. want toggle visibility of controls in markup based on property's value. however, using following syntax: <td style="display:<%#(container.pagecontrolmode == pagecontrolmode. pagemode.wizard) ? "none" : "inline" %;"> i have following property in code behind: public pagemode pagecontrolmode { get; set; } does not work , generate errors. way around it? <td style="display:<%#(container.pagecontrolmode == pagecontrolmode. pagemode.wizard) ? "none" : "inline";%>"> try that

PHP: Check for duplicate values in a multidimensional array -

i have issue multidimensional arrays. given following multidimensional array: array( [0] => array("a", "b", "c") [1] => array("x", "y", "z") [2] => array("a", "b", "c") [3] => array("a", "b", "c") [4] => array("a", "x", "z") ) i want check values , find duplicates (i.e. keys 0, 2 , 3) leaving 1 key - value pair deleting others, resulting in somthing this: array( [0] => array("a", "b", "c") [1] => array("x", "y", "z") [2] => array("a", "x", "z") ) how can that?? this remove duplicate items array using array_unique() : $new_arr = array_unique($arr, sort_regular);

mysql - How to optimize this SQL query? (Movie Database) -

i'm using mysql , reason takes lot of time execute queries this: select distinct (movies.id) id, movies.unmoid unmoid, movies.runtime runtime movies inner join acted on acted.unmoid = movies.unmoid inner join actors on acted.unmoactorid = actors.unmoactorid inner join directed on directed.unmoid = movies.unmoid inner join directors on directed.unmodirectorid = directors.unmodirectorid actors.name '%spiderman%' or directors.name '%spiderman%' or movies.originaltitle '%spiderman%' or movies.englishtitle '%spiderman%' or movies.alsoknownas '%spiderman%' or movies.taglines '%spiderman%' or movies.plot '%spiderman%' , movies.validated =1 , movies.agecertificate <=20 group movies.id order added desc this give me: "executed query in 6.5320 seconds , got 2 result(s)." explain particular query gives: id select_type table type possible_keys key key_len

unit testing - How to separate production and test code in Haskell -

in other languages put unit tests in different directory structure production code keep things cleanly separated. there typical convention in haskell of how or similar? there typical convention codified @ http://www.haskell.org/haskellwiki/structure_of_a_haskell_project . additionally, can add test build main cabal in https://github.com/ekmett/speculation/blob/master/speculation.cabal there bonuses separate cabal method. namely testing methods quickcheck generators datatypes available in second project-test style cabal others can import if using data structures in projects, prefer single cabal approach. depends on purpose of library though. haskell testing workflow useful more testing info.

apache - How to fetch HTTP headers in perl when using CGI -

i'm using perl/cgi/apache , want fetch x-forwarded-for http header. how do that? except few headers handled specially, cgi stores value of header-name: in environment variable http_header_name . so, x-forwarded-for (if present in request) should found in $env{http_x_forwarded_for} .

javascript - Why this handler is not restricted to CTRL+L? -

i have xbl handler following signature: <handler event="keypress" modifiers="control" keycode="dom_vk_l"> as see, should fired when user press ctrl+l . but, reason, fires when user press ctrl+. why? , how make work exclusively ctrl+l ? there's no such attribute keycode in current standard . if meant implementation, not follow standard, should mention in question text. and if speak mozilla xbl1.0, need use 1 followings: <handler event="keyup" modifiers="control" keycode="dom_vk_l"> <handler event="keypress" modifiers="control" charcode="108"> 108 ascii code small l.

android - How can I parse a seemingly standard Timestamp in Java? -

very simple task. want reformat timestamp sent me service format of wed, 26 jan 2011 22:27:09 +0000 . string format = "eeee; mmmm d, yyyy"; string timestamp = "wed, 26 jan 2011 22:27:09 +0000"; date date = new simpledateformat(format).parse(timestamp); log.d("test", date.tostring()); i haven't been able find formats .parse() method allow 1 throws parseexception . have tried: string format = "eee, dd mmm yyyy hh:mm:ss z"; when use format parse test string, (in central time): wed jan 26 16:27:09 cst 2011

c# - How to Run a Program from a Console Application? -

i looking resources have examples creating console application. past "hello world" stage stumped @ point need run application. have string need run pulled batch file trying automate in c# app. need knowing classes , namespaces have functionality need run it. edit: sorry poorly asked question. i'll rewrite it. i trying create console application replace batch file have partially written. of data , file manipulations need more complex can done in batch file. far reading, writing, , manipulating files fine. having difficulty when trying figure out how run command execute application on server proper arguments being passed in. update: coworker gave me following code snippit needed move forward. sorry question worded badly. public static string mydosmethod() { processstartinfo si = new processstartinfo("cmd.exe"); si.redirectstandardinput = true; si.redirectstandardoutput = true; si.useshellexecute = false;

Access SQL Query Help Using Not Exists -

i have table named sys_event_log following columns: user_name, event_type, event_message, time_stamp login , logout events tracked event_type of either "login success" or "logout event" using sql in access i'm trying return list of distinct users have logged database have not yet logged out based strictly on event log event_types , time_stamps. the query have come far is: select distinct a.user_name, a.event_type, a.time_stamp sys_event_log not exists ( select 1 sys_event_log b b.time_stamp > a.time_stamp , a.user_name = b.user_name , a.event_type = "logout event" ) , a.event_type = "login success"; it feels close not returning expected dataset. select a.user_name , count(*) logins , ( select count( b.time_stamp ) sys_event_log b b.user_name = a.user_name , b.event_typ

objective c - Validating fonts and colors NSToolbarItem items -

using cocoa latest sdk on osx 10.6.6 i have nstoolbar custom toolbar items , built in fonts , colors nstoolbaritem items (nstoolbarshowfontsitem , nstoolbarshowcolorsitem identifiers). i need able enable/disable in various situations. problem validatetoolbaritem: never called these items (it being called other toolbar items). the documentation not clear this: the toolbar automatically takes care of darkening image item when clicked , fading when disabled. code has validate item. if image item has valid target/action pair, toolbar call nstoolbaritemvalidation’s validatetoolbaritem: on target if target implements it; otherwise item enabled default. i don't explicitly set target/action these 2 toolbar items, want use default behavior. mean can't validate these items? or there other way can this? thanks. after trial , error, think able figure out , find reasonable workaround. post quick answer here future reference others facing sa

memory leaks - Javascript remove all descendants of a div/node -

i've been working on memory leaks in javascript time now. i've come point feel solution @ least of leaks remove given div , of it's descendants. meaning children, grandchildren, etc. now i'm under impression need recursive function if want this, i'm still new javascript. don't know if recursion works same way in javascript i'm used to. i'm open ideas on how such thing, perhaps i'm way off mark idea of recursion. this destroy node , children: var _dummynode; var destroy = function(node){ if(!_dummynode) _dummynode = document.createelement('div'); _dummynode.appendchild(node.parentnode.removechild(node)); _dummynode.innerhtml = ""; } destroy(nodetodestroy); it creates dummy div never gets appended doc doesn't show. node removed parent , appended dummy. it's wiped out innerhtml. however - fail if still have variable references nodes. should use ajax library , use appropriate addeventlistener a

asp.net - Serialize Control to viewstate -

i'm writing custom user control. feel i'm doing hard way. i understand in order control's state preserved between postbacks, have save data viewstate. i've done several fields in user control's class. however, seems tedious. there way make asp.net save serializable fields in user control viewstate @ once when page done loading? i have solution still need adapt situation because sample (re)stores state of control, properties set asp.net runtime. remember serializable not settable on property of field, class/struct. can create own attribute (viewstateserializable?) use decorate properties want retain during postbacks. remember viewstate going on wire client if have lot of users might upset.... protected override object saveviewstate() { dictionary<string, object > dict = new dictionary<string, object>(); foreach (var prop in this.gettype().getproperties()) { // here decide sa

flash - How would I go about hideing a specified value from displaying in an array in a datagrid? -

for example, have: public var usersonlinearray:array = new array(bob,jim,tim,marry,luke); and when put datagrid this: buddylist.dataprovider = new dataprovider(usersonlinearray); buddylist.rowcount = buddylist.length; bldbuddylist(buddylist); how i, let's say, prevent luke appearing in datagrid? make him not appear technically "still there" can make him reappear later but? i'd start using arraycollection rather array since can make use of data binding way. arraycollection has filterfunction property allow hide things still keep them in collection. docs expand on of gist is: make arraycollection, takes plain ole array in constructor. public var usersarr:array = [bob, jim, tim, marry, luke]; public var usersac:arraycollection = new arraycollection(usersarr); set ac data provider list. buddylist.dataprovider = usersac; define filter function. function takes object , returns true if should visible, false if not. public function myf

Better alternative to Strategy pattern in Scala? -

when i'm programming in java (or similar language), employ simple version of strategy pattern, using interfaces , implementation classes, provide runtime-selectable implementations of particular concept in code. as contrived example, might want have general concept of animal can make noise in java code, , want able select type of animal @ runtime. write code along these lines: interface animal { void makenoise(); } class cat extends animal { void makenoise() { system.out.println("meow"); } } class dog extends animal { void makenoise() { system.out.println("woof"); } } class animalcontainer { animal myanimal; animalcontainer(string whichone) { if (whichone.equals("cat")) myanimal = new cat(); else myanimal = new dog(); } void doanimalstuff() { ... // time animal make noise myanimal.makenoise(); ... } simple enough. recently, though, i&#

java - Convert Byte[] to int -

i have method converts signed or non-signed byte int , doesn't return supposed return. can point out issue in below code? public int convertbytetoint(byte[] b){ int value= 0; for(int i=0;i<b.length;i++){ int n=(b[i]<0?(int)b[i]+256:(int)b[i])<<(8*i); value+=n; } return value; } edited : i'am actualy reading wav file in order calculate snr. returned value conversion should give beetween 0 , 255. application should compare 2 waves file, on orignal 1 , other modified , calculate snr . are writing code exercise, or looking way it? if latter, suggest using bytebuffer . has getint method should trick.