Posts

Showing posts from September, 2012

regex - Regexp: is it possible to search for string 'string' but not 'string({' -

i trying find out occurences of concrete word (method call deprecated api) in files in directory. need regexp find such occurences not contain updated call (new api). can me please? example: deprecated api: method(a,b,c) new api: method({a:a, b:b, c:c}) the regexp should find files containing 'method' not 'method({'. thank you. i'd proper way use negative look-ahead operator, ?! /method(?!\(\{)/ the above states, "any occurence of method not followed ({ " it meets requirements better suggested /method([^{]/ latter not match string end (i.e. abc abc method ) , doesn't handle combination of 2 characters ({ requested well.

floating point - Is if(double) valid C++? -

i ran line of code: if( linedirection.length2() ){...} where length2 returns double . kind of puzzles me 0.0 equivalent 0, null , and/or false . is part of c++ standard or undefined behaviour? it standard behavior (boolean conversion) $4.12/1 - "an rvalue of arithmetic, enumeration, pointer, or pointer member type can converted rvalue of type bool. 0 value, null pointer value, or null member pointer value converted false; other value converted true."

How to implement custom client-side wcf caching -

i need implement custom caching of client proxy of wcf service. i've implemented ioperationbehavior interface. on server-side can set operationdescription.invoke property in applydispatchbehavior method , implement ioperationinvoker interface control operation execution. on client-side can't it. in client-side can use iclientmessageinspector, iparameterinspector, iclientmessageformatter interfaces control message flow. main problem have store in cache service answer without information message format. when restore values cache should create message again in case of service response. cannot break following internal message processing. on moment lose necessary information message such encoding, content-type(json, xml) in case of restful services. final result - wcf cannot process such message. want disable message processing if cached value exists. how can it? i choose absolutely different approach. instead of injecting functionality wcf pipeline define interface w...

.net - GridView HeaderText is empty in some cases -

it returns empty string! <asp:templatefield headertext='<%= "2323" %>'> how solve it? want invoke page method. using headertemplate solved problem, doesn't explain why. :/

iphone - NSRunLoops in Cocoa? -

let's have 2 threads, 1 main thread , one, secondary thread. main thread being used most, (rarely) want secondary thread work based on calls main thread. of time secondary thread should sleep. after searching understand way use runloops. tried read apple's docs ( http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/multithreading/runloopmanagement/runloopmanagement.html#//apple_ref/doc/uid/10000057i-ch16-sw5 ) but looks me complex , i'm having hard time there. there elegant , simple way achieve described? similar runloop code examples out there can run , play with? thanks matt gallagher has nice blog article comparing secondary thread approach other ways of getting background work done. http://cocoawithlove.com/2010/09/overhead-of-spawning-threads.html in case, don't have concerned thread-creation overhead. matt's code examples might provide insight managing secondary thread's runloop. all said, go joshua's advice , u...

javascript - Avoiding repetition when using callback functions and asynchronous requests -

i writing javascript/jquery code requires me make lots of requests various apis. have come across problem many times , basic example of 1 instance of it. the code makes asynchronous request server , if condition returned data not met, code makes request. second request has callback contains of same logic parent. know avoiding repetition calling returnfunction in each callback there way avoid altogether? var container = []; $.getjson("http://www.url.com/api/?callback=?", { data: "mydata" }, function(data) { if(!data.length) { // no results } else { // put results array $(data).each(function(k, v){ container.push(v.some_data); }); // if query did not return enough results if(data.length < limit) { var number_missing = limit - data.length; // more results , append array myfunctiontogetsomethingelse(number_missing, function(response){ ...

c - CPU-Core thread classification Function -

i'm going writing multi-threaded shared memory messaging system ultra high-volume message delivery between processes. messages originate worker threads of web-server. i'd exploit cpu cache locality cores on same cpu share. when wake worker thread on receiving end of ipc system, wake thread on same cpu. i need linux (prefferably posix in genaral) , windows api calls , bitmasking need extract information let me classify executing thread-id -- context of said thread -- using following struct: struct thread_core_id { uint16_t cpu_id; uint16_t core_id; }; functions both platforms appreciated. i'm hoping can done without system calls -- i.e., context-switches. -- edit -- i'm focusing on x86 @ moment, other architectures useful well. for linux should able required information out of /proc/cpuinfo , /sys/devices/system/cpu/cpu*/cache , use sched_{s|g}etaffinity() calls. take @ what every programmer should know memory , if haven't already, a...

Not parsing layout xml in Magento -

i following book "php architects guide programming magento" try incorporate rewards feature in magento. my problem rewardpoints.xml file not being parsed. triggers magento parse xml files(updates) layout folder? why not parsing rewardpoints.xml file? know not parsing because left error in xml file , not showing up here rewardpoints.xml error(closing tag rewardpoints/dashboard_points.phtml any explanation help. thank margots a few quick guesses. if doesn't work, let me know , can try other things. first, make sure tell magento layout exists. in module config, make sure following xml exists. may need change <frontend> <adminhtml> if developing backend. make sure layout file in corresponding layout directory (adminhtml or frontend). <config> <frontend> <layout> <updates> <rewardpo...

python - How to use importlib for rewriting bytecode? -

i'm looking way use importlib in python 2.x rewrite bytecode of imported modules on-the-fly. in other words, need hook own function between compilation , execution step during import. besides want import function work built-in one. i've did imputil , library doesn't cover cases , deprecated anyway. having had through importlib source code, believe subclass pyloader in _bootstrap module , override get_code : class pyloader: ... def get_code(self, fullname): """get code object source.""" source_path = self.source_path(fullname) if source_path none: message = "a source path must exist load {0}".format(fullname) raise importerror(message) source = self.get_data(source_path) # convert universal newlines. line_endings = b'\n' index, c in enumerate(source): if c == ord(b'\n'): break elif c == ord(b'\r'): ...

.net - jquery selecting/unselecting checkboxes in children/parent <li> -

i have following <ul> <li>main <ul> <li><input type="checkbox" onclick="$.selectchildren(this);" /> parent 1 <ul> <li><input type="checkbox" onclick="$.selectchildren(this);" />sub 1</li> <li><input type="checkbox" onclick="$.selectchildren(this);" />sub 2 <ul> <li><input type="checkbox" onclick="$.selectchildren(this);" />sub sub 2</li> <li><input type="checkbox" onclick="$.selectchildren(this);" />sub sub 3</li> </ul> </li> </ul> </li> <li><input type="checkbox" onclick="$.selectchildren(this);" />parent 2</li> </ul> </li...

java - access URL parameters without cookies -

my application should work without cookies. how can parameters of url java file if cookies disabled. req.getparameter("abc") gives null when tried. i've 3 spring genericfilterbeans in application , can see values inside filters. how can make parameters available others controllers , other files.. the presence , accessibility of request parameters unrelated cookie support. the cause of problem lies somewhere else. programmatic redirect involved caused parameters lost. or request modified/wrapped/replaced in improper manner. verify filters.

c# - ebXML Message Service Handler for .NET...? -

currently looking @ implementing ebxml msh using .net. has done before, and/or know of open source .net examples out there? any comments/advice welcome ;-) my company going use covast ebxml adapter biztalk. whilst not 100% .net based solution 1 of few microsoft focused products deals ebxml. think memory license $3000 aud. in end decided go apache camel esb uses hermes ebxml messaging layer.

What is the proper way to check if a string is empty in Perl? -

i've been using code check if string empty: if ($str == "") { // ... } and same not equals operator... if ($str != "") { // ... } this seems work (i think), i'm not sure it's correct way, or if there unforeseen drawbacks. doesn't feel right it. for string comparisons in perl, use eq or ne : if ($str eq "") { // ... } the == , != operators numeric comparison operators. attempt convert both operands integers before comparing them. see perlop man page more information.

perl - How to extend a binary search iterator to consume multiple targets -

i have function, binary_range_search , called so: my $brs_iterator = binary_range_search( target => $range, # eg. [1, 200] search => $ranges # eg. [ {start => 1, end => 1000}, ); # {start => 500, end => 1500} ] brs_iterator->() iterate on @$ranges on $range overlaps. i extend binary_range_search able call multiple ranges target, eg: target => $target_ranges # eg. [ [1, 200], [50, 300], ... ] search => $search_ranges # above so, when search on $range->[0] exhausted, should move on $range->[1], , on. here function in question, in original form: sub binary_range_search { %options = @_; $range = $options{target} || return; $ranges = $options{search} || return; ( $low, $high ) = ( 0, @{$ranges} - 1 ); while ( $low <= $high ) { $try = int( ( $low + $high ) / 2 ); $low = $try + 1, next if $ranges->[$tr...

c# - How to use entity framework in business layer and/or data layer? -

i use entity framework in asp.net application. i can use linq entities in layer, know should put entity framework? (dal, bal or direct use in presentation). entityframework should go in data access layer. expose presentation layer tightly couples presentation database, allowing changes @ database level flow presentation layer. what have done on of our projects use entity framework @ dal, transform entities our business objects (which quite simple object used dto's of our logic contained in services act on objects - route isn't everyone, fitted architecht wanted).

html DOM generation and html regeneration out of DOM -

i want html content of html file , modify areas (actually want translate text in html page )and rebuild new html file out of modified dom tree.can please show me way how can ?i have found html dom parsers,but dont regenerate modified html file me .they give me dom , can modify text nodes things want can not have new html file. thank notice. mehrnaz take @ jquery's $.html function. may able along lines of: var newbody = '<div>translated text</div><div>more translated text</div>'; $('body').html(newbody); this function replaces inside <body> tag new contents.

how to reference a coldfusion object via ajax -

i'm working page in coldfusion , have instantiated object on page. let's call object myobject. i'm able access methods of object (such myobject.getname()) on page , pages included part of page flow. but load page in via ajax, , want able reference same object, seems cannot that. further, on ajax-loaded page want remote-call methods part of object. can remote-call methods themselves, again, if these methods invoke other object methods using, instance, this.getname() things don't work. is there way reference previously-created object in ajax-loaded page works seamlessly? (i thought doing encapsulating object in session variable, , work, i'd prefer find solution can work in multi-server environment.) i'm using railo, believe in turn supports cf8 functionality. i'm not using oo frameworks , can't project. you can't reference object instantiated on page ajax. component you've instantiated serverside. ajax client side. cfajaxpro...

Connecting to remote hosts in an HTML/Javascript web app -

i've been thinking of developing web application using html , javascript little while now, i've hit wall during ponderings. want able connect (long-term, not briefly) remote host app, 1 unfortunately not server page requested from. from i've read, javascript can't support long-term connections, , furthermore won't request anywhere that's not domain page downloaded from. considered hidden java or flash objects, flash seems cost money, , java requires signed applet (and don't know whether it's worth getting signed). the solution think work using server proxy others (through unsigned java applet?), don't want if can it. realistic option, or there other solutions haven't considered yet? (i considered asking on 1 of other so-alike sites, stackoverflow seemed apt, since largely programming , design issue.) after considering own plans application, i've decided go forward server-as-proxy approach. having client handle connections s...

java - j8583 cannot handle field 128 -

i've been using j8583 parse , construct iso 8583 message in java. seems until 1 of message has field 128 in it. field missing when construct or parse message has bit 128, other bit (2...127) fine. i've double check xml configuration, , nothing wrong there. is me or there bug in j8583? know how solve this? i'm on tight schedule, changing library iso 8583 unlikely i'm author of j8583. reviewed code , there indeed problem messagefactory.newmessage() won't assign field 128 new messages. committed change, can latest source repository , new messages include field 128. i reviewed parsing code , couldn't find wrong there. if parse message field 128 , it's in parsing guide, message should contain it. however, i've encountered iso8583 implementations in message has 128 field set in bitmap it's not in message. in these cases j8583 can't parse message because there's missing data. i'm still trying figure out how handle this. w...

.net - When hosting a WCF REST service in a console app, error finding contract name -

i have wcf rest service works windows service (.net 3.5). make easier build , debug, run console. when this, setting endpoints in console app. when create endpoint, fails error: "the contract name 'irestservice' not found in list of contracts implemented service 'system.runtimetype'." my interface have [servicecontract] attached it: namespace restservicelibrary { [servicecontract] public interface irestservice ... here console app: namespace restserviceconsole { class program { static void main(string[] args) { webservicehost2 webhost = new webservicehost2(typeof(restservice), new uri("http://localhost:8082")); serviceendpoint ep = webhost.addserviceendpoint(typeof(irestservice), new webhttpbinding(), ""); servicedebugbehavior stp = webhost.description.behaviors.find<servicedebugbehavior>(); stp.httphelppageenabled = false; ...

How can I build a string resource from other string resources in WPF? -

here's 'sample code', including i'm trying do. obviously, doesn't work @ moment, there way can make work? <resourcedictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:system="clr-namespace:system;assembly=mscorlib" > <system:string x:key="productname">foo</system:string> <system:string x:key="windowtitle">{productname} + main window</system:string> </resourcedictionary> the way add computed string resourcedictionary in way create markupextension . markupextension used this: <resourcedictionary ...> <sys:string x:key="productname">foo</sys:string> <local:mystringformatter x:key="windowtitle" stringformat="{0} main window" arg1="{staticresource productname}" /> </resourcedictiona...

algorithm - How to determine if a point is in a 2D triangle? -

is there easy way determine if point inside triangle? it's 2d, not 3d. in general, simplest (and quite optimal) algorithm checking on side of half-plane created edges point is. here's high quality info in topic on gamedev , including performance issues. and here's code started: float sign (fpoint p1, fpoint p2, fpoint p3) { return (p1.x - p3.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p3.y); } bool pointintriangle (fpoint pt, fpoint v1, fpoint v2, fpoint v3) { bool b1, b2, b3; b1 = sign(pt, v1, v2) < 0.0f; b2 = sign(pt, v2, v3) < 0.0f; b3 = sign(pt, v3, v1) < 0.0f; return ((b1 == b2) && (b2 == b3)); }

sql server 2005 - SQL Select a row and store in a SQL variable -

so, i'm writing stored proc , suck @ sql. my question guys is: can select entire row , store in variable? i know can like: declare @someinteger int select @someinteger = (select someintfield sometable somecondition) but can select entire row sometable , store in variable? you can select fields multiple variables: declare @a int, @b int select @a = col1, @b = col2 sometable ... another, potentially better, approach use table variable: declare @t table ( int, b int ) insert @t ( a, b ) select col1, col2 sometable ... you can select table variable regular table.

combinations - Python get all permutations of numbers -

i'm trying display possible permutations of list of numbers, example if have 334 want get: 3 3 4 3 4 3 4 3 3 i need able set of digits 12 digits long. i'm sure simple using itertools.combinations can't quite syntax right. tia sam >>> lst = [3, 3, 4] >>> import itertools >>> set(itertools.permutations(lst)) {(3, 4, 3), (3, 3, 4), (4, 3, 3)}

sql server - Including initial value in a select Statement -

i have select query returns following o/p.. 1 arun, 2 kumar, 3 babu, 4 ram, is possible add intial value o/p without inserting value table, in other means hardcoding intial value. can o/p as 0 select, 1 arun, 2 kumar, 3 babu, 4 ram try this: select 0, 'select' union <your query>

math - map points between two triangles in 3D space -

Image
edit i don't know important, destination triangle angles may different these of source. fact makes transformation non-affine ? (i'm not sure) i have 2 triangles in 3d space. given know (x,y,z) of point in first triangle , know vectors v1,v2,v3. need find point (x',y',z'). transformation should point (x,y,z) vectors v1,v2,v3 transformed point in second triangle ? thanks !!! you want matrix transformation t such t x = x', x matrix columns co-ordinates of vertexes of first triangle , x' same second triangle. multiplying each side inverse of x yields t = x' x -1 .

Subclassing Python dictionary to override __setitem__ -

i building class subclasses dict , , overrides __setitem__ . method called in instances dictionary items possibly set. i have discovered 3 situations python (in case, 2.6.4) not call overridden __setitem__ method when setting values, , instead calls pydict_setitem directly in constructor in setdefault method in update method as simple test: class mydict(dict): def __setitem__(self, key, value): print "here" super(mydict, self).__setitem__(key, str(value).upper()) >>> = mydict(abc=123) >>> a['def'] = 234 here >>> a.update({'ghi': 345}) >>> a.setdefault('jkl', 456) 456 >>> print {'jkl': 456, 'abc': 123, 'ghi': 345, 'def': '234'} you can see overridden method called when setting items explicitly. python call __setitem__ method, have had reimplement 3 methods, this: class myupdatedict(dict): def __init__(self, *args, **kwar...

ms access - MSAccess - populate text box with value from query -

i have combo box , several text boxes on form. when select value combo box want run query based on value , populate text boxes data returned query. query should return 1 record , textboxes correnspond different columns in record. i have code: private sub cbo_equip_loc_change() dim location string me.cbo_equip_loc.setfocus location = dlookup("name", "query1", "position = '" & me.cbo_equip_loc.seltext & "'") me.text51.setfocus me.text51.text = location end sub but error: "this property read-only , can't set" any ideas? solved: im idiot. i had value in control source trying before. removed , worked! textbox text51 locked, set property locked false.

maven 2 - Unable to use Apache Archiva as Mirror -

i think supposed simple task, i've been unable accomplish it. i've set archiva repository this: 2 internal maven1 repos (old projects) 1 internal maven2 repo 7 remote repos (central, java.net, jboss.org, etc.) for each internal repo i've created proxy connection each remote repo. i've added new mirror settings.xml file explained in archiva documentation: <mirror> <id>archiva.default</id> <url>http://repo.mycompany.com:8080/archiva/repository/internal/</url> <mirrorof>*</mirrorof> </mirror> when try building simple project 1 dependency of remote repositories, no artifacts downloaded. why?!? thanks help. archiva doesn't assign repositories special roles. make requests specific managed repository maven (so settings, internal ), , serve in there, or proxy remote repositories have been connected proxy connector. default, central - adding new remote repository has no effect until connecte...

Rename master branch for both local and remote Git repositories -

i have branch master tracks remote branch origin/master . i want rename them master-old both locally , on remote. possible? other users tracked origin/master (and updated local master branch via git pull ), happen after renamed remote branch? git pull still work or throw error couldn't find origin/master anymore? then, further on, want create new master branch (both locally , remote). again, after did this, happen if other users git pull ? i guess result in lot of trouble. there clean way want? or should leave master , create new branch master-new , work there further on? the closest thing renaming deleting , re-creating on remote. example: git branch -m master master-old git push remote :master # delete master git push remote master-old # create master-old on remote git checkout -b master some-ref # create new local master git push remote master # create master on remote however has lot of caveats. first, no existing checkouts...

filter - Twitter URL for returning /user_timeline Searches -

i may overlooking can't seem filter user_timeline results keyword in rest api. example: http://twitter.com/status/user_timeline/starbucks.json?q=pumpkin returns results, not ones filtered word 'pumpkin'. i figured out method if else needs it, http://search.twitter.com/search.json?q=+pumpkin+from:starbucks remember url encode special chars after (?) , top string didn't need it.

INSERT INTO MySQL and PHP -

i have mysql table ( members ) 6 columns ( firstname, lastname, email, username, password, key) i need insert string key column username admin how go doing this? suppose string want insert literal string 'mystring' . update table this: update `members` set `key` = 'mystring' `username` = 'admin' some things note: i've enclosed column names, such key , in identifier quotes (backticks). because know mysql may treat word 'key' sql reserved word, might result in failing parse update query. this assumes column key has string datatype, such text or char(20) . if doesn't (for example if it's int ), doesn't make sense try update contain string. i assume column length, if it's char or varchar , long enough contain string (i.e. it's of length @ least 8). if column short contain string i'm trying put in it, mysql either truncate string or issue error message, depending on sql mode. alternatively, if th...

google maps - Open info window if user hovers longer than x milliseconds -

what i'm trying simple: open marker's info window if user has hovered on marker longer x millisecond. i can't find how anywhere. appreciate little code snippet show me how set up! the jquery hoverintent plugin might able you http://cherne.net/brian/resources/jquery.hoverintent.html hoverintent plug-in attempts determine user's intent... crystal ball, mouse movement! works (and derived from) jquery's built-in hover. however, instead of calling onmouseover function, waits until user's mouse slows down enough before making call.

Difference between WCF sync and async call? -

i new wcf, want know difference make sync call or async call, helpful if 1 explain example thanx async call client same ohter async operation in .net framework. when make sync call thread wcf service thread hang on. means thread not able other work until service call returns response or exception. in contrast async call run in separate thread (created framework) main thread able continue in operation , notified completion of async call callback (event). so suppose have winforms application wcf client , want call wcf service. if make sync call take several seconds complete application hangs on processing time = user not able application (only kill task manager). if use async call interactive because async operation handled background thread. async operations suitable interactive solutions or if need multiple operations in parallel. for example check how article msdn. just completness described difference between sync , async calls = synchronous , asynchronous proce...

lisp - Scheme Code Analysis for Space vs. Time -

i'm working way through online mit lectures classic 6.001 course: structure , interpretation of computer programs. i'm trying gain understanding of analyzing code complexity in terms of memory usage vs. execution time. in first few lectures, present solution in scheme fibonacci series. the solution present in videos 1 has characteristic of growing in memory space x (linear recursion performance), presents big problem fibonacci series. try find larger fibonacci number, space required recursion becomes huge. they suggest trying find way linear iteration performance, memory space needed remains constant throughout computation , doesn't depend on x. my solution below. specific question is, performance analysis of scheme code below, in terms of memory usage vs. execution time? (define (fib x) (define (fib-helper target total current-index i-2 i-1) (if (> current-index target) (if (= target 1) 0 total) ...

Relational algebra - what is the proper way to represent a 'having' clause? -

yes, homework question names have been changed protect innocent. meaning, not asking homework question itself, rather small part of can understand whole. let's have sql query this: --the query list car prices occur more once. select car_price cars group car_price having count (car_price) > 1; the general form of in relational algebra y (gl, al) r y greek symbol, gl list of attributes group, al list of aggregations so relational algebra like: y (count(car_price)) cars so, how "having" clause written in statement? there shorthand? if not, need select relation? maybe? select (count(car_price) > 1) [y (count(car_price)) cars] i have searched internet on hours , have found no examples of converting having relational algebra. help! select count(*) (select * cars price > 1) cars; also known relational closure.

HTML / JAVASCRIPT : Disable HTML CONTENT in contentEditable=true -

what want? i want div works textarea , don't want have ability edit things in div, , paste images , on plain text. example www.facebook.com - best example facebook's news feed. why need way? if check out facebook's news feed, see area can write post, expands write post or hit lots of enters. this same reason why want use div contenteditable, because in textarea can't that. # please no jquery javascript resizable textarea using pure javascript without frameworks: <html> <head> <script> function taoninput() { var dis = this; settimeout( function(){ var span = document.createelement("div"); span.innerhtml = escape(dis.value).replace(/[%]0a/g, "<br/>")+"<br/>."; //extra br padding... textarea uses %0a, not \n span.style...

How to get random slice of python list of constant size. (smallest code) -

hi have list 100 items, want slice of 6 items should randomly selected. way in simple simple concise statement??? this came (but fetch in sequence) mylist #100 items n=100 l=6 start=random.randint(0,n-l); mylist[start:start+l] you use shuffle() method on list before slice. if order of list matters, make copy of first , slice out of copy. mylist #100 items shufflelist = mylist l=6 shuffle(shufflelist) start=random.randint(0,len(shufflelist)-l); shufflelist[start:start+l] as above, use len() instead of defining length of list. as thc4k suggested below, use random.sample() method below if want set of random numbers list (which how read question). mylist #100 items l=6 random.sample(mylist, l) that's lot tidier first try @ it!

tree - Displaying a Graph structure in JSP -

i have table in db holds child&parent relationships. trying display info in jsp graph (a single child can have multiple parents). may need use recursive calls in jsp. has come across kind of work? any examples/pointers ? thanks could hierarchy fit combination of list / map data structures? have hierarchal data i'm working on showing in jsp, 3 or levels deep. map has key-value set of lists, list has other lists, etc. here of jsp code. uses expression langauge , jstl tags keep things simpler: <section id="content" class="body"> <ol id="posts-list" class="hfeed"> <c:foreach items="${learningentries}" var="learningentry"> <li> <table class="wisientry"> <tr> <td class="picturecell"> <img class="wisientry-pic" src="${learningentry...

unit testing - How to execute sql-script file using hibernate? -

i gonna write several intergration tests test interatcion db. each test need have snapshot of db. each db snapshot saved in .sql file. want execute script file in test method, this: @test public void test_stuff(){ executescript(finame.sql); ... testing logic ... clean_database(); } does hibernate has means this? you can automatically execute sql script @ startup of hibernate: write sql commands in file called import.sql , put in root of classpath. you don't need clean database test, make test transactional rollback @ end of each test. hence, sure database not contaminated tests. instance, using spring: @transactional @transactionconfiguration public class mytest { ... } if don't use spring, try test framework default-rollback transaction support.

.net - Import Quartz DLL in C# VIsual Studio -

i'm in need quartz dll , i've downloaded source , , there quartz.dll , common.logging.dll files, don't know how use them in own applications. can tell me how this, it's 1 step that's stopping me doing all. thanks sandeep, don't mind discussing you, need know application trying use quartz library for. unfortunately, quartz library documentation isn't quite should be, , took several days me absorb product myself. the jest of using following: create schedulerfactory create scheduler create jobdetail create trigger schedule job (with detail , trigger) from there, else in details on task trying accomplish. can't give more specifics without info. hope 30 second lesson gets on way.

insert - SQL Server generate unique value -

sql server 10, .net, c# this similar this question not same. when user creates new event on event-scheduling web site, unique sort-of easy remember code generated, code can communicated (via phone, let's say) participants. generated code looks like: johmonblue5 <abbriviated name><abbriviated week day><some uniquefying suffix><index> yes, e-mail link, suppose that's not option. note: chose use uniquefying suffix color, since think it's easier remember color, number. still use number in case of collision. question : what's way implement (i have unique constraint on column already): i can generate index on app side, , use try { insert } catch { retry } . in case, how tell "duplicate column value" exception other exception? message text? use in mssql server increment trailing number until uniqueness reached. i suggest not using catch handle duplicates exclusively. catch should used true errors , beside...

locking - How to lock/unlock a field at runtime in C#? -

can lock/unlock fields or objects @ runtime against writing? in other words changing objects read-only temporarily @ runtime... for example: int x = 5; // x 5 lockobject(x); x = 7; // no change unlockobject(x); x = 10; // x 10 if not can give me possible solutions? you can use accessors this... public class x { private bool locked = false; private int lockedvar; public int lockedvar { { return lockedvar; } set { if (!locked) lockedvar = value; } } public void lockobject() { locked = true; } public void unlockobject() { locked = false; } }

git - How can I discard remote changes and mark a file as "resolved"? -

i have local files, pull remote branch , there conflicts. know keep local changes , ignore remote changes causing conflicts. there command can use in effect "mark conflicts resolved, use local"? git checkout has --ours option check out version of file had locally (as opposed --theirs , version pulled in). can pass . git checkout tell check out in tree. need mark conflicts resolved, can git add , , commit work once done: git checkout --ours . # checkout our local version of files git add -u # mark conflicted files merged git commit # commit merge note . in git checkout command. that's important, , easy miss. git checkout has 2 modes; 1 in switches branches, , 1 in checks files out of index working copy (sometimes pulling them index revision first). way distinguishes whether you've passed filename in; if haven't passed in filename, tries switching branches (though if don't pass in branch either, try checking out ...

web config - Different Default Document Type in Subfolder on IIS 6 -

i've never worked on iis server php before, question can set default document type subfolder in web.config, have in mind (its bbpress forum): <location path="forum"> <system.webserver> <defaultdocument> <files> <add value="index.php" /> </files> </defaultdocument> </system.webserver> </location> thanks , virtual beer person answers :d if you're using iis7, configuration suggest indeed change default document subfolder forum index.php . if iis 6 won't work non-administrative user. iis 6 stores these settings in metabase , can edited using: iis management console programmatically, modifying application requires administrator rights direct metabase editing the <system.webserver> xml web.config settings applicable iis 7 , above, iis 6 ignore these.

java - How to make a TextView bold? -

i want able make textview bold. how setting it's appearance (i need in code): nametext.settextappearance(getapplicationcontext(), r.style.bluetext); pricetext.settextappearance(getapplicationcontext(), r.style.bluetext); changetext.settextappearance(getapplicationcontext(), r.style.bluetext); here style.xml <!-- blue color --> <style name="bluetext"> <item name="android:textcolor">#4871a8</item> </style> how can make sure textview bolded? <!-- blue color --> <style name="bluetext"> <item name="android:textcolor">#4871a8</item> <item name="android:textstyle">bold</item> </style>

java - Trying to create REST-ful URLs with multiple dots in the "filename" part - Spring 3.0 MVC -

i'm using spring mvc (3.0) annotation-driven controllers. create rest-ful urls resources , able not require (but still optionally allow) file extension on end of url (but assume html content type if no extension). works out-of-the-box spring mvc long there no dots (period/full-stop) in filename part. however of urls require identifier dots in name. e.g. this: http://company.com/widgets/123.456.789.500 in case spring looks content type extension .500 , finds none errors. can use work-arounds adding .html end, encoding identifier or adding trailing slash. i'm not happy if these live adding .html . i've unsuccessfully looked way of overriding default file extension detection in spring. is possible customize or disable file extension detection given controller method or url pattern, etc? the @pathvariable pattern matching bit twitchy when comes dots in url (see spr-5778 ). can make less twitchy (but more picky), , better control on dot-heavy urls, set...

javascript - this in event handlers for another object -

class (mine) implements event handlers class b (3rd party). within these event handlers, access class a's properties. using this in class a's handlers not work because references class b's scope. global variables seem option. missing better alternative? another solution bind event handlers object! you first need add bind method function object. use code: function.prototype.bind = function(scope) { var func = this; return function() { return func.apply(scope, arguments); } } now can register class b event handlers class a methods way: var = new a(); var b = new b(); b.registerevent(a.eventhandlermethod.bind(a)); this way references this within code of a.eventhandlermethod point object a . if need deeper understanding of stuff can read great article: http://www.alistapart.com/articles/getoutbindingsituations/ another article: http://alternateidea.com/blog/articles/2007/7/18/javascript-scope-and-binding

.net - Mimicking Validation Behaviour without Validation -

we have several data objects in our application wind bound grids. have them implementing idataerrorinfo interface, adding error messages properties, see rowheader change style , datagridcells gain red border. , good. we have additional requirement rather merely having errors, have errors , warnings. warnings identical errors except should produce yellow border instead of red one. we created new interface, idatawarninginfo, based on idataerrorinfo. works fine. can access @ runtime, have rowvalidatiionrules that able access it, , set yellow row header instead of red one, appropriate tooltip, etc. i'm missing ability set given cell's border yellow, on basis databound property property has warning message. i retrieve warning message passing name of databound property interface; suspect under hood, validation code doing that. i'm missing how in xaml. specifically, think need apply style cell, style contains datatrigger somehow passes object name of databound...

xamarin.ios - How can Apple tell if an app was built in MonoTouch? -

monotouch compiles app native code. how can apple know app built using monotouch? monotouch leaves signature in application? does monotouch has own libraries trace of origin or compiles code , .net libraries native code? the resulting .app package contains application binary, resources required additional libraries, such as: montouch.dll; system.dll; system.xml.dll , on. as such, trivial them check if application built monotouch or not - simple right clicking package , select "show package contents" in finder. however, need not worry that, apple has relaxed license agreement: http://daringfireball.net/2010/09/app_store_guidelines

javascript - HTML5 drop event child prevented -

i using html5 d&d. have 1 "parent" drop area, e.g. "parent". in parent drop childs, e.g. "child". each dropped child become dropped area, e.g. accept d&d events. if dragging on "parent" area, highlighted, same "child" areas. face issue, "drop" event, fires "parent" area. if dragging on "child" area, "dragenter", "dragleave" work fine. "drop" event doesn't fire. instead, "parent" area fire it. i resolve issue unbing in moment "drop" event "parent" area, it's not solution. how fix in normal way? ok, found have use event.stoppropagation(); event.preventdefault(); in "drop" event. ensure it's binded not via jquery live.

linux - Using diff and suppressing entirely different files -

i have 2 copies of application source code. 1 copy encoded, while other not. there config files scattered through-out application's directory structure, , compare. is there way use diff where-by can ignore wildly different files (ie: encrypted file , unencrypted file), , report difference on similar-yet-different files (the configs). you write script uses find find files based on name or other criteria , file determine whether have same type of contents (i.e. 1 compressed, 1 not). for me more specific need give more details whether these parallel directory structures (files , directories appear in same places in 2 trees) , whether files looking have names distinguish them files want ignore. additional information can provide might more.

ASP.NET, how stop number of retry at login Page -

in asp.net website, implement account lock @ login page. not using provider that. auto-unlock account after configurable time. as know microsoft provide account lock feature provider, have different requirements 1. using oracle database 2. not store account lock info in database. because require administrator involvement. 3. there auto-unlock way of doing? please help? you use singleton pattern create object maintains information betweens requests in same way cache or session object does. with in mind you can construct in memory object can use limit repeat requests in site maintaining information of each failed request, can combine timers remove requests older specified time. allows check user hasn't exceeded failed request count, , timer auto unlock automatically removing old requests. http://www.dofactory.com/patterns/patternsingleton.aspx the singleton exist life of application process if cycles down clear requests information , therefore locks - think i...

linux - What happens to open file handles after an execv call? (C++) -

on linux, have c++ code want execv application. program outputs data stderr. therefore redirect stderr calling freopen() stderr stream parameter. thing is, want redirect stderr process run. here scenario working with. fork() current process; in child process, redirect stderr; execv() run separate application. firstly, have sentry set redirect stderr output. here code: class stderrsentry { public: stderrsentry() { freopen( "nul", "wt", stderr ); } ~stderrsentry() { fclose( stderr ); } }; then later in code: pid_t pid = fork(); int retval=-1; if( pid < 0 ) { success = false; } else if( ! pid ) { // child process stderrsentry stderrsentry; // redirecting stderr here! pid_t chid = setsid(); if (chid == -1 ) { exit(-1); } else { // here execv() call: if( execv(command[0].c_str(), const_cast<char**>(&c_args[0])) < 0 ) { exit( -1 ); } } } // ... else etc... will stderr redirect sti...

c# - Dictionary of Linq Expression -

possible duplicate: declaring func<in t,out result> dynamically i'm trying build query using linq-to-sql and, in order provide sorting capabilities, wrote this: private dictionary<string, expression<func<dataaccess.auditing, object>>> orderdict { get; set; } orderdict = new dictionary<string,expression<func<augeos.gereonweb.dataaccess.auditing, object>>>(); orderdict.add("date", p => (datetime)p.requestdatetime); orderdict.add("username", p => (string)p.cdusername); orderdict.add("portfolio", p => (string)p.cdportfolio); orderdict.add("url", p => (string)p.requestedurl); orderdict.add("result", p => (bool)p.requestresult); orderdict.add("duration", p => (float)p.requestduration); private iqueryable<dataaccess.auditing> setorder(string orderby, bool orderdirection, iqueryable<dataaccess.auditing> query) { if (orderdirection) ...

iphone - Adding description between Section in UITableViewController -

just wanted ask if there easy way add description text between sections in uitableviewcontroller ? can take @ want in "settings > general > keyboard" in iphone/ipod. section footers used descriptions. so, implement following uitableviewdatasource method in subclass of uitableviewcontroller : - (nsstring *)tableview:(uitableview *)tableview titleforfooterinsection:(nsinteger)section for more information see documentation .

SQL error in php -

hey, wrote code extracting information out of database , checking see if met $_cookie data. getting error message: error: have error in sql syntax; check manual corresponds mysql server version right syntax use near ')' @ line 1 my code far is: $con = mysql_connect("xxxx","xxxxx","xxxxxxx"); if (!$con) { die('could not connect: ' . mysql_error()); } mysql_select_db("xxxxxx", $con); $id = $_cookie['id']; $ends = $_cookie['ends']; $userid = strtolower($_session['username']); $querystring = $_get['information_from_http_address']; $query = "select * xxxxx"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array($result)){ if ($querystring == $row["orderid"]){ $sql="update members set orderid = ''where (id = $id)"; $sql="update members set level = 'x'where (id = $id)"; $sql=...

HTML Different link type Question -

what difference between? thank you. <img src="images/file.jpg"></img> between <img src="/images/file.jpg"></img> between <img src="./images/file.jpg"></img> between <img src="../images/file.jpg"></img> you need learn relative , absolute paths . here explanations examples, realy should read link in order understand concepts. if base url "http://example.com/resources/" then: <img src="images/file.jpg"></img> will get: http://example.com/resources/images/file.jpg it adds src url base url. <img src="/images/file.jpg"></img> will get: http://example.com/images/file.jpg bacuse image url rooted (starts / ) uses domain , adds image src domain. <img src="./images/file.jpg"></img> will get: http://example.com/resource/images/file.jpg in case, uses relative path current directory ( ....

iphone - ScrollView with scrollViews - what is the right way to do it? -

client wants tricky stuff , don't know start it. idea there horizontal scrollview each page consists of vertical scrollview. example, on horizontal axis there galleries, on vertical scroll through selected gallery's images. possible? i'd glad hear comments on one! you have manage state yourself. when 1 scrollbar selected other has disabled , vice versa. can disable user scrolling , handle swiping touch events. (on clearcolor uiview topmost view).

.net - Is it possible to to execute code befor all tests are run? -

i writing integration tests.now, before tests run want setup database initial data.for this, have created separate project, run before test project executed(using msbuild file).but, want merge db setup code in testproject, , have executed before tests executed.i using mbunit 3.is possible? you can declare class [assemblyfixture] attribute; , few methods class [fixturesetup] , [fixtureteardown] attributes define assembly-level setup , teardown methods. [assemblyfixture] public class myassemblyfixture { [fixturesetup] public void setup() { // code run before test fixture within assembly executed. } [fixtureteardown] public void teardown() { // code run after test fixture within assembly executed. } } in fact, syntax similar done @ test fixture level well-known [testfixture] , [setup] , , [teardown] attributes.

javascript - which approach is more correct to get element in document with focus? -

i have went through couple of questions asked related , have found 2 common approach. have global element , update attaching onfocus() event each of element. document.activeelement , have following code update element in case of old browser not support property var focusedelement; document.addeventlistener("focus", function(e) { focusedelement = e.target; }, true); document.addeventlistener("blur", function(e) { focusedelement = null; }, true); now question 1 more correct/easy/efficient approach of above two? why? all, your solution 1 horribly inefficient. attaching event handler each , every (focusable) element on page when attach body itself? not correct/easy/efficient way sure. solution 2 looks pretty good.

unix - SVN encrypted password store -

i installed svn on ubuntu machine , can't head around something. whenever checkout terminal error saving non-encrypted password: ----------------------------------------------------------------------- attention! password authentication realm: <[...]> subversion repository can stored disk unencrypted! advised configure system subversion can store passwords encrypted, if possible. see documentation details. can avoid future appearances of warning setting value of 'store-plaintext-passwords' option either 'yes' or 'no' in '/home/[...]/.subversion/servers'. ----------------------------------------------------------------------- i goggled bit couldn't find useful. found 1 topic said client issue, not server one, i'm still not convinced. it says "configure system"; mean that? server or client? if i'm server, there can it? besides hiding warning (like says)... thanks! it client issue. warns credent...

$_SERVER['DOCUMENT_ROOT'] does not work in the php script running through cron -

i use $_server['document_root']."/lib/sft_required.php"; include 'sft_required' file in php script. when run file using browser, works fine when run cron job job, not work. seems file not included when run script through cron. assuming running script directly through cron (as opposed web server accessed http request triggered cronjob (e.g. cron running wget)), of course doesn't work. there no server, $_server not set.

Is Lua based primarily on well-established programming-language ideas? -

lua occupies place in space of languages can embedded. primary ideas behind lua's design new ideas implementors, or lua well-executed combination of well-established ideas? comparison of properties , features of lua other pls particularly appropriate. this interesting question. day job study programming languages, , lua repay careful study. few other languages (perhaps icon , clu). please note language whole , not individual features, makes lua worthy of study. is result of interesting new ideas implementors had, or result of execution of well-established ideas? both. details, best source answer question paper the evolution of lua , appeared @ third acm symposium on history of programming languages. add few comments. the use of lua tables only mutable, non-atomic type of data invented lua team. inspired developments in clu, , believe aware of similar work in awk , icon, refinement degree important contribution of lua team. tables have efficient im...