Posts

Showing posts from July, 2015

php - Improving a constructor -

alright, i'm working on making member class website. want make optimized possible. currently, constructor can take ($resource) either int (to grab info 1 member in database, based on id) or array of ints (to grab multiple members database, , store them in array member variable). i know if there inprovements can make block of code below, before move on creating more parts of website. changed make better? there better layout should follow doing kind of thing? public function __construct($resource) { global $database; if (is_string($resource) || is_int($resource)) { $resource = (int)$resource; $query = $database->query("select * members member_id = {$resource} limit 1"); $row = $database->get_row($query); foreach ($row $key => $value) { $this->field[$key] = $value; } } else if (is_array($resource)) { $query = $database->query("select * members member_id in(" . implode(...

Trying to write to a MySQL database with a PHP form -

i'm trying simple write database html form, using php. i've run sql query in database , works perfectly. however, using form doesn't work. i'm not sure why. help? user/pass/db name correct. <?php if(isset($_post['submit'])) { $con = mysql_connect("localhost","delives0_ideas","ideas"); if (!$con) { die('could not connect: ' . mysql_error()); } mysql_select_db("delives0_ideas", $con); mysql_query("insert data (firstname, lastname, email, idea) values ('$_post['firstname']','$_post['lastname']', '$_post['email']', '$_post['idea']')"); //also email besides writing database mysql_close($con); ?> <form method="post"> <strong>first name:</strong> <input type="text" name="firstname"/> <br/> <strong>last name:</strong> <input type="text" name...

javascript - Jquery event for changing an element's class attribute -

i need execute jquery code when element's class attribute changed. example, element : <div class="my-class"> . so, when new class added div, (i.e. <div class="my-class new-class"> , have trigger jquery code. how do in jquery? there event attribute change? if have absolutely no means of telling when external function changes class (like, custom event, example), have this: $(document).ready(function(){ // cache required element window.elementinquestion = $('#element-that-changes-class'); function checkclass(){ if (window.elementinquestion.hasclass('new-class')) { // trigger custom event $(document).trigger('elementhasclass'); // if need check until first time class appears // can cancel further checks here clearinterval(window.classcheckerinterval); } } // check if element has class every once in while window....

How to migrate data from one product to another without revealing database structure? -

what best way best way migrate data 1 product if both software companies refuse reveal database structure 1 another? dump data csv , hand other company. dba can take data , write sufficient import script maps them correct datatypes on other end.

Hierarchical Data In ASP.NET MVC -

i trying come best way render hierarchical data in nested unordered list using asp.net mvc. have tips on how this? i suggest jquery tree view plugins making function tree, render, put in recursive lambda helper nesting.

unicode - What do I need to know to globalize an asp.net application? -

i'm writing asp.net application need localized several regions other north america. need prepare globalization? top 1 2 resources learning how write world ready application. a couple of things i've learned: absolutely , brutally minimize number of images have contain text. doing make life billion percent easier since won't have new set of images every friggin' language. be wary of css positioning relies on things remaining same size. if things contain text, not remain same size, , need go , fix designs. if use character types in sql tables, make sure of might receive international input unicode (nchar, nvarchar, ntext). matter, standardize on using unicode versions. if you're building sql queries dynamically, make sure include n prefix before quoted text if there's chance text might unicode. if end putting garbage in sql table, check see if that's there. make sure web pages definitively state in unicode format. see joel's article,...

Navigation positioned wrongly in html/css -

i'm coding new portfolio , navigation on in wrong place , can't figure out why. http://i26.tinypic.com/25psi10.png i want text inline lines on sides instead it's moved right , down , can't figure out why it's done this. this relevant coding: body { padding: 0px; margin: 0px; background:url('images/background.png'); font-family: century gothic; } #nav { text-decoration: none; color: white; } #container { margin: 0 auto; width: 960px; } #logo { background:url('images/logo.png'); height: 340px; width: 524px; float: left; margin-left: 0px; <!--check--> } #nav { background:url('images/nav_container.png'); width: 427px; height: 33px; float: right; margin-top: 100px; padding: 0px; } #main_nav li { list-style: none; display: inline; font: 18px century gothic, sans-serif; color: white; margin-right: 18px; padding: 0px; } <html...

java - Moving Axis 1.4 stub project to a Maven based project (Type Access restriction) -

for compatibility reasons have build axis 1.4 skeleton classes exiting wsdl-file. use shipped wsdl2java ant-task axis 14. i'm using myeclipse 8.5 on java sdk 1.6.0_18, added required libraries build path , goes fine. now moved normal project apache maven2 project, added dependencies following warnings (~500): description resource path location type access restriction: constructor qname(string, string) not accessible due restriction on required library /usr/local/uvst/standard/jdk1.6.0_18/jre/lib/rt.jar i have read similar question here don't agree answers @ access restriction on class due restriction on required library rt.jar? . because in normal java project no access restriction on class due restriction warning appears. the classpath setup in normal java project contains libraries shipped latest distribution of axis 1.4 (i know it's rather old). the dependency section of pom.xml: <dependency> <groupid>org.apache.a...

Storing multiple arrays in Python -

i writing program simulate actual polling data companies gallup or rasmussen publish daily: www.gallup.com , www.rassmussenreports.com i'm using brute force method, computer generates random daily polling data , calculates 3 day averages see if average of random data matches pollsters numbers. (most companies poll numbers 3 day averages) currently, works 1 iteration, goal have produce common simulation matches average polling data. change code of anywhere 1 1000 iterations. and problem. @ end of test have array in single variable looks this: [40.1, 39.4, 56.7, 60.0, 20.0 ..... 19.0] the program produces 1 array each correct simulation. i can store each array in single variable, have have program generate 1 1000 variables depending on how many iterations requested!? how avoid this? know there intelligent way of doing doesn't require program generate variables store arrays depending on how many simulations want. code testing mccain: test = [] while x < ...

.net - Automate Safari web browser using c# on Windows -

i wondered if had managed, or knew how automate safari web browser on windows platform. ideally automate safari in similar way using mshtml internet explorer. failing way inject javascript running process fine. i've used javascript injection method automate firefox via jssh plug-in. i'm looking automate browser using .net enhance existing automation framework watin edit : whilst think selenium might great choice automating safari in scenarios, use solution not require installing software on server i.e. selenium core or intermediate proxy server in case of selenium remote control. update: 23-03-2009 : whilst i've not yet found way automate safari, have found way automate webkit inside of chrome. if run chrome using --remote-shell-port=9999 command line switches (ref: http://www.ericdlarson.com/misc/chrome_command_line_flags.html ) can send javascript browser. once connected remote debug seesion send debug() attach current tab send javascript command usin...

c# - How to save the output of a console application -

i need advice on how have c# console application display text user through standard output while still being able access later on. actual feature implement dump entire output buffer text file @ end of program execution. the workaround use while don't find cleaner approach subclass textwriter overriding writing methods both write file , call original stdout writer. this: public class dirtyworkaround { private class dirtywriter : textwriter { private textwriter stdoutwriter; private streamwriter filewriter; public dirtywriter(string path, textwriter stdoutwriter) { this.stdoutwriter = stdoutwriter; this.filewriter = new streamwriter(path); } override public void write(string s) { stdoutwriter.write(s); filewriter.write(s); filewriter.flush(); } // same above writeline() , writeline(string), // plus whatever methods need override inherit // textwriter (encoding.get guess). } public static void main(s...

sql - accdb vs mdb access database file -

what difference between these 2 extensions? i need write access database word file using adodb connection when create new access database gives me option make accdb file , reason cannot make mdb file can please me create mdb file able make adodb connection in order write database/? look @ this explanation . also, in access, 'save as' give older versions save (including .mdb). (from above link) using accdb format, able to: include attachments in database. (supports blobs) use multivalued fields. (store "check apply" in 1 field) safe integration sharepoint , outlook (you can e-mail accdb , outlook won't block them) encryption improvements accdb databases not support user level security or replication.

multithreading - Threads or asynch? -

how make application multithreaded ? use asynch functions ? or spawn new thread ? think asynch functions spawning thread if job doing file reading, being lazy , spawning job on thread "waste" ressources... there kind of design when using thread or asynch functions ? spawning threads going waste resources if start spawning tons of them, 1 or 2 threads isn't going effect platforms proformance, infact system has on 70 threads me, , msn using 32 (i have no idea how messenger can use many threads, exspecialy when minimised , not doing anything...) useualy time spawn thread when take long time, need keep doing else. eg calculation take 30 seconds. best thing spawn new thread calculation, can continue update screen, , handle user input because users hate if app freezes untill finished doing calculation. on other hand, creating threads can done instantly pointless, since overhead of creating (or passing work existing thread using thread pool) higher doing job i...

html - Using CSS how best to display name value pairs? -

should still using tables anyway? the table code i'd replacing is: <table> <tr> <td>name</td><td>value</td> </tr> ... </table> from i've been reading should have like <label class="name">name</label><label class="value">value</value><br /> ... ideas , links online samples appreciated. i'm developer way out of design depth. edit: need able both display data user , edit values in separate (but near identical) form. i think definition lists pretty close semantically name/value pairs. <dl> <dt>name</dt> <dd>value</dd> </dl> definition lists - misused or misunderstood?

excel - Tool for deciphering Spreadsheets? -

i had multipage excel spreadsheet/workbook dumped in lap. there tools aid in deciphering spreadsheets? @ moment click in little cell see what's there, click in other little cell references, click in 3 other cells uses , i'm lost in maze of twisty little cells, alike. i need extract "business logic" sheets in non-laborious manner. it's quite hard problem, in formulae aren't business logic, they're there excel understand you're trying do, e.g. simple look-up list. although can't recommend specific tool, find working copy, , moving things around can help. example, moving "result" or "total" type formulae in column a, cells referenced result in b, cells these reference in c , on. you'll have kind of tree structure. may beneficial move look-ups next formulae they're used in, or put them on same sheet. this far perfect, it's little more structured poking about.

ASP.NET MVC ViewData (using indices) -

i had working solution using asp.net mvc preview 3 (was upgraded preview 2 solution) uses untyped viewmasterpage so: public partial class home : viewmasterpage on home.master there display statement this: <%= ((genericviewdata)viewdata["generic"]).skin %> however, developer on team changed assembly references preview 4. following this, code no longer populate viewdata indexed values above. instead, viewdata["generic"] null. as per this question , viewdata.eval("generic") works, , viewdata.model populated correctly. however, reason solution isn't using typed pages etc. because kind of legacy solution. such, impractical go through large solution , update .aspx pages (especially compiler doesn't detect sort of stuff). i have tried reverting assemblies removing reference , adding reference preview 3 assembly in 'bin' folder of project. did not change anything. have tried reverting project file earlier version , sti...

Rails Render Helper Not Rendering -

one of helper functions render partials not rendering correctly. def render_contact_list @contact_groups = contactgroup.find(:all, :conditions => ["user_id = ?", current_user.id]) @contact_groups.each |contact_group| @contacts = contact.find(:all, :conditions => ["group_id = ? , owner_id = ?", contact_group.id, current_user.id]) render :text => "#{contact_group.name}<br />" render(:partial => 'contacts/partials/view_contacts', :collection => @contacts, :as => :contact) end end all displays on page is ## when looking @ html of rendered page, looks this: #<contactgroup:0x103090c78>#<contactgroup:0x103090b60> i commented out block function , still displayed above. what doing wrong? edit : realized ## coming @contact_groups being last value assigned on page. returning value , not rendering of code within block. your helper function returnin...

android - I want a progressbar but get a spinner progressdialog -

i using public asyntask download data, , trying show progress bar show download progress. think have code right, spinner progressdialog. missing something? why isn't progress bar showing up? here code. pointers. public class filedownloader extends asynctask<string, integer, void> { private context _appcontext; private httpurlconnection _urlconn; private progressdialog _progressdia = null; private dialoginterface.oncancellistener _progdiacancellistener = new dialoginterface.oncancellistener() { /** * when progress dialog canceled, stop request. */ public void oncancel(dialoginterface dialog) { filedownloader.this.cancel(true); } }; /** * constructor. * @param appcontext */ public filedownloader(context appcontext) { _appcontext = appcontext; _progressdia = new progressdialog(_appcontext, progressdialog.style_horizontal); _progressdia.setmax(100); _progressdia.settitle(_appcontext.getstring(r.string.diaheader1)); ...

struts2 dojo tag is displaying abovethe struts form tag why so? -

i trying use struts2 dojo: autocompleter tag inside struts2:form tag autocompleter tag displaying out of struts:form . can't use struts-dojo-tag inside struts form tag ? thanks it should work inside struts form. have custom theme?

windows - polyline with gradient -

is there way draw line along curved path gradient varies in direction perpendicular direction of line? using gdi+ framework graphics. the simple answer no. can create graphicspath in order describe draw, using addpoint/addline/addbezier , forth needed describe complex path of want draw. when draw path can provide brush can lineargradientbrush or radialgradientbrush. neither of gradient brushes reacts actual path being drawn in sense of changing direction drawing occurs. have specify angles etc constant entire gradient area.

Seeking a good solution for SVG + Javascript framework -

i'm looking hear others experiences svg + javascript frameworks. things i'd framework handle - dom creation, event handling , minimal size. jquery svg plugin - http://keith-wood.name/svg.html seems 1 can find. raphael javascript framework manipulating vector graphics, either svg or vml, depending on browser supports.

xcode3.2 - Navigating autocomplete entries in XCode -

sometimes when type words, xcode offer autocomplete several options. if press enter, automatically puts curser on first option , selects when start typing part gets replaced. after that, how next option, without having double click it? for example, if type following: uialertview *alert = [[uialertview alloc] ini then xcode offers autocomplete following: uialertview *alert = [[uialertview alloc] initwithtitle: (nsstring *)title message: (nsstring *)message delegate: (id)delegate cancelbuttontitle: (nsstring *)cancelbuttontitle otherbuttontitles: (nsstring *)otherbuttontitles everything appears above in bold highlighted, meaning replaced programmer. if press enter accept autocomplete, xcode put in above code, , select first highlighted item, (nsstring *)title . if start typing something, replaced type. when i'm done replacing this, want move directly replacing next highlighted item, in case (nsstring *)message . can double clicking on it, there kin...

winapi - In Ruby's Win32API.new, isn't 'L' the same as 'I', and what about 'N' or 'P'? -

in documentation, ruby's win32api has 'l' , 'n' specify "number"... , in documentation, 'l' "long". 'n' deprecated, , isn't 'l' same 'i' actually? "number" not specific. in http://rubyforge.org/docman/view.php/85/3463/api.html#m000001 there no specifying boolean parameter 'b' or 'i' , return value... in http://www.ruby-doc.org/stdlib/libdoc/win32api/rdoc/classes/win32/registry/error.html#m001622 there is win32api.new('kernel32.dll', 'formatmessagea', 'lpllplp', 'l') instead of more common ['l', 'p', 'l', ...] format hwnd 'l' , therefore 'i' work too? ( hwnd handle window) boolean parameter 'b' , same 'i' ? so basically, can use things 'i' ? 'p' should 4-byte, 'i' should work well? there more formal specification? update: think m...

How can I concatenate two arrays in Java? -

i need concatenate 2 string arrays in java. void f(string[] first, string[] second) { string[] both = ??? } what easiest way this? i found one-line solution old apache commons lang library. arrayutils.addall(t[], t...) code: string[] both = (string[])arrayutils.addall(first, second);

Python + DNS : Cannot get RRSIG records: No Answer -

i dns records python program, using dns python i can various dnssec-related records: >>> import dns.resolver >>> myresolver = dns.resolver.resolver() >>> myresolver.use_edns(1, 0, 1400) >>> print myresolver.query('sources.org', 'dnskey') <dns.resolver.answer object @ 0xb78ed78c> >>> print myresolver.query('ripe.net', 'nsec') <dns.resolver.answer object @ 0x8271c0c> but no rrsig records: >>> print myresolver.query('sources.org', 'rrsig') traceback (most recent call last): file "<stdin>", line 1, in <module> file "/usr/lib/python2.5/site-packages/dns/resolver.py", line 664, in query answer = answer(qname, rdtype, rdclass, response) file "/usr/lib/python2.5/site-packages/dns/resolver.py", line 121, in __init__ raise noanswer ...

cappuccino - Clip a CPImage into a circle or other shape -

i have rectangular cpimage setup so var img = [[cpimage alloc] initwithcontentsoffile:"resources/img.jpg""]; i'd display in cpview subclass in circle part of image clipped (what lies outside eclipse) remaining transparent. tried this: - (void)drawrect:(cgrect)arect { var path = [cpbezierpath bezierpathwithovalinrect:arect]; [[cpcolor colorwithpatternimage:img] set]; [path fill]; } but black circle. the problem here can't use image fill (yet) in cappuccino. it'll turn out black discovered, commands you're using technically correct. i'm not aware of work around try posting cappuccino user list , see if working on feature right now.

c# - send image via web service -

i want write 1 program visual studio 2008 (c# , asp) has web application , windows application. i want clients images in web app(upload) , store them in db (mysql) send these images windows app via web service (so new web service, not web site). have 2 problems: i have 2 ways store images in mysql, first should have blob field in db -that takes more space-, second should save name of each image in db(so have image in 1 folder) -in way don't know how image clients , store them in folder-. one? or other? how (code) can transfer image via web service(byte[] or? ). one of options transfer image using wcf convert image byte array , pass client. convert byte[] image on client side.

c# - Headless HTML rendering, preferably open source -

i'm looking perform headless html rendering create resources off screen , persist result image. purpose take subset of html language , apply small screen devices (like pocketpcs) because our users know html , transition photoshop html markup acceptable. i considering using wpf imaging if can weigh in comments use (particularly tools point users creating wpf layouts can convert images , how performs) appreciated. my order of preference is: open source high performance native c# or c# wrapper lowest complexity implementation on windows i'm not worried how feature rich headless rendering since won't make big use of javascript, flash, nor other embedded objects aside images. i'd fine uses ie, firefox, webkit, or custom rendering implementation long implementation close standards compliant. http://www.phantomjs.org/ full web stack phantomjs headless webkit javascript api. has fast , native support various web standards: dom handling, css selec...

Speeding the Android edit-debug cycle -

developing applications android in eclipse, press f11 run program in emulator. however, means waiting emulator bootup (and unlocking emulator's screen) each time want test changes program. there way around delay? ojw are closing emulator after test app? if leave running , start application eclipse again re-deploy , start (and avoid overhead of starting emulator). you can stop application emulator perspective in eclipse before re-starting it. -- frank

version control - How do I ignore a directory with SVN? -

i started using svn, , have cache directory don't need under source control. how can ignore whole directory/folder svn? i using versions , textmate on os x , commandline. set svn:ignore property of parent directory: svn propset svn:ignore dirname . if have multiple things ignore, separate newlines in property value. in case it's easier edit property value using external editor: svn propedit svn:ignore .

What is the best IDE for PHP? -

i'm php developer , use notepad++ code editing, lately i've been searching ide ease work. i've looked eclipse , aptana studio , several others, i'm not decided, nice enough bit complicated. i'm sure it'll easy once used it, don't want waste time. this i'm looking for: ftp support code highlight svn support great ruby , javascript great are sure you're looking ide? features you're describing, along impression of being complicated got e.g. aptana, suggest perhaps want editor syntax highlighting , integration common workflow tools. this, there tons of options. i've used jedit on several platforms successfully, , alone puts above of rest (many of ides cross-platform too, aptana , eclipse-based going pretty heavy-weight, if full-featured). jedit has ready-made plugins on list, , syntax highlighting wide range of languages. can bring shell in bottom of window, invoke scripts within editor, , forth. ...

sql server - Data Comparison -

we have sql server table containing company name, address, , contact name (among others). we regularly receive data files outside sources require match against table. unfortunately, data different since coming different system. example, have "123 e. main st." , receive "123 east main street". example, have "acme, llc" , file contains "acme inc.". is, have "ed smith" , have "edward smith" we have legacy system utilizes rather intricate , cpu intensive methods handling these matches. involve pure sql , others involve vba code in access database. current system not perfect , cumbersome , difficult maintain the management here wants expand use. developers inherit support of system want replace more agile solution requires less maintenance. is there commonly accepted way dealing kind of data matching? here's wrote identical stack (we needed standardize manufacturer names hardware , there sorts of ...

How to check if a column exists in SQL Server table -

i need add specific column if not exist. have this, returns false: if exists(select * information_schema.columns table_name = 'mytablename' , column_name = 'mycolumnname') how can check if column exists in table of sql server database? sql server 2005 onwards: if exists(select 1 sys.columns name = n'columnname' , object_id = object_id(n'schemaname.tablename')) begin -- column exists end martin smith's version shorter: if col_length('schemaname.tablename', 'columnname') not null begin -- column exists end

c++ - Visual studio to gcc, code compiles well in gcc but gives std::badalloc error at runtime -

i have big code uses standard c++ libs , compiles in gcc. code written in vs c++ 6.0. code runs fine in visual studio when use gcc compiler gives no errors on compilation , when run it gives error "terminate called after throwing exception @ instance std::bad_alloc what() bad alloc" 1 more confusion is numerical simulation code, doesn't show exception while using gdb debugging , terminates doesn't show right results. using gdb doesn't terminates anywhere. thats stuck. unable diagnose bad_alloc happening. the code consists of c , c++ routines memory allocated through new gdb doesn't show segabort or exception during debugging how can debug problem? if you're on linux, give valgrind try debugging.

sql server - Select Max Limit 1 from Group -

i'm making in webpage cache system. wanted make simple page rank system along output. problem is, want display recordset highest relevance score per unique domain. 1 domain may have multiple records different titles, descriptions, etc. problem is, instead of getting 1 recordset containing unique domain, groups recordsets of unique domain , outputs them all. want recordset highest relevance score per unique domain per group before outputs next (and different domain highest relevance group) select title, html, sum(relevance) ( select title, html, 10 relevance page title ‘%about%’ union select title, html, 7 relevance page html ‘%about%’ union select title, html, 5 relevance page keywords ‘%about%’ union select title, html, 2 relevance page description ‘%about%’ ) results group title, html order relevance desc; i'm getting: domain1 title html domain1 title html domain1 title html domain2 title html domain2 title html domain2 title html what want domain1 t...

objective c - How do I find working examples of Cocoa/Carbon API? -

i find hard find working examples of cocoa/carbon framework functions, whereas there documented function prototypes apple. for example, lsopenitemswithrole function has defined prototype , guess examples great mac programming beginners me. how can find working examples cocoa/carbon api? doesn't apple provide that? msdn has working examples, expect similar thing apple. you can find sample code on apple's developer site, , of can found within xcode documentation viewer. in fact in cases, not enough, you'll see links sample code right @ bottom of api documentation.

c# - Return a different list depending on generic -

i've asked question before don't think explained myself i'm going try again. i have below code; public interface idocumentmerger { list<???????> process(); } public class emailmerger : idocumentmerger { public void process() { return new list<mailmessage>(); } } public class documentmerger<t> t : idocumentmerger { public t objmerger; public documentmerger() { type t = typeof(t); objmerger = (t)activator.createinstance(t); } public list<???????> process() { return objmerger.process(); } } i want use above this; documentmerger<emailmerger> merger = new documentmerger<emailmerger>(); list<mailmessage> messages = merger.process(); documentmerger<smsmerger> merger = new documentmerger<smsmerger>(); list<smsmessage> messages = merger.process(); but can't figure out how return either list of type mailmessage or list of typ...

jquery - Ambethia Recaptcha unable to rerender after Ajax form submission in Webkit browsers -

i have ajax form in rails app contains recaptcha markup provided helper in ambethia recaptcha gem: recaptcha_tags :ajax => true on submit, form hits create action, responds create.js.erb contains following: $('#message-form').replacewith("<%= escape_javascript(render('message')) %>"); the 'message' partial contains same form markup rendered, including recaptcha_tags, may display if there errors in validation @ point. in firefox, form gets re-rendered , displays refreshed captcha. reason, in webkit browsers (safari , chrome), 'dynamic_recaptcha' recaptcha element gets emptied, if recaptcha.create(public_key, element_id) never gets called. in safari developer console, able call recaptcha.create(public_key, element_id) , regenerate captcha. can tell me what's going on here? thanks. i had same problem , couldn`t work recaptcha_tags in webkit browsers. finally followed official guideline , wrote (in haml) ...

flex - How to get the number of items in Datagrid -

i using datagrid control in flex. i need count of number of items in datagrid. method that? you can find number of items checking data provider data grid: var count:number = (mydatagrid.dataprovider icollectionview).length; per documentation, data sources assigned data provider either implement icollectionview already, , if don't, changed class implement icollectionview.

c# - How to reinterpret cast a float to an int? Is there a non-static conversion operator or user-defined assignment operator for conversion on 'this'? -

1. how can reinterpret cast float int (or double long)? float f = 2.0f; int = (int)f; // causes conversion i want copy bit-pattern f i . how can done? 2. implicit , explicit operators in c# uses 1 intermediate object because operator function static public static implicit operator myclass(double s) { return new myclass(s); } .. .. myclass m = 2.2; // code uses 'm' , 1 intermediate object. this fine reference types, value-types big (say 20-30 bytes), cause unnecessary data copy. understanding correct? , if yes, why doesn't c# have non-static conversion operator or user-defined assignment operator conversion/assignment takes place on 'this'? if does, whats way it? the bitconverter class can retrieve bytes primitive type, can use create int. option buffer.blockcopy if have large amounts of converting do. float ff = 2.0f; int ii = bitconverter.toint32(bitconverter.getbytes(ff), 0); float[] ff = new float[...]; int[] ii = new int[ff.len...

iPhone: Making a simple high score system using SQLite -

i want make simple highscore system game. no posting online, storing best scores on device, maybe being able share them on twitter or that. my table this: create table highscores ( name varchar(10), score int ) and want find easy way retrieve name, score , order score descending, returning top 5. select name, score highscores order score desc limit 0, 5 i tried this, following sqlite tutorial: http://dblog.com.au/iphone-development-tutorials/iphone-sdk-tutorial-reading-data-from-a-sqlite-database/ i created database, set up, tried make own wrapper, got following problems: it worked loading score, loading name, tried convert nsstring* in tutorial, wouldn't work, returned 0 though had set name "johannes" if navigated away scores page, , menu, , clicked on scores page again app crashed. any ideas? i'm stressed can't find online this. :[ dude... overkill. just save data in object or array, save , restore object betweens sessions use n...

.net - How do I start a process from C#? -

how start process, such launching url when user clicks button? as suggested matt hamilton, quick approach have limited control on process, use static start method on system.diagnostics.process class... using system.diagnostics; ... process.start("process.exe"); the alternative use instance of process class. allows more control on process including scheduling, type of window run in and, usefully me, ability wait process finish. using system.diagnostics; ... process process = new process(); // configure process using startinfo properties. process.startinfo.filename = "process.exe"; process.startinfo.arguments = "-n"; process.startinfo.windowstyle = processwindowstyle.maximized; process.start(); process.waitforexit();// waits here process exit. this method allows far more control i've mentioned.

regex - Replace an asterisk (*) using Perl regular expression -

i have following string: $_='364*84252'; the question is: how replace * in string else? i've tried s/\*/$i/ , there error: quantifier follows nothing in regex . on other hand s/'*'/$i/ doesn't cause errors, doesn't seem have effect @ all. something else weird here... ~> cat test.pl $a = "234*343"; $i = "foo"; $a =~ s/\*/$i/; print $a; ~> perl test.pl 234foo343 found something: ~> cat test.pl $a = "234*343"; $i = "*4"; $a =~ m/$i/; print $a; ~> perl test.pl quantifier follows nothing in regex; marked <-- here in m/* <-- here 4/ @ test.pl line 4. solution, escape special characters variable using \q , \e , example (timtowtdi) ~> cat test.pl $a = "234*343"; $i = "*4"; $a =~ m/\q$i\e/; print $a; ~> perl test.pl 234*343

How do I extract the version and path from an SVN working copy into a nant variable? -

i creating new build process dotnet project held in subversion. for each dll/exe compile (via nant) include 2 additional attibutes in dlls built. i understand workings of 'asminfo' nant task. need retrieving information hope embed in binaries. the build happen full working copy (checked out build process itself.) , therefore have .svn directory available. the attributes want add repositoryversion , repositorypath. (i understand these not names information goes in svn) in order need extract repositoryversion , repositorypath represented working copy folder buildfile sits within. how extract information given .svn folder 2 nant variables? firstly, can use "svn info --xml >out.xml" svn information text file. can use nant xml-peek value out of file variable. <xmlpeek file="out.xml" xpath="/info/entry/url" property="svn.url" />

algorithm - Data range filters in C++ -

i want allow user able define ranges filter data. ranges defined contiguous, on lapping, or separated (e.g. user enters following ranges: 1-10, 5-10, 10-12, 7-13, , 15-20). i want filter data user displayed within ranges. i create code on different layer combine ranges appropriate (so above example become 1-13 , 15-20, don't want data service concerned that, must able handle example above) i have lot of data , speed priority, don't want have iterate through list of ranges each data item check if should displayed user or not. is there data structure (or algorithm) used achieve this? you can use boost's filter_iterator achieve this.

COMException when creating COM object for Excel Automation in C# -

i've got error when create com object in order use excel automation. 1 knows why getting error? system.runtime.interopservices.comexception(errorcode = -2146959355) message: retrieving com class factory component clsid {00024500-0000-0000-c000-000000000046} failed due following error: 80080005. the call stack following: system.runtime.remoting.remotingservices.allocateuninitializedobject(runtimetype objecttype) @ system.runtime.remoting.remotingservices.allocateuninitializedobject(type objecttype) @ system.runtime.remoting.activation.activationservices.createinstance(type servertype) @ system.runtime.remoting.activation.activationservices.iscurrentcontextok(type servertype, object[] props, boolean bnewobj) @ system.runtimetypehandle.createinstance(runtimetype type, boolean publiconly, boolean nocheck, boolean& canbecached, runtimemethodhandle& ctor, boolean& bneedsecuritycheck) @ system.runtimetype.createinstanceslow(boolean publiconly, boolean fillc...

ruby on rails - Custom Formtastic Control with Multiple Parameters -

i'm attempting build custom control formtastic takes latitude , longitude, however, i'm not sure how go passing method names through. ideally i'd have following in semantic_form_for block: f.input :latitude, :longitude, :as => :location i've tried passing array: f.input [:latitude, :longitude], :as => :location but in both cases, fails - first on number of parameters, second on first parameter not being symbol. is there way of passing 2 methods #input i'm missing? ok, i've sorted out writing a plugin formtastic . i've added multi_input function can take number of parameters , (optional) options hash. i've added map_input type outputs map control , js (framework agnostic). more details @ above link.

c# - NHibernate: Default value for a property over a null column -

i'm working old database used other applications, can't modify structure. have nullable columns want map non nullable type. instance have nullable endvalidity column on database want map on non nullable datetime, and, if null, should datetime.maxvalue, or more simple example, nullable bit column must false if null. i'm thinking writing custom user type (with parameters if possible), or there included in nhibernate it? if solution write custom usertype, boolean case, can override fluentnhibernate conventions apply usertype booleans? it depends on how want poco class act. firstly if load null value want null value re-saved or want session commit/flush update record new default null field. if want keep null value in db how detect poco object boolean value save ie booleans have true , false options / values bit class has options / values of null, 0 , 1? if say: want have nullable bits boolean , not nullable boolean dataype in poco class , have class update db...

C#: Partial Classes & Web Services: Separating form and functionality -

i dabbling in world of web services , i've been making simple web service mimics mathematical operations. firstly simple, passing in 2 integers , binary operator applied these (plus, minus etc) depending on method called. then decided make things little more complex , started passing objects around, discovered web service exposes data side of class , not functional side. i told way deal make class on service side partial class (this side of class encapsulating form) , on client side have partial class (where side of class encapsulates functionality). seems elegant way of doing things.. so, have set 2 classes described above, doesn't seem working told. is attempting possible? if so, going wrong? partial classes tool separate auto-generated code developer code. a example windows forms designer in vs, or new dbml linq datacontext generated code. there's argument using them vss style source control providers 1 user can edit file @ 1 time. it's not...

jsf - How to display a line break with outputText? -

i need render line break using outputtext can utilize rendered attributed. tried <h:outputtext value="<br/>" escape="false" /> but generated exception the value of attribute "value" associated element type "null" must not contain '<' character. that's indeed not valid since facelets because it's syntactically invalid in xml. you'd need manually escape xml special characters < , > , on. <h:outputtext value="&lt;br/&gt;" escape="false" /> you can emit <br/> in template text without need <h:outputtext> . <br/> to render conditionally, wrap in example <ui:fragment> . <ui:fragment rendered="#{bean.rendered}"><br /></ui:fragment> a <h:panelgroup> valid doesn't emit html anyway. <h:panelgroup rendered="#{bean.rendered}"><br /></h:panelgroup>

Parsing C++ to generate unit test stubs -

i've been trying create units tests legacy code. i've been taking approach of using linker show me functions cause link errors, greping source find definition , creating stub that. is there easier way? there kind of c++ parser can give me class definitions, in easy use form, can generate stubs? you may want investigate http://os.inf.tu-dresden.de/vfiasco/related.html#parsing . c++ parsing hard. on other hand, maybe ctags or similar can extract class definitions... you may try write own simple (?) parser generate class stubs header files... i tried give pointers. see, problem not easy. can automate @ least part of it.

c++ - The most elegant way to iterate the words of a string -

what elegant way iterate words of string? string can assumed composed of words separated whitespace. note i'm not interested in c string functions or kind of character manipulation/access. also, please give precedence elegance on efficiency in answer. the best solution have right is: #include <iostream> #include <sstream> #include <string> using namespace std; int main() { string s = "somewhere down road"; istringstream iss(s); { string subs; iss >> subs; cout << "substring: " << subs << endl; } while (iss); } for it's worth, here's way extract tokens input string, relying on standard library facilities. it's example of power , elegance behind design of stl. #include <iostream> #include <string> #include <sstream> #include <algorithm> #include <iterator> int main() { using namespace std; string sentence ...

Events in C++ -

i'm not sure how online... think might called different in c++ i want have simple event system, somthing like event mycustomevent; mycustomevent.subscribe( void myhandler(string) ); mycustomevent.fire("a custom argument"); // myhandler prints out string passed in first argument event mynewcustomevent; mynewcustomevent.subscribe( void mynewhandler(int) ); mynewcustomevent.fire(10); // myhandler prints 10 i can pretty simple class -- when want have event passes different type or amount of arguments subscriber have write, , define entirely new event class.. figure there has library, or maybe native in visual c++ 2008 work similar this. it's basicly implementation of observer pattern, can't impossible in c++ this makes me appreciate how nice in javascript not have worry arguments passing. tell me if stupid question. i use sigslot purpose.

language design - RunOnce in Foreach -

i'm writing little scripting language bit of fun , learning of codes :p i opinions/suggestions. have idea don't want include people going want spit on. plan on making language open source once, soon. does think cool have like: [foreach] uppercase letter s in case-insensitive word sallysawtheseafishandateit: count++. s.highlight: true. runonce.protectedmethod.activateprotectedmethod: istrue. [protected method.lockto: [foreach]].istrue statusbar.message: match s found. total: count.. runonce.protectedmethod.disable. explanation: above searches through string of text "sallysawtheseafishandateit" , highlights every single match. when finds first match "s", runs method called "istrue", , sets statusbar text "match found...". , deactivates runonce method may no longer accessed, since there's no need run again. this might not best example, think idea. there have be...

java - How do you format the body of a JMS text message? -

does use xml in message? there alternatives xml? if use xml, define xml schema clients know how send messages service? we use xml, think important thing tailor solution problem. reason use xml sending object across in message. there's no reason can't plain text, if applicable message sending, using headers send along properties if appropriate. haven't defined xsd or dtd our xml messages, have formal document describing composition other teams can use our feeds without bugging us.

c++ - Encode URLs into safe filename string -

i'm writing simple c++ class in cache picture thumbnails versions of images downloaded web. such, use hash function takes in url strings , outputs unique string suitable filename. is there simple way without re-writing function myself? searched around simple library, couldn't find anything. surely common problem. a simpler approach replace not character or number underscore. edit: here's naive implementation in c: #include <cctype> char *safe_url(const char *str) { char *safe = strdup(str); (int = 0; < strlen(str); i++) { if (isalpha(str[i])) safe[i] = str[i]; else safe[i] = '_'; } }

email - In CodeIgniter, How Can I Have PHP Error Messages Emailed to Me? -

i'd receive error logs via email. example, if warning-level error message should occur, i'd email it. how can working in codeigniter? you extend exception core class it. might have adjust reference ci's email class, not sure if can instantiate library this. don't use ci's email class myself, i've been using swift mailer library. should on right path. make file my_exceptions.php , place in /application/libraries/ (or in /application/core/ ci 2) class my_exceptions extends ci_exceptions { function __construct() { parent::__construct(); } function log_exception($severity, $message, $filepath, $line) { if (environment === 'production') { $ci =& get_instance(); $ci->load->library('email'); $ci->email->from('your@example.com', 'your name'); $ci->email->to('someone@example.com'); $ci-...

javascript - Code only works if I alert out before the code that's bombing out? -

this freakin weird me. if don't function bindalbumandphotodata() { // array of user's albums var aalbums = getallalbums(userid, token); alert("aalbums: " + aalbums); if (aalbums == null || aalbums == "undefined") return; // set default albumid var defaultalbumid = aalbums[0].id; }; so undefined error on line var defaultalbumid = aalbums[0].id; if don't uncomment alert("aalbums: " + aalbums); what heck? if comment out alert("aalbums: " + aalbums); undefined var defaultalbumid = aalbums[0].id; this weird. i've been working night figure out why kept getting undefined aalbum[0] , add alert used have above it, fine...makes no sense me. here's full code of getallalbums: function getallalbums(userid, accesstoken) { var aalbums = []; // array var uri = "/" + userid + "/albums?access_token=" + accesstoken; aler...

java - Avoiding != null statements -

the idiom use when programming in java test if object != null before use it. avoid nullpointerexception . find code ugly, , becomes unreadable. is there alternative this? i want address necessity test every object if want access field or method of object. for example: if (someobject != null) { someobject.docalc(); } in case avoid nullpointerexception , , don't know if object null or not. these tests appear throughout code consequence. this me sounds reasonably common problem junior intermediate developers tend face @ point: either don't know or don't trust contracts participating in , defensively overcheck nulls. additionally, when writing own code, tend rely on returning nulls indicate requiring caller check nulls. to put way, there 2 instances null checking comes up: where null valid response in terms of contract; and where isn't valid response. (2) easy. either use assert statements (assertions) or allow failure (for example, ...

architecture - How to avoid circular data-access object dependencies when you need to do lazy loading (and using an IOC Container)? -

note: examples below c# problem should not specific language in particular. so building object domain using variant of s# architecture . unfamiliar it, , save reading time idea have data access object interface each of domain objects responsible loading to/from persistence layer. might ever need load/save given object accepts object's data access interface dependency. example can have following product lazy load customer purchased needed: public class product { private icustomerdao _customerdao; private customer _customer; public product(icustomerdao customerdao) {_customerdao = customerdao;} public int productid {get; set;} public int customerid {get; set;} public customer customer { get{ if(_customer == null) _customer = _customerdao.getbyid(customerid); return _customer; } } public interface icustomerdao { public customer getbyid(int id); } this , until reach situation 2 objects need able load each other. examp...