Posts

Showing posts from January, 2012

vb.net - How to communicate between 2 programs efficiently? -

what easy implement way communicate between 2 vb.net (3.5) form applications running on same machine? the current problem in each program user needs logged use. if user logged one, , clicks button launch another, should pass logged in not need log in again in second program. i looking solution can used other purposes well. note: not vb.net developer myself, member of team managing expressed difficulties task , trying research possible solution him. you can use socket pass information around. solution work 2 programs written in language.

split - C function for separate a string in array of chars -

i want create function split text using separator in c. 2 parameters text , separator passed function , function should return array of chars . for example if string hello word of c , separator white space . then function should return, 0. hello 1. word 2. of 3. c as array of chars. any suggestions? does strtok not suit needs ?

Python code for calculating number of an alphabet -

i need find number of alphabet in range of alphabets ie = 1, b=2 , c =3.... if returning value should 1 is there shorter method provided in python(inbuilt) find other declaring dictionary of 26 alphabets respected values. please if know of such function..... use ord() >>> c = 'f' >>> ord(c) - ord('a') + 1 6 if want 'f' , 'f' both return 6, use lower() >>> c = 'f' >>> ord(lower(c)) - ord('a') + 1 6 you might interested in chr() >>> c = 'f' >>> chr(ord(c) + 1) 'g'

.net - Entity Framework - Querying Inheritance -

Image
i tasked homework assignment make task tracker. wanted learn entity framework assignment, how use inheritance aspects. projects, tasks , sub-tasks have lot of similar properties, thought use inheritance, can't figure out how query particular projects. i drew diagram in visual studio: i created database model. how can employees projects? i've started this: modelcontainer m = new modelcontainer(); var employee = (from e in m.employees e.username == username select e).first<employee>(); but ((employee)employee).projects not available, ((employee)employee).items is. ((employee)employee).items.projects not available. how employee's projects? should add navigation property employees this? you'll have use queryable.oftype(tresult) extension method in order filter entities of type manager: using (var model = new modelcontainer()) { manager manager = (from m in model.employees.oftype<manager>()

java - Byte Array to Double Array -

i have array of bytes representing data .wav file. want convert array of doubles, can operations such fft on determine whether 1 file contained in other. right now, cast bytes doubles, gives me decent results, not precise like. know improper conversion, , feel causing me miss data, because of difference in bytes , doubles represent. how can convert byte array double array before doing fft correlation? if each byte represents signed 8-bit sample value, data has been lost when sample recorded, , there nothing improper or imprecise casting double (which can accurately represent values byte can) - there isn't else can do.

debian - Running linux serial script in background -

i'm running simple script connect serial port of electricity monitor , save output file: cu -s 57600 -l /dev/ttyusb0 >> /var/www/power.txt i'd ideally set off going in background , leave running, think might need daemon this? have experience using cu unattended? thanks, laurence i haven't used cu before, in general can make command run in background putting & after it. e.g cu -s 57600 -l /dev/ttyusb0 >> /var/www/power.txt &

logging - Ruby: Proxy pattern, reducing method calls -

how proxy ruby logger , keep performance? so, have requirement @ work, quite reasonable. when program sent signal hup log flushed , restarted. class localobject attr_accessor :logger def initialize context # 1 less method call! yea! performance++ @logger = context.logger end def @logger.info "hello world" end end the problem, if context.logger reset, @logger still points old one. so, thought proxy logger: class loggerproxy attr_accessor :logger def debug *args @logger.send :debug, args end def info *args @logger.send :info, args end end context.logger = loggerproxy.new context.logger.logger = logger.new 'my_file.log' signal.trap('hup') { context.logger.logger = logger.new 'my_file.log' } ... @logger = context.logger @logger.info "hello world" this works fine, except i've traded 1 method call 2 method calls (1 accessor; returns logger). still have call loggerproxy.:debug,

python - Extending Numpy with C function -

i trying speed numpy code , decided wanted implement 1 particular function code spent of time in c. i'm rookie in c, managed write function normalizes every row in matrix sum 1. can compile , tested data (in c) , want. @ point proud of myself. now i'm trying call glorious function python should accept 2d-numpy array. the various things i've tried are swig swig + numpy.i ctypes my function has prototype void normalize_logspace_matrix(size_t nrow, size_t ncol, double mat[nrow][ncol]); so takes pointer variable-length array , modifies in place. i tried following pure swig interface file: %module c_utils %{ extern void normalize_logspace_matrix(size_t, size_t, double mat[*][*]); %} extern void normalize_logspace_matrix(size_t, size_t, double** mat); then (on mac os x 64bit): > swig -python c-utils.i > gcc -fpic c-utils_wrap.c -o c-utils_wrap.o \ -i/library/frameworks/python.framework/versions/6.2/include/python2.6/ \ -l/library/f

css - menu selected and ie6 .. again -

here page : http://pfibco.ca/01-accueil-fra.php i try block hover highlight menu... work fine just selected class dont apply... why ? #menu ul li .selected{ and worst... menu destroy in ie6, why ? used block propriety.. no choice hover... display: block; how fix ? try selected problem: #menu ul li.selected { the html has selected class on <li> css should match that. i can't ie6 though, destroys lot of things , nerves 1 of things.

Is there an HTML safe truncate method in Rails? -

i have string of html in rails. i'd truncate string after number of characters not including html markup. also, if split happens fall in middle of opening , closing tag, i'd close open tag/s. example; html = "123<a href='#'>456</a>7890" truncate_markup(html, :length => 5) --> "123<a href='#'>45</a>" there 2 different solutions both same name: truncate_html https://github.com/ianwhite/truncate_html : gem , uses html parser (nokogiri) https://github.com/hgmnz/truncate_html : file put in helpers directory. uses regular expressions , has no dependencies.

ruby on rails - How can I use Devise Authentication to validate that a sign up email address is from certain domain? -

i make sure people email address of domain can signup site using devise. for instance if people sign-up email joe@mysite.com, should confirmation email if sign joe@yoursite.com, should error message. uncommenting line in config/initializers/devise.rb # regex use validate email address # config.email_regexp = /^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i and changing use domain wanted limit to: config.email_regexp = /\a([\w\.%\+\-]+)@mysite\.com\z/i did trick.

c# - Check If Thread Is on Gui Context -

how can check if current running thread on gui context or not? it's unfortuntaley hard answer question 100% accuracey because it's not entirely obvious constitutes gui context. it's more of heuristic yes / no answer. , heuristic different every gui framework. for wpf 1 check , see if there active dispatcher current thread public static bool iswpfguithread() { return dispatcher.fromthread(thread.currentthread) != null; } however can fooled setting dispather on random thread not putting gui on top of it. for winforms 1 check current synchronizationcontext . public static bool iswinformsguithread() { return synchronizationcontext.current windowsformssynchronizationcontext; } however can fooled temporarily (or longer) reseting current value synchronization context. thread global , can set anyone. it's common change in applications visual studio (but that's wpf app though)

html table - jQuery toggled tr elements drift down page -

the gist of problem have table every row hidden, , visibility toggled using anchor on row above. works correctly, in browsers (safari , chrome) tr below 1 appeared moves down further should have. if keep toggling hidden tr next sibling drifts down page. here bare bones code shows issue (requires jquery) <script type="text/javascript"> $(function() { //document ready $('.details').hide(); $('.show_hide').click(function(event){ event.preventdefault(); $(this).parents('tr').next().slidetoggle('slow'); }); }); //end doc ready </script> <style> table { width: 500px; } .main td { width: 33%; } </style> <table> <tr class="main"> <td>title</td> <td>some detail</td> <td><a href="#" class="show_hide">show/hide</a></td> </tr> <tr class="details">

batch file - How to use the echo command after a set /p command -

i wanted make script work somehow, find after use set /p variable= whater want here if use echo command after it, hidden or because wont come up... @echo off cls color :main cls echo. echo. echo ================================= echo. set /p var= name? :: not show (starting here) echo. echo ================================= :: not show (ending here) set /p answer= name %var%? if %answer%== yes echo thats amazing name! if %answer%== no goto main the part thats surrounded remarks doesnt want show reason... ideas? if i'm understanding trying do, code need: @echo off cls color :main cls echo ================================= echo name? echo ================================= set /p var= set /p answer= name %var%? if %answer%== yes echo thats amazing name! if %answer%== no goto main pause

algorithm - Balancing a ternary search tree -

how 1 go 'balancing' ternary search tree? tst implementations don't address balancing, suggest inserting in optimal order (which can't control.) the article in dr. dobbs ternary search trees says: d.d. sleator , r.e. tarjan describe theoretical balancing algorithms ternary search trees in "self-adjusting binary search trees" (journal of acm, july 1985). can find online versions of paper favorite search engine.

To invoke thickbox using javascript -

how invoke thickbox using javascript function. using code. //javascript function function click_fn() { self.location="upload.php?keepthis=true&tb_iframe=1&width=1000&height=400&model=true"; } calling thickbox via javascript var url = "http://www.blah.com/something?keepthis=true&tb_iframe=true&width=300&height=200"; tb_show("my caption", url); syntax: tb_show(caption, url, imagegroup) code allows call thickbox javascript.

iphone - after submiting the project to app store ,why appstore image(512*512) geting glass effect? -

after submitting project app store, why app store image(512*512) shown glass effect? my original image not have glass effect, after uploading, getting glass effect. how can avoid glass effect? that done default, it's done app icon. take @ this when creating ios app (xcode), how can turn off automatic icon 'gelling'

iphone - How to set UITableView background to image? -

i've noticed number of apps have custom background image uitableview (or have set background color.) i can't find api in uitableview class affect this, , attempts in interface builder have failed (trying set color of uiview) any suggestions? i've seen third party app pictures, know can done. add line in code want set background color image [yourview(or imageview) setbackgroundcolor:[uicolor grouptableviewbackgroundcolor]]; thanks

jquery countdown pause and resume feature? -

i need code pause , resume jquery countdown . script: http://plugins.jquery.com/project/jquery-countdown use plugin's stop function, this: <span id="count">8</span> <input type="button" id="pause" value="pause" /> <input type="button" id="resume" value="resume" /> and js: function start() { $('#count').countdown({seconds: parseint($('#count').text())}); } function pause() { $('#count').countdown.stop(); } $('#pause').click(pause); $('#resume').click(start); start(); look @ working here .

javascript - How to implement finding in UIWebView with next and Previous? -

i have been stuck on quite while. have been searching lot of time. had implemented find , highlight text using java script. had referred http://hi.baidu.com/ncudlz/blog/item/826ede354694da1f90ef3900.html link. this helpful needed want implement next , previous button while searching when java script find first occurrence uiwebview should scrolled position. on click on next button should scroll next position , on previous if click on previous button. so how can scroll webview when occurrence of text. thank in advance you can use element.scrollintoview(); method scrolls element view.

ios - How do I assign this text to label in iPhone SDK -

i want assign below text uilabel , gave me many errors: smslbl.text = @"____ |----|-o /______\ |______| \______/"; basically want assign ascii art of handgrenade label text. can please suggest correct way of assigning uilabel ? thanks! use control characters advantage: smslbl.text = @"____\n |----|-o\n/______\\\n|______|\n\\______/"; here using \n newline character signify new line, , i'm escaping literal \ characters \ character.

asp.net mvc - JQuery Document.ready functionality flashes at page start-up -

i'm using jquery's document.ready hide things mvc master page. when page loads, though, can see elements i'm removing flash second before disappearing. this how i'm doing it: <asp:content id="maincontent" contentplaceholderid="maincontent" runat="server"> <script type="text/javascript"> $(document).ready(function () { $("#hidediv").remove() }); </script> how can rid of flashing? want elements i'm removing gone before page renders. update: i should point out i'm doing dynamically, hiding things on pages. hidediv example name gave, perhaps poor one. for example, have menu bar @ top has links various pages. want remove link page when user on page. rather manually adding wanted links on each page, have them in master page, , hide ones don't want shown on page. apparently document.ready not time this? might better way accomplish that?

sql - MYSQL Query for top 10 users per location -

i need top 10 users per cc, based on total prints have made. hierarchy looks this business unit cost centre user it 1 many relation. tables this: business unit 'id', name, bu_no cost center 'id', bu_id, name user 'id', username, fullname, email, total_prints this in excel, data mysql. i need find mysql query show top 10 users (most prints) per cost centre. any appreciated. thanks sorting descending put prints @ top , limit 10 select top ten records. here code sample show i'm talking about. select * user user.id = cost_center.id order total_prints desc limit 10;

android - how to disable a element in gridlayout? -

Image
i disigning calendar application.now have populated grid elements.but grid layout shows dates of pervious month.how disable particular cell in grid layout? , if possible let me know how enable grid lines? thing image: agree flo, create state (boolean value) each element , check deciding: responding/design.

Oracle sub select query qith aggregation function -

id firstname lastname 1 john smith 2 mike smith 3 ben bray 4 john bray 5 john smith 6 bill lynch 7 bill smith hi there. i'm trying subselect query in oracle min , max functions, can't seem on right track. appreciated. example: i'm looking in table carl brayland. if doesn't exist want first name before carl brayland give me id 3 -> ben bray example2: i'm looking in table mike mad if doesn't exist want first name before mike mad give me id 6 -> bill lynch last name should leading. use rownum on sorted set (here :p_lastname := 'mad'; :p_firstname := 'mike'; ): sql> my_data ( 2 select 1 id, 'john' firstname, 'smith' lastname dual 3 union select 2, 'mike', 'smith' dual 4 union select 3, 'ben' , 'bray' dual 5 union select 4, 'john', 'bray' dual 6

How to make Django restart runserver on template change? -

when make modification in python source file in project, django detects , restart runserver itself. when modify django template, have kill runserver , restart again : how can have runserver restart automatically on template change ? the file default read disk on every request, there no need restart anything. there caching template loader, disabled default. see the documentation more info.

algorithm - range splitting problem -

folks, have heard of problem quite time back. thought of posting it, views of doing using construct or other efficient means(specialized trees may be) given set of ranges in pairs (5,18) (12,23) (15,30) split them possible subranges seen overlapping other ranges in set. (5,11) (12,14) (15,18) (19,23) (24,30) thanks all, appreciate that... rajan... ps aa standard problem, if yes, tu know name chuck range endpoints list, mark them start/end-points. [(5, s), (18, e), (12, s), (23, e), (15, s), (30, e)] sort them position, breaking ties putting start-points before end-points. [(5, s), (12, s), (15, s), (18, e), (23, e), (30, e)] then can work out ranges iterating through list, keeping track of how many start- minus end-points we've processed far. if see start point, that's start of new range output. if our count positive, have end current range first though. if see end point, end current range.

mysql - Count and group by date should return 0 on no values -

i'm trying report number of interviews did per day. so have table of interviews such as interviewid,staffid,date,comments... and date reference table containing date 2005 2020. having single date field named ref. my query : select count(*) cnt `interviews` right join `dateref` on `date` = ref type = 2 , date > date_sub(now(),interval 7 day) group date_format(ref,'%y-%m-%d') is works fine display interview did not when did not interviews... for example returns : 1 2 4 but should return 0 1 0 2 0 4 0 edit: apparently problems comes clause because if remove it, query works fine... try replace to right join instead left join another change is where type = 2 to where type = 2 or type null so final query select count(*) cnt `interviews` right join `dateref` on `date` = ref (type = 2 or type null) , date > date_sub(now(),interval 7 day) group date_format(ref,'%y-%m-%d')

sql - Default null values in stored procedures are not Null -

i have been testing faulty procedure, , realised problem null values being passed in not being defaulted procedure value... create procedure testvarcharmaxisnull (@myvar varchar(max) = '') select 'hello' @myvar null go exec testvarcharmaxisnull null go exec testvarcharmaxisnull '' go exec testvarcharmaxisnull go drop procedure testvarcharmaxisnull output run 1 - "hello" run 2 - "" run 3 - "" i assumed null values defaulted value assigned in stored procedure parameter, shows if exists parameter takes value pass in. there setting in sql server can change behaviour? the empty string '' not equivalent null value. so say (@myvar varchar(max) = '') means when don't pass in argument empty string in @myvar, in turn means when say where @myvar null will evaluate true when explicitly pass in null argument, in first test case.

Castle Windsor Interceptor selectors and hooks -

i'm doing project in castle windsor , have problems interceptor hook in config file created class impements iproxygenerationhook : public class loggingproxygenerationhook : iproxygenerationhook { #region iproxygenerationhook members public void methodsinspected() { //throw new exception("the method or operation not implemented."); } public void nonvirtualmembernotification(type type, system.reflection.memberinfo memberinfo) { //throw new exception("the method or operation not implemented."); } public bool shouldinterceptmethod(type type, system.reflection.methodinfo methodinfo) { return methodinfo.name.startswith("save", stringcomparison.ordinal); } #endregion } all want intercept methods name start "save" , hook them dynamically in config file. also, in config file have following: <component id="loggingaspect" type="dynamicinterceptor.logging

how to type ajax correctly? -

i know how use 1 form data use ajax: $.ajax({ type:'get', url:'blabla.php', data:$('#abc').serialize(); ......... but how if want type: $('#exportmod').click(function(){ $.ajax({ "datatype":'json', "type":'get', "url":'shows_merchan.php', "data": [ action:"searchmodelqp", jhead:"aadata", month:$("#search_month").val(), year:$("#search_year").val(), export:"excel" ], "success":function(json){ fncallb

c# - Is it possible to make [XmlAttribute] as default for a class? -

i have lot of properties serialize using xmlserializer . need tag each (simple) property [xmlattribute] make output little shorter. i'm wondering if there easier way it. there way make default class, simple type properties serialized attribute instead of element? you can create code snippets . create 1 properties attribute set, , use when writing them.

How to display image in list component in Flash cs4? -

i used list component in flash, , have display image in list component instead text. there solutions ? thanks it depends on trying do. lee brimelow has example of using images icons in list component alternatively might want consider using tilelist component (search "displaying images tilelist component").

Crosspost Wordpress blog post to blogger -

i want publish same post published in worpress blog blogger & facebook automaticaly. know possible , there various plugin out there. cant find 1 free use plugin this. i used 'network publisher' plugin. free facebook need pay if want add on blogger or other. working me in facebook now worried blogger automatically posted wordpress. at last got blogger (.blogspot) post automatically wordpress. the blogger can configured post via email. there in blogger account have create secret email address in setting tab format - name_of_the_site.secretcode@blogger.com (so mail send address automatically posted in blogger) and in wordpress install plugin named crosspress required stuff put email address , signature want show underneath each post. test creating new post , publishing it. same in blogger done......

Django django-smart-select: get TemplateSyntaxError during adding of data in admin site -

i'm django newbie. want try app django-smart-selects . "customer" adress being auto-populated choosing appropiate "customer" in "order" form of admin site. so have defined following models.py from smart_selects.db_fields import chainedforeignkey django.db import models # adress model class adresse (models.model): strasse = models.charfield(max_length=50) plz = models.integerfield(max_length=5) ort = models.charfield(max_length=50) def __unicode__(self): return self.strasse # customer model class customer (models.model): name = models.charfield(max_length=50) adresse = models.foreignkey(adresse) def __unicode__(self): return self.name # order model class order (models.model): name = models.charfield(max_length=50) delivery_time = models.datetimefield() created_at = models.datetimefield(auto_now_add=true) kunde = models.foreignkey(customer, related_name="kunde") ad

ftp - windows batch file to copy a file from a server to local -

i write little code copy on local pc file (a server). which windows batch file function can use write little batch file program, (ftp maybe?) and visualize message on pc (the local pc) thanks all just use wget . it can called batch file , download http , ftp.

c# - am i in console app? -

is there way detect inside component in c# if application uses component running in console application or others? use environment.userinteractive . if true in console. if false in service.

iphone - No RequestToken to Authorize -

i have created iphone application integration of soundcloudapi. when try run application getting following error message: error domain=soundcloudapierror code=2001 "the operation couldn't completed. (nsurlerrordomain error - 1012)" userinfo=0x13cbc0 {httperrorstatus=error domain=nsurlerrordomain code=-1012 "the operation couldn't completed. (nsurlerrordomain error - 1012.)" userinfo=0x137b90 {nserrorfailingurlkey=http://api.soundcloud.com/ oauth/access_token, nserrorfailingurlstringkey=http:// api.soundcloud.com/oauth/access_toekn, nsunderlyingerror=0x13b590 "the operation couldn't completed. (kcferrordomaincfnetwork error - 1012.)"}, nslocalizeddescription=the operation couldn't completed. (nsurlerrordomain error - 1012.)} any 1 please tell me how resolve it. thanks. i have resolved problem. issue is; did not entered callback url under "callback url (oauth 2 redirect uri)" to enter this, follow below step

javascript - How to show google maps and street view in the same time? -

i want show google maps , street view , have relation between them if user moved in map street view refresh, http://www.mashedworld.com/dualmaps.aspx without birds eye. this default behavior of streetview http://code.google.com/apis/maps/documentation/javascript/examples/streetview-simple.html

c# - Concurrent ASP.NET request using InProc session management -

first let me attempting accomplish. notify user(s) of web application if changes made document working on. intend use long polling achieve desired results. when send request long polling page (which polls , sleeps 250ms between iterations until timeout expires) , attempt simultaneously load page on web site, second request queued until first complete. there solution problem? ahead of time, using web garden or form of session management inproc not acceptable in situation. can offer. this session synchronization causing requests handled sequentially. if can change long-polling handler not session aware, should fix problem. you didn't target if it's .ashx or custom ihttphandler not implement irequiressessionstate request not attach (or synchronize with) session. of course means long polling request not have access session.

ASP.NET MVC users not being copied over on publish -

i'm new asp.net mvc, , i'm trying convert simple asp.net application mvc authorization. i have working locally fine, when publish iis, users database apparently not copied on correctly (even though running on same machine developing on) it not appear database access issue, since when create new user using register link can log in fine. problem is, users (and associated roles) created using asp.net web site administration tool aren't being recognized. error message gives me simple "log in or password incorrect" - there's nothing not being able access database or that. does know should source of problem, or has else had problem before? potentially releveant additional information: when first published project, got error in web.config said "applicationservices" defined, preventing me accessing page on site. "fixed" in manner called "hacky" if trying polite - added " <remove name="applicationservices" /

java - Injection through Annotations vs injection through XML file in Spring 3. Limitations related to inheritance -

i have following abstract class, property called portletbaseviewname meant different every concrete controller extending abstractcontroller . public abstract class abstractcontroller { private string portletbaseviewname; protected string getportletbaseviewname() { return portletbaseviewname; } @required @value("") public void setportletbaseviewname(string portletbaseviewname) { this.portletbaseviewname = portletbaseviewname; } } @controller @requestmapping("view") public class reservationofbooksviewcontroller extends abstractcontroller{} i know possible declaring injections in xml, doing so: <bean id="abstractcontroller" class="es.alcampo.portalweb.portlets.common.controller.abstractcontroller" abstract="true"> <property name="portletbaseviewname" value="" /> </bean> <bean id="reservationofbooksviewcontroller" class="

asp.net - How to edit a gridview inside of a modal popup? -

i have gridview appears in modal popup generated dynamically , bound dynamically generated sqldatasource. i did take advantage of gridview's automatic editing capabilities. my problem when edit button clicked modalpopup closes due full postback in spite of fact gridview in update panel... i looked @ solutions here , here neither fixed problem. i've tried every combination under sun regarding positioning of modalpopupextender in relation update panel etc, , have tried changing updatemode conditional well. markup: <span class="none"><asp:button id="btndummy" runat="server" text="dummy" /></span> <ajax:modalpopupextender id="mplabel" runat="server" targetcontrolid="btndummy" backgroundcssclass="modalbackground" popupcontrolid="pnllabels"></ajax:modalpopupextender> <asp:panel id="pnllabels" defaultbutton="btnok" style="

jquery - Load image into appended element -

i having problem trying load image after element has been appended when thumbnail has been clicked on, replace /t/ /i/ loads appended element code: $('.main-image img').live('click', function () { var image_url = $(this).attr('src'); var loadurl = image_url.replace(/\/t\//, '/i/'); $('.container').slideup('slow'); $('#pop-up').append('<div class="container tcenter"><p id="close-preview" class="link tcenter">close</p><div class="quick-view"><img src="img/loading.gif" /></div></div>', function() { $('<img />').attr('src', loadurl).load(function() { $('.quick-view').empty(); $(this).appendto('.quick-view'); }); }); // ignore part - above needs helping $('.quick-view').css('line-height', ($('.quick-view').parents().find('.contain

android - trouble with nested layouts -

i'm beginning android , have gotten myself stuck. i've made simple app/view. idea draw line-maze in top, motion buttons on bottom. app draws x couple lines in frame, works. problem buttons being drawn far down, , clipped in height. i assume problem in layout xml: <?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <framelayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" > <none.maze.mazeview android:id="@+id/maze" android:layout_width="fill_parent" android:layout_height="fill_parent"

iphone - Is there a convenient way to have two different "nil-like" possible return values from a method? -

the method in question (actually polymorphically-implemented family of recursive search methods) returns pointer type of object. had been returning nil in cases of failure. want have 2 different kinds of failure. easiest way implement that? the best way keep return nil; , take error pointer 1 of function arguments. way, can send in error, , check value afterward see happened. function still run, you'll have control on gets returned. as example, here's code use saving managedobjectcontext: nsmanagedobjectcontext *moc = [self managedobjectcontext]; nserror *error; if (![moc save:&error]) { nsstring *description = [error localizedescription]; nsinteger code = [error code]; } i've tweaked inside of block show couple of ways pull info out of error. you, it'd best use simple error codes distinguish between different nil values. here's code example (though not best way, you'll have duplicate code interpret error messages):

geometry - Max spread of multiple points -

i have group of points (x,y) , need find out distance between 2 farthest apart. what efficient way find this? thanks well, compairing every point against every other point not efficient. the efficient way involves finding convex hull, convex polygon (no angles > 180) surrounding points. after that, find farthest points on hull, using antipodal pairs. algorithm described here: http://www.seas.gwu.edu/~simhaweb/cs153/lectures/module1/module1.html

Android: Programmatically change android:name attribute for Application and BroadcastReceiver -

is possible programmatically change android:name attribute in code application , broadcastreceiver? change name of app icon , widget names programmatically, in order reuse our existing localization infrastructure. a better solution might have library project contains base code , projects use library can override existing resources having same name. helpful..

character encoding - get char value in java -

how can utf8 code of char in java ? have char 'a' , want value 97 have char 'é' , want value 233 here table more values i tried character.getnumericvalue(a) gives me 10 , not 97, idea why? this seems basic appreciated! char numeric type containing unicode value (utf-16, exact - need two char s represent characters outside bmp) of character. can can int . character.getnumericvalue() tries interpret character digit.

python - Jython, Jepp or Pylons for the performance -

i'm trying incorporate server-based code diff , highlighting in gwt (java) project. managed incorporate pygments , difflib into code using jython . basic idea generate complete markup on server , inject code page innerhtml . found jython inadequate relatively small files (2k-3k lines) takes pygments or difflib forever (minutes not seconds) process these files. difflib reliably causes oom errors in process dedicated 500m of memory i'm wondering if my current setup wrong or jython unsuitable purpose? if so, what's next? discover jepp have build project each platform , has little documentation , don't seem stable. possibility run pylons separate webservice on same host , markup directly client or channel through server. , yet way use java system execute python script process , capture output. i interested hear solid suggestion on matter. having separate service sounds best way go. pygments, there service available (on google app engine). source app bs

java - Spring Roo @Id field not populated in DataOnDemand test -

i working web application built on spring roo 1.0.2. have defined entity has primary key personid column several other fields. @id @column(name = "personid", precision = 10, scale = 0) private long personid; @size(max = 50) @column(name = "name") @notnull private string name; ... the roo-managed integration tests contain function instantiates mock object , populates each of non-id fields. public person persondataondemand.getnewtransientperson(int index) { person obj = new person(); obj.setname("name_" + index); //set other non-id fields return obj; } this function called integration tests , subsequently fails database table has not null constraint on personid column. have tried explicitly setting @notnull annotation on personid column, has no effect. suspect has fact personid non-autogenerated primary key. i know can address overriding integration tests , populating id myself, avoid if possible. know way can fi

LINQ, "Value cannot be null", yet query evaluates -

i have following linq query: var test = vendorcontact.vendorcontactitem .where(x => x.itemnumber == vendorcontactitem.item_number) .firstordefault(); it fails on piece of code, "value cannot null, parameter name: source" ... yet displays, in local variables window, "test" variable properties populated. vendorcontact.vendorcontactitem is null. presumably first element added list. how "test" evaluating correctly while simultaneously throwing error? i'm new linq, excuse me if obvious question. if in loop test in locals window contains last value of test , last iteration of loop. edit: has nothing linq, how debugger works.

iphone - Facebook and iOS -

is there open source api allow me post on groups of facebook? secondly, need create application or no need? i'd through ios. you should able use the facebook graph api , simple http requests (using ios sdk) this. there's actively developed open source facebook ios sdk should make process easier.

asp.net - Monitoring SQL statements application-side by attaching to w3wp/WebDev.WebServer.exe (SQL Sever) -

i must missing something... oracle has simple, useful , free tools attaching process , monitoring sql statements can't similar sql server . incredibly useful across number of scenarios, particularly when dealing third-party assemblies (1). ants 6 seems support (2), though doesn't allow view stack-trace lead query dynatrace does. don't think dottrace tracks parameter values, either. surely there's available option profiling sql application-side? (1) - http://blog.dynatrace.com/2009/02/09/sharepoint-lookup-value-performance/ (2) - http://www.simple-talk.com/dotnet/performance/under-the-orm-hood-revealing-the-sql/ sql server comes tool called sql server profiler . can use connect sql server instance, , you'll able see sql statements issued on server. you can filter application name, username, etc. see statements of particular application want monitor. here free express version.

should unit tests be black box tests or white box tests? -

say have 3 methods, similar different input types: void printlargestnumber(int a, int b) { ... } void printlargestnumber(double a, double b) { ... } void printlargestnumber(string numberasstring, string numberasstring) { ... } all 3 use same underlying logic. example: maybe double version 1 compares numbers, , other 2 convert inputs double . we imagine few different unit tests: first input larger, second larger, both inputs negative, etc. my question should 3 methods have full set of tests (black box since don't assume core implementation same) or should double version tested heavily , other 2 tested lightly verify parameter conversion (white box testing since know share same implementation , it's been tested in double tests)? if of methods public, i.e. callable outside world, i'd test of them full set of tests. 1 reason white-box tests more brittle black-box tests; if implementation changes public contract might change of methods.

impersonation - Impersonate admin account to edit registry key not working (C#) -

i using following code edit registry key in local machine hive ('software\microsoft\windows nt\currentversion\profilelist\%sid%'). seems fine until try open registry key (with write permissions); securityexception thrown message 'requested registry access not allowed.' i've checked , rechecked permissions registry key , user i'm impersonating , checks out. code runs fine when logged impersonated user's account, when logged in restricted user, fails. it's if impersonation works except giving thread administrative privileges. ideas how fix appreciated! string key_str = "software\\microsoft\\windows nt\\currentversion\\profilelist\\" + windowsidentity.getcurrent().user.value; windowsimpersonationcontext admincontext = null; intptr tokenhandle = new intptr(0); try { logonuser(username, domainname, password, logon32_logon_interactive, logon32_provider_default, ref tokenhandle); if (tokenhandle.equals(new intptr(0))) logonuser(usern

algorithm - Better distance metrics besides Levenshtein for ordered word sets and subsequent clustering -

i trying solve problem involves comparing large numbers of word sets , each of contains large, ordered number of words set of words (totaling around 600+, high dimensionality!) similarity , clustering them distinct groupings. solution needs unsupervised possible. the data looks like [apple, banana, orange...] [apple, banana, grape...] [jelly, anise, orange...] [strawberry, banana, orange...] ...etc the order of words in each set matters ([apple, banana, orange] distinct [apple, orange, banana] the approach have been using far has been use levenshtein distance (limited distance threshold) metric calculated in python script each word being unique identifier, generate similarity matrix distances, , throwing matrix k-mediods in knime groupings. my questions are: is levenshtein appropriate distance metric use problem? is mean/medoid prototype clustering best way go groupings? i haven't yet put thought validating choice 'k' in clustering. evaluating sse cur

android - rss parsing using dom, html format tags -

i have parse rss feed , display same in android. using dom parser. able parse tag except tag has html formatting tags. example <description> <p><span style="font-family: arial, geneva, sans-serif; font-size: 11px;"> <p style="font-family: arial, helvetica, sans-serif; max-width: 600px; margin-top: 8px; margin-right: 0px; margin-bottom: 8px; margi <strong>will kids love rock of ages as will?</strong>&nbsp;we think have great time, should know age of 14.</span></p> </description> could 1 please guide me how unformatted text content tag . also, changing rss feed not option... thanks you won't able use dom parser, , shouldn't either. use saxparser class instead, check out answer here linked tutorial.

How can I find my working revision in mercurial -

in mercurial repo can run hg {revision} change revision of working directory, command can run discover revision i'm looking at? this command: hg parent

c# - How can I convert a ConcurrentDictionary to a Dictionary? -

i have concurrentdictionary object set dictionary object. casting between them not allowed. how do it? the concurrentdictionary<k,v> class implements idictionary<k,v> interface, should enough requirements. if need concrete dictionary<k,v> ... var newdictionary = yourconcurrentdictionary.todictionary(kvp => kvp.key, kvp => kvp.value, yourconcurrentdictionary.comparer); // or... // substitute actual key , value types in place of tkey , tvalue var newdictionary = new dictionary<tkey, tvalue>(yourconcurrentdictionary, yourconcurrentdictionary.comparer);

graphics - WPF Control that renders a 2d dimension? -

i need render value of width or height of 2d geometry object , request not text, dimension set of building plans. this image ... oops new post images ...like image googled - http://www.archidigm.com/lounge/archdim/centerline_dim_1.gif i have looked this, haven't been lucky in search. fine creating it, thought try not reinvent wheel if possible. know of control or library out there renders this? this article looks helpful: http://msdn.microsoft.com/en-us/library/bb613591.aspx . although talks optimizing drawing, gives mention lot of different classes can use. specifically, take @ drawing class: http://msdn.microsoft.com/en-us/library/system.windows.media.drawing.aspx#snippetgroup1 if want shapes interactive (because seems building cad-like application), drawinggroup might help. check out example: http://msdn.microsoft.com/en-us/library/system.windows.media.drawinggroup.aspx#snippetgroup also, drawinggroup might way group actual shape (for example, wall in bu

localization - Localize the content of a Link Module in DNN -

i using default links module create list of links in dotnetnuke. so have added module inside page , gave title of "links". have added 2 links pointing page of site (link 1 , link 2). now translate page , modules language. have been able translate on page except title of every link inside module (link 1/link 2). is there way accomplish this? using these features in correct way? generally speaking, there way localize dnn standard modules? a bit late might suggest ealo text html module . might solution

PHP Compare Array Values for Validation -

ok, have pretty customized question bear me. i have 2 sets of data want compare lot of different possibilities. $data = array( 'object'=>'ball', // should check valid (rule 2) 'color'=>'white', // valid (rule 2) 'heavy'=>'no', // valid (rule 1) 'name'=>'wilson', // valid (rule 5) 'funny'=>'no' // invalid (rule 4) ); $data_2 = array( 'object'=>'box', // valid (rule 2) 'color'=> 'blue', // valid (rule 2) 'texture'=>'hard', // valid (rule 1) 'heavy'=>'yes', // invalid (rule 4) 'stupid'=>'no' // invalid (rule 4) // name invalid because missing (rule 3) ); $required = array( 'color'

delphi - Encrypt/Decrypt a MS Access 2000 (*.mdb) Database File (Extra Security) -

for security, encrypt/decrypt ms access 2000 (*.mdb) database file. i using delphi 7 , looking free or opensource solution (possible 2 functions allow pass file name , key). i perform decrypt before app starts, , encrypt when app shuts down. best places this. oncreate, ondestroy events? i assume first have create small utility uses encrypt portion of solution encrypt database file first? thanks i understand reasons have encrypt old access database , because security of access 2000 , 2003 weak. primary recommendation try upgrade access 2007 or higher uses microsoft cryptographic api, , incorporates significant improvements in security. if can't upgrade, here leave option encrypt mdb file. 1) encrypt data can use jwawincrypt unit part of jedi jwscl library, can download library here . check sample function uses 3des algorithm encrypt file. uses classes, jwawintype, jwawincrypt, sysutils; procedure cryptfile(const infilename, outfilename,

satellite - Is there a way to use Google Maps to estimate empty lots in NYC? -

i came presentation manhattan borough president said having running record of empty lots in new york city important in regards available land potential green space or community gardens important. currently, these numbers derived volunteers on street count numbers of homeless. satellite imagery google maps , lots of brains, couldn't automated process? wouldn't accurate due lag in available satellite images, way better , easier people on street. here's large empty lot on 46th street , 8th avenue. http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=8th+avenue+and+47th+street&sll=40.718241,-73.95844&sspn=0.001262,0.00284&ie=utf8&hq=&hnear=8th+ave+%26+w+47th+st,+new+york,+10036&ll=40.759899,-73.987089&spn=0.001262,0.00284&t=h&z=19 many lots (unlike 1 above) abandoned spaces owners don't care about. i know bit unorthodox stackoverflow question figured throw out here. you'd need decide constitut

html - CSS formating is giving me an error when I try to validate the file -

line 8, column 7: end tag "style" omitted, declaration not permit ✉ •you forgot close tag, or •you used inside tag not allowed, , validator complaining tag should closed before such content can allowed. next message, "start tag here" points particular instance of tag in question); positional indicator points validator expected close tag. line 7, column 1: start tag here <html> <head> <title>randy's first html web page !</title> <style type="text/css"> </head> body h1 { background-color:#6495aa; margin-right:1350px; } h2 { background-color:#b0c4de; margin-right:1350px; } p { background-color:#649fff; margin-right:1350px; } div { background-color:#efffff; } </style> you closed head before style, validator sees you've finished <style> , , take forgot close before </head> , try: <html> <head> <title>randy's first html web page !</title> <style

sorting - PHP scandir results: sort by folder-file, then alphabetically -

php manual scandir : by default, sorted order alphabetical in ascending order . i'm building file browser (in windows), want addresses returned sorted folder/file, alphabetically in subsets. example: right now, scan , output aardvark.txt bardir bazdir dante.pdf foodir and want bardir bazdir foodir aardvark.txt dante.pdf other usort , is_dir() solution (which can figure out myself), there quick , efficient way this? the ninja wrote this comment on right track - best way? does give want? function readdir($path) { // make sure have trailing slash , asterix $path = rtrim($path, '/') . '/*'; $dirs = glob($path, glob_onlydir); $files = glob($path); return array_unique(array_merge($dirs, $files)); } $path = '/path/to/dir/'; readdir($path); note can't glob('*.*') files because picks folders named like.this .