Posts

Showing posts from August, 2011

Column height per class with JavaScript and PHP -

i have following code in script set max height each column. however, intend set max height individually 4 columns per row . won't execute function per class. here's javascript: <script type="text/javascript" > $(document).ready(function() { <?php $test = $cart->count_contents(); ($i=0, $n=$test; $i<$n; $i++) { ?> setheight('.<?php echo 'col'.$i; ?>'); <?php } ?> }); //initialize global variable, store highest height value var maxheight = 0; function setheight(col) { //get element class = col col = $(col); //loop col col.each(function() { //store highest value if($(this).height() > maxheight) { maxheight = $(this).height();; } }); //set height col.height(maxheight); } </script> i pull out each row mysql database php , generate following html: <div class="ui-grid-c ui-bar ui-bar-e"> <div class="ui-block-a"><div class="ui-bar ui-bar-b" style=&quo

number formatting - JSTL padding int with leading zeros -

i'm trying use jstl build form. have select input months need months 2 digits i.e. padded left 0 1-9. i have obvious doesn't give me want. <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <select class="forminput"> <c:foreach var="i" begin="1" end="12" step="1" varstatus ="status"> <option><fmt:formatnumber pattern="##" value="${i}" /></option> </c:foreach> </select> this has have been done before can't find example after bit of searching. found answer: minintegerdigits <select class="forminput"> <c:foreach var="i" begin="1" end="12" step="1" varstatus ="status"> <option><fmt:formatnumber minintegerdigits="2" value="${i}" /></option>

security - Where should I store an encryption key for php? -

i'm writing php application accepts sensitive customer data, , need encrypt before storing in mysql database. i'm going use mysql's built-in aes functionality column-level encryption. i want avoid storing encryption key on server, , i'm going provide web-page administrator log-in, , enter encryption key. want store key in memory while application running, never permanently disk. what best way this? can modify $_server array store information between requests? can store key apache in way? maybe shared memory? rather rely on mysql aes encryption, why not use php's native openssl encryption scheme (a pecl extension). requires private , public key, public encrypt, private decrypt, , keys can kept in separate places.

c# - How to retrieve the data out of a Silverlight DataContext Object -

i have silverlight application collection of form fields , buttons. i've created method stub handles click event in xaml.cs. when inspect sender during debug, can see base type textblock, , in datacontext object within textblock see custom type's properties. 1 of them guid - sender's type, cast textblock , can see datacontext, not sure how type's field value out of object: private void sometextfield_mouseleftbuttondown(object sender, system.windows.input.mousebuttoneventargs e) { var datacontext = (textblock) sender; var assetguid = datacontext.datacontext. / // intellsense not show fields, indexers, or getters - says "get or set datacontext fields in datacontext". } as stated, if debug , place watch on sender, go 2 levels deep can see objects fields. thanks. if can see in debug mode, datacontext of textblock needed object, have cast object. private void sometextfield_mouseleftbuttondown(object sender,

cpu usage - Unable to import android.server.* package -

i trying use android.server.processstats class cpu usage statistics (pcpu, idle time, etc) of app on android device, i'm not able import package android.server required use class. after searching on net, came know android.server package not part of standard sdk. can please tell me how/where should find package. thanks! there go . rest of package included.

c# - Scheduling Dependent Jobs in Quartz.Net -

i need help. trying figure out how schedule jobs in quartz.net. jobs in quartz correspond tasks in web application, each apart of job in web application. want users able launch job (webapplication context) on demand , have run or schedule job in future and, possibly repeat on given interval. know how these items accomplished in quartz individually, having hard time putting together. for example, in web application, may have job several task, in specific order. want able schedule these tasks in quartz execute in same order determined in web application. have idea of how this? have read on quartz documentation saying store next job in jobdatamap, struggling it. i waiting create quartz jobs until user requests either schedule job or run it. think should creating job , trigger on creation of task in web app , pulling information task object scheduling in quartz? on second paragraph: if understand correctly, have set of jobs, user can select , put in order of execut

java - Get Enum Instance from Class<? extends Enum> using String value? -

i'm finding difficult put exact question words, i'll give example. i have 2 enum types: enum shape { cat, dog; } enum color { blue, red; } i have method: public object getinstance(string value, class<?> type); i use method like: // somevalue "red", , someenumclass color.class color c = getinstance(somevalue, someenumclass); i've been having trouble determining how implement getinstance() . once know exact enum class want instantiate, it's easy: color.valueof("red"); but how can above line accomplished unknown class ? (it is, however, known someenumclass subclass of enum .) thanks! public static <t extends enum<t>> t getinstance(final string value, final class<t> enumclass) { return enum.valueof(enumclass, value); } and method used as: final shape shape = getinstance("cat", shape.class); then again, can use final shape shape = shape.valueof("cat");

winforms - Visual C# Windows Form Textbox Not Auto-updating -

i'm attempting code application reads in values imu. i'm trying different values of attitude (i.e. direction) of imu 1 second when using getatr_click method. however, while calling get_attitude function, changes textbox values once on form. how make change each time? (i want see 10 different values flash on textbox). here's code: using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.linq; using system.text; using system.windows.forms; using system.threading; using system.timers; using vectornav.devices; namespace windowsformsapplication1 { public partial class form1 : form { public static vn100 vn100 = new vn100("com5", 9600); // new vn100 on com5 private void get_attitude() //gets current yaw, pitch, roll in degrees, , displays { var attitude = vn100.currentattitude; yaw.text = convert.tostring(attitude.ypr.yawindegs); pitch.tex

Insert Java.sql.Date into Derby Database -

i trying insert date object database says im trying insert integer. here code: public void insertassignment(long studentid, string newassignment, int ptstotal, int ptsrecieved, string category, date duedate, string term, int yr) { java.sql.date temp = new java.sql.date(duedate.gettime()); try{ s.execute("insert assignments " + "values (" + studentid + ",'" + newassignment + "'," + ptstotal + "," + ptsrecieved + ",'" + category + "'," + temp + ",'" + term + "'," + yr + ")"); system.out.println("assignment inserted."); } catch(sqlexception error){ system.err.println("unable insertassignment."); error.printstacktrace(system.err); system.exit(0); } } my error: java.sql.sqlsyntaxerrorexception: columns of type 'date' ca

c++ - Emulate "double" using 2 "float"s -

i writing program embedded hardware supports 32-bit single-precision floating-point arithmetic. algorithm implementing, however, requires 64-bit double-precision addition , comparison. trying emulate double datatype using tuple of 2 float s. double d emulated struct containing tuple: (float d.hi, float d.low) . the comparison should straightforward using lexicographic ordering. addition bit tricky because not sure base should use. should flt_max ? , how can detect carry? how can done? edit (clarity): need significant digits rather range. double-float technique uses pairs of single-precision numbers achieve twice precision of single precision arithmetic accompanied slight reduction of single precision exponent range (due intermediate underflow , overflow @ far ends of range). basic algorithms developed t.j. dekker , william kahan in 1970s. below list 2 recent papers show how these techniques can adapted gpus, of material covered in these papers applicable indepe

php - Help with jquery image gallery -

i creating portfolio image gallery website i'm having trouble... when click on 1 of icons first image goes away (thats suppose happen) next image won't open... heres code: $(".portlink").click(function() { $(".large-image").addclass("hidden"); var $alt = $(this).attr("alt"); $(".", $alt).removeclass("hidden"); }) and html/php... function portfolio() { $sql = "select * db order id desc"; $res = mysql_query($sql) or die(mysql_error()); while($row = mysql_fetch_assoc($res)) { ?> <div id="large-image" class="<?php echo $row['name'] ?> large-image hidden"> <a href="<?php echo $row['website_address'] ?>"><img src="img/uploads/<?php echo $row['website_image'] ?>" alt="" /></a> </div> <?php } } // end portfol

.net - How can I know that the binding of a dependency property has changed? -

as mentioned in this question , there @ least 2 ways can notified value bound dependency property has changed: dependencypropertydescriptor.addvaluechanged dependencyproperty.overridemetadata on derived class own propertychangedcallback. this working fine need notified when actual binding set on property not every time value changes. there way register callback or event need listen to? i have looked in msdn on classes dependencyproperty , dependencyobject , bindingoperations , dependencypropertydescriptor . i don't think there "official way" that, although had same problem days ago , came quite stupid @ least efficient workaround private bool isset = false; public static readonly dependencyproperty dummyproperty = dependencyproperty.register("dummysource", typeof(dummytype), typeof(whateveryouwant), new pr

Appending arrays in PHP -

i have 3 arrays represent category ids in wordpress, format $base_cat_id['term_id'] . want assign post 3 of these categories using following function: wp_set_post_categories($entry['post_id'], $base_cat_id + $generic_n_cat_id + $specific_n_cat_id); however, when post assigned first 2 categories. using right method add these arrays together? edit: i got work doing following: $cat_ids = array($base_cat_id['term_id'], $generic_a_cat_id['term_id'], $specific_a_cat_id['term_id']); wp_set_post_categories($entry['post_id'], $cat_ids); it's not pretty. found using array_merge same string id not work, overwrites values. union not work either can use union 2 arrays. please let me know if there better way! use function array_merge(). arguments many arrays merging , returns arrays merged in 1 array, returns array. like this: wp_set_post_categories($entry['post_id'], array_merge($base_cat_id, $generic_n_cat_id,

javascript - jscript if for global variable -

here's code var isnew = true function limb(a,b) { if (isnew=true) { post(a,b); isnew = false; post ("first"); } else { post(a,b); post ("not first"); } } the problem i'm having else condition never triggered. i'm assuming value of isnew never updated, have no idea why. in languages = used both assign values , compare them. javascript uses different operators each of these. x = 10 means "set x 10 , , give me value of x ". x == 10 means "tell me if x equal 10 ". so condition have been if(isnew == true) , have worked. can put if(isnew) .

Java memory dump issue -

i have tried create memory dump using below code **/usr/lib/jvm/j2sdk1.5-sun/bin/jmap -heap 10699** but got below mentioned error, can me attaching process id 10699, please wait... error attaching process: sun.jvm.hotspot.debugger.debuggerexception: can't attach process i'm using java 5 to proactive, i'll assume you're running ubuntu. in case, type following: echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope if you're not running ubuntu, i'll recommend run jmap same user ran target process

perl - Quick question about XML parsing -

this might silly question not getting it. tried ways, maybe making silly mistake somewhere. still learning parsing. surely me enhance knowledge. want extract forename , lastname of authors authorlist. have tried write code not sure if right. use lwp::simple; use xml::simple; use data::dumper; open (fh, ">:utf8","xmlparsed1.txt"); $db1 = "pubmed"; $q = 16404398; $xml = new xml::simple; $urlxml = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=$db1&id=$q&retmode=xml&rettype=abstract"; $dataxml = get($urlxml); $data = $xml->xmlin("$dataxml", forcearray => [qw( meshheading authorlist )]); print fh dumper($data); print fh "authors: ".join '$$', map $_->{lastname},@{$data->{pubmedarticle}->{medlinecitation}->{article}->{authorlist}->[0]->{author}}; this gives me lastname want forename 'atul j butte'. also, generalized code such xml file correct mention

python - What's the difference between pyodbc and MySQLdb? -

i have code written pyodbc on win x64 using python 2.6 , no problem. using same code switching mysqldb errors. example. long object not iterable.... whats difference between pyodbc , mysqldb? edit import csv, pyodbc, os import numpy np cxn = pyodbc.connect('dsn=mysql;pwd=me') import mysqldb cxn = mysqldb.connect (host = "localhost",user="root",passwd ="me") csr = cxn.cursor() try: csr.execute('call spex.updtop') cxn. commit except: pass csr.close() cxn.close() del csr, cxn without seeing code, it's not obvious why you're getting errors. can connect mysql databases using either one, , both implement version 2.x of python db api, though underlying workings totally different, ignacio vazquez-abrams commented. some things consider: are using extensions python db api might not implemented in both? are 2 libraries translating mysql datatypes python datatypes same way? is there example code

iphone - NSMutableArray elements not being released in dealloc -

i have define nsmutablearray in .h file nsmutablearray *arraybatlevel; init in .m file - (void)viewdidload { [super viewdidload]; [self datatimer]; } -(void)datatimer { [recorddatatimer invalidate]; recorddatatimer = [nstimer scheduledtimerwithtimeinterval:[timeinterval.text floatvalue] target:self selector:@selector(recorddata) userinfo:nil repeats:yes]; } -(void)recorddata { if ([aswitch ison] == yes) { if (arraybatlevel == nil) { arraybatlevel = [[nsmutablearray alloc] init]; nslog(@"alloc arraybatlevel"); } [arraybatlevel addobject:batlevel.text]; } } and release in dealloc - (void)dealloc { [arraybatlevel release]; [super dealloc]; } but, seems it’s not releas

android - WebView.loadUrl(url) does nothing -

i wrote simple twitter app android learn ropes of twitter api , oauth. the app's main activity asks username follow. calls activity handles oauth & twitter api calls. redirects user authorization page, returns app after user finishes. it used work fine, reason when call webview.loadurl(authorizationurl), nothing happens. never changed affect webview stuff though... here's code: @override public void onresume() { super.onresume(); try { if(weneedcredentials()) { obtaincredentials(); } follow(musername); } catch (oauthexception oae) { // omitted } } private boolean weneedcredentials() { // assume method returns true } private void obtaincredentials() { final token requesttoken = moauthservice.getrequesttoken(); string authurl = moauthservice.getauthorizationurl(requesttoken); // verified authurl correct url (and != null) final webview oauthview = (webview) findviewbyid(r.id.oaut

iphone - Weird issue with UITextView -

Image
i have issue uitextview. whenever try type uitextview goes beyond frame , can't seem anything. why this? some screenshots: when type in first word: then typing word, shifts , can't see thing: some code: self.messagetextview = [[uitextview alloc] initwithframe:cgrectmake(0, 0, 600, 30)]; [self.messagetextview setautocorrectiontype:uitextautocorrectiontypeno]; [self.messagetextview setautocapitalizationtype:uitextautocapitalizationtypenone]; [self.messagetextview setfont:[uifont fontwithname:@"arialmt" size:16.0]]; self.messagetextview.delegate = self; did try, textview.contentinset = uiedgeinsetszero;

php - Problem with regex -

i have following regex: /[0-9#%@_$&!?^\/|*<>]+/i which not supposed accept letters. accept letters when letters not entered @ first place. e.g.: finds match if enter "123e" (but should not because there letter) what problem in regex? thanks your regex checks if there one or more of list characters specified -- , that's true 123e . it doesn't check if string contains only those . might want edit regex, looks : /^[0-9#%@_$&!?^/|*<>]+$/i where i've added 2 following anchors : ^ indicating " beginning of string / line " $ indicating " end of string / line " which means regex check if string starts 1 of characters, end 1 of those, , contains those.

java - Is catch block able to catch Throwable (both error and exception) -

in 1 of interview, asked me, possible write throwable in catch() this try{ code } catch(throwable t) { } i said yes. not give compile time error jvm not handle if there occur error (sub class of throwable ), since errors irreversible conditions can not handled jvm. further asked use of writing throwable . please give me proper reply can use throwable in catch. if yes why. it possible catch throwable . , yes, catch instances of java.lang.error problem when comes e.g. outofmemoryerror 's. in general i'd not catch throwable 's. if have to, should @ highest place of call stack, e.g. main method (you may want catch it, log it, , rethrow it). i agree argumentation, not make sense catch events you're not able handle (e.g. outofmemoryerror). nice post here .

c# - Deleting items more than 1 day old from sql database -

i trying remove items created more 1 day old, items still remain. changes committed database since using removeitem method in other locations well. using (var db = new commerceentities()) { datetime checkexpirydate = datetime.utcnow.adddays(-1); var itemstodelete = c in db.shoppingcarts c.datecreated < checkexpirydate select new { c.cartid, c.productid, c.color, c.size, }; foreach (var item in itemstodelete) { try { //remove item code.... //removeitem(string cartid, int productid, string color, string size) } public void removeitem(string cartid, int productid, string color, string

java - Weblogic replays request exactly after 5 minutes -

we're investigating issue specific web request processing lasts long on our weblogic 10.3 server. after 5 minutes server starts processing same request, causing error in application logic. happens 3 or 4 times. can me server setting or whatever might cause this? in logs can see these entries: <bea-000337> <[stuck] executethread: '5' queue: 'weblogic.kernel.default (self-tuning)' has been busy "667" seconds working on request "weblogic.servlet.internal.servletrequestimpl@2f35bea[ ....... ]", more configured time (stuckthreadmaxtime) of "600" seconds. stack trace: thread-65 "[stuck] executethread: '5' queue: 'weblogic.kernel.default (self-tuning)'" <alive, in native, suspended, priority=1, daemon> { } the solution: client software resending request in loop if connection timed out.

c# - How to set the revision Number to a file -

i using file upload in project. set revision number file uploading in database. i.e. upload sd.doc file first time saved version 1. after downloading file make changes , save should saved version 2. while viewing should show both version , should choose file based on version. can 1 me solve issue. thanks in advance. if right understand problem, need versioning system docs. 1 of solutions can think off, using of mercurial dvs. can create simple ui interafce interact it's command line "hg". provides huge potential, probabbly no need in app, saving "revision" number, enable others query it, done + given huge amount of options future development. but depends on project requirements. keep eye on , make choice. hope helps. regards.

Is developer provisioning profile/code signing required to test game center in simulator? -

i in strange problem of getting "this application not recognized game center". i developed game in app store no game center option. working on make game center-enabled. few hours ago, enabled game center , added leaderboard , achievements using itunes connect. when try access game center in iphone simulator gives me following error: gamekithelper error: { nslocalizeddescription = "the requested operation not completed because application not recognized game center."; } the bundle id of application same application uploaded in itunes connect, don't have valid provisioning profile now, there no code signing in application. now question this: require provisioning profile associated corresponding application test game center in simulator? or sufficient application bundle id matches uploaded application bundle id? if second case true why getting error? i using sandbox account generated simulator. sandbox account. please, me! the

WPF Binding To Application Properties -

i need bind static properties in app.xaml.cs class , have far done using: property="{binding source={x.static application.current}, path=somepath}" this works ok when application being run directly, when application started application, these bindings don't work believe application.current points @ parent application rather application xaml sits under. how bind immediate app.xaml.cs file properties rather parent application? hope makes sense! so 1 solution i've found far put class between app.xaml.cs , xaml i'm trying bind: app.xaml.cs: public partial class app : application { public static string sometext; protected override void onstartup(startupeventargs e) { base.onstartup(e); sometext = "here text"; } } myproperties.cs: public class myproperties { public static string sometext { { return app.sometext; } } } mainwindow.xaml: <window.resources> <local:my

Flex Google Chrome cache issue -

i have 1 issue web project use release new swf, older version gets cached in chrome , have clear cache see it. same not happen in firefox , ie. environment used: - web application (flex), browser tested on ie, firefox , google chrome. is there programmatic solution can solve problem using javascript, html or through flex? solution tried (does not work): - i have following headers: meta http-equiv="content-type" content="text/html; charset=utf-8" /> meta http-equiv="cache-control" content="no-store, no-cache, must-revalidate" /> meta http-equiv="pragma" content="no-store, no-cache" /> meta http-equiv="expires" content="0, -1" /> use naming convention swf includes version , build number. file name difference address caching being best practice numerous reasons. it's hard argue it's better guess version of code base "myapp.swf" versus "myapp.2.

c++ - Question on Virtual and default arguments -

i wanted have confirmation following things: virtual mechanism: i f have base class , has virtual method, in derived class generally, not include virtual statement in function declaration. virtual mean when included @ dervied class definition. class { public: virtual void something(); } class b:public { public: virtual void something(); } does, mean want override method somethign in classes derive class b? also, question is, i have class a, derived 3 different classes.now, there virtual method anything(), in base class a. now, if add new default argument method in base class, a::anything(), need add in 3 classes right. my pick answers: if method virtual in base class redefined in derived class virtual might mean shall overridden in corresponding derived classes uses class base class. yes.if not overriding not have meaning. pls let me know if feel(above 2) correct. thanks, pavan moanr. the virtual keyword can omitted on override in derived classe

assembly - Wrong integer push on the stack -

am trying understand why instruction: pushl 0x4013ea not pushing value expected rather have on stack: (gdb) x/wx $esp 0x22ff18: 0xc3899090 i on windows using gdb if help thanks i bet 0x4013ea being treated memory address, therefore, value @ address being pushed onto stack rather literal value itself. try pushl $4013ea (might need include 0x, depends on assembler syntax)

flash - Font Embedding Issue -

i have as3 project. uses 100 swfs, these small swf's 5-15 kb piece. of these swf's have textfield in them. need embed font in text fields. if embed font in every swf, that's going bump size lot . i cannot break apart text it's dynamic. text formatting different in different swf's taking points consideration, best way embed font , how ? http://www.adobe.com/devnet/flash/quickstart/embedding_fonts.html did u try way?

jquery - Render partial onclick in rails -

is possible render partial when link clicked? i have searched google , here can't find useable. thanks yes possible. following example uses jquery, tagged : in view file (the page displayed) : <%= link_to "display new view", path_to_controller, :remote => true %> in controller action (path_to_controller), add js response : respond_to |format| format.js end and in path_to_controller.js.erb (the js response file) : $("#your-placeholder-id").prepend('<%= escape_javascript(render 'path/to/view') %>'); hope helps!

Rails 3.1.rc4 with compass (git rev-parse HEAD (Errno::ENOENT)) -

after upgrading osx lion, there error in terminal every rails command. /users/danielpuglisi/.rvm/gems/ruby-1.9.2-p0@rails31/bundler/gems/compass-2124003550bf/lib/compass/version.rb:44:in ``': no such file or directory - git rev-parse head (errno::enoent)

asp.net - Configuration Error on roleManager in web.config on subdirectory -

Image
i getting error in web.config file @ <rolemanager enabled="false"> can 1 tell how resolve this verify virtual directory configured application in iis. http://learn.iis.net/page.aspx/150/understanding-sites-applications-and-virtual-directories-on-iis-7/

A simple (clone only) Mercurial client in pure Java? -

there recurring questions whether there's pure java mercurial client available (or whether possible run mercurial in javafied python environment, such jython. googling around, nothing recent found , seems jython not able support mercurial on whole. but have tightly focused requirement: perform hg clone (from scratch). maybe relaxed constraint makes possible solve problem. knows it? my problem operation must performed webapp running in virtualized host there's no hg support. have other choices (such downloading files browsing web access forces offer), of course direct integration preferred. thanks. there's hg4j . recent version 0.1.0 (as of july 21) doesn't seem support clone, seems possible according sources . maybe try unofficial build. personally go downloading archive hgweb offers.

ios - move row from UITableView to second UITableView -

i have 2 uitableview , scenario want move row first uitableview second uitableview . need help. if not need drag/drop functionality(animations) need change data in individual data-sources 2 table-views , reload them both! can triggered , eg, button. data cell deleted 1 table-view data-source , added other. animations tricky! i'll start working on right away , post here if nice happens. hey... i've uploaded (partially) working solution @ github ps: needs lot of improvement. now, you'll have tap cell dragged once, , then, hold , drag required area.

javascript - post form to same site -

do know how post form same site form is? this not work: <form action="window.location.href();" method="post">...</form> empty action <form method="post">...</form> works! http://binarious.de/sandbox/post.php or php action="<?php echo $_server['php_self'] ?>" or smarty action="{$smarty.server.php_self}"

android - How to Put Buttons on VideoView in Different Places? -

how put buttons on videoview , change video url on click event of buttons? use framelayout , add videoview & button layout. since framelayout allows children views overlay, can have visible button on videoview. implement onclick() listener listen button press event. do need code same ?

cryptography - How long to brute force a salted SHA-512 hash? (salt provided) -

here algorithm in java: public string gethash(string password, string salt) throws exception { string input = password + salt; messagedigest md = messagedigest.getinstance(sha-512); byte[] out = md.digest(input.getbytes()); return hexencoder.tohex(out); } assume salt known. want know time brute force when password dictionary word , when not dictionary word. in case, breaking hash algorithm equivalent finding collision in hash algorithm. means don't need find password (which preimage attack ), need find output of hash function equal hash of valid password (thus "collision"). finding collision using birthday attack takes o(2^n/2) time, n output length of hash function in bits. sha-2 has output size of 512 bits, finding collision take o(2^256) time. given there no clever attacks on algorithm (currently none known sha-2 hash family) takes break algorithm. to feeling 2^256 means: believed number of atoms in (entire!!!) universe 10^80 2^266

tool for testing logic expressions -

can recommend software (preferably mac) or web based tool, can used evaluate logic expressions? for example able test whether 2 expressions like: $a = 'foo'; $b = 'bar'; $c = 'foo'; ( !(($a == $c) && ($b == $c)) ) // , ( ($a != $c) || ($b != c$) ) are interchangeable or not. and also, there agreed upon best practice in relation how construct such expressions? example try minimize use of negation, order of elements or that? sometimes find myself struggling bit these things :) you can use http://www-cs-students.stanford.edu/~silver/truth/ , compare generated truth tables.

java - Need help with regular expression when only one number changes in string -

how check in java regular expression if string matches monday ptnumber operating mode where number ( after pt ) has concrete value 0,1,...99,.. - integer? mondaypt , operating mode hardcoded number can change in string. this extract number. string input ="monday pt23 operating mode"; pattern p = pattern.compile("monday pt([0-9]+) operating mode"); matcher m = p.matcher(input); boolean found = m.find(); if (found) { string number = m.group(1); system.out.println(number); }

iphone - How to display 2^3 in Javascript -

i building app using appcelerator needs display mathematical expression e.g 2^3 3 being small number above 2. there way express mathematical expressions in javascript? notes the text static bit of text. language in use javascript. runs on iphone/android simulator in appcelerator framework. appcelerator escapes html thanks in advance assistance. "2"+"3".sup() should give correct formatting. you can use .sub() subscript.

coding style - Is using “NOT EXISTS” considered to be bad SQL practise? -

i have heard lot of people on years that: "join" operators preferred on “not exists” why? in mysql , oracle , sql server , postgresql , not exists of same efficiency or more efficient left join / null . while may seem "the inner query should executed each record outer query" (which seems bad not exists , worse not in , since latter query not correlated), may optimized other queries optimized, using appropriate anti-join methods. in sql server , actually, left join / null may less efficient not exists / not in in case of unindexed or low cardinality column in inner table. it heard mysql "especially bad in treating subqueries". this roots fact mysql not capable of join methods other nested loops, severely limits optimization abilities. the case when query benefit rewriting subquery join this: select * big_table big_table_column in ( select small_table_column small_table ) sm

asp.net mvc - mvc music store -

i'm trying mvc musicstore tutorial, , after part 6 when using edit i'm getting error: store update, insert, or delete statement affected unexpected number of rows (0). entities may have been modified or deleted since entities loaded. refresh objectstatemanager entries. description: unhandled exception occurred during execution of current web request. please review stack trace more information error , originated in code. exception details: system.data.optimisticconcurrencyexception: store update, insert, or delete statement affected unexpected number of rows (0). entities may have been modified or deleted since entities loaded. refresh objectstatemanager entries. any idea why reason? [httppost] public actionresult edit(album album) { if (modelstate.isvalid) { db.entry(album).state = entitystate.modified; db.savechanges(); return redirecttoaction("index"); } viewbag.genreid = new selectlist(db.genres,

c - expected ‘uint32_t’ but argument is of type ‘uint32_t *’ -

i new in c, trying call function, gives me error can not understand why int set_price(&colour->type.name); it returns me expected ‘uint32_t’ argument of type ‘uint32_t *’. warning: passing argument ‘int set_price’ makes integer pointer without cast where pointer house_list *colour = null; and name defined in struct as uint32_t name; the original function accept int set_price(uint32_t name) { / do here / } what do wrong? if in struct member, name defined uint32_t, , defined pointer colour, believe need use & before colour->type , use dot before name isn't it? thank you set_price(&colour->type.name); remove & , you'll fine set_price(colour->type.name); set_price expects integer argument, not pointer integer. i suggest should read a c book .

java - Test a method if it would throw an exception or not without invoking it -

how can test whether given method throw exception or not (depending on passed object) without invoking it? for example: public static boolean isallowed(someobject obj) { try { mymethod(obj); return true; } catch(exception ex) { return false; } } but above method perform mymethod() , how can achieve in java? edit: actually, want validate filename. see this: validate file name on windows as others have said, in general impossible tell whether exception thrown based on input without computing it. java turing complete, reducible halting problem . however, can find exceptions method can throw @ runtime: try { method mymethod = this.getclass().getmethod("mymethod"); system.out.println(arrays.tostring(mymethod.getexceptiontypes()); } catch (nosuchmethodexception e) {}

Aptana Ruby on Rails Problem, rails: command not found -

i installed aptana studio 3 , attempted create first rails file, receive error sh.exe: rails: command not found am supposed edit system variables include path? if so, heck rails.exe because cannot find directory. based on "sh.exe" filename, assuming running windows. need verify command "rails" accessible in system path aptana can find it. modifying "path" system variable include directory ruby installation (this may require restart take affect). instructions modifying system path can found here: http://www.computerhope.com/issues/ch000549.htm if used installer of ruby packaged windows such railsinstaller, point path of installation. gems place executable files in "\bin" folder. "rails" executable script rails gem.

.net - How can I restrict remote access to Elmah? -

with elmah installed on our dev web server .. can restrict remotely accesses it? f hardcode username/passwords (hashed?) or via ip? there 2 settings, 1 in <elmah> : <elmah> <security allowremoteaccess="1"/> </elmah> the other is, if allow remote access, can use <location> control accesses it: <location path="elmah.axd"> <system.web> <authorization> <allow roles="administrator"/> <deny users="*"/> </authorization> </system.web> </location> you can put in main web.config after </runtime> tag

migration - How to create a model in rails 3 with 2 columns that has a string length = 8 and decimal(2,2)? -

how can create database table column has string length = 8 , decimal(2,2) using rails 3 migration? you're right, isn't in guide have check docs. see column method: http://api.rubyonrails.org/classes/activerecord/connectionadapters/tabledefinition.html add_table :foo |t| t.string :foobar, :length => 8 t.decimal :foobat, :precision => 4, :scale => 2 end

if statement - Go Back to Start If no input is entered (Bat File) (#2) -

this follow-up question: go start if no input entered (bat file) final touch , file perfect :) here's relevant code part: :: delete variable %f% set "f=" set /p f=folder or file trget: attrib +s +h +r %f% if set non input, file makes relevant files in same folder , same extension (as in attrib +s +h +r *.bat ) ,(in case, bat) in system files i apologize bad wording the complete procedure of script (it's not script onlly on part of it) :hide @echo off cls color 0c echo. echo. :: delete variable %f% set "f=" set /p f=folder or file trget: attrib +s +h +r %f% @echo off cls echo. echo. echo ###################################################### echo # # echo # 1 - set other system attribute folder or file # echo # 2 - remove system attribute folder or file # echo # 3 - exit # echo # # echo

UNION JOIN and MS-ACCESS -

really confusing is, works under jet, not working under access.... how inner join union select field1, field2 (select field1, field2, field3 table1 join table3 on table1.id=table3.id union select field1, field2, field3 table2 join table4 on table2.id=table4.id) field3=1 the result: 3131 --"syntax error in clause" i reduced into: select field1 (select field1, field3 table1 union select field1, field3 table2) field3=1 but still not working even this: select * (select field1 table1 union select field1 table2) doesn't work select field1 table1 union select field1 table2 - works.... you need add field3 in query select t.field1, t.field2 ( select field1, field2, field3 table1 union select field1, field2, field3 table2 ) t t.field3=1 based on edit new query need following: select x.field1, x.field2 ( select t1.field1, t1.field2, t1.field3 table1 t1 inner join table3 t3 on t1.id=t3.id union

algorithm - What is the most efficient way to get all combinations? -

possible duplicate: finding possible combinations of numbers reach given sum problem you have list of people input, each person has number of credits. given total has achieved using 1 or more persons credits. function should output combinations exist result in total. for example see below:- static void main(string[] args) { int total = convert.toint32(args[0]); var persons = new list<person>(); persons.add(new person { credits = 10, name="steve"}); persons.add(new person { credits = 5, name = "paul" }); persons.add(new person { credits = 4, name = "david" }); persons.add(new person { credits = 1, name = "kenneth" }); printallcombinations(persons, total); // function in question } public class person { public string name { get; set; } public int credits { get; set; } } in above example, given total of 10, printallcombinations function should output similar to:- combination 1) s

c++ constructor question -

i still confused ctors: question 1: why line 15 call a:a(int) instead of a:a(double&) ? question 2: why line 18 did not call a:a(b&) ? #include <iostream> using namespace std; class b{}; class a{ public: a(int ) {cout<<"a::a(int)"<<endl;} a(double&){cout<<"a::a(double&)"<<endl;} // work if a(double), without & a(b&){cout<<"a::a(b&)"<<endl;} }; int main() { /*line 15*/ obj((double)2.1); // call a(int), why? b obj2; obj3(obj2); /*line 18*/ obj4(b); // did not trigger output why? } line 15: a(double&) can take lvalues, i.e. variables can assigned to. (double)2.1 rvalue. use a(const double&) if need accept rvalues reference too. line 18: b type, not value. a obj4(b); declares function name obj4 taking b , returning a .

c# - Pattern for reverse-accessible logic changes? -

i'm trying find design pattern or best practice, or other solution problem keeping versions of business logic within application. specifically, looking find way determine logic used issue insurance policy. i have code looks this: public double fixeddeductiblesurchageamount() { double percent = fixeddeductiblesurchargepercent(); double base_premium = collisionpremium() + theftpremium(); return (base_premium * percent); } i needing make change business logic function looks more like: public double fixeddeductiblesurchageamount() { double percent = fixeddeductiblesurchargepercent(); double base_premium = collisionpremium() + theftpremium() + medicalpremium(); return (base_premium * percent); } where run trouble existing policies should rate previous logic. there design pattern this? if not, there ways implement it? strategy pattern sounds applicable. you'd need factory method or such takes in date return appropriate strategy.

java question to decide who called this method -

i have following scenario both testone() , testtwo calls same callme() method. how decide inside callme() method called callme(). public void testone(){ callme(); } public void testtwo(){ callme(); } public void callme(){ system.out.println("i called following method."+methodname); } sort of appreciated. any solution has generating stacktrace , looking @ second frame 1 going lead pain - doing bypassing idea of passing function needs in order function it's work. if need name of caller method, just pass parameter . if need other piece of data decide in callme() method, pass (as boolean , int , etc.). it confuse other developers working on code why callme() has secret parameters. public void testone(){ callme("testone"); } public void testtwo(){ callme("testtwo"); } public void callme(string methodname){ system.out.println("i called following method."+methodname); }

dst - Determine if daylight saving time is active? SQL Server -

i have table users, utc time offset, , if observe daylight saving time. there built in way correct user time? right i'm doing this: select case usedaylightsaving when 1 case datediff(hh,getutcdate(),getdate()) -- know server set mountan time , follows daylight saving time -- mdt = -6 -- mst = -7 when -6 dateadd(hh,timezoneoffset+1,getutcdate()) else dateadd(hh,timezoneoffset,getutcdate()) end else dateadd(hh,timezoneoffset,getutcdate()) end users it works if server get's moved timezone or doesn't fallow daylight saving time i'm hosed.

visual studio 2010 - Intellisense - Hide inherited members? -

my coworkers , discussing annoyance have in visual studio. if you're working class that's inherited large class, controller , you're going have huge list of inherited members in intellisense. sometimes, want see own members defined yourself, instead of having find things amongst huge list of other things. i suppose if you're looking defined, should know it's called. know i've run frustration when classes bit more complicated. there built in way have intellisense hide inherited things, or maybe there plugin somewhere provides this? otherwise guess 1 of has write it. visual assist x has such feature. allows push inherited members end of list , more: access non-inherited entries having them listed first. scroll see entries base classes. enable feature in options dialog. use in combination bolding of non-inherited members , shrinking optimal efficiency. this feature can enabled or disabled dynamically filtering toolbar.

java - Hard time choosing ... IO vs NIO -

i ask more appropriate choose when developing server similar smartfoxserver. intend develop similar yet different server. in benchmarks made ones developed above server had 10000 concurrent clients. made bit of research regarding cost of using many threads(>500) cannot decide way go. once made server in java small application , had nothing heavy loads. thanks take @ apache mina . they've done alot of heavy lifting required use nio in networking application. whether or not nio increases ability process concurrent connections depends on implementation, performance boosts in tomcat, jboss , jetty plenty evidence in positive.

java - Hibernate - Use native query and alias to Bean with enum properties? -

i having trouble using native query in hibernate alias bean contains enum properties. getting invocationtargetexception when query.list() called. example below: @entity(name = "table1") public class class1 { @column(name = "col1") @notnull private integer prop1; @column(name = "col2") @notnull private string prop2; @column(name = "col3", length = 6) @enumerated(value = enumtype.string) private myenumtype prop3; // ... getters/setters... } public list getclass1list(){ string sql = "select col1 prop1, col2 prop2, col3 prop3 table1"; session session = getsession(boolean.false); sqlquery query = session.createsqlquery(sql); query.addscalar("col1", hibernate.integer); query.addscalar("col2", hibernate.string); query.addscalar("col3", hibernate.string); query.setresulttransformer(transformers.aliastobean(class1.class)); return

actionscript 3 - flash allow button cannot be pressed -

Image
i noticed before. in browsers flash camera dialog won't able press allow button access camera, microphone. issue exposed on here can't click allow button in flash on firefox , adobe tracking issue bug http://bugs.adobe.com/jira/browse/fp-4656 . the purposed solution works not always. other workaround wound on web set margin-left , margin-right css in flash container this: margin-left: 0.5px; margin-right: auto; well os x lion came out , damn thing doesn't work in browser! tried facebook profile photo taker uses flash taking photos. there cant press allow button. same youtube video recorder etc... what do? the solution works today adjust "flash player general settings" specific domain

c++ - how to see the value of CXX and CXXFLAG -

before compiling c++ program, export ed cxx , cxxflags command line. $ export cxx="/media/space/gcc-dist/bin/g++" $ export cxxflags="-std=c++0x" but want see values of cxx , cxxflags . how do that. i'm using kubuntu 11.04 you can on linux systems opening terminal , entering echo $cxx echo $cxxflags

didselectrowatindexpath - UITableViewController indexPathForSelectedRow returns incorrect value -

i'm not sure going on have list has 3 items , selecting row 1. i using viewcontroller uitableviewcontroller , has property tableview accessing indexpathforselectedrow during didselectrowatindexpath. for reason value incorrect sometimes... what cause this? the uitableview * param on didselectrowatindexpath called tableview. if table has more 1 section can confuse things (it's caught me before). indexpath.row return row number in section of table, not row number of overall table. if that's not you're expecting it'll appear wrong.

Android 3.0 Couldn't read row#, column# from cursor window -

i have application runs fine on android 2.1, when trying transition 3.0 cursor error i'm not familar with. java.lang.illegalstateexception: couldn't read row0, column -1 cursor window. make sure cursor initialized correctly before accessing data it. all data storred in sqlite database , code works fine in android 2.1. cursor have initialized differently in android 3.0? listed below code. private void opengroupdata(){ sqlitedatabase db = openorcreatedatabase(database_name,context.mode_private,null); cursor cur = db.rawquery("select groupid properties group groupid" + ";" , null); linearlayout glayout = (linearlayout) findviewbyid(r.id.grouplayout); linearlayout gwindow = (linearlayout) findviewbyid(r.id.groupwindow); textview data = new textview(this); glayout.addview(data); data.settext(""); int id = cur.getcolumnindex("groupid"); int idvalue; setrequestedorientation(activityinfo.screen_orientation_user); try{

regex - Regular Expression in Java for validating username -

i'm trying username chains in java following rules: length >=3 valid characters: a-z, a-z, 0-9, points, dashes , underscores. could me regular expression? try regular expression: ^[a-za-z0-9._-]{3,}$

jquery width() with newly generated element -

when use following : div = '<div class="tag-tooltip" id="tooltip_view_1">first item</div>'; $('#products').append(div); var tooltip_width = $('#tooltip_view_1').width(); var tooltip_height = $('#tooltip_view_1').height(); the tooltip_height gives correct value, while tooltip_width returns 0. idea why happening , should width of newly created element? just i've solved problem - appears css property : text-indent affecting visibility of element. had set negative value , once removed property altogether - started working fine.

css - Offset div from center -

i'm trying position div x amount of pixels right of center of page. div therefore relative center. so far, i've tried stupid like margin:0 auto; margin-left:20px; but don't need test in browser know wouldn't work. thanks in advance help. i'd try using 2 divs, 1 inside another. this: <div class="outer"> <div class="inner">hello, world!</div> </div> .outer { width: 1px; /* or zero, or small */ margin: auto; overflow: visible; background: red; /* color debug */ } .inner { margin-left: 20px; background: yellow; /* color debug */ width: 100px; /* depending on desired effect, width might needed */ } see this example live @ jsfiddle . the outer div horizontally centered per question/answer: how horizontally center <div> in <div>? then, inner diff moved 20 pixels right, using margin. note that, if leave width auto , width zero, , might not want.

cakephp - Applying a CSS whitelist to HTML in PHP -

lets have following $string... <span style='text-decoration:underline; display:none;'>some text</span> i want allow style text-decoration , want php function following... $string = stripstyles($string, array("text-decoration")); similar strip_tags , using array instead. $string be... <span style='text-decoration:underline;'>some text</span> i using cake, if can done sanitize better. this tricky, should able domdocument . should started, it's require serious tweaking. // load html string $dom = new domdocument(); $dom->loadhtml($your_html_string); // <span> tags $spans = $dom->getelementsbytagname("span"); // loop on span tags foreach($spans $span) { // if have style attribute contains "text-decoration:" // attempt replace contents of style attribute text-decoration component. if ($style = $span->getattribute("style")) { if (preg_match('/text-d

php - Caching Web applications -

which php cache should use? how implement cache? and for? i thinking of using chat application wrote in php. use or dynamic? user memcached it's reliable , easy use. cache article on wikipedia

java swing redrawing buttons -

i pasting following code here. puzzled at: why there no jbuttons added jpanel, though event correctly listened , responded. thank help. import java.awt.component; import java.awt.toolkit; import java.awt.event.keyadapter; import java.awt.event.keyevent; import javax.swing.boxlayout; import javax.swing.grouplayout; import javax.swing.jbutton; import javax.swing.jframe; import javax.swing.jpanel; import javax.swing.jtextfield; public class panelcontrolbuttons extends jframe { private jpanel jpanel1 = new jpanel(); private jpanel jpanel2 = new jpanel(); private jpanel jpanel = new jpanel(); private jtextfield jtf = new jtextfield(20); public panelcontrolbuttons() { setsize(400, 300); getcontentpane().add(jpanel); jpanel.setlayout(new boxlayout(jpanel, boxlayout.x_axis)); jpanel2.setlayout(new boxlayout(jpanel2, boxlayout.x_axis)); jpanel.add(jpanel1); jpanel.add(jpanel2); jpanel2.add(new jbutton(&quo