Posts

Showing posts from March, 2014

observer pattern - magento change default number rows displayed in adminhtml grid pages -

i set default number of displayed rows in admin higher 20. following along @ http://inchoo.net/ecommerce/magento/magento-admin-grid-how-to-change-number-of-rows/ , i'm trying make module task. magento version 1.4.2.0. the error getting mage registry key "_singleton/grid/observer" exists . i have in app/code/local/company/custom/etc/config.xml : <config> <adminhtml> <events> <core_block_abstract_prepare_layout_before> <observers> <grid_observer> <class>grid/observer</class> <method>applylimittogrid</method> </grid_observer> </observers> </core_block_abstract_prepare_layout_before> </events> </adminhtml> </config> and in app/code/local/company/custom/model/observer.php : class company_custom_grid_model_observer { public function applylimittogrid(varien_event_observer $observ...

ruby on rails - Capybara: How to test the title of a page? -

in rails 3 application using steak, capybara , rspec how test page's title? since version 2.1.0 of capybara there methods on session deal title. have page.title page.has_title? "my title" page.has_no_title? "my not found title" so can test title like: expect(page).to have_title "my_title" according github.com/jnicklas/capybara/issues/863 following working capybara 2.0 : expect(first('title').native.text).to eq "my title"

Injecting data caching and other effects into the WCF pipeline -

i have service returns same results given parameter. naturally cache results on client. is there way introduce caching , other effect inside wcf pipeline? perhaps custom binding class site between client , actual http binding. edit: just clear, i'm not talking http caching. endpoint may not http , looking @ far more effects caching. example, 1 effect need prevent multiple calls same parameters. the wcf service can use cache-control directives in http header client how should use client side cache. there many options, the part of http protocol . can example define how long client can data local cache instead of making requests server. clients implemented http, web browsers, follow instructions. if client use ajax requests wcf server, corresponding ajax call return data local cache. moreover 1 can implement many interesting caching scenarios. example if 1 set "cache-control" "max-age=0" (see here example), client make revalidation of ca...

Is it just me or something is seriously wrong with new Python futures module on windows -

i on windows xp , have problems new python 3.2 futures module. seems unable processpoolexecutor work. session example: python 3.2 (r32:88445, feb 20 2011, 21:29:02) [msc v.1500 32 bit (intel)] on win32 type "help", "copyright", "credits" or "license" more information. >>> concurrent import futures >>> executor = futures.processpoolexecutor() >>> def pio(x): ... print("i here") ... return true ... >>> fut = executor.submit(pio, 5) >>> process process-1: traceback (most recent call last): file "c:\python32\lib\multiprocessing\process.py", line 259, in _bootstrap self.run() file "c:\python32\lib\multiprocessing\process.py", line 114, in run self._target(*self._args, **self._kwargs) file "c:\python32\lib\concurrent\futures\process.py", line 133, in _process_worker call_item = call_queue.get(block=true, timeout=0.1) f...

python random number -

i wondering if can clarify line me. create function die(x) rolls die x times keeping track of how many times each face comes , returns 1x6 array containing these numbers. i not sure means when says 1x6 array ? using randint function numpy output array (or list) im not sure. thanks def die(x): return np.bincount(np.random.random_integers(0, 5, size=x)) np.random.random_integers(0,5,size=x) rolls die x times (faces represented numbers 0 5 including). np.bincount() returns number of occurrences of each value in array i.e., how many times each face comes up. example >>> = np.random.random_integers(0, 5, size=10) >>> array([3, 5, 0, 5, 0, 5, 5, 1, 3, 0]) >>> np.bincount(a) array([3, 1, 0, 2, 0, 4])

java - How can I extract all substring by matching a regular expression? -

i want extract values of src attribute in string, how can that: <p>test&nbsp; <img alt="70" width="70" height="50" src="/adminpanel/userfiles/image/1.jpg" /> test <img alt="70" width="70" height="50" src="/adminpanel/userfiles/image/2.jpg" /> </p> here go: string data = "<p>test&nbsp;\n" + "<img alt=\"70\" width=\"70\" height=\"50\" src=\"/adminpanel/userfiles/image/1.jpg\" />\n" + "test \n" + "<img alt=\"70\" width=\"70\" height=\"50\" src=\"/adminpanel/userfiles/image/2.jpg\" />\n" + "</p>"; pattern p0 = pattern.compile("src=\"([^\"]+)\""); matcher m = p0.matcher(data); while (m.find()) { system.out.printf("found: %s%n", m.group(1)); } most regex flav...

algorithm - Shuffle and deal a deck of card with constraints -

here facts first. in game of bridge there 4 players named north, south, east , west. all 52 cards dealt 13 cards each player. there honour counting systems. ace=4 points, king=3 points, queen=2 points , jack=1 point. i'm creating "card dealer" constraints example might hand dealt north has have 5 spades , between 13 16 honour counting points, rest of hands random. how accomplish without affecting "randomness" in best way , having effective code? i'm coding in c# , .net idea in pseudo code nice! depending on how fast computer is, might enough this: repeat: do random deal until board meets constraints as performance questions, thing try , see! edit tried , saw: done 1000000 hands in 12914 ms, 4424 ok this without giving thought optimisation - , produces 342 hands per second meeting criteria of "north has 5 spades , 13-16 honour points". don't know details of application seems me migh...

javascript - Any tips for writing cross-browser Greasemonkey userscripts? -

i have few scripts clean-up of sites use. but, have switched on chrome firefox , of scripts don't work, though can install them. can offer tips on how write userscripts work (nearly) cross-browser? specifically, firefox , chrome, , maybe opera. i've been working on a user script engine comparison table should know gm_apis can depend on. other need write cross browser javascript long topic; recommend the dom compatibility tables offered quirksmode cross browser dom usage.

matlab - How to find all minimum elements in a vector -

in matlab, function min(), can 1 single minimum element of vector, if there can several equal minimum elements. wondering how indices of minimum elements in vector? for example, v=[1,1]; i indices 1 , 2, both of index smallest elements 1. thanks , regards! you can use find find min values: find(v == min(v))

linq - If I expose IQueryable from my service layer, wouldn't the database calls be less if I need to grab information from multiple services? -

if expose iqueryable service layer, wouldn't database calls less if need grab information multiple services? for example, i'd display 2 separate lists on page, posts , users . have 2 separate services provides list of these. if both provides iqueryable, joint in 1 database call? each repository creates context itself. it's best think of iqueryable<t> single query waiting run. if return 2 iqueryable<t> instances , run them in controller, wouldn't different running them separably in own service methods. each time execute iquerable<t> results, run query independent of other iquerable<t> objects. the time (as far know) make impact if there enough time between 2 service calls database connection might close, need considerable amount of time in between service calls case. returning iquerable<t> controller still has usefulness, such easier handling of paging , sorting (so sorting done on controller , not done on service...

html - Ruby + ActiveRecord: Reading from the Database -

i've written ruby script parses tab-delimited text file , writes output sqlite3 database activerecord. next, need write ruby script display database's contents static html. the text file i'm working list of parts company has sale. database has 1 table; each row in database different part, , each column different attribute of part (i.e., size, weight, list price, , on , forth). need able sort table "short description" column in alphabetical order, output each row series of html tables. i've got no idea next. i've been working ruby 2 weeks, , i've been using activerecord 4 days, i'm little lost. i've been googling answer morning, i've not found i'm wanting do. here's copy of sqlite3 table declaration, if it's help: create table parts_info(item_number integer primary key asc, location text, quantity integer, make text, year integer, model text, serial text, volt integer, phase integer, weight integer, list_price real,...

html - How do I incorporate the line number of php source code in a custom error message? -

i want proper error generator when i'm programming (html + php). how can take line, when have error, , put in variable? example : echo " error # 03: variable undefined line # ".$line." "; thanks. the variables you'd looking are: __line__ __file__ __function__ __class__

ruby on rails - How to use auto_link inside of a controller -

in controller need build json object. how can use auto_link() inside controller? right errors: nomethoderror (undefined method `mail_to' #<conversationscontroller:0x144c3f880>): app/helpers/application_helper.rb:48:in `html_format' app/controllers/conversations_controller.rb:326:in `comments' app/controllers/conversations_controller.rb:322:in `comments' thank ideas auto_link helper , can reference if view. , there's reason that: representing information view responsibility. in case, either create json template or, if really need use helper in controller, include actionview::helpers::texthelper module in controller. class conversationcontroller < applicationcontroller include actionview::helpers::texthelper include actionview::helpers::urlhelper end you might need include al dependencies, such module contains mail_to helpers.

iphone - Uploading image or a video to server as a raw data without encoding -

is possible upload media(image & video ) directly server without encoding picking using uiimagepickercontroller, if please suggest me how it.please provide sample this. in case of video upload can send file without encoding on server here code that: if ([type isequaltostring:(nsstring *)kuttypevideo] || [type isequaltostring:(nsstring *)kuttypemovie]) { nsurl *urlvideo = [info objectforkey:uiimagepickercontrollermediaurl]; } //in urlvideo path of media file(video files) nsstring *str = [nsstring stringwithformat:@"%@/uploadvideo.php",appurl]; nsurl *url =[nsurl urlwithstring:[str stringbyaddingpercentescapesusingencoding:nsutf8stringencoding]]; asiformdatarequest *request = [asiformdatarequest requestwithurl:url]; [request setpostvalue:self.gameid forkey:@"gameid"];//value gameid parameter [request setfile:strurl forkey:@"uploadfile"]; //setfile method used upload video files [request setrequestmethod:@"post...

java - Without changing code, how to force httpClient to use proxy by environment variables or JVM arguments -

i found setting http.proxyhost , http.proxyport of no use httpclient. how force httpclient use proxy environment variables or vm arguments or without changing code? in https://issues.apache.org/jira/browse/httpclient-1128 systemdefaulthttpclient added ver. 4.2 see http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/systemdefaulthttpclient.html

listview of image and text in Android -

i have button , when click on it, want show listview image & text (static text). how can this? my code.. public class category extends listactivity { button category; textview selection; private static final string[] country = { "iceland", "india", "indonesia", "iran", "iraq", "ireland", "israel", "italy", "laos", "latvia", "lebanon", "lesotho ", "liberia", "libya", "lithuania", "luxembourg" }; private static final string[] curr = { "isk", "inr", "idr", "irr", "iqd", "eur", "ils", "eur", "lak", "lvl", "lbp", "lsl ", "lrd", "lyd", "ltl ", "eur" }; /** called when activity first create...

java - Is .jar archive not anymore useful if I need to apply a patch to a library? -

i've downloaded lucene jar file. i'm including in classpath run lucene application. however, need apply patch. should download lucene sources, apply patch , compile.. right ? cannot use anymore jar... thanks ps. need know how apply patches in java actually... what's command terminal ? there may alternative approaches, creating new jar file best bet, imo. it'll lot harder mess subtle issues providing second jar file take priority some classes, etc.

How to develop in Java on Mac with OSX Lion -

im new java developer , thinking getting mac. heard osx lion not support java. mean cannot develop java on mac? or have go java downloads myself? what means right now, nothing has changed, except jdk 6 , on separate download via software update. jdk 7 available oracle, maybe through app store if lucky! what has happened apple has quit mangling own jdk os , delegating responsibility oracle supply jdk osx going forward . isn't installed default, after fact just on every other platform other solaris . arguably thing, apple jdk lags 6 months plus behind official sun/oracle one. having more vested interest in technology on platforms thing! original press release as of release of java mac os x 10.6 update 3, version of java ported apple, , ships mac os x, deprecated. means apple-produced runtime not maintained @ same level, , may removed future versions of mac os x. java runtime shipping in mac os x 10.6 snow leopard, , mac os x 10.5 leopard, continue sup...

uibutton - iPhone action button image file available anywhere? -

i'm working on app , want use image action type toolbar button (the 1 arrow coming box use share etc) in custom button. there way can hold of .png it? thanks there open source uikit artwork extractor project available @ github: https://github.com/0xced/uikit-artwork-extractor

Using Column headers to parse excel sheets using roo - Ruby -

can use column headers specify column number parsing excel sheet using roo gem? current code now: oo = openoffice.new("simple_spreadsheet.ods") oo.default_sheet = file.sheets.first (2..oo.last_row).each |line| date = oo.cell(line,'a') start_time = oo.cell(line,'b') end_time = oo.cell(line,'c') pause = oo.cell(line,'d') ... end i parse column headers instead of specifying columns 'a' 'b' 'c' .. . can acheive using roo ? you can grab entire header row array , hash entire row key'd on header row. oo = openoffice.new("simple_spreadsheet.ods") oo.default_sheet = file.sheets.first header = oo.first_row 2.upto(oo.last_row) |line| row_data = hash[header.zip oo.row[line]] ... end you use row_data[line] nest hashes later use.

SQL Server database file not being truncated -

i have database ~4gb in size. i've copied database , deleted 99% of data on because need database schema , basic data (mostly static data kept). the problem mdf file still ~4gb in size. if read size of tables (using this , example), sum less 20 mb together. log file shrunk, none of scripts ran worked shrinking db file. note: don't this, time need shrink database (i know it's not recommended) edit: +useful info command: exec sp_spaceused output: database_name database_size unallocated_space accudemiaemptydb 3648.38 mb 4.21 mb command: select object_name(id) objname, sum(dpages*8) dpages, count(*) cnt sysindexes group id order dpages desc output: object_name(id) sum(dpages*8) count(*) sysdercv 675328 1 sysxmitqueue 359776 1 sysdesend 72216 1 sysconvgroup 47704 1 sysobjvalues 4760 5 sec_opera...

html - Background Repeat not working in IE -

ie playing (as usual), i've got div image in bottom right hand corner set 'no-repeat', ie rendering repeated images... here's link if kind enough check out - it's half way down right hand side column entitled 'advertise': http://inside-guides.co.uk/brentwood/pages/index.html here's css (can check on developer's tools) .right-nav .bg.advertise-home {background:url(/images/structure/sign.png) right 100% no-repeat;} any ideas?? hate ie! it seems caused border-radius.htc behaviour use. if one: http://code.google.com/p/curved-corner/ should @ issues seems known issue patches near end of discussion.. http://code.google.com/p/curved-corner/issues/detail?id=1

C#/COM interop working only in debugger -

i have problem com interop c# application inproc com server component. i have reduced problem simple c# test program. instantiates server component's interop class, sets value of string property on instance, , sets string property. i'm not doing unusual marshalling. using interop class generated when added reference com component. like: using mylib; // interop assy // ... mycomp comp = new mycomp(); comp.prop1 = "abc"; comp.prop2 = "xyz"; outcomes: if run test program outside vs then, when second property set, consistently comexception hresult of 0x80010105 ( rpc_e_serverfault )‎. if run test program inside visual studio 2005 consistently works correctly. i wrote equivalent code in unmanaged c++ (no atl, plain interface pointers) , works correctly both in , out of vs. my question : different environment in interop occurs when running inside debugger might account i'm seeing? assume e_rpc_serverfault being generated interop marshalle...

Rails redirect issue - Hartl's Rails Tutorial 10.2.3 -

i'm complete noob working through michael hartl's (awesome) rails tutorials, , have issue friendly redirect in ch.10.2.3. purpose try store location, redirect sign in page, redirect original intended destination when sign-in complete. problem renders standard user profile page after signing in/creating session, rather redirecting. i have in sessions_controller: def create user = user.authenticate(params[:session][:email], params[:session][:password]) if user.nil? flash.now[:error] = "invalid email/password combination." @title = "sign in" render 'new' else sign_in user redirect_back_or user end end and in sessions_helper: def authenticate deny_access unless signed_in? end def deny_access store_location redirect_to signin_path, :notice => "please sign in access page." end def redirect_back_or(default) redirect_to(session[:return_to] || default) clear_ret...

php - Following a tutorial resulted in broken MAMP installation -

hooked mamp on macbook (osx) month ago , fine. followed bogus tutorial on how debug php in eclipse (didn't work), , php files open with: file:///applications/mamp/htdocs/ instead of: http://localhost:8888/ which displays code now. php files can viewed on server if append filename localhost url in browser, can tell me how configure php/mamp properly? i'm new @ stuff , tried fix on own, no dice =/ most of work reconfiguring /etc/apache2/httdp.conf. configuring apache vast topic, might better off using google find tutorial. @ least, you'll need handler eg.: # php file handlers. <ifmodule php5_module> addtype application/x-httpd-php .php addtype application/x-httpd-php-source .phps <ifmodule dir_module> directoryindex index.html index.php </ifmodule> </ifmodule>

php - String date current date/time? -

i using $date = date("d m d, y g:i"); . when echo $date , shows correct date/time. need string. i have tried string($date) ; nothing happens here. and $today = strtotime($date); here weird numbers.. i need string can put $today in message. what correct method this? the date() function returns string. doing : $date = date("d m d, y g:i"); you'll have current date in $date variable, string -- no need additional operation .

objective c - How to show a "loading" buttonless AlertView while performing REST requests -

i'm trying following: show buttonless uialertview showing "loading" message perform rest request like currentplans = [restutils restsynchnonouscall:url usingmethod:@"get" withbody:nil]; dismissing uialertview return currentplans i've looked dispatch_async pattern, i've looked @ thread uialertview starts show, screen dims, doesn't pop until it's late! without understanding much... :( thank in advance! alert view supposed inform user can cancel or ask simple things yes/no. loading/connecting suggest use uiactivityindicator . please note changing behavior of standard components not comply human interface guidelines. user should able dismiss alert view on his/her wish.

linq - Entity Framework Select new POCO without .ToList() first -

i'm creating application service layer (wcf website) , silverlight 4 client. ria services not option, create intermediary classes pass , forth. purpose of question let's assume i'm passing , forth tasty food objects. public class fooddata { public int id { get; set; } public string name { get; set; } public tastyness tastylevel { get; set; } } the ef model same class, table 3 basic fields (the tastyness int corresponds our enum tastyness). i find myself using kind of statement lot when doing entity framework queries: public list<fooddata> getdeliciousfoods() { var deliciousfoods = entities.foods .where(f => f.tastyness == (int)tastyness.delicious) .tolist() // necessary? , if so, best performance list, array, other? .select(dfood => dfood.tofooddata()) .tolist(); return deliciousfoods; } without .tolist() call e...

php - Variable based tables -

is possible create variable influenced table? like instead of creating standard table. can let users create custom table. on sign can create table under database , table's name influenced php variable? , same thing fields in table? for example, $username.table tables , $username_field fields in table? why? need user able add fields need. sort of letting them create onlin form then need engineer database allow this. not lazy , create tables form fields. not security risk, never scale well. here poor example of how engineer table based system handle dynamic form generation. drop table "main"."form"; create table "form" ( "id" integer not null, "name" text not null, primary key ("id") ); drop table "main"."form_field"; create table "form_field" ( "form" integer not null, "id" integer not null, "name" text not null, primary key ("...

c# - Calculate execution time of one or more lines of code -

is there way (a class-made in c #) that allow me to calculate the time required to execute some lines in program. ex : try { string connectionstring = getconnectionstring(); using (sqlconnection conn = new sqlconnection(connectionstring)) { conn.open(); ***// start counting: // time = 0*** using (sqlcommand cmd = new sqlcommand( “select * books”, conn)) using (sqldatareader reader = cmd.executereader()) { while (reader.read()) { console.writeline(“{0}\t{1}\t{2}”, reader.getint32(0), reader.getstring(1), reader.getint32(2)); } ***// end counting // time = 10 sec*** } } one option use built-in stopwatch class: var sw = stopwatch.startnew(); // sw.stop(); console.writeline("time elapsed: {0} milliseconds", sw.elapsedmilliseconds);

c# - Calling and Leaving Voice Messages with .Net? -

i'm looking way call phones , leave voice messages using .net. dialog need constructed @ runtime each phone message. nice if handle if person picks or answering service. is can use our cisco voip phones do? if not, whats better using service (if available) or putting modem in machine? # of calls low. i think twilio you're after. it can read , record voice

Rails ActiveRecord :counter_cache not updated if assocation not set up before create. Intentional? -

i've implemented belongs_to relation :counter_cache => true , notice counter cache not updated if relation not set before initial save. for instance, company has_many employees. if do company.employees << employee.new(:name => "joe") the counter gets updated correctly if do company.employees << employee.create(:name => "joe") the counter remains unchanged. for more details, here models: class employee < activerecord::base belongs_to :company, :counter_cache => true end class company < activerecord::base has_many :employees end and here's rails console session demonstrates this: loading development environment (rails 3.0.5) ruby-1.9.2-p180 :001 > company_a = company.create(:name => "acme") => #<company id: 1, name: "acme", created_at: "2011-07-22 01:31:39", updated_at: "2011-07-22 01:31:39", employees_count: 0> ruby-1.9.2-p180 :002 > company_a....

Is there a way to export a Makefile from a Java Eclipse project? -

so have java project made of several classes, external jar files , executable java program. export whole code , external jars external directory , produce makefile build program dependencies. there automated way it? thank you tunnuz i think understand question. of course if use external build system maven or ant, decoupling build process ide. (but in cases ide integrate pretty closely build tool.) but if want continue building using eclipse , generate ant file 1 fine day, there tool that. called ebuild . leverages classpath information eclipse has , builds generic ant file out of it.

how to map a collection of enums in spring-data for mongodb -

spring-data 1.0.0.m3 mongodb. how come spring can map class: import org.springframework.data.document.mongodb.index.indexdirection; import org.springframework.data.document.mongodb.mapping.document; @document public class enumsmapper { private indexdirection d = indexdirection.ascending; } and fails one: import org.springframework.data.document.mongodb.index.indexdirection; import org.springframework.data.document.mongodb.mapping.document; import java.util.list; import java.util.arrays; @document public class enumsmapper { list<indexdirection> list_enum_test = arrays.aslist( new indexdirection[] {indexdirection.ascending}); } with a: java.lang.illegalargumentexception: can't serialize class org.springframework.data.document.mongodb.index.indexdirection the same happens other collections (sets, ...), , arrays. spring can map enum, writing mapper doesn't solve problem. bug or there's way map collection (set/map) holding enums? it...

authentication - CakePhp - blocking the site with Auth - how? -

i want block website - using auth. in "normal" usage redirecting user login page while can still see layout. want prevent it. i want unauthorized guest see login form edit i saw option use empty layout in login function, guess there way, there? edit bumping, anyone? switch different layout in beforefilter if user not logged in: function beforefilter() { if (!$this->auth->user()) { $this->layout = 'anonymous'; } } put in appcontroller. the other way around works of course: if user logged in, use "full" layout , make default.ctp minimalistic instead.

c# - MongoDB - Hosting on multiple servers -

i wanting use mongodb on windows server , using .net code at: https://github.com/atheken/norm/wiki/ i have 2 web servers need host mongodb on , keep database on both instances in sync. should looking @ accomplish this? seems master/slave replication option ideal. if this, can keep connection string as? mongodb://localhost/mydatabase?strict=false thanks help. first attempt using mongodb. mongodb doesn't support kind of peer-to-peer replication, master-slave data written primary database sync'd out secondary replicas. can, however, distribute reads across replicas using slaveok option. check out replica sets more info. distribute writes, take @ sharding . also, might not ideal host mongodb , web server on same box. mongo greedy when comes memory, , if database grows larger available ram web server performance suffer.

How to configure HSQLDB 2.2.5 in Maven POM? -

i unable find hsqldb-2.2.5 pom @ http://repo1.maven.org/maven2/org/hsqldb/hsqldb . can how maven pom can set work hsaldb-2.2.5 version? maybe has not been uploaded yet? there appears 2.2.4 here: http://repo1.maven.org/maven2/org/hsqldb/hsqldb/2.2.4/ in order reference dependency in pom.xml, guess you'll have add dependencies block <dependency> <groupid>org.hsqldb</groupid> <artifactid>hsqldb</artifactid> <version>2.2.4</version> </dependency>

c - Resolving dining philosophers deadlock using semaphores -

i trying solve dining philosophers problem using semaphores in c. below code. in code each chopstick represented semaphore. each philosopher process. use concept atmost 4 chopsticks can in "picked up" state @ given time avoid deadlock. why set dt 4. please let me if below code correct , if logic sound #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sched.h> #include <signal.h> #include <sys/wait.h> #include <time.h> #include <semaphore.h> #define stacksize 10000 #define numprocs 5 #define rounds 10 sem_t dt,c1,c2,c3,c4,c5; int child (void * philnum) { int* phil1 = (int *)philnum; int phil = *phil1; int = 0 ; ( ; < rounds ; ++ ) { switch(phil){ case 1: sem_wait(&dt); sem_wait(&c1); sem_wait(&c5); case 2: sem_wait(&dt); sem_wait(&c1); s...

c# - WPF MVVM Event Subscription -

for simplicity have modelview (mymodelview) contains scheduler property has timer inside of (scheduler). timer used check against current time, , if match, signal 'event match' modelview should somehow notified of. mymodelview knows scheduler, not other way around. public scheduler() { schedulecollection = new observablecollection<schedule>(); timespan ts = new timespan(30000); _timer = new dispatchertimer(); _timer.interval = ts; _timer.tick += new eventhandler(eventtimercheck_tick); _timer.start(); } private void eventtimercheck_tick(object sender, eventargs e) { eventstolaunch = locatecurrentevents(); if (eventstolaunch.count > 0) { raisehasevents(); } } public void raisehasevents() { eventhandler handler = this.hasevents; if (handler != null) { var e = new eventargs(); handler(this, e); } } public event eventhan...

iphone - Need help creating .plist in app -

Image
my app ships .plist looks this: i want user able add custom exercisename. so need create new .plist in user's document folder mimics format. can me this? i need (pseudo code) if (userdata == nil) { create .plist file; setup .plist mimic format of img above. } save exercisename appropriately. update: if (exercisearray == nil) { nsstring *path = [[nsbundle mainbundle]pathforresource:@"data" oftype:@"plist"]; nsmutablearray *rootlevel = [[nsmutablearray alloc]initwithcontentsoffile:path]; self.exercisearray = rootlevel; [rootlevel release]; } what want load plist nsdictionary, , encode nsdictionary plist file in applications document folder. in applicationdidfinishloading: method, this: nsstring * documentfile = [nshomedirectory() stringbyappendingformat:@"/documents/myplist.plist"]; if (![[nsfilemanager defaultmanager] fileexistsatpath:documentfile]) { // create copy of our resource nsstri...

security - Grails/Groovy: Harms of run-app compared to using .war -

can enumerate exposing myself (and site) running/deploying grails app "grails run-app" rather doing "correctly" .war file? grails.org saysl grails should never deployed using grails run-app command sets grails in "development" mode has additional overheads. is only performance, or there security issue there too? performance big difference. if must use run-app sure run 'grails prod run-app' @ least of optimizations in place. run-app designed devloper-friendly, lots of reloading, , corresponding file system scans necessary support that. when running in war, gsps precompiled, saves permgen , results in faster performance. there's no caching in run-app since developer don't want have restart, in production need make changes redeployment, caching more aggressive.

node.js - Passing route control with optional parameter after root in express? -

i'm working on simple url-shortening app , have following express routes: app.get('/', function(req, res){ res.render('index', { link: null }); }); app.post('/', function(req, res){ function makerandom(){ var text = ""; var possible = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789"; for( var i=0; < 3 /*y u looking @ me <33??*/; i++ ) text += possible.charat(math.floor(math.random() * possible.length)); return text; } var url = req.body.user.url; var key = makerandom(); client.set(key, url); var link = 'http://50.22.248.74/l/' + key; res.render('index', { link: link }); console.log(url); console.log(key); }); app.get('/l/:key', function(req, res){ client.get(req.params.key, function(err, reply){ if(client.get(reply)){ res.redirect(reply); } else{ res.render('index', { link: null }); ...

ios - Populating UITableView with XML data -

i parsing information server , have information being downloaded having rough time trying figure out how add information table view. know how take information have , add nsmutablearray count object , add table view everytime add strings mutable array nothing... know information being parsed correctly logs , lable placed testing purposes... here code using information. how can take string used , populate table view? -(void)parser:(nsxmlparser*)parser didstartelement:(nsstring *)elementname namespaceuri:(nsstring *)namespaceuri qualifiedname:(nsstring *)qname attributes:(nsdictionary *)attributedict{ nslog(@"parser called"); if ([elementname isequaltostring:@"element"]) { nslog(@"elements recieved %@", [attributedict objectforkey:@"themename"]); themenamestring = [nsstring stringwithformat:@"%@", [attributedict objectforkey:@"themename"]]; //test first string label.text = ...

php - Sessions?? How can I display a the users row? -

i want display attributes of game character, under users table. so, want display specific attributes of user has logged in, since should in row. need register users session, because didn't. this code used sessions user in when login in <? if(isset($_post['login'])) { if (ereg('[^a-za-z0-9]', $_post['name'])) {// before fetch database want see if user name in correct format. echo "invalid username."; }else{ $query = "select password,id,login_ip users name='".mysql_real_escape_string($_post['username'])."'"; $result = mysql_query($query) or die(mysql_error()); $row = mysql_fetch_array($result); // search database , password, id, , login ip belongs name in username field. if(empty($row['id'])){ // check if id exist , isn't blank. echo "account doesn't exist."; }else{ if(md5($_post['password']) != $row['passw...

jQuery: is there a way to make this code more compact? -

if mouseover class1a, css of class2a , class2b change. it's same pattern on , on again class names keep changing. it's resulting in lot of code..i'm wondering if there's way use jquery make more compact? note, willing change class names...just have able distinguish them see in code... $('.class1a').mouseover(function(){ $('.class2a, .class2b').css( {height : '50px' , top: '75px'}); }).mouseout(function(){ $('.class2a, .class2b').css({height : '25px' , top: '100px'}); }); $('.class1b').mouseover(function(){ $('.class2c, .class2d').css({height : '50px' , top: '75px'}); }).mouseout(function(){ $('.class2c, .class2d').css({height : '25px' , top: '100px'}); }); you can predefine variables selectors , css objects have multiple occurances, can use .hover() method var s1 = '.class2a, .class2b'; var s2 = '.class2...

Static Website Generators in MVC3 or ASP.NET in general -

i see lot of projects in other languages generating static web sites dynamic engines. things frank, jekyll, hyde, webby , poole. there large list here: http://iwantmyname.com/blog/2011/02/list-static-website-generators.html but can't seem find in .net space. i find interesting angle of combining performance , usability on relatively static content blogs. but can see great html based generation system. , don't mean api documentation, there seems hundred projects. mean actual application documentation or other documentation. so, great static website generators in .net space? a relatively recent development 52 code project pretzel - .net static code generator. worth if know jekyll.

python - Twisted > How to read a TCP message longer than TCP frame-length e.g. 1380 bytes from a window TCP client -

i writing twisted server read tcp messages 64kb. discovered mt datareciever called linereciever class every 1380 bytes, turned out windows client's tcp frame size. there way around without having loop through these 1380 byte blocks? from twisted.internet.protocol import protocol twisted.internet.protocol import factory twisted.enterprise.adbapi import connectionpool class csvreceiver(protocol): def datareceived(self, line): print 'line rx :', len(line) , ' : ' , str(line) the datareceived gets called , prints every 1380 bytes, e.g. 4x when tcp message of 6kb sent our server. method avoid can process entire string in 1 call-back? thank you. stan you asked question on python_forum, answered there. want using linereciever, , want set max_length higher number.

tsql - Converting Rows to Columns in SQL SERVER 2008 -

in sql server 2008, i have table tracking status history of actions ( status_history ) has 3 columns ( [action_id],[status],[status_date] ). each action_id can have variable number of statuses , status dates. i need convert these rows columns preferably this: [action_id], [status_1], [status_2], [status_3], [date_1], [date_2], [date_3] where total number of status columns , date columns unknown, , - of course - date_1 correlates status_1 , etc. , i'd status in chronological order ( status_1 has earliest date, etc.) my reason doing can put 10 recent statuses on report in access adp, along other information each action. using subreport each status in new row cause report far large. is there way using pivot ? don't want use date or status column heading. is possible @ all? i have no idea begin. it's making head hurt. let suppose brevity want 3 recent statuses each action_id (like in example). then query using cte should job: with rown...

wcf - reading system.servicemodel section from database -

we have dynamically composed application, in user can add services , operations. application installed on server cluster. since adding services application involves writing web.config , wondering if possible read system.servicemodel section database instead of web.config . seems microsoft's implementation of configuration tightly coupled stored. there no "out-of-the-box" way that. however, possible. few feet below, configuration class uses filestream instance can use stream . particular step can replaced custom implementation of iinternalconfighost interface (a lot of properties , methods implement there). particularly interesting openstreamforread , openstreamforwrite , both returning stream instances. there can put logic pull xml of configuration sections database configurationsection instances , put configurationsection instances xml database. the next step create instance of configuration class. however, here must dirty because construc...

javascript - Extending the format plugin for Aloha Editor -

Image
is there real out there on how extend aloha editor? what trying extend floating menu- want add drop down list custom fields. for instance, if user selects custom field label added html , like: <special_field> appears inside content editable. update: code initialization part of plugin far... example.product.init = function() { var = this; // floating menu "insert template field"-button var insertbutton = new gentics.aloha.ui.button({ label: 'template field', 'size': 'small', 'onclick': function() { that.insertfield(); }, 'tooltip': this.i18n('button.insertfield'), 'toggle': false }); gentics.aloha.floatingmenu.addbutton( 'gentics.aloha.continuoustext', insertbutton, gentics.aloha.i18n(gentics.aloha, 'floatingmenu.tab.insert'), 2 ); // product scope & product att...

ruby on rails - RSpec Error: Mock "Employee_1" received unexpected message:to_ary with(no args) -

my application has 2 models: user , employee, , relation user has_many employees. as trying write rspec test case employee controller: describe "get 'edit'" "should user/edit log in" log_in(@user) employee = mock_model(employee, :id=>1, :user_id=>@user.id) :edit, :id=>employee response.should be_success end end i got result as: ....f failures: 1) employeescontroller 'edit' should user/edit log in failure/error: :edit, :id=>employee mock "employee_1" received unexpected message :to_ary (no args) # c:in `find' # ./app/controllers/employees_controller.rb:41:in `edit' # ./spec/controllers/employees_controller_spec.rb:51:in `block (3 levels) in ' finished in 4.31 seconds 5 examples, 1 failure can me out please? thanks rails able infer id true model instance, how works: @employee = employee.create :edit, :id => @employee this doesn't wor...

oracle - Strange memory usage pattern in C# Windows Form app -

Image
i trying understand going on in app written in c#. below several images taken performance monitor. blue line #bytes in heaps. green line large object heap size. start app , log me in. app remains idle. first image shows loh increases reason , drops. pattern clear. responsible such behavior? more. heavy processing starting in (see image below) using oracle database through odp.net. after app remains idle again. loh not drop. instead keeps increasing reason. note application idle. open in desktop. not interacting it. memory keeps increasing (each image represents 1:15:00). after more 2 hours decreases , after while starts increasing/decreasing again (see below) in first image. time app idle. going on? memory leak? don't think so. profiled app , couldn't find anything. loh increases without activity. there no open connection oracle database. can odp.net culprit? the problem due odp.net. if disable connection pool problem not manifest. each connection odp...

ajax - jQuery to update select list -

i have form user can submit form indicate systems need updated. in form, can dynamically add systems form not have unique ids available. in form, have select platform (unix, hp, wintel, etc) , corresponding model accompany selected platform - think chained select. when first selected list in "item" changed, ajax call made obtain values 2nd select list. how can update 2nd select list in "item" corresponding chained select? i'm using clone method allow users add items form. such, id no longer unique on page i'm using class figure out select button change. way working right now, every 2nd select list updated , want select chained select list corresponding 1st select list changed updated. believe next() answer guess syntax incorrect. the class of 1st select list platform , 2nd 1 model. updates every 2nd select list : $("select.model").html(options) nothing updates : $("select.model").next().html(options); any appreciated...

java - How to get biggest BigDecimal value -

how can largest possible value of bigdecimal variable can hold? (preferably programmatically, hardcoding ok too) edit ok, realized there no such thing since bigdecimal arbitrary precision. ended this, sufficiently purpose: bigdecimal = bigdecimal.valueof(double.max_value) its arbitrary precision class, large you'd until computer runs out of memory.

jsp - Using jQuery Templates in Struts2 -

i attempting update page using struts2 ( using jowl display ontology ). original html page uses jquery templates, having several lines such as: <h2 class="propertybox title" data-jowl="rdfs:label">${rdfs:label}</h2> <span class="alt">${?p}</span><span>: </span><span>${?t}</span> to display variable determined in jquery script file. works enough .html file. however, .jsp file thinks attempting use struts variables rather jquery template. crashes when encounters colon , question mark. i did find jquery struts2 libraries , didn't see tags map jquery templates. there way this? your issue jsp thinks ${} el. need somehow escape part of express, isn't going pretty: from jsp 2 spec: literal values include character sequence ${, jsp 2.0 provides way escape them using sequence ${'${'. example, following character sequence translated literal value ${expr}: ${'${'}expr} ...

design - Packaging all files associated with a project -

i took on poorly documented , packaged project while has prompted me looking software (preferably less $200usd) allow me package files associated embedded project hand off client @ point exit project. a few features: generate html index navigate files archiving util... files include: latest release of every file - schematics, gerbers,parts lists, source code, binaries, board bring instructions, firmware programming tools, datasheets, test procedures altium , have type of ability, skewed towards hardware, expensive ad coupled development tools. preferably packaging software decoupled development software. what recommend? is there reason why arranging sensible folder structure , putting in zip file wouldn't work?

dojo - scaml interpolation in html attributes -

i have this: -@ var id:string %div{:dojotype => 'dojo.data.itemfilereadstore', :jstype => 'store', :url => "/path/to/resource?id=#{id}"} i hoping variable interpolation work here, puts #{id} html. tried: %div{:url => 'path/to/resource?id='+id} and doesn't compile. right way this? the correct syntax is: %div{:url => {"/path/to/resource?id="+id}}

Getting the next textbox using the next() function in jquery -

i trying write jquery code value of next textbox of class "in". code have here isn't working, value undefined. think using next() function incorrectly not sure, have input? <!doctype html> <html> <body> <input type="text" class="mm" /> <br> <input type="text" class="in" /> $(document).ready(function() { $("input").focus(function() { var value = $(this).next(".in").val(); if (value) { alert(value); } }); }); </script> </body> </html> your example you've given html works. can see here: http://jsfiddle.net/jfriend00/rgsdq/ . based on comments, sounds want first sibling has class "in" whether it's next sibling or not. .next() examines next sibling. if want first sibling has class "in" if it's not next sibling, can either of these: $(this).nextall("...

iphone - Fast app switching, what do I need? -

my app works fine without multitasking support. when activate in info.plist, crashes every time pushed on navigationcontroller , hit home button, came app , used navigationcontroller again. error message doesn't me either. what need multitasking support in app, when want app nothing in background , come was. sadly instruments doesn't work correct either since xcode 4.1 -_-". the error-message in console sometimes: terminating app due uncaught exception 'nsinvalidargumentexception', reason: '-[cacontextimpl _iscached]: unrecognized selector sent instance 0x5b783d0' sometimes exc_bad_... in view create switch ??? if clicked home button before! if push view , go back. click home-buttom. tap app-symbol. , try push same view again crashes. when push view, go , push view, works. crashes, when in springboard (clicked home button). edit: //appdelegate class - (bool)application:(uiapplication *)application didfinishlaunchingwithoptions:(nsdicti...