Posts

Showing posts from April, 2012

c# - Is there an easy way to refactor between coding practices to C#4 from C#1,C#2 and C#3 -

i going admit battling changing face of c# , unlearning learnt since starting out c#1. i started years ago writing greenfield c# 1.1 code , work lot maintenance work on code written previous versions of c#. being exposed old ways of doing things hard battling unlearn code have written in past , have @ daily written in previous versions of c#. having maintain java projects doesn't similar c#1. time unlearn bad practices project deadlines hard do. my lazy mind against me logic says if use oo , dry principles , code compiles boss happy , thinks when not simplifying code new ways of doing things. i have started reading jon skeet's c# in depth 2ed gives code solutions specific tasks each of c#1,c#2,c#3,c#4 each time showing code examples how simplifies code finding hard remember , put practice these new methods due having still deal legacy code daily , still having balance jack of trades dev jobs. is there easy way refactor between coding practices c#1,c#2,c#3 c#4 e

perl - Grep command to find blank line - works in terminal, not in the file itself? -

i writing perl script, called qmail each incoming mail, parse content , find body of email. reason doing add user information database, append body, , forward address (a listserv). unsolveable problem this: cat dbody.txt|grep -a1000 '^\s*$' purpose: find first blank line (being end of header information) , return after that when run line command line (using terminal) (ie. directly) - works fine. returns body of email. when run in script - it doesn't . have tested endlessly , cannot think of reason why be, or should change. help! lines script - first "test" - works fine. $test =`cat dbody.txt|grep -a1000 '^\s*$'`; $body= `cat dbody.txt|grep -a1000 '2,/^$/d'`; when print above final email - $test returns full text (as test), $body remains blank. you can use perl this: use strict; use warnings; $body; open $file, "<", "dbody.txt" or die("$!"); while (<$file>) { $body .= $_ if

php - Decoding string... to array format -

i'm trying decode return string array... dont know whether json format or not return code this.. doing wrong? [ [ ["संकल्प", "resolution", "saá¹…kalpa", ""] ], [ ["noun", ["प्रस्ताव", "संकल्प", "समाधान", "स्थिरता", "चित्त की दृढ़ता", "प्रण"], [ ["प्रस्ताव", ["offer", "proposal", "motion", "resolution", "proposition", "offering"], , 0.69811249], ["संकल्प", ["resolution", "resolve", "determination", "pledge", "solemn vow"], , 0.53526145], ["समाधान", ["solution", "resolution", "settlement", "key", "resolvent", "redress"], , 0.064934582], ["स्थिरता", ["stabilit

php - CakePHP save objects state -

i'm trying out cakephp framework, , have question objects state. previously, have been used serializing objects , unserializing them upon reload. in way, objects keep state, i'm not sure if that's best practice. what best practice keep track of products added shopping cart , general state of model? save object state somehow in sessions? or keep data in sessions , rebuild model when page reloaded? does cakephp offer build-in functionality should know when comes objects , states? it seemed fitting answer questions in reverse order. does cakephp offer build-in functionality should know when comes objects , states? yes!, cakephp has built in wrapper php $_session object can add , remove objects , supplied convenience methods. what best practice keep track of products added shoopingcart , general state of model? save object state somehow in session? or keep data in session , rebuild model if page reloaded? i never found need persist i

php - Bootbox.js Confirm choice before submitting form -

hello have decided use bootbox.js simple way incorporate bootstrap modal can make user confirm choice before form posted , changes made. i using laravel, jquery, bootstrap , bootbox.js in default layout file: layout.blade.php <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script>window.jquery || document.write('<script src="js/vendor/jquery-1.9.1.min.js"></script>')</script> <script src="js/plugins.js"></script> <script src="js/main.js"></script> <script src="js/vendor/bootstrap.js"></script> <script src="js/vendor/modernizr-2.6.2.min.js"></script> <script src="js/vendor/bootbox.js"></script> user page: {{form::open('choice')}} @foreach($items $item) <tr> <td>{{ html::image($item->image, '&#

linux - Wildcard TDM400P REV H digium card configuration -

i using wildcard tdm400p rev h digium card making outbound calls. have installed dahdi 2.3.0 , asterisk 1.6.0.1. when making outbound call getting following error message. app_dial.c:1450 dial_exec_full: unable create channel of type 'dahdi' (cause 34 - circuit/channel congestion) any idea error message??? urgent. this error mean card not setuped correctly. please consult page: http://www.voip-info.org/wiki/tdm400p for see not ok use following commands: to info config errors dahdi_cfg -vvvv to more debug in asterisk console core set verbose 10 dahdi set debug on

c# - How to exclude already existing items from dropdownlist? The values are populated based on some condition in xml -

in web application project have linkbutton , when clicking popup page addcontrolspopup.aspx come . on page have fill ddlvalues dropdownlist xml condition. the first dropdownlist ddlvalues. dropdownlist populated data. the second dropdownlist ddlcontroltype third dropdownlist ddlconditioncontrol. in popup page there exists button add controls , need select values these 3 dropdownlist. after clicking button, 3 dropdownlist values added xml controls section. in page there exist button add controls. saved xml. this process. my doubt after adding combination of controlvalue, controltype , conditioncontrol, have exclude controlvalue first dropdownlist ddlvalues pls i have xml file following data. < controlset> < control> < values> < valueid>1< /valueid> < valuename> abc < /valuename> < /values> < values> < valueid>2< /valueid> < valuename> def< /valuename> < /values> &l

jquery.transit hover not working -

i trying create basic hover effect using jquery.transit. when cursor hovers on 1 of icons, want icon scale 100%, , reduce 100% when cursor moves away. here's example of code i'm using: $(document).ready(function() { $('enqbutton').hover( function () {$(this).transition({ scale: [2] });, function () {$(this).transition({ scale: [0] }); }); }); enqbutton div class. any idea i'm doing wrong? you not selecting class rather html element, change selector to, $('.enqbutton') also must enclose functions in curly braces, try keep code formatted helps spot these errors, example of how write it; $(document).ready(function() { $('.enqbutton').hover( function () { $(this).transition({ scale: [2] }); }, function () { $(this).transition({ scale: [0] }); } ); }); doing allows spot errors otherwise hard spot saving hours of finding these errors allowing

ruby on rails - Authenticate rails_admin with admin attribute -

i want able let users have admin attribute set true access rails_admin. so, if user has is_admin attribute true, can access rails_admin interface. i have checked documentation , can find authentication here: https://github.com/sferik/rails_admin/wiki/authentication please, me so? thanks from https://github.com/sferik/rails_admin/wiki/authorization config.authorize_with redirect_to main_app.root_path unless current_user.is_admin? end

no such column error in android database -

when perfom search method given me run time error error:- 05-04 14:04:00.227: e/androidruntime(4559): caused by: android.database.sqlite.sqliteexception: no such column: ww (code 1): , while compiling: select distinct faculty, deparment, name, officenumber, phonenumber, emailaddress, officehour teacherinfo name=ww i need search on teacher name when user enter name , display information teacher such name ,faculty,deparment,phone,email,officenumber,officehour thiss getrecord method in dbadapter.java public cursor getrecord(string n1) throws sqlexception { cursor mcursor =db.query(true,tablename , new string[] {facultyc, deparmentc, namec, officenumberc,phonec ,emailaddressc,officehourc},namec + "=" + n1, null, null, null, null, null); if (mcursor != null) { mcursor.movetofirst(); } return mcursor; } and search method in information.java public void search(){ db.open(); cursor c = db.getrecord(n); i

javascript - Converting Span to Input -

i developing web app, have such requirement whenever user click on text inside span need convert input field , on blur need convert back span again. using following script in 1 of jsp page. java script: <script type="text/javascript"> function covertspan(id){ $('#'+id).click(function() { var input = $("<input>", { val: $(this).text(), type: "text" }); $(this).replacewith(input); input.select(); }); $('input').live('blur', function () { var span=$("<span>", {text:$(this).val()}); $(this).replacewith(span); }); } jsp code: <span id="loadnumid" onmouseover="javascript:covertspan(this.id);">5566</span> now problem is, works fine first time. mean whenever click on text inside span first time converts input field , again onblur coverts input

java - NotImplementedException is internal proprietary API -

i became following warning when try build project ant. build.xml ist auto-generated eclipse: warning: notimplementedexception internal proprietary api , may removed in future release in eclipse there no error @ line , if remove line (are annotation hibernate) error occur in line. seems error comes in first line of java file. i tried replace hibernate , annotations new version javax persistence. nothing helped. i hope else has same failure , knows need do. edit: @entity @inheritance(strategy=inheritancetype.table_per_class) @table(name="myclass") public class myclass implements cloneable { the second row generates warning. if remove row next generate same warning. if remove annotations last line generates warning. are importing sun.reflect.generics.reflectiveobjects.notimplementedexception somewhere?. sun classes not part of official java api , may changed/removed @ time without notice. apart that, might missing if runs application on different jvm

vba - Taking user back to specific textbox -

i have little routine checks time input... ie if user enters "8", change 08:00 etc etc... works great. now thought i'll smart , make sure user enters max of 4 number , if not, msgbox pops up. far easy enough how on earth take him textbox can correct entry ? tried .setfocus nothing happens ?? ideas ? private sub zb_exit(byval cancel msforms.returnboolean) if len(zb) = 2 zb = zb & ":00" elseif len(zb) = 1 zb = "0" & zb & ":00" elseif len(zb) = 4 zb = left(zb, 2) & ":" & right(zb, 2) elseif len(zb) = 3 zb = left(zb, 1) & ":" & right(zb, 2) elseif len(zb) > 4 msgbox "what trying ???" zb.setfocus else end if end sub santosh's suggestion great limiting characters allowed in textbox. alone may resolve problem. here answer others may not able use character limit readily can in example. to return focus textbox zb , this:

java - Capture image with camera in android and save with a custom name -

i have create android application capture picture , save in sdcard folder,now want save image custom name. import java.io.bytearrayoutputstream; import android.view.menu; import android.app.activity; import android.content.intent; import android.graphics.bitmap; import android.os.bundle; import android.provider.mediastore; import android.view.view; import android.widget.button; import android.widget.imageview; public class mainactivity extends activity { private static final int camera_request = 1888; private imageview imageview; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); this.imageview = (imageview) this.findviewbyid(r.id.imageview1); button photobutton = (button) this.findviewbyid(r.id.button1); photobutton.setonclicklistener(new view.onclicklistener() { @override public void onclick(vi

jquery - Fancybox gallery with images in different places -

i have (html) page image gallery (all images together) , 1 separate image. i put images image gallery in a <div id="imagegallery"> i put separate image in a <div id="separateimage"> and have javascript $('#imagegallery a').fancybox(); $('#separateimage a').fancybox(); fancybox works fine on both, image gallery , separate image. can cycle through image gallery, however, separate image not part of cycle. how can make cycles through images: image gallery , separate image? i tried adding rel="gallery" to anchors explained @ https://www.inkling.com/read/javascript-jquery-david-sawyer-mcfarland-2nd/chapter-7/advanced-gallery-with-jquery but apparently works if images in same div (id)!? the issue binding fancybox 2 different selectors : $('#imagegallery a') , $('#separateimage a') in order make gallery, elements whether within same div or not, need use same selector (fancybox v2.x

android - New layouts in TabHost -

i'm using tabhost in application in 1 of views (corresponding 1 of tabs) have button have take me activity , layout. question is: how new layout can continue have access tabs? or better say, how load new layout inside framelayout ?. here have uploaded i'm trying do: http://imageshack.us/photo/my-images/541/exampleu.png/ thanks in advance.! pd: i'm new in android, maybe there better way achieve purpouse without using tabactivity. i'm open suggestion. edited: decided use fragments suggested. , have following: aplicationactivity extends fragmentactivity clientactivity extends fragment settingsactivity extends fragment dataclientactivity extends fragment and following layouts: activity_aplicacion activity_client activity_settings activity_data_client the activity_aplicacion.xml has tabhost, framelayout , tabwidget , these can go clientactivity , settingsactivity using tabs. in clientactivity have button called "new" , when press but

iphone - UITableView with dynamic height inside UIScrollView: -

Image
i have screen uinavigationcontroller , uitabbar . uinavigationcontroller screen uiview (in figure below, in red), haves image in top , uiscrollview (in figure below, in green). uiscrollview have 2 uilabel ("some text") , uitableview not enable scrolling. every time list become bigger, need enlarge tableview height, dynamically. @ same time, think need enlarge uiscrollview . see image below: how can define dynamical height uitableview , uiscrollview ? my goal is: every time list become bigger, uiscrollview become bigger too. my environment: my uitableview not enable scrolling i using xcode 4.6 , view freeform my view using autolayout i tried setting uitableview height , without success. how can this? you can calculate height of table view bin method heightforcellatindexpath: in method pass height of each row in can calculate height creating globale variable , in variable add row height each time. or can find having no of row

Tech differences between chrome and firefox packages apps & other html5 apps in blackberry,tizen -

need understand basic technical differences between chrome , firefox packages apps & other html5 apps in blackberry,tizen. all of them support apps in html,css,js , how technically different 1.can 1 app created 1 platform used without changes 2.if cannot used across how can migrated 3.are differences in manifest , main browser/os specific i don't think there easy answer one. you'd have study each platform's api layer , comparison. start chrome.* , research other platforms. if end doing this, please publish results i'm sure many future html5 app developers love read findings!

jquery - sort search result but keep the result - django -

i stuck in issue: i have search engine in page. 1 can search , results of more 2 pages. rendering pages paginator. current problem once search , sort result, search result distroyed. after sort, getting different search results. the architecture this: normal search: page/found-items/?state=bla&place=bla sort on page/found-items/?state=bla&place=bla runs jquery.load() function url: /sort/?sortid=bla . in views.py have 2 functions: def search(result): #search in db def sort(request): #sort search result, how keep result after sort??? the code long, thats why posted form of functions , urls.. appeciate help python lists have built-in sort() method modifies list in-place, there sorted() built-in function builds new sorted list iterable.

algorithm - Find a largest prime number less than n -

how can find largest prime number less n, n ≤ 10¹⁸ ? please me find efficient algorithm. for(j=n;j>=2;j--) { if(j%2 == 1) { double m = double(j); double = (m-1)/6.0; double b = (m-5)/6.0; if( a-(int)a == 0 || b-(int)b == 0 ) { printf("%llu\n",j); break; } } } i used approach not efficient solve n>10^10; how optimize this.. edit: solution: use primality test on each j. miller rabin , fermat's test . i don't think question should dismissed, efficiency not easy determine numbers in range. first of all, given average prime gap ln(p) , makes sense work down given (n) . i.e., ln(10^18) ~ 41.44) , expect around 41 iterations on average working down (n) . e.g., testing: (n), (n - 2), (n - 4), ... given average gap, next step decide whether wish use naive test - check divisibility primes <= floor(sqrt(n)) . n <= (10^18) , need test against primes <= (10^9) . there ~ 50 million primes in range

linux - Ubuntu custom URL protocol handler -

i want ask question, first show files <html> <body> <a href="cloudje:firefox">open firefox</a> </body> </html> my .desktop file: [desktop entry] encoding=utf-8 version=1.0 type=application terminal=false exec=/usr/bin/cloudjerun -c gedit name[en_us]=gedit comment[en_us]=small, easy-to-use program access itunesu media name=tunesviewer comment=small, easy-to-use program access itunesu media icon=/usr/share/icons/hicolor/scalable/apps/tunesview.svg categories=application;network; mimetype=x-scheme-handler/cloudje; comment[en_us.utf8]=small, easy-to-use program access itunesu media tutorial: http://jarrpa.net/2011/10/28/creating-custom-url-handlers-in-ubuntu-11-04-11-10-gnome-3-0/ ok, cool. .desktop file placed in /usr/share/applications. if execute command 'xdg-open cloudje:firefox' or 'xdg-open cloudje:example', execute gedit using python script named 'cloudjerun'. how can execute firefox using command &#

How to align Text in TextView for Android? -

Image
i have png file seems like: i want create textview should like: here did far: selector speaker.xml <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@drawable/speaker_over" /> <item android:state_enabled="false" android:drawable="@drawable/speaker_disabled" /> <item android:drawable="@drawable/speaker_default" /> </selector> and textview : <textview android:id="@+id/speaker" android:background="@drawable/speaker" android:text="@string/button_speaker" android:gravity="center" android:textcolor="@drawable/text_incall_button_color" android:layout_width="match_parent" android:layout_height

Python embedded data persistence that's simple, modifiable, and reliable -

looking python 2.7 is: simple - , running without lot of overhead modifiable - can handle changes come prototyping , frequent changes data schema reliable - able recover no matter what, i.e. if there's power outage i'm not going lose entire data store because it's corrupt. some candidates , comments: text / csv / json file - seems simple, reliable if keep backup copy of file frequently, or implement simple backup-plus-journal setup (make backup of file when program starts, write changes journal file) sqlite - simple , reliable, handling frequent changes seems little cumbersome. shelve / marshal / cpickle - simple , modifiable, not sure how reliable it's going be. if file ends corrupted, seems you're sol. @ least human-readable file piece together. zodb - might winner. i'm unclear, require objects inherit? i'd keep separation of persistence layer since initial prototyping , may change once schema hashed out. sqlalchemy - small proje

c - Clarification of the leading dimension in CUBLAS when transposing -

for matrix a , documentation states corresponding leading dimension parameter lda refers the: leading dimension of two-dimensional array used store matrix a thus presume number of rows of a given cublas' column major storage format. however, when consider op(a) , leading dimension refer now? nothing changes. leading dimension always refers length of first dimension of array. data order flags (normal, transpose, conjugate) indicate blas how data within array stored. have no effect on array itself, column major ordered , requires lda value indexing in 2d. so whether matrix data stored in transposed form or not, m x n array has lda>=m.

statistics - Having weights shown as an unused argument in logistf R function -

i kept getting problem following code; "weights=weight" shown unused argument. how should solve problem? x_0 <- rbinom(1,100, 0.01) x_1 <- rbinom(1,100, 0.1) x <- c(0,0,1,1) y <- c(0,1,0,1) weight <- c(100-x_0, x_0, 100-x_1, x_1) result <- logistf(y ~ x, weights=weight)$coef[2] also, there way perform whole process shown above 30, 60, or 100 times , generate time (or count) , x_0 , x_1 , , result each time? suggestion great. thanks. i managed run following code without problems (r v 3.0.0 logistf v 1.10): arr <- t(sapply(1:30, function(i){ x_0 <- rbinom(1,100, 0.01) x_1 <- rbinom(1,100, 0.1) x <- c(0,0,1,1) y <- c(0,1,0,1) weight <- c(100-x_0, x_0, 100-x_1, x_1) list(count=i,x_0=x_0,x_1=x_1, res= logistf(y ~ x, weights=weight)$coef[2]) }))

c - Macro SWAP(t,x,y) exchanging two arguments of type t -

so trying make swap(t,x,y) macro exchanges 2 arguments of type t. trying think of going around problem when these 2 arguments of form v[i++] , w[f(x)] , i.e. swap(int, v[i++], w[f(x)]). the code below crashing ... #define swap(t,x,y) {t *p = x; t *q = y; t z = *p; *p = *q; *q = z;} int f (int x){ return (0-x); } int main(void) { int v[] = {1,2,3}; int = 0; int w[] = {4,5,6}; int x = -1; int *p = v; int *q = w; swap(int*, v[i++],w[f(x)]); return 0; } any ideas may go wrong? swap(int*, v[i++],w[f(x)]); v[i++] int element assigning pointer object in: t *p = x; so when dereferencing p in t z = *p; segfault. if want pointer element use & operator. moreover v[i++] has side-effect (it modifies i++ ) , should never pass expressions have side-effects in macro call.

C++: Reading elements from a vector, loops being skipped over -

currently trying write program ask user input string, read off these values via iterator. final step program apply simple caesar shift message before displaying user. however, since appear have made error causes program skip on "for" loop (or whichever loop use, have tried "for" "while" "if, else" loops). i'm relatively new c++, i'm hoping set loop incorrectly, despite best efforts. #include <iostream> #include <vector> #include <string> int main () { std::vector <std::string> vector_1; int c; int d = 0; int = 0; std::string message; std::vector<std::string>::iterator it_1; std::cout << "please input message caesar shifted \n"; while (std::cin >> message, d != 0) { vector_1.push_back (message); ++d; } std::cout << "encrypted message is"; (std::vector<std::string>::iterator it_1 = vector_1.begin (); it_1 != ve

delphi - Indy IMAP - which property to use for identifying new email messages? -

using: delphi xe2, latest indy snapshot svn (10.6.0.4997) in case of imap there 2 properties - uid , msgid can used uniquely identify message in mailbox. i'm writing email client, , need know more reliable or recommended of 2 store everytime client connects , retrieves message list. what sequence of steps needed check new emails? i'm looking correct sequence , set of indy idimap4 commands new emails. tia. unlike pop3/smtp, imap defines flags on emails. tidmessage.flags property has mfrecent , mfseen flags available (amongst others). client can emails have mfrecent set on them, update flags on server clear mfrecent , set mfseen needed.

c++ - delete pointers, VC++, Debug Assertion Failled -

i having error "debug assertion failed" @ run time code below. compiled code mvc++ 2010, in debug mode when click on retry on error window directs me file dbgdel.cpp @ line _asserte(_block_type_is_valid(phead->nblockuse)); when comment line delete result; in code, error disappears... i appreciate understand problem. sould delete pointer result, new used create clone method (sorry can't post full code , big) thanks help /***code****/ ######## file: drawshapebase.cpp ... ... base* drawshapebase::setoutput(base* data) { return (data->clone()); } .... base* drawshapebase::draw(base* data){ base* result = setoutput(data); ... ... return result; } /*##############*/ file: derived.cpp ... ... base* derived::clone() { base* b = new derived(*this); return b; } ... ... /*##############*/ file base.h public: base(); virtual ~base(); virtual base* clone(void) = 0; .... /*##############*/ main.cpp

Racket, access structure fields in function -

i have fold function want use on number of different structures, each structure arbitrarily named fields. thus, need tell fold function kind of structure passed it, , field access. need this: (define-struct test (element)) (define test_struct (make-test 0)) (define (getfield elementname structure) ((typeof structure)-elementname structure)) (getfield element test_struct) the last line equivalent to: (test-element test_struct) of course none of above correct syntax, should display i'm going for. based on other questions here on stackoverflow, seems answer has syntax have no idea how works. what won't work although can introspect struct type @ run time , don't see how use in macro @ compile time. because @ compile time don't have give object-name except piece of syntax -- not live struct object type: (require (for-syntax racket/syntax)) (define-syntax (get-field stx) (syntax-case stx () [(_ field-name s) (with-syntax ([id (fo

nosql - Error while replicating couch db -

when replcating couch db remote system local system through _changes feed, error `05-04 19:19:48.089: error/couchdb(984): [error] [<0.115.0>] error in replication `a4b53e74a33b773bbca688073b6bbe0d+continuous` (triggered document `cloud2airline`): {worker_died,<0.532.0>, {process_died,<0.547.0>, {function_clause, [{string,tokens1,[undefined,";",[]]}, {mochiweb_util,parse_header,1}, {couch_httpd,get_boundary,1}, {couch_httpd,parse_multipart_request,3}, {couch_api_wrap,'-open_doc_revs/6-fun-1-',4}, {couch_api_wrap_httpc,process_stream_response,5}, {couch_api_wrap,'-open_doc_revs/6-fun-2-',4}]}}} restarting replication in 5 seconds.` node js proxy code `'use strict'; /*! * middleware forwarding request couchdb. */ /** * module dependencies. */ var httpproxy = require('http-proxy'), util = require('./util'); module.exports =

ruby on rails - Devise rubygem - How do you filter actions for authenticated/non-authenticated users? -

i new rails , need create simple rails project these conditions: there must page articles (title + body) anyone can read articles only authenticated users can create/edit/delete articles i used scaffold generate controller articles , gem devise create authentication system. dont know how implement necessary conditions. thanks reply. if user model called user , include following in controller: before_filter :authenticate_user! if not called user , replace word user in authenticate_user whatever is. you add directly under controller declaration, so: class articlescontroller < applicationcontroller before_filter :authenticate_user! #rest of code end if want restrict actions in controller logged in users, can use except exclude actions. here, index , show can seen anyone: before_filter :authenticate_user!, :except => [:index, :show] or only include specific actions. here, authenticated users can listed actions: before_filter :authenticate

ruby on rails - (postgreSQL error) FATAL: role "demo" does not exist (PG::Error) -

so i've installed postgresql homebrew , have initialized new demo_app the: rails new demo_app -d postgresql command. albeit, getting following error when starting server rails s . snippit : /usr/local/rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.13/lib/active_record/connection_adapters/postgresql_adapter.rb:1216:in `initialize': fatal: role "demo" not exist (pg::error) full log: /usr/local/rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.13/lib/active_record/connection_adapters/postgresql_adapter.rb:1216:in `initialize': fatal: role "demo" not exist (pg::error) /usr/local/rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.13/lib/active_record/connection_adapters/postgresql_adapter.rb:1216:in `new' /usr/local/rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.13/lib/active_record/connection_adapters/postgresql_adapter.rb:1216:in `connect' /usr/local/rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.13/lib/active_record/connection

c++ - C++11 memory pool design pattern? -

i have program contains processing phase needs use bunch of different object instances (all allocated on heap) tree of polymorphic types, derived common base class. as instances may cyclically reference each other, , not have clear owner, want allocated them new , handle them raw pointers, , leave them in memory phase (even if become unreferenced), , after phase of program uses these instances, want delete them @ once. how thought structure follows: struct b; // common base class vector<unique_ptr<b>> memory_pool; struct b { b() { memory_pool.emplace_back(this); } virtual ~b() {} }; struct d : b { ... } int main() { ... // phase begins d* p = new d(...); ... // phase ends memory_pool.clear(); // b instances deleted, , pointers invalidated ... } apart being careful b instances allocated new, , noone uses pointers them after memory pool cleared, there problems implementation? specifically concerned fact this poin

c# - Reactive extensions dispose event handler -

hi guys have externaldataservice firing real time data, contained in lib. i have wrapper class subscribes , puts updates on observable.. public class myservice { private externaldataservice _externaldataservice; public myservice() { _externaldataservice= new externaldataservice (); } public iobservable<double> getdata() { return observable.create<double>(i => { _externalpriceservice.ondatachanged += (s, e) => { i.onnext(e); }; return () => { // do here? }; }); } } consumed as... var p = new myservice(); var disposable = p.getdata().subscribe(i => console.writeline(i)); how unsubscribe _externalpriceservice.ondatachanged when dispose called on disposable? use observable.fromevent or observable.fromeventpattern, instead of observable.create. dispose subscription. depending on eventhandle

How can I introduce a cross signing certificate into a chain? -

i maintain java applet locally deployed. purchased code signing certificate go daddy (it inexpensive, , host our site). certificate chain follows (all files available @ https://certs.godaddy.com/anonymous/repository.pki ): my company gdig2.cer gdroot-g2.crt unfortunately, root not installed default on windows 7 (used ie) or windows jre (used other browsers, think). manually installing root certificate doable, requires users have administrator access or run unfamiliar commands (it doesn't make sense security standpoint "you can trust applet, , prove it, run command on computer"). i change certificate chain to my company gdig2.cer gdroot-g2_cross.crt gd-class2-root.crt which seems more prevalent (for example, 1 in windows jre, , used validate https://www.godaddy.com , gets windows 7). go daddy not able me ("our support using 1 of our code signing certificates limited"), i'm left doing on own. following this answer , promising appro

objective c - Performance issue when converting many floats to NSNumbers -

in application, i'm receiving csv file contains 30,000 objects , each object there 24 values (a total of 720,000 values). format this: object1,value1,value2,...,value24 object2,value1,value2,...,value24 ... objectn,value1,value2,...,value24 when parse file, convert each row in nsarray of nsstring . next following each value of array: convert nsstring float using - (float)floatvalue convert float nsnumber store nsnumber in nsmutablearray this process takes several seconds , instruments time profiler i'm spending 3.5 s in step 2 & 3 720,000 values. how can proceed avoid nsnumber translation? can use c style array, [] ? or cfmutablearrayref ? if helps, know there 24 values each object. thanks help, sébastien. personally i'd use c-style array. if want process data row row, have object representing each row, this: @interface row : nsobject { float values[24]; } @end then create row instance each row, set 24 valu

http - Rails server return "404 Not Found" after user login -

our rails 3.2.12 app running on ubuntu 12.04 passenger/nginx server. has been verified both nginx , passenger running fine. after user login, there 404 not found page thrown out. the page redirected session instead of user menu . here production log login (the app running fine rails server locally): started "/nbhy" 73.15.38.185 @ 2013-05-04 20:50:55 +0000 processing authentify::sessionscontroller#new html rendered /home/ubuntu/.bundler/ruby/2.0.0/authentify-ac308b622f90/app/views/authentify/sessions/new.html.erb within layouts/sessions (3.0ms) completed 200 ok in 12ms (views: 7.8ms | activerecord: 0.6ms) the rails app logs shows user has been authorized successfully. somehow page redirected session instead of user menu should be. did rake assets:precompile , did not help. cause error? help. update: here output under .rvm/.../bundler. notice gem authentify installed on 5/5 seems have less right 1 installed on 5/2. less right on authentify cause of 404 page?

Breakpoint in MACRO - IAR Assembly MSP430 -

i trying measure clocks each instruction takes when executed in assembly program iar won't allow me set breakpoints inside macro. can set breakpoint before macro call , click "step over" few times until comes out of loop cannot see each instruction on macro executed, can see same instruction flash each time (the 1 calls macro) until finishes , moves next instruction. does know how put breakpoint inside macro? or how measure clocks each instruction inside macro takes? thanks! if set breakpoint before macro can set breakpoint @ point in disassembly window code generated macro function listed. can step through code in way setting breakpoints on disassembled code. if want know how many clocks or processor cycles macro takes run can either use data sheet processor add cycle counts each of instructions in compiled output visible in disassembly window, or can @ cyclecounter value in cpu registers window. works in debugger simulator mode or families of msp (i

qt - Introducing a delay in OpenCV::VideoCapture -

i have class camera inheriting cv::videocapture, core method convert cv::mat live stream qimage : qimage camera::getframe() { if(isopened()) { cv::mat image; (*this) >> image; cv::cvtcolor(image, image, cv_bgr2rgb); return qimage((uchar*) image.data, image.cols, image.rows, image.step, qimage::format_rgb888); } else return qimage(); } and encapsulating class cameradelayedview calls method , adds delay : void cameradelayedview::timerevent(qtimerevent *evt) { if(cam != null) { buffer.enqueue(cam->getframe()); if(buffer.size() > delay*fps) { setpixmap(qpixmap::fromimage(buffer.dequeue())); } } } i can see delay of 5seconds initial display of video delayed, after runs smoothly. seems images still somehow linked live feed through pointers (or qqeueue not proper fifo doubt it)... ? if is, way may give answer other people going through same thing, , interested in efficient way of

tomcat - SSL on Home page of site -

i have home page enough heavy static content images, css, js work on making , must. also page has login form, security had make home page load using https. 1. load static content every time page gets loaded? 2. how make sure static content cached, if have home page secure? i using struts2, tomcat development.

iphone - ejabberd offline_message_hook not called -

i'm trying ejabberd server send offline push notifications using custom offline_message_hook module. problem hook never seems called. i've tried setting priority of hook 0, 49, , 50 still doesn't work. this code module: % name of module must match file name -module(mod_offline_push). %% every ejabberd module implements gen_mod behavior %% gen_mod behavior requires 2 functions: start/2 , stop/1 -behaviour(gen_mod). %% public methods module -export([start/2, stop/1, create_message/3]). %% included writing ejabberd log file -include("ejabberd.hrl"). %% ejabberd functions jid manipulation called jlib. -include("jlib.hrl"). start(_host, _opt) -> ?info_msg("mod_offline_push loading", []), inets:start(), ?info_msg("http client started", []), ejabberd_hooks:add(offline_message_hook, _host, ?module, create_message, 0). stop (_host) -> ?info_msg("stopping mod_offline_push", []), ejabberd_hoo

java - SpringMVC initbinder - binding list items form Integer -

i have page has list of custom items register custom editor in init binder of controller allow data binding. list passed form view. problem having on view bind different object.however both objects have attribute in common crimerecno. i have created binder function under when data passed view controller custom object list create binder receives integer , returns list. under example of have far, isnt binding: i need know how register custom editor accepts integer crimerecno , returns list , bind list. binder function this not binding crimerecnobindervictimlist.registercustomeditor(integer.class, "crimerecno", new customcollectioneditor(list.class){ protected object convertelement(object element) { list<citizens> victimlist = new arraylist<citizens>(); string crimerecno = null if (element instanceof string) { crimerecno = (string) element; } logger.info("insid

android - Can UIAutomator be used remotely? -

i want use uiautomator's functionality inside java application runs on computer connected android device. possible? i've looked @ monkeyrunner/chimpchat uiautomator seems provide more functionality. thanks in advance. you can if device rooted - can run same uiautomator runtest command adb shell. see answer here.

wget - Robot names for robots.txt -

suppose have website uses wget crawl other websites. provide website owners chance of not being crawled website. should use robot name wget in robots.txt file, or have create other name? common practice disallow , allow popular uas this: user-agent: google disallow: user-agent: * disallow: / so think don't have problems using wget way

postgresql - Why is this SQL updating the entire table -

i've been hit classic beginner mistake. if i'd done update no clause. here's sql: "update teams set description = ? " + "from teams t " + "join team_memberships tm on t.id = tm.team_id " + "join users u on tm.user_id = u.id " + "where t.id = ? , u.uid = ?"; and despite t.id = ? sql still updates entire table. ... can see problem? try one, update teams t set description = ? team_memberships tm join users u on tm.user_id = u.id t.id = tm.team_id , t.id = ? , u.uid = ? please backup db first before executing statement above

javascript - How To Call A Function After 'X' seconds Of onmousedown event -

i want call function after user hold button 'x' seconds. please help. call settimeout() perform action after 3000 milliseconds, storing identifier settimeout() variable scoped above function. on element's mouseup(), clear timeout if exists via cleartimeout(). var divmousedown; $('#div-id').mousedown(function() { divmousedown = settimeout(function() { // timeout action... }, 3000); }); $('#div-id').mouseup(function() { if (divmousedown) { cleartimeout(divmousedown); } });

android - How to : get port number of AVD and send message to itself -

how : 1) potnumber of avd [from code not command line .] 2) send message avd using port number obtained in step1. [ it's possible : could 1 emulator send sms itself ] sending sms console: 1) open console; 2) type 'telnet localhost xxxx' xxxx emulator id. same number precedes emulator's name in title bar, 5554 unless have additional emulators running; 3) type 'sms send 1234567 message' message text of sms message 4) watch notification bar on emulator, , you'll see sms message delivered as long you're willing meatware sms gateway, manually transmitting messages between emulators, can want. sending sms between emulator instances: use emulator id phone number. seems emulators use dummy phone numbers in format 1 555 521 xxxx xxxx emulator id, e.g. 1 555 521 5554.

Android: Custom TextView Inflate Exception -

i have created custom textview , thing did put 1 "instance" in layout xml. causes crash app " inflate exception " : here's complete custom class (actually there nothing "custom" in yet...): package com.example.testapp; ... public class mytextview extends textview { public mytextview (context context) { super(context); } @override protected void onmeasure(int widthmeasurespec, int heightmeasurespec) { super.onmeasure(widthmeasurespec, heightmeasurespec); } @override public void ondraw(canvas canvas) { super.ondraw(canvas); } } the complete layout file: <?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <com.example.testapp.mytextview android:l

ios6 - iOS 6 Twitter share without using system account -

on current project let user not have twitter account setup login , tweet. use case: area of app being used many different end users part of check-in process. not personal ipad, use 10 minutes check-in event. during check-in process want let them share fb , twitter if choose. i able accomplish facebook share without using system account using facebook's presentfeeddialogmodallywithsession api, works great. there similar api in twitter sdk? there way leverages social or twitter framework? recommendations appreciated. you cannot built-in twitter sdk. need use "old" way of doing this, via oauth or xauth. framework can found on github called fhstwitterengine . need make own ui twitter itself, handles login/authentication as possible. also this page may useful find other 3rd party frameworks (that updated twitter themselves) if need go outside of regular sdk , above not want.

ajax - how can I stop everything else loading, with Jquery? -

i'm having lot of trouble jquery , ajax in scripts.js file. i've been trying follow patterns in console frustratingly unpredictable. ajax that? (the code i'm working on stuff else did.) how put in line of code says basically, 'stop, , don't else! no more loads of - until button clicked, or action called somewhere else'. i think fix of problems. i've put function below, , want stop. help. function initialize_google_maps2() { console.log('google maps 2 initialized'); var currentlatlng = new google.maps.latlng(map_latitude, map_longitude); var zoom = 10; var myoptions = { zoom: zoom, center: currentlatlng, maptypeid: google.maps.maptypeid.roadmap, // roadmap, satellite, hybrid streetviewcontrol: false }; map = new google.maps.map(document.getelementbyid("map_canvas2"), myoptions); var marker = new google.maps.marker({map: map, position: currentlatlng, icon:{oppacity:0