Posts

Showing posts from January, 2011

Handling HTML SELECT Options with event delegation to javascript on iPhone Safari -

we developing web application gui customized use on iphone. page on app has 3 subsequent select dropdowns, selection of option 1st dropdown derives options 2nd dropdown, , forth. subsequent dropdown options populated javascript based on onchange event on previous dropdown. problem that, on iphone options select appears 'prev' , 'next' links move previous , next control. when 'next' link clicked, control moves next select , displays options. javascript triggered onchange event previous select , populates options next select. on dropdown 2nd select displays previous options before repopulated javascript. there workaround or event can sequence execution of javascript , selection of next control? there event can triggered when select option selected , before control leaves select element? there handle next , previous links select dropdown option display? maybe use focus event, in jquery be: $('#select2').focus(function () { // update sel...

linked list - Passing a object by reference in c++ -

this noobie question, i'm not sure how pass reference in c++. have following class sets node , few functions. class node { public: node *next; int data; node(int dat) { next = null; data = dat; } node* getnext() { return next; } void setnext(node *n) { next = n;} void reverse(node *root) { node *previous = null; while(root != null) { node *next = root->getnext(); root->setnext(previous); previous = root; root = next; } root = previous; } }; now, purpose of little class create singularly linked list , have ability reverse it. , seems work fine, if return node named 'previous' @ end of reverse. but @ main function: int main() { node *root = new node(1); node *num2 = new node(2); node *num3 = new node(3); node *num4 = new node(4); root->setnext(num2); num2->setnext(num3); num3->setnext(num4); root->printlist...

c# - Approaches to do keyword search in FAQ -

my site (asp.net + c#) has faq data pull site's web service in xml format. data size pretty small (just 50 faqs). want implement keyword search faq , highlight search keyword. fast , easy approach this? my first thought using c# string search or xml search method. know not scalable. consider faq little, may not need index faq. wrong. can give me suggestions? thanks. the best solution using regular expressions . regex scales too, don't need worry speed. using regex replace, adding tag around matches make them stand out easy well. you can find regex tutorial here . has info both general regex use, , link goes explanation .nets implementation. regex has step learning curve, worth effort, because incredibly powerful.

What am I missing? GetLine function (C++) -

string getline() { char parameter[26] = {null}; infile.getline (parameter,26,' '); return parameter; } now example of input file looks this: ~in.txt~ bac bca(space after last a) ~end file~ i have have space after or else function line won't work. there way not have space after , still work? i have 26, because input line have 26 letters in it. i need have them separated have because how use it: string in, post; in = getline(); post = getline(); thanks suggestions on this, small chunk of code program i'm still working on. wanna cover bases because professor testing program own input file , don't know if input file end space. this kind of silly redundant function, , don't know why call "getline", here ya go: string getline() { string s; infile >> s; return s; }

design patterns - Advice on POCO Validation with ASP.NET MVC/Entity Framework -

here's scenario: asp.net mvc2 web application entity framework 4 (pure poco's, custom data context) repository pattern unit of work pattern dependency injection service layer mediating controller -> repository so basically, cool stuff. :) flow of events basic ui operation ("adding post"): controller calls add(post) method on service layer service layer calls add(t) on repository repository calls addobject(t) on custom data context controller calls commit() on unit of work now, i'm trying work out can put validation. at stage, need 2 types of validation: simple, independant poco validation such "post must have title". seems natural fit data annotations on poco's. complex business validation, such "cannot add comment locked post". can't done data annotations. now, have been reading "programming entity framework, second edition" julie lerman (which excellent btw), , have been looking hoo...

c# - Correct Process for Routing with Admin Subsite -

i'm building first asp.net mvc2 site, , i'm trying add /admin area site. i don't want area visibile main set of users accessible when enter http://intranet/admin what have newscontroller regular users want admin newscontroller , i'm not sure how setup class hierarchy , folders when add views in correct location. inside global.asax.cs i've added , routes resolve correctly. routes.maproute( "default", // route name "{controller}/{action}/{id}", // url parameters new { controller = "home", action = "index", id = urlparameter.optional }, // parameter defaults new string[] { "intranet.controllers" } ); routes.maproute( "admin", // route name "admin/{controller}/{action}/{id}", // url parameters new { controller = "admin", action = "index", id = urlparameter.optional }, // parameter defaults new string[] { "intranet.controllers.ad...

ios4 - UIPopOverController for iPhone (currently only available for iPad) -

before implement similar iphone, i'm wondering if has implemented similar of uipopovercontroller iphone . far available ipad. see implementation here: https://github.com/werner77/wepopover it has same interface uipopovercontroller generalized iphone , support custom background views.

string - " escape sequence in C? -

what escape sequence ' " ' in c? in other words, how can ask while-statement search occurance of ' " '? in character constant, don't need escape " character; can use '"' . in string literal, need escape " character since it's delimiter; prefixing backslash ( "\"" ). note can escape " character in character constant ( '\"' ); it's not necessary.

C#: how to get first char of a string? -

can first char of string retrieved doing following? mystring.tochararray[0] just mystring[0] . uses string.chars indexer.

c - Implementing LRU page replacement algorithm -

edited include short description of expected code. #include <sys/file.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #define max_page 0xff+1 /* page table entry may need add own fields it*/ typedef struct { unsigned short frame;/*location*/ unsigned int valid:1; unsigned int in_mem:1; unsigned int dirty:1; unsigned int last_frame; } pt_entry; /* list entry physical frames*/ struct list_item { unsigned short frame; struct list_item *next; struct list_item *prev; int page_num; }; typedef struct list_item *list; void start_simulation(file *); void resolve(int); unsigned short find_frame(void); unsigned short find_victim(void); void display_stats(void); void to_resident_set(list); void free_mem(list); void invalidate(unsigned short); /*============================ header ends here ============================== * /*#include "lru.h"*/ pt_entry pte[max_page]; /* page table */ int mem_size; /* physical m...

.net - How to force Nunit to release handles on native DLLs? -

i have code require me pinvoke 3rd party native dll. issue when use nunit test runner tests, native dll locked nunit processes (nunit.exe , nubit-agent.exe). post-build copy command fails because of this. the way generate 'successful build' (includes post-build command) first close nunit, rebuild project , re-open nunit (wash, rinse , repeat). becoming tedious , frustrating. is there way force unit release handles onto loaded assemblies? have poked around nunit settings bit no avail. side note: other thoughts have had along lines of how using 3rd party dll ( it's c# swig version of quantlib). there may issues wrapper c# code , idisposable pattern used (based on comment received on question). you can use command line option tool unlocker release handles . or load pinvoke functions separate app domain , release domain. edit: in second case. when create appdomain , load assembly p/invokes domain, don't load assembly primary app domain. when testin...

python - Problem with MPICH2 & mpi4py Installation -

i'm on windows xp2 32-bit machine. i'm trying install mpich2 & mpi4py. i've downloaded & installed mpich2-1.2.1p1 i've downloaded & mpi4py when run python setup.py install in mpi4pi\ directory. get running install running build running build_py running build_ext mpi configuration: directory 'c:\program files\mpich2' mpi c compiler: not found mpi c++ compiler: not found mpi linker: not found checking mpi compile , link ... error: unable find vcvarsall.bat my c:\program files\mpich2\bin added in $path & contains: clog2toslog2.jar irlog2rlog.exe jumpshot.jar jumpshot_launcher.jar mpiexec.exe smpd.exe traceinput.dll tracetoslog2.jar wmpiconfig.exe wmpiexec.exe wmpiregister.exe i've googled no find solution. edit: per "high performance" mark's suggestion i've gone through installation script , found searching mpicc , mpicxx , mpild mpi compiler wrappers. these wrapper scripts not installed mpi...

sql - Can a Check constraint relate to another table? -

let´s have 1 table called projecttimespan (which haven´t, example!) containing columns startdate , enddate . and have table called subprojecttimespan , containing columns called startdate , enddate , set check constraint makes impossible set startdate , enddate values "outside" projecttimespan.startdate projecttimespan.enddate kind of check constraint knows another tables values... is possible? in response comment on gserg's answer, here's example check constraint using function: alter table yourtable add constraint chk_checkfunction check (dbo.checkfunction() = 1) where can define function like: create function dbo.checkfunction() returns int begin return (select 1) end the function allowed reference other tables.

iPhone does not receive UDP data over WiFi -

with wifi connection, udp data not received. stops at: recvfrom(sock, buf, recv_buf_size, 0, (sockaddr*)&raddr, (sock_len*)&len); when run same program in iphone simulator on ethernet works well. missing? look @ man page. like so: recvfrom(msock,recvbuff,1024,0,(struct sockaddr *)&from, &fromlen); providing parameter values setting correct try in case try: recvfrom(sock, buf, recv_buf_size, 0, (struct sockaddr *)&raddr, &len);

How to implement constructor wrapping in Java? -

this i'm trying (in java 1.6): public class foo { public foo() { bar b = new bar(); b.setsomedata(); b.dosomethingelse(); this(b); } public foo(bar b) { // ... } } compiler says: call must first statement in constructor is there workaround? you need implement this: public class foo { public foo() { this(makebar()); } public foo(bar b) { // ... } private static bar makebar() { bar b = new bar(); b.setsomedata(); b.dosomethingelse(); return b; } } the makebar method should static, since object corresponding this not available @ point calling method. by way, approach has advantage does pass initialized bar object foo(bar) . (@ronu notes approach not. of course means foo(bar) constructor cannot assume foo argument in final state. can problematical.) finally, agree static factory method alternative approach.

PHP: fopen() Permission denied -

i confused code: test.php: fopen('test.txt','a+'); when execute it, error: warning: fopen(test.txt): failed open stream: permission denied in /var/www/html/yuelu3/mobile/text.php on line 2 test.txt: -rwxrwxrwx. 1 jt jt 87 10月 7 20:58 test.txt where problem? thanks lot!i have found problem,i use fc13,because of protect of selinux,some action denied.so, need rid of protect. try fopen('/path/to/file/test.txt','a+'); as fopen('test.txt','a+'); is looking in directory

menuitem - ASP.Net Menu Control - Horizontal - Not Showing Sub Options -

i trying use asp:menu control. rather simple. want horizontal. each of first level items have sub items. can horizontal , when hover on instant reports or configurable reports choice seems pop down div or empty. have tried formatting , can think of find on internet. doing wrong? <asp:menu id="mnuchoices" runat="server" orientation="horizontal" datasourceid="dssitemap"> </asp:menu> <asp:sitemapdatasource id="dssitemap" runat="server" showstartingnode="false" /> here sitemap file. <?xml version="1.0" encoding="utf-8" ?> <sitemap xmlns="http://schemas.microsoft.com/aspnet/sitemap-file-1.0"> <sitemapnode url="" title="menuitems" description=""> <sitemapnode url="" title="instant reports" description=""> <sitemapnode url="" title="current system...

Django: Adding extra logic to the login method? -

i've got django app views use @login_required decorator. what's easiest/best way add logic login system? want add constraints such subscription site still valid. if has expired want direct them page says subscription has expired , they'll need pay again. ideally signal great, can't find kind of post_login signal. failing suppose options write own login handler, or have kind of check_valid_user() method call inside each of views. don't favour latter since dev forget add it, , users content free. what approach people recommend? thanks you can write own login view or better own authbackend(second example). from django.contrib.auth.views import login core_login #myapp/views.py @ratelimit_post(minutes = 1, requests = 4, key_field = 'username') def login(request,template_name): django.contrib.auth import authenticate user = authenticate(username='john', password='secret') template_name = "template_name...

Join multiple subrepos into one and preserve history in Mercurial -

currently have project consisting of multiple repositories, e.g.: +--- project (main repo) +--- core (subrepo) +--- web (subrepo) \--- tests (subrepo) unfortunately code between subrepos quite coupled doesn't work nicely branches. is there way consolidate subrepos 1 main repository preserving history? i start using hg convert filemap excludes .hgsub , subrepos. next, use hg convert on subrepos rename entries in filemap like: rename . core once have new repos, can use hg pull -f import changesets converted subrepos converted main repo 1 @ time. you'll need merge them new main repo (they form separate heads null revision recent common ancestor).

regex - mod_rewrite allow percentage sign in url -

i have rewrite rule rewriterule ^([a-za-z0-9\/\-\_]+)+$ .?p=$1 [l] but if have % sign in url, won't work. how modify rule work percentage sign? you can add % character class ( […] ). character class specifies group of characters successful matches. rewriterule ^([a-za-z0-9/_%-]+)$ .?p=$1 [l]

Is a 128MB PHP memory limit a lot? -

today added new feature in content management system i'm building. depending on uploading image to, php resize image fit designated location. works quite well, when try upload larger image, in 3mb image, i'm getting fatal error: fatal error: allowed memory size of 134217728 bytes exhausted (tried allocate 42520 bytes) in... i'm thinking 128mb of memory quite lot, considering don't run much... @ least don't think so. tried allocate 42520 bytes resizing process, failed. my question should (a) increase limit or (b) re-evaluate why i'm using memory in first place? 128mb number or large/too little? thanks, ryan resolution i concluded 128mb resizing image , focused @ looking @ other options... exec() options, never took closer @ "sample" data. turns out, though large image 2.83mb, on 10000px wide. that's problem. :) gd stores images bitmaps in memory, wouldn't rule out possibility jpg images (for example, high resolution, hi...

javascript - jQuery count how many divs with a class there are and put into string -

is there way in jquery count how many divs have , put number string <div class="name">some text</div> <div class="name">some other text</div> <div class="different">different text</div> so count divs class name , put string output this var strnodivs = 2 any ideas? thanks jamie var nb = $('div.name').length;

wpf - Start template animation as soon as control is loaded -

i have following code inside controltemplate : <eventtrigger routedevent="controltemplate.loaded"> <eventtrigger.enteractions> <beginstoryboard> and want start storyboard have defined in controltemplate, when control loaded. question is: in controltemplate rises loaded event? i can't use frameworkelement.loaded object target of animation aren't accessible when loaded event fired. p.s. controltemplate.loaded not working the controltemplate class has no loaded event. try using loaded or xxx.loaded xxx name of type of control templating, not controltemplate .

c# - Size of an object at runtime -

how size(in bytes) of object or data structure @ runtime, know there profiler tools interested in doing @ runtime. data structure list<object> i trying find out how space entire collection taking , how space individual object taking, not there should, in theory, difference between two. i think sizeof operator works value , unmanaged types; marshal.sizeof might give need.

In C# how can i use the || operand in an if statement where im looking for 2 files? -

i'm getting error "operator '||' cannot applied operands of type 'bool' , 'string'" when use below statement. if (file.exists(@"c:\file1.exe") || (@"c:\file2.exe")) { } how can this? thanks you had it... if (file.exists(@"c:\file1.exe") || file.exists(@"c:\file2.exe")) { //do } in if statement, if want use || need make sure treat them separate pieces of statement. in case, compiler have no way "guess" wanting know if file exists on right-hand statement, need explicit it. just if want check see if person's age less 20 greater 18, following: if (age < 20 && age > 18) {} you can't age < 20 || 18 because talking anything, not age. if wanted weight or height second check? c# won't able guess you.

c# - DataGrid in WPF 3.5 -

how add column datagrid in wpf? if you're talking programatically, can this: datagrid.columns.add(new datagridtextcolumn()); or xaml <datagrid height="148" horizontalalignment="left" margin="12,21,0,0" name="datagrid1" verticalalignment="top" width="225" /> you best served checking out tutorial on wpf datagrids . also, here's tutorial on how to add controls datagrid @ runtime

sql - How to fetch data from oracle database in hourly basis -

i have 1 table in database mytable, contents request coming other source. there 1 column in table time, stores date , time(e.g. 2010/07/10 01:21:43) when request received. want fetch data table on hourly basis each day. means want count of requests database receive in each hours of day. e.g.for 1 o'clock 2 o'clock count 50 ..like this.. run query @ end of day. requests received in day group each hour. can me in this. i want query take less time fetch data database size huge. any othre way omg ponies answer. use to_char function format datetime column, can group aggregate functions: select to_char(t.time, 'yyyy-mm-dd hh24') hourly, count(*) numperhour your_table t group to_char(t.time, 'yyyy-mm-dd hh24')

C++ whether a template type is a pointer or not -

possible duplicate: determine if type pointer in template function i looking method determine whether template pointer or not @ compiling time. because when t not pointer, program not compile cannot delete normal type variable. template <typename t> void delete(t &avar) { // if t point delete avar; avar = 0; // if t not point, nothing } basically, learning create link list(not using stl list) myself. , tried use template in list can take types. when type pointer, want delete (the keyword delete) automatically destructor. the problem is, writen above, when use int rather pointer of class in list, vc2010 wont compile because cannot delete none pointer variable. looking method, such macro deceide when delete avar should compiled or not according template type that handy utility, think it's better used assigning null after using native delete . to function considered modifiable pointer type arguments, use template< typenam...

soap - PHP Server was unable to process request -

this coding can 1 help: <?php class clswsseauth { private $username; private $password; private $meruser; private $merpass; function __construct($username, $password) { $this->username=$username; $this->password=$password; //$this->merhcantusername=$meruser; //$this->merhcantpassword=$merpass; } } /*class clswssetoken { private $usernametoken; function __construct ($innerval){ $this->usernametoken = $innerval; } }*/ ?> <!--step2: create soap variables username , password --> <?php include("lib/nusoap.php"); $username = $_request['usname']; $password = $_request['uspass']; $meruser = $_request['merusname']; $merpass = $_request['meruspass']; //check provider security name-space using. $strwssens = "http://localhost/royal_new/"; $o...

PHP get 31 days distance from starting date -

how can date after 31 days starting $startdate, $startdate string of format: yyyymmdd. thank you. strtotime give unix timestamp: $date = '20101007'; $newdate = strtotime($date.' + 31 days'); you can use date format same format, if that's need: echo date('ymd', $newdate);

Vim commands :Explore :Sexplore :Hexplore doesn't work in cygwin -

3.3 in cywing 2.721, installation made using cywing, every thing works when try use following command. :explore vim said e492: not editor command also neither :sexplore or :hexplore works. is there way activate functionality? this in machine windows xp. well solved reading the :help usr_01.txt it said necessary run command !cp -i $vimruntime/vimrc_example.vim ~/.vimrc inside vim, copy .vimrc home user. i close , opened vim , :explore, hexplore, vexplore worked.

Disable Drag & Drop of windows explorer using Delphi -

how can disable drag & drop item of windows explorer using delphi app ? want disable drag & drop user can,t drag file form windows explorer ... regards, mojtaba . i doubt there way application runs @ same security level user possibly control throughout whole system. it possible can controlled using os' group policy support. should search on ms' site information group policy. however, such fundamental feature of os, better approach may control can copied through acls on the files want restrict.

c - Implicit Type Conversion -

#include<stdio.h> int main(void) { signed int a=-1; unsigned int b=1; int c= a+b; printf("%d\n",c); return 0; } according rule of implicit type conversion, if 1 operand unsigned int ,the other converted unsigned int , result unsigned int in binary operation. here b unsigned int , a should type casted unsigned int .as unsigned int +ve , value of a 1.so c=1+1=2 .but output 0 .how ? -1, when cast unsigned become largest possible value type -- e.g. 32-bit unsigned, it'll 4,294,967,295. when add 1 that, value "wraps around" 0.

c++ - Overloading virtual functions in two different interfaces -

i have issue have interface has parts make sense templated, , parts make sense not-templated. i'm in middle of refactor i'm splitting out 2 different interfaces more specific (the templated one) inherits other one. e.g., have interface iarray , contain functions size() since doesn't care data type. i'd have interface itarray<datatype> have datatype getelement(...) . (this illustration, don't yell @ me use std::vector). reason i'm doing refactor there lot of consumers of non-templated interface , they'd not have write templated functions accept templated interface if don't need templated type (generally extern "c" stuff) the problem have overloaded functions appear in both interfaces, reason can't resolve base class functions. here's simple example put that's not compiling in msvc: #include <iostream> class ia { public: virtual void x()=0; }; template <class datatype> class ita : public ia...

c - Refresh a region in window before drawing text -

i'm drawing text on window @ wm_paint message, there way can refresh window region before drawing new line of text old text @ same location erased? you need call invalidaterect window berase parameter set true erase before wm_paint generated. this required when window static text control, don't erase automatically when change value. make sure window handling wm_erasebkgnd , window class doesn't have null background brush, mechanism used invalidaterect erasing.

Embedding images in a Rails Builder generated RSS feed -

i'm building rss feed rails application using builder (the wealth of tutorials out there doing way helped), become little bit stuck when comes adding image alongside (which has been uploaded via paperclip), lot of top publications do. i'm using make text appear should in reader: xml.description xml.cdata!page.description.gsub(/\n/, '<br />') end so how go including image in feed when display them in a @page.assets.each |asset| block. thanks.

iphone - Getting video to play in simulator -

so have alert view pop in application , on clicking view button video supposed play nothing happens in simulator. don't want test on device until working in simulator. code below far can tell should work. reaches log statement , outputs console video not play. ideas? -(void)alertview:(uialertview *)alertview clickedbuttonatindex: (nsinteger)buttonindex{ if (buttonindex == 1) { nsurl *url = [nsurl urlwithstring:@"http://srowley.co.uk/endyvid.mp4"]; mpmovieplayercontroller *player = [[[mpmovieplayercontroller alloc] initwithcontenturl:url] autorelease]; //---play movie--- [player setfullscreen:yes]; [self.view addsubview:[player view]]; nslog(@"player should play!"); [player play]; } } you need set frame on player's view. [[player view] setframe: [self.view bounds]];

objective c - Custom OSX window skin? -

how make custom buttons app window on osx? i'd skin entire window. are there easy classes or ways this? tutorials show how? if want deviate little standard os x interface, should take @ nsthemeframe , class draws standard os x windows. can read little bit here , , find out more using google.

ruby on rails - How to edit docx with nokogiri and rubyzip -

i'm using combination of rubyzip , nokogiri edit .docx file. i'm using rubyzip unzip .docx file , using nokogiri parse , change body of word/document.xml file ever time close rubyzip @ end corrupts file , can't open or repair it. unzip .docx file on desktop , check word/document.xml file , content updated changed other files messed up. me issue? here code: require 'rubygems' require 'zip/zip' require 'nokogiri' zip = zip::zipfile.open("test.docx") doc = zip.find_entry("word/document.xml") xml = nokogiri::xml.parse(doc.get_input_stream) wt = xml.root.xpath("//w:t", {"w" => "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}).first wt.content = "new text" zip.get_output_stream("word/document.xml") {|f| f << xml.to_s} zip.close i ran same corruption problem rubyzip last night. solved copying new zip file, replacing files neces...

asp.net mvc - How can i recreate a spreadsheet or sharepoint datasheet view on a website? -

Image
i trying migrate users off of sharepoint solution website + sql backend. 1 thing seems sharepoint view , data sheet view editing , managing information. what best spreadsheet / access data editing solution. there third party asp.net mvc widgets alternatives telerik's grid mvc supposed good, may want consider alternative traditional grid ui experience. the mvc paradigm not explicitly define how should things- that's 1 of it's many strengths. encourage users directions: testing; maintainability; separation of concerns (logical isolation); design patterns; user experience; user centered design; etc, etc. in mind there alternative grid may able use? repeating elements? in line editing (think facebook comments)? don't show items, top 10 relevant user? live search filter without options? maybe can create better experience users without grid, , you're going use mvc, best time it. see how easy turn sad looking ..into happy keys ideas: remo...

SWF to HTML5 or iPad compatible format -

is there swf html5 converter or format can run on ipad? not smokescreen... other alternatives.......? thanks! you can't directly convert swf html5. there not straightforward 1-to-1 relationship @ all. different beasts. depending on in swf, may able rebuild html5 , javascript, haven't listed project does.

php - Uploading files with jquery's .post -

i have form uploads file's perfectly, post-page-refresh-form. however have ajaxiefied form jquery's $.post all of data except file upload saving nicely. is there somthing special need form or in jquery upload work? thanks! you cannot upload javascript (it mean granting js file access on computer, no go security standpoint). uploadify has nice solution.

javascript - Confirmation before deleting (jquery) -

i show simple confirmation dialog box show before running delete function. here have far html: <!-- delete confirmation dialog box --> <div id="confirm" style="display:none;"> <div class="message">are sure want delete?</div> <div class="buttons"> <div class="cancel">no</div><div class="accept">yes</div> </div> </div> <!-- delete button/s --> <a href="javascript:void(0);" onclick="delete("1")"><img src="images/48x_delete.png" alt="48x_delete" width="24" height="24"/></a> <a href="javascript:void(0);" onclick="delete("2")"><img src="images/48x_delete.png" alt="48x_delete" width="24" height="24"/></a> ...etc... jquery: function delete(id) { filen...

Is appengine Python datastore query much (>3x) slower than Java? -

i've been investigating appengine see if can use project , while trying choose between python , java, ran surprising difference in datastore query performance: medium large datastore queries more 3 times slower in python in java. my question is: performance difference datastore queries (python 3x slower java) normal, or doing wrong in python code that's messing numbers? my entity looks this: person firstname (length 8) lastname (length 8) address (20) city (10) state (2) zip (5) i populate datastore 2000 person records, each field length noted here, filled random data , no fields indexed (just inserts go faster). i query 1k person records python (no filters, no ordering): q = datastore.query("person") objects = list(q.get(1000)) and 1k person records java (likewise no filters, no ordering): datastoreservice ds = datastoreservicefactory.getdatastoreservice(); query q = new query("person"); preparedquery pq = ds.prepare(q); // force query...

c# - Problem in generating random number -

possible duplicate: why appear random number generator isn't random in c#? dear friends i want generate 4 random number between 1 - 55 ,but problem of time receive 2 number same :( example generated number 2 2 5 9 or 11 11 22 22! dont know why? use : random random = new random(); return random.next(min, max); for generating random number. put them in while repeating 4 times. idea?would u me plz? you should create 1 random() object , reuse instead of creating new 1 each random number generate. the reason every time create new random object seeds current time. if create multiple random objects within short period of time then seed same time, , generate same numbers.

encryption - Using OpenSSL and PHP to store data? -

for 1 of roles, i've been receiving couple of documents people via email. it's non-sensitive data email fine, i'd make small portal people can upload files , when submit files required notification request complete. regardless of content, i'd store documents securely. it's got me thinking encryption in general other needs. looked @ aes encryption in mysql general consensus no key readily available in server. got me thinking public/private key encryption. here's plan i'm researching see if work or if it's been done , can't find standard implementation: i generate public/private key pair. public key goes web server, private key stays me @ computer. user uploads file via webpage web server through https site. upload script takes file, encrypts public key, , stores in file system or database. upon completion, notified , connect server , download files via ssh or other encrypted connection. finally, locally decrypt files using private key ,...

what physical android device you use for testing purpose? -

Image
any recommendation of physical android device testing purpose? i looking device ipod touch in apple camp ios developer test stuff. know there nexus one, thing pretty expensive , don't care phone stuff, can let developers test accelerometer, touch screen, orientation etc. any idea? you try the official android unlocked dev phones but really, you'll want try consumer-grade phone 2.2 , 1.6, because 2 main 'camps' believe in terms of compatibility. devices can run 2.1 able run 2.2, , update, lot of devices running 1.6 won't ever upgrades imo. , 1.5 requires lot of hacks things compatible newer standards. here's official historical distrubution of android versions

Scala, JPA & nullable fields -

in trying use scala jpa, have following snippet part of definition of entity @column(name = "acc_int", nullable = true) @beanproperty var accint: double = _ all fine until retrieve data , following exception: org.springframework.orm.hibernate3.hibernatesystemexception: null value assigned property of primitive type setter of com.jim.fi.sppa.riskdata.accint; nested exception org.hibernate.propertyaccessexception: null value assigned property of primitive type setter of com.jim.fi.sppa.riskdata.accint .... caused by: org.hibernate.propertyaccessexception: null value assigned property of primitive type setter of com.jim.fi.sppa.riskdata.accint @ ... caused by: java.lang.illegalargumentexception: can not set double field com.jim.fi..sppa.riskdata.accint null value i think going on here -- scala trying treat double double, i'm not sure how around it. double in scala double , primitive type. wrapper type refer java.lang.double .

php - What's the best technique to build scalable (extensible), maintainable, and loosely coupled software? -

i have been playing around concept of 'module' mvc frameworks implement , seems solution, , tdd, think there must more, design pattern missed (i know few), let me build applications can grow (in code) no limits. any thoughts? edit : thing modules can built in way application-independent, can reused. in "facts , fallacies of software engineering," robert l. glass says: fact 15. reuse-in-the-small well-solved problem. fact 16. reuse-in-the-large remains unsolved problem. fact 17. reuse-in-the-large works best in families of related systems. in other words, can reuse modules, between applications work similarly. trying make modules versatile can resuse them in any application hard. end making modules configurable they're overly complex use, , contain lots of code handle scenarios of no use given application. you'd better off coding custom module each application, each application needs, , no more. important language php,...

java - Youtube Direct API: Could not retrieve YouTube upload token: 400 -

i got error when using youtube direct: ( link ) when try upload video youtube. "could not retrieve youtube upload token: 400: upload token returned youtube api null. please make sure request parameters valid." its hosted on appspot. app authenticated , developer key provided. did had same problem? edit: seems script dosnt post sessionid "post /getuploadtoken?sessionid=undefined http/1.1" in debug log warning: <?xml version='1.0' encoding='utf-8'?> <errors><error><domain>yt:validation</domain> <code>too_short</code> <location type='xpath'>media:group/media:keywords/text() </location></error></errors> stupid error. youtube requires "video title","video description" , "tags". need @ least 2 characters long.i putting one.

objective c - Broadcast data bytes through iPhone app -

i want broadcast data bytes in particular wifi range through iphone app...so every receiver in particular range receive bytes. new concept. is there sample app? thanks in advance... this class interesting doing socket in objective-c, either udp or tcp : http://code.google.com/p/cocoaasyncsocket/

storekit - iphone in-app purchase: On error, whose responsibility is notifying the user? -

i have complete in app purchase solution wondering if handling errors correctly. handle errors using code similar apple example here; - (void) failedtransaction: (skpaymenttransaction *)transaction { if (transaction.error.code != skerrorpaymentcancelled) { // optionally, display error here. } [[skpaymentqueue defaultqueue] finishtransaction: transaction]; } but question - storekit display relevant errors user (unable connect, payment declined etc) or need handle this? seems testing when storekit working ok, indeed handle errors itself, can silently dump them (well, in fact log them on server). however when storekit sandbox playing up, random errors indicate problem, , no alerts storekit itself. what guys errors? alert user or end duplicating alerts storekit has given. thanks roger it app's responsibility handle errors. the os doesn't display message because message display, or whether display 1 @ (as opposed to, say, removing item ta...

android - How to remove focus from single editText -

possible duplicate: stop edittext gaining focus @ activity startup? in application have single edittext textviews, button , spinner. edittext receives focus since focusable view in activity, believe. edittext shows orange border , cursor on field. remove focus field (i don't want cursor , border show). there way this? have been able focus on button doing button.sefocusableintouchmode() , button.requestfocus(). highlights button , not want. check question , selected answer: stop edittext gaining focus @ activity startup it's ugly works, , far know there's no better solution.

camera.setParameters failed in android -

i have included camera functionality in application. have launched app in market. got error message 1 of users getting error while opening camera. i have tested app on device on 2.1. error got user using nexus 1 run 2.2...here's logcat error i've received... java.lang.runtimeexception: setparameters failed @ android.hardware.camera.native_setparameters(native method) @ android.hardware.camera.setparameters(camera.java:647) @ com.cameraapp.preview.surfacechanged(preview.java:67) @ android.view.surfaceview.updatewindow(surfaceview.java:538) @ android.view.surfaceview.dispatchdraw(surfaceview.java:339) @ android.view.viewgroup.drawchild(viewgroup.java:1638) @ android.view.viewgroup.dispatchdraw(viewgroup.java:1367) @ android.view.viewgroup.drawchild(viewgroup.java:1638) @ android.view.viewgroup.dispatchdraw(viewgroup.java:1367) @ android.view.viewgroup.drawchild(viewgroup.java:1638) @ android.view.viewgroup.dispatchdraw(viewgroup.java:1367) @ android.view.view.draw(view.ja...

validation - jquery validate with multiple rules -

how validate email address field 3 rules 3 customized messages in div container. ie. rules: { email: { validationrule: true, email: true, remote: '/ajax/emailduplicationcheck.php' } } if first 1 false message should "validation rule failed" if second 1 false(fail) "enter email address" if third(remote) failed. message should "account exist in database". i can added 1 message rules want customize message respect rules. try this: $("#myform").validate({ // replace #myform id of form rules: { email: { required: true, email: true, remote: { url: "/ajax/emailduplicationcheck.php", type: "post", data: { email: function() { return $("#email").val(); // add #email id email field } } } }, message...

android - how to insert xml file into sql lite database -

i have problem android application in application have use sql lite database have data in xml format. facing problems in inserting data database. just go through link answer inserting , storing xml data how store parsed xml file sqlite database in android?

c - How to ensure that when my process is operating on a file, no other process tries to write to it or delete it? -

if process trying read file, how ensure code (c language) no other process either writes or deletes (include system commands deleting file)? also, can achieved on os (windows, linux, solaris, hp-ux, vxworks etc)? edit: i'll answer unix/linux as gspr , others said, take @ file locking using fcntl , flock , etc. however, warned advisory locking methods. what mean? means can warn other processes accesing file, or portion of it, you can't forcibly keep them ignoring , writing on file . there no compulsory locking primitives. can use permissions advantage, you'll never have full guarantees -- root user can override limitations. don't think there's way work around that.

sql server - Shared Data Sources vs. OLE DB Connections In SSIS -

i've been using shared data sources in of ssis projects because thought "best practice". however, under source control (tfs) every time open package updates data source connection in package. either have roll change or check in nonsense description. i saw ssis best practice blog entry , got me thinking whether shared data sources way go. don’t use data sources: no, don't mean data source components. mean .ds files can add ssis projects in visual studio in "data sources" node there in every ssis project create. remember data sources not feature of ssis - feature of visual studio, , significant difference. instead, use package configurations store connection string connection managers in packages. best road forward smooth deployment story, whereas using data sources dead-end road. nowhere. what experiences data sources, configuration , source control? we use svn, doesn't integrate in same way tfs do...

c++ - '<function-style-cast>' : cannot convert from 'int' to 'CString' -

this code written in visual studio 2003, compile in 2008. int afxapi afxmessagebox(lpctstr lpsztext, uint ntype = mb_ok, uint nidhelp = 0); if(iirecd == socket_error || iirecd == 0) { ierr = ::getlasterror(); afxmessagebox(cstring(ierr)); goto prereturncleanup; } in 2003, works fine, in 2008, shows me error: error 50 error c2440: '<function-style-cast>' : cannot convert 'int' 'cstring' what error mean? it's bit hard without information, erroneous code , want there. here's guess: want convert int cstring , somehow this: int = 42; cstring str = (cstring)i; if you're using mfc/atl cstring try following int = 42; cstring str; str.format("%d", i); cstring::format takes format string printf , stores result in cstring. edit i'm interpreting comment below code causes error. bit surrounding text , explanation nice, though. if(iirecd == socket_error || iirecd == 0) { ierr = ::getlaster...

How to make a plain text-only Silverlight button? -

i want button no background or other plain text. have done following , button not show @ all: <usercontrol.resources> <controltemplate x:key="linkbuttons" targettype="button"> <textblock foreground="white" fontsize="28" fontfamily="verdana" padding="10"></textblock> </controltemplate> </usercontrol.resources> <button template="{staticresource linkbuttons}" content="hello world!"/> the problem button designed have content, not text - it's kind of contentcontrol. so, display content, template should have in it: <contentpresenter x:name="contentpresenter" content="{templatebinding content}" contenttemplate="{templatebinding contenttemplate}" verticalalignment="{templatebinding verticalcontentalignment}" horizontalalignment="{templatebinding horizontalcontentalign...

geolocation - CCLocation (iPhone SDK) accuracy -

how accurate cclocation class? 20 meters? more or less? because i'd accurate values user's location. thanks, regards you can request accuracy desired using desiredaccuracy property of cllocationmanager . actual accuracy delivered depends on other factors outside control including whether device using gps, cell tower, or wifi.

sql - How to update one table from another one without specifying column names? -

i have 2 tables identical structure , large number of fields (about 1000). need perform 2 operations 1) insert second table rows fist. example: insert [1607348182] select * _tmp_1607348182; 2) update first table second table update can't found proper sql syntax update. queries like: update [1607348182] set [1607348182].* = tmp.* [1607348182] inner join _tmp_1607348182 tmp on tmp.recordid = [1607348182].recordid or update [1607348182] [1607348182] inner join _tmp_1607348182 tmp on tmp.recordid = [1607348182].recordid are invalid. not sure if you'll able accomplish without using dynamic sql build out update statement in variable. this statement return list of columns based on table name put in: select name syscolumns [id] = (select [id] sysobjects name = 'tablename') not sure if can avoid loop here....you'll need load results above cursor , build query it. psuedo coded: set @query = 'update [1607348182] set ' load cursor ...

How can the block size of a file store be portably obtained in Java 7? -

i've looked @ java.nio.file.attribute.attributes , java.nio.file.filestore , couldn't find way discover block-size of disk-file. here article on buffer size vs i/o throughput. synopsis: nio handles of you. so post concludes should use power of 2.

javascript - How to prevent users from clicking multiple times on a linked image? -

i have page linked image, link takes bit of time load. therefore, users tend click multiple times on it. causes errors crop in code. how prevent users clicking on link more once? in attempt remedy this, changed link onclick event , in function used code: $('#myimageid').unbind('click'); window.location.href = "mylink"; however, doesn't seem helping. also, i'd prefer keep simple linked image instead of using javascript. once solution add class element used flag determine of code should run. here's example: http://jsfiddle.net/qlhr8/ $('#myimageid').click(function() { var $th = $(this); if( !$th.hasclass( "pending" ) ) { // add "pending" class, subsequent clicks not // run code inside if() $th.addclass( "pending" ); window.location.href = "mylink"; // settimeout remove class // if new page never loads } }); with add...

java - Handle key presses using draw2d and swt -

every org.eclipse.draw2d.figure class has addkeylistener() method. when key presses not every figure handle it. kind of figure handles key-events? thanks. hm. don't know real answer. variant - add listener shell , handle in specific way.

java - Is there an image design community that collaborates with developers to create applications with a better and more polished look and feel? -

so after lot of hard (and fun) work in development i’ve gotten close end of application development..or thought. i’m developing game android (but that’s irrelevant post). until now, images/drawables using placeholders took 5 minutes in mspaint create. so, have working game, started trying create visually stimulating game interface. in doing so, have come realize tough, since have virtually 0 experience in image design. ultimately, i’m questioning ability of game successful without polished game interface feel users expect nowadays. are there individuals willing collaborate on application? there community of designers content work , in return receive name attached application? sunk unless want fork on pretty penny designer? options have , can go put “illustrations in book” speak? thanks. is there community of designers content work , in return receive name attached application just looking @ sentence should send off bells in head. if there expert @ doing ...

iphone - Assets Library Framework on iPad -

is there possibilities use assets library framework on ipad? know framework of ios4 , higher, need use in ipad application. no, you'll have code ios4.2 on ipad, coming year. should able install on test device.

Django reverse routing - solution to case where reverse routing is less specific than forward routing -

i have route defined follows: (r'^edit/(\d+)/$', 'app.path.edit') i want use reverse function follows: url = reverse('app.path.edit', args=('-id-',)) the generated url gets passed js function, , client side code replace '-id-' correct numeric id. of course won't work, because 'reverse' function won't match route, because url defined containing numeric argument. i can change route accept type of argument follows, loose specificity: (r'^edit/(.+)/$', 'app.path.edit' i create separate url each item being displayed, i'll displaying many items in list, seems waste of bandwidth include full url each item. is there better strategy accomplish want do? you can rewrite regexp this: (r'^edit/(\d+|-id-)/$', 'app.path.edit') but prefer this: (r'^edit/([^/]+)/$', 'app.path.edit') # can still differ "edit/11/" , "edit/11/param/" usually a...