Posts

Showing posts from February, 2015

java - Acquire a lock on a file -

i want acqeuire lock on file when threo read gets started on specific file ,so no other application can read file has been locked , want release lock file when thread terminates. you can acquire filelock via filechannel . obtain filechannel: in release file channel can obtained existing fileinputstream , fileoutputstream , or randomaccessfile object invoking object's getchannel method, returns file channel connected same underlying file. however, java doesn't have control on type of file locking os offers , therefore recommendation of api use lock if advisory file lock. whether or not lock prevents program accessing content of locked region system-dependent , therefore unspecified. native file-locking facilities of systems merely advisory, meaning programs must cooperatively observe known locking protocol in order guarantee data integrity. on other systems native file locks mandatory, meaning if 1 program locks region of file other programs prevente...

solaris - What is your experience with Sun CoolThreads technology? -

my project has money spend before end of fiscal year , considering replacing sun-fire-v490 server we've had few years. 1 option looking @ coolthreads technology. know sun marketing, may not 100% unbiased. has played 1 of these? i suspect no value us, since don't use threads or virtual machines , can't spend lot of time retrofitting code. spawn ton of processes, doubt coolthreads of there. (and yes, money better spent on bonuses or something, that's not going happen.) disclosure: work sun (but engineer in client software). you don't necesarily need multithreaded code make use of these machines. having multiple processes make use of multiple hardware threads on multiple cores. the old t1 processors (t1000 , t2000 boxes) did have single fpu, , weren't suitable tasks more 1% floating point. newer t2 , t2+ processors have fpu per core. that's still not great massive floating point crunching, more respectable. (note: hyper-threading te...

Read large xml file and extract it's data into a form application in C#.Net project -

i want read xml file data , extract information show in form in c#.net vs2008 env. can't read data list in memory, want have .exe file project can run in computer system. think, can't use database saving , retrieving data! please me solve problem! use system.xml.xmlreader read xml file. forward reader loads bit of xml @ time. combine iterator method produces ienumerable, such example, myxmldata class representing held in xml file , class forms can work with: public ienumerable<myxmldata> queryfile(string xmlfile) { using (var reader = xmlreader.create(xmlfile)) { // these variables want read each 'object' in // xml file. var prop1 = string.empty; var prop2 = 0; var prop3 = datetime.today; while (reader.read()) { // here you'll have read xml node @ time. // read, assign appropriate values variables // declared above. if (/* have fi...

perl - best way to write code to compile with strict -

what best way check arguments provided subroutines compile strict ( solution works there better way of doing ? ) i have large old library, want correct code can add use strict; it, of error (on page load generates 189 errors): use of uninitialized value in string eq @ ../lib/cgilibtest.pl line 1510 use of uninitialized value in concatenation (.) or string @ ../lib/cgilibtest.pl line 1511. they generated subroutines writen this: #!/usr/bin/perl -w sub example() { $var1 = shift @_; $var2 = shift @_; $var3 = shift @_; if($var2 eq ""){var2 = "something";} # line generates first type of error beacause $var2 not defined return "var1 = ".$var1.", var2 = ".$var2.", var3 = ".$var3; # line generates second type of error, beacause $var3 not defined } print "content-type: text/html\n\n"; $somevar = &example("firstvar"); print $somevar; my solution use ternary operator , write them as: #!/u...

bug tracking - Bug template in Bugzilla -

is there way enforce template in bugzilla guide users fill in bugs descriptions ? actually, i'd put markup texts in bug description field , avoid creation of custom fields. i've installed version 3.2rc1. indeed, check ../enter_bug.cgi?format=guided , forms example of template feature. half work done you.

iphone - iVars, With and Without self? -

i curious role self plays within object. understand writing [[self datafortable] count] refers directly ivar contained in object. if miss self off , directly specify ivar [datatable count] how differ, protecting against using self, uniquely specify ivar rather maybe similar local variable? @implementation viewcontroller @synthesize datafortable; ... nsuinteger datacount = [[self datafortable] count]; much appreciated gary. writing [[self datafortable] count] does not refer directly ivar. there's behind-the-scenes stuff going on... if use ivar in code without self, that's direct access ivar. if use either [self someivarname] or self.someivarname, you're sending message object (which self). runtime attempts resolve message , use 1 of number of mechanisms: if have defined method matching name, method used, if no such method (or property) exists, key-value-coding use identically named ivar default. as impact, differ based on code. example if prop...

Which environment, IDE or interpreter to put in practice Scheme? -

i've been making way through the little schemer , wondering environment, ide or interpreter best use in order test of scheme code jot down myself. racket ( formerly dr scheme ) has nice editor, several different scheme dialects, attempt @ visual debugging, lots of libraries, , can run on platforms. has modes geared around learning language.

objective c - NSManagedObjectContext: autoupdate or not? -

i need understand nsmanagedobjectcontext update. have uisplitview uitableviewcontroller on rootview , uiviewcontroller on detail view. when tap in row data, load data labels , uitextview can update field: - (void)textviewdidendediting:(uitextview *)textview { nsindexpath *indexpath = [self.tableview indexpathforselectedrow]; [[listofadventures objectatindex:indexpath.row] setadventuredescription:textview.text]; } ok. works correctly, description updated. also, might wants delete row: - (void)tableview:(uitableview *)tableview commiteditingstyle:(uitableviewcelleditingstyle)editingstyle forrowatindexpath:(nsindexpath *)indexpath { if (editingstyle == uitableviewcelleditingstyledelete) { nspredicate *predicate = [nspredicate predicatewithformat:@"playerplaysadventure.adventurename==%@",[[listofadventures objectatindex:indexpath.row] adventurename]]; nsarray *results = [[adventurefetcher sharedinstance] fetchmanagedobjectsforentity:@"player" withpred...

Serialize a .net Object directly to a NetworkStream using Json.net -

is there way have json.net serialize object directly networkstream? in other words, have json.net send serialized result network serializes object (in streaming fashion). i avoid having serialize object memory , send via networkstream. any thoughts? regards you can create textwriter on top of networkstream , , serialize textwriter ; or can create jsontextwriter on top of textwriter , serialize that. you don't need serialize to, say, temporary string or byte array first.

jquery - cant get values to keep adding to input -

i have issue hope can me with. i'm able retrieve text value of checkbox. want achieve every time click on checkbox, adds text input id of "selected". example: if checkbox a, checkbox b, checkbox c checked, want show "a, b, c". instead i'm getting text of current 1 checked. great. $(document).ready(function(){ $("#listbox input").click(function() { var cbtext = $(this).next().text(); $('#selected').val(cbtext); }); }); it sounds want #selected have text values selected checkboxes. if that's right, try this : http://jsfiddle.net/naacw/4/ (updated) $(document).ready(function(){ $("#listbox input").click(function() { var cbtext = $('#listbox').find(':checked').next() .map(function() { return $.text([this]); }).get().join(', '); $('#selected').val(cbtext); }); });​ e...

ide - How to remotely develop software? -

suppose have server runs on linux on develop software (mainly ocaml, c/c++ , java). is there way "remote develop" these things? mean ide allows me modify files remotely (they uploaded when modified , saved) , compile through ssh (basically invoking make or omake ). i looking makes process transparent developer, without caring of doing things hand. i'm used use eclipse wonder if plugin achieve exists or if there other choices? mind may happen local machine not able build software intend (for example ocaml) should rely on remote connection. thanks in advance i think answer ide-centric. kde's ioslaves support access on both sftp , ssh (using fish, uses perl script uploaded remote machine). believe gnome has virtual file system (gvfs) supports remote filesystem access. my recommendation, therefore, choose ide supports virtual filesystem can operate on ssh/sftp , allows specify build command. need specify build command output remote make command (...

this operator in javascript -

suppose have javascript code myclass = function(){ function dosomething(){ alert(this); // this1 } } alert(this); //this2 what 2 'this' objects refer for?? the this value in global execution context, refers global object, e.g.: this === window; // true for function code, depends on how invoke function, example, this value implicitly set when: calling function no base object reference : myfunc(); the this value refer global object. calling function bound property of object : obj.method(); the this value refer obj . using new operator : new myfunc(); the this value refer newly created object inherits myfunc.prototype . also, can set explicitly value when invoke function, using either call or apply methods, example: function test(arg) { alert(this + arg); } test.call("hello", " world!"); // alert "hello world!" the difference between call , a...

wpf - Recommend best approach in this situation -

i'm experimenting mvvm , can't quite wrap mind around it. i have view (windows) has several repeated controls. let's have 4 textbox - button pairs. behavior should same, after pressing button paired textbox says "hello world!" i have tried several options think of: one viewmodel, 4 string properties binded textboxes, 1 command when bind each button same command can't tell property needs set. passing enum commandparameter feels awkward. one viewmodel , usercontrol hosts textbox , button repeated 4 times. now need expose properties command, commandparameter, text etc.. seems lot of work. still can't property needs updated after click. each usercontrol has viewmodel this solves button clicking , setting property, have no clue how extract texts nested viewmodels window viewmodel. is there other way? suspect datatemplates of use, i'm not sure how. what describe such abstract , contrived idea doesn't warrant mvvm. y...

.net - What is function of each file in a simple C# project? -

i want ask files found in folder of simple c# project . (.pdb file , .vshost file , .manifest file ) in bin folder ( .csproj.filelistabsolute.txt file , .pdb file ) in debug folder (assemblyinfo.cs ) in properties folder what function of each file of them ? and of them in msil , if there no file of them in language how can file in msil ? another question : specific part converts c# code msil ?? , c# compiler ? there specific name ? technically, pdb, vshost, , manifest file are not part of c# project , part of output generated when build project. the pdb file contains symbol information used debugger associate code within assembly sources files. allows debugger identify line of source code corresponds set of instruction in msil of assembly. the vshost.exe file hosting process visual studio generates helps accelerate debugging of application. caches app domain process reduce startup time debugger. the manifest file contains information assemblies in pr...

[iPhone]How would you design Core Data Object Model for the given below structure -

json dictionary { headers = ( { backgroundimageurl = ""; datafield = name; headertext = name; id = name; itemrenderer = ""; tooltip = ""; width = 60; }, { backgroundimageurl = ""; datafield = bidprice; headertext = bid; id = bidprice; itemrenderer = ""; tooltip = "bid price"; width = 30; }, { backgroundimageurl = ""; datafield = askprice; headertext = ask; id = askprice; itemrenderer = ""; tooltip = "ask price"; width = 30; }, { backgroundimageurl = ""; datafield = pricechg; headertext = chg...

c++ - Stream Operator Overloading -

why should overloading of stream operators(<<,>>) kept friends rather making them members of class? when overload binary operator member function of class overload used when first operand of class type. for stream operators, first operand stream , not (usually) custom class. for reason overloaded stream operators custom classes designed used in conventional manner can't member functions of custom class, must free functions. (i'm assuming stream classes not open changed; if add member functions stream classes cope additional custom types undesirable dependency point of view.) whether or not friends should depend on whether need access non-public members of class.

.net - What are the best practices for using Assembly Attributes? -

i have solution multiple project. trying optimize assemblyinfo.cs files linking 1 solution wide assembly info file. best practices doing this? attributes should in solution wide file , project/assembly specific? edit: if interested there follow question what differences between assemblyversion, assemblyfileversion , assemblyinformationalversion? we're using global file called globalassemblyinfo.cs , local 1 called assemblyinfo.cs. global file contains following attributes: [assembly: assemblyproduct("your product name")] [assembly: assemblycompany("your company")] [assembly: assemblycopyright("copyright © 2008 ...")] [assembly: assemblytrademark("your trademark - if applicable")] #if debug [assembly: assemblyconfiguration("debug")] #else [assembly: assemblyconfiguration("release")] #endif [assembly: assemblyversion("this set build process")] [assembly: assemblyfileversion("th...

How do I write Facebook apps in Java? -

i have looked in vain example or starting point write java based facebook application... hoping here know of one. well, hear facebook no longer support java api true , if yes mean should no longer use java write facebook apps?? there's community project intended keep facebook java api date, using old official facebook code starting point. you can find here along getting started guide , few bits of sample code.

linux - Easy way of installing Eclipse plugins on Ubuntu -

i'm running eclipse (versions 3.6 , 3.5) on ubuntu , i'm having trouble installing eclipse plugins. there easy way install eclipse plugins in eclipse , doesn't work me on ubuntu! way works under windows , mac osx. just in tutorial, create folder inside eclipse sdk folder named links . in folder, create file eclipse-cpp-helios-linux-gtk.lnk or eclipse-cpp-helios-linux-gtk.link contains line: path=/home/taher/opt/eclipse/third-party-eclipse-links/eclipse-cpp-helios-linux-gtk and save it, when start eclipse doesn't recognize plugin! how can resolve problem? with eclipse galileo (3.5) or helios (3.6), rather recommend external directory called 'mydropins' (for instance), can reference eclipse.ini , option: -dorg.eclipse.equinox.p2.reconciler.dropins.directory=c:/prog/java/eclipse_addons this called shared dropins folder . see in so answer example of plugin deployment in shared dropins folder. (your link refers previous provisionin...

mysql - reload a .sql schema without restarting mysqld -

is possible reload schema file without having restart mysqld? working in 1 db in sea of many , have changes refreshed without doing cold-restart. when "reload schema file", assume you're referring file has sql statements defining database schema? i.e. creating tables , views , stored procecures , etc.? the solution simple - keep file sql creates tables , etc. in file, , before create statements, add delete/drop statement remove what's there. when want reload, do: cat myschemafile.sql | mysql -u userid -p databasename

mysql - Grouping by X days -

i have database shows me different stats different campaigns, each row has timestamp value name "date". i wrote code choosing , summarizing range of dates, example: 21-24/07/2010. need add option choose range of dates, group stats each x days. let's user chooses see stats month: 01/07-31/07. present him stats grouped x days, let's 3, see stats 01-03/07, 04-06/07,07-09/07 , on... i managed doing using code: select t1.camp_id,from_days( floor( to_days( date ) /3 ) *3 ) 'first_date' facebook_stats t1 inner join facebook_to_campaigns t2 on t1.camp_id = t2.facebook_camp_id date between 20100717000000 , 20100724235959 group from_days( floor( to_days( date ) /3 ) *3 ) , t2.camp_id it group (by 3 days), problem reason starts 16/07, , not 17/07, grouping each time 3 days @ time. would love hear solution code or gave, or better solution have in mind. to_days returns number of days since year 0. when divide 3, considers quotient , not remainder...

Segmentation Fault in rvm'd Ruby on Mac when running RSpec -

i developing @ uni, saved dropbox intending continue @ home. message greeted me: $ spec graph_spec.rb /users/amadan/.rvm/gems/ruby-1.9.2-rc1/gems/priorityqueue-0.1.2/ext/priority_queue/cpriorityqueue.bundle: [bug] segmentation fault ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0] however, $ `which spec` graph_spec.rb ........................................................................... finished in 0.046973 seconds 75 examples, 0 failures what heck going on here? for reference: $ spec /users/amadan/.rvm/gems/ruby-1.9.2-rc1/bin/spec update: noticed 1.8.7 there... how did there? top of spec file says: $ head `which spec` #!/users/amadan/.rvm/rubies/ruby-1.9.2-rc1/bin/ruby # # file generated rubygems. # # application 'rspec' installed part of gem, , # file here facilitate running it. # require 'rubygems' where "run 1.8.7"?!? it's rvm messing gems , rubies. recommend testing on cleaned rvm installation (wi...

php class static variables ,concat -

is have 2 class first <?php require_once( 'error/disconnectedhandler.php' ); require_once( 'error/nosuchrequesthandler.php' ); class networkmanager { public static final $response_jump = 1000; .... second <?php require_once( '../networkmanager.php' ); class disconnectedhandler implements handler{ public static $type = 2000; public static $response_type = self::$type + networkmanager::$response_jump; public static $ver = 0; i error in line public static $response_type = self::$type + networkmanager::$response_jump; eclipse ide paint $type in red , says multiple annotations found @ line: - syntax error, unexpected '$type', expecting 'identifier' - syntax error, unexpected '$type', expecting 'identifier' what correct syntax ? thank in advanced static variable declarations (as class constants) must literally defined , cannot co...

unix - How do I get the find command to print out the file size with the file name? -

if issue find command follows: $ find . -name *.ear it prints out: ./dir1/dir2/earfile1.ear ./dir1/dir2/earfile2.ear ./dir1/dir3/earfile1.ear what want 'print' command line name , size: ./dir1/dir2/earfile1.ear 5000 kb ./dir1/dir2/earfile2.ear 5400 kb ./dir1/dir3/earfile1.ear 5400 kb find . -name '*.ear' -exec ls -lh {} \; just h jer.drab.org's reply. saves time converting mb mentally ;)

python - How to import a module given the full path? -

how can load python module given full path? note file can anywhere in filesystem, configuration option. for python 3.5+ use: import importlib.util spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py") foo = importlib.util.module_from_spec(spec) spec.loader.exec_module(foo) foo.myclass() for python 3.3 , 3.4 use: from importlib.machinery import sourcefileloader foo = sourcefileloader("module.name", "/path/to/file.py").load_module() foo.myclass() (although has been deprecated in python 3.4.) python 2 use: import imp foo = imp.load_source('module.name', '/path/to/file.py') foo.myclass() there equivalent convenience functions compiled python files , dlls. see also. http://bugs.python.org/issue21436 .

algorithm - Interview: lists intersection with limited memory -

you given 2 sets of integers, sizes m , n m < n. perform inner equal join on these 2 sets (i.e., find intersection of 2 lists). how perform if both lists in files , available memory of size k < m < n using in-place sorting algorithm sort both lists first. once both m n sorted, calculating intersection race. place 2 markers a , b @ beginning of each list. these steps until marker reaches end of list. in pseudocode: until > m.size or b > n.size if m[a] < n[b] a++ continue if n[b] < m[a] b++ continue print m[a] // common element // advance both indexes avoid infinite loop a++ b++ given decent in-place sorting algorithm, complexity of o(nlogn) .

How can I execute Javascript before a JSF <h:commandLink> action is performed? -

this question has answer here: confirmation on submit 1 answer if have jsf <h:commandlink> (which uses onclick event of <a> submit current form), how execute javascript (such asking delete confirmation) prior action being performed? can simplified this onclick="return confirm('are sure?');"

ASP.NET: connecting to a sql server database -

(very newbie question, please if can) how connect visual web developer sql server express 2008? in database explorer, right click on data connections, click add connection..., , in data source box choose microsoft sql server (sqlclient), i'm guessing doesn't connect me database file, sql server express itself(?). in server name box when click drop down box, there's nothing there , that's stuck. can provide link how can connect sql server express; preferably not msdn link since i've been there , struggled walkthrough. usually can type in .\sqlexpress connect local sql server express install... the dot means computer on, localhost, , \sqlexpress sql server instance server running on...this default instance name anyway sql server express...

javascript - Display date/time in user's locale format and time offset -

i want server serve dates in utc in html, , have javascript on client site convert user's local timezone. bonus if can output in user's locale date format. seems foolproof way start utc date create new date object , use setutc… methods set date/time want. then various tolocale…string methods provide localized output. example: // come server. // also, whole block made mktime function. // bare here quick grasping. d = new date(); d.setutcfullyear(2004); d.setutcmonth(1); d.setutcdate(29); d.setutchours(2); d.setutcminutes(45); d.setutcseconds(26); console.log(d); // -> sat feb 28 2004 23:45:26 gmt-0300 (brt) console.log(d.tolocalestring()); // -> sat feb 28 23:45:26 2004 console.log(d.tolocaledatestring()); // -> 02/28/2004 console.log(d.tolocaletimestring()); // -> 23:45:26 some references: tolocalestring tolocaledatestring tolocaletimestring gettimezoneoffset

c# - Multiple Forms and a Single Update,Will it work? -

i need make application in .net cf different/single forms lot of drawing/animation on each forms.i prefer have single update[my own state management , on] function can manage different states, [j2me gaming code] work without changes.i have came possible scenarios. of 1 perfect? have single form , add/delete controls manually , use of gamelooping tricks. create different forms controls , call update , application.doevents() in main thread.[ while(isapprunning){ update() application.doevents() } create update - paint loop on each of form required. any other ideas. please give me suggestion regarding this if game i'd drop of forms , work bare essentials, work off bitmap if possible , render either overriding main form's paint method or control resides within (perhaps panel). give better performance. the main issue compact framework isn't designed lot of ui fun don't double-buffering free in full framework, proper transparency bitch winform control...

Create many constrained, random permutation of a list -

i need make random list of permutations. elements can assume integers 0 through x-1. want make y lists, each containing z elements. rules no list may contain same element twice , on lists, number of times each elements used same (or close possible). instance, if elements 0,1,2,3, y 6, , z 2, 1 possible solution is: 0,3 1,2 3,0 2,1 0,1 2,3 each row has unique elements , no element has been used more 3 times. if y 7, 2 elements used 4 times, rest 3. this improved, seems job (python): import math, random def get_pool(items, y, z): slots = y*z use_each_times = slots/len(items) exceptions = slots - use_each_times*len(items) if (use_each_times > y or exceptions > 0 , use_each_times+1 > y): raise exception("impossible.") pool = {} n in items: pool[n] = use_each_times n in random.sample(items, exceptions): pool[n] += 1 return pool def rebalance(ret, pool, z): max_item = non...

objective c - difference between nil and released object -

i'm new objective-c , and can't understand this. know can send message nil (it's hyped feature of objective-c), can't send message released object, getting exception in case, difference between them? nil memory address 0. runtime knows not when address messaged, because the predefined nonexistant object address. however, deallocated object random memory address, because pointer isn't cleaned when formerly valid object destroyed. since not prescribed nonexistant object address, runtime doesn't know it's invalid, , try send message. crash program right away. you can avoid setting variables nil once you've released them.

objective c - Launching App using 'launchedTaskWithLaunchPath' Cocoa/objecive-c API -

i need launch 'textmate' app, , used following code. [nstask launchedtaskwithlaunchpath:@"/applications/textmate.app" arguments:[nsarray arraywithobjects:@"hello.txt", nil]]; but, got following error return. *** nstask: task create path '/applications/textmate.app' failed: 22, "invalid argument". terminating temporary process. what's wrong code? tried run "textmate hello.txt". added i make run follows. [nstask launchedtaskwithlaunchpath:@"/applications/textmate.app/contents/macos/textmate" arguments:[nsarray arraywithobjects:@"hello.txt", nil]]; and asked another question see how many other ways available. in case, invalid parameter application's name. if check documentation nstask you'll see method you're using wrapper low-level exec() system call. means need provide name of actual executable or binary file able create process. in case, you're giving d...

ruby - Curb curb-fu gem installation problem -

i've installed curb , curb-fu gem , libcurl on ubuntu box. if go irb , run following irb(main):001:0> require 'rubygems' => true irb(main):002:0> require 'curb' => true irb(main):003:0> require 'json' => true irb(main):004:0> require 'curb-fu' => true irb(main):005:0> so seems have access gems. but i've created simple ruby app that's giving me error: #!/usr/bin/ruby require 'rubygems' require 'curb' require 'json' require 'curb-fu' response = curbfu.get('http://slashdot.org') puts response.body i following error back. /usr/lib/ruby/gems/1.8/gems/curb-fu-0.4.4/lib/curb-fu/authentication.rb:3: uninitialized constant curbfu::authentication::curl (nameerror) i have feeling it's libcurl , have tried several different versions still no joy. can offer assistance? cheers togs i managed work. i uninstalled both curb , curb-fu gem , re-install...

php - MySQL UNION with COUNT aliasing -

i trying retrieve 2 counts 2 separate tables 1 sql query use php. current sql query: select count(entryid) total rh_entries union select count(pentryid) attended rh_playerentries playerid=79 this php using utilize data: $result = mysql_query($query); $attendance = mysql_fetch_assoc($result); echo "total: " . $attendance['total'] . " attended: " . $attendance['attended'] . " percentage: " . (int)$attendance['total'] / (int)$attendance['attended'] . " <br />"; i getting output: warning: division 0 in /home/content/g/v/i/gviscardi/html/guilds/sanctum/raidinfo/player.php on line 41 total: 6 attended: percentage: apparently $attendance['attended'] not being set properly. missing on how union or count or works? union combines contents of 2 queries single table. queries have different column names, merge won't work properly. you'll want like: select (select ...

validation - Is there any difference between 'valid xml' and 'well formed xml'? -

i wasn't aware of difference, coworker says there is, although can't up. what's difference if any? there difference, yes. xml adheres xml standard considered formed, while xml adheres dtd considered valid.

java - How Do I Create a New Excel File Using JXL? -

i'm trying create new excel file using jxl, having hard time finding examples in api documentation , online. after messing around awhile longer found worked , saw there still wasn't solution posted here yet, here's found: try { string filename = "file.xls"; writableworkbook workbook = workbook.createworkbook(new file(filename)); workbook.createsheet("sheet1", 0); workbook.createsheet("sheet2", 1); workbook.createsheet("sheet3", 2); workbook.write(); workbook.close(); } catch (writeexception e) { }

java - Why is it impossible, without attempting I/O, to detect that TCP socket was gracefully closed by peer? -

as follow recent question , wonder why impossible in java, without attempting reading/writing on tcp socket, detect socket has been gracefully closed peer? seems case regardless of whether 1 uses pre-nio socket or nio socketchannel . when peer gracefully closes tcp connection, tcp stacks on both sides of connection know fact. server-side (the 1 initiates shutdown) ends in state fin_wait2 , whereas client-side (the 1 not explicitly respond shutdown) ends in state close_wait . why isn't there method in socket or socketchannel can query tcp stack see whether underlying tcp connection has been terminated? tcp stack doesn't provide such status information? or design decision avoid costly call kernel? with of users have posted answers question, think see issue might coming from. side doesn't explicitly close connection ends in tcp state close_wait meaning connection in process of shutting down , waits side issue own close operation. suppose it's fair enough iscon...

android - Is it possble to detect an endless loop? -

i wrote thread application runs infinite loop. problem since defined thread loop not holding , process hostage use lot of processing power hence reducing battery life. know not how programs written considering fact rouge applications may built, precaution android take stop processes implement infinite loop. while @ it, there specific class can access access memory usage application , processor usage? the code... package com.shouvik.handlerthread; import android.app.activity; import android.app.progressdialog; import android.os.bundle; import android.os.handler; import android.os.message; import android.util.log; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; public class handlerthread extends activity{ private progressdialog progressdialog; /** called when activity first created. */ @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); ((...

Haskell syntax for a case expression in a do block -

i can't quite figure out syntax problem case expression in do block. what correct syntax? if correct example , explain best. module main main = putstrln "this test" s <- foo putstrln s foo = args <- getargs return case args of [] -> "no args" [s]-> "some args" a little update. source file mix of spaces , tabs , causing kinds of problems. tip 1 else starting in haskell. if having problems check tabs , spaces in source code. return (overloaded) function, , it's not expecting first argument keyword. can either parenthesize: module main import system(getargs) main = putstrln "this test" s <- foo putstrln s foo = args <- getargs return (case args of [] -> "no args" [s]-> "some args") or use handy application operator ($): foo = args <- ge...

c - Daemon logging in Linux -

so have daemon running on linux system, , want have record of activities: log. question is, "best" way accomplish this? my first idea open file , write it. file* log = fopen("logfile.log", "w"); /* daemon works...needs write log */ fprintf(log, "foo%s\n", (char*)bar); /* ...all done, close file */ fclose(log); is there inherently wrong logging way? there better way, such framework built linux? unix has had long while special logging framework called syslog . type in shell man 3 syslog and you'll c interface it. some examples #include <stdio.h> #include <unistd.h> #include <syslog.h> int main(void) { openlog("slog", log_pid|log_cons, log_user); syslog(log_info, "a different kind of hello world ... "); closelog(); return 0; }

c++ - Moving between dialog controls in Windows Mobile without the tab key -

i have windows mobile 5.0 app, written in c++ mfc, lots of dialogs. 1 of devices i'm targetting not have tab key, use key move between controls. fine buttons not edit controls or combo boxes. have looked @ similar question answer not suit. i've tried overriding cdialog::onkeydown no avail, , rather not have override keystroke functionality every control in every dialog. thoughts far write new classes replacing cedit , ccombobox, checking if there easier way, such temporarily re-programming key. i don't know mfc that good , maybe pull off subclassing window procedures of controls single class, handle cases of pressing cursor keys , pass rest of events original procedures. you have provide own mechanism of moving appropriate control, depending on cursor key pressed may worth usability gains. if worked, enumerate dialog controls , subclass them automatically. windows mobile 6 allows switching between dialog controls using cursors default - it's new...

c# - query that gets only the records needed to the page using Linq- not fetched the record based on page size -

i have used query fetch record of datatable based on pagesize. ienumerable<datarow> query1 = row in dt.asenumerable().take(page_size).skip(offset) select row; datatable boundtable= query1.copytodatatable(); first time when opens offset =0; gives 10 records, next time pass offset 10 next ten records, not giving enum values. showing me message says ' enumeration yielded no results ' but dt querying has 1000 records. wrong made here... you're using skip , take in wrong order. try this: ienumerable<datarow> query = dt.asenumerable() .skip(offset) .take(pagesize); (i removed query expression syntax wasn't doing favours here.) you doing take skip - saying like, "give me first ten records, skip eleventh of ten." that's not going give results :) the above says, "skip eleventh record, give me first ten records left."

Javascript - Problem in accessing global variables -

i want share values across 2 javascript functions below in second function unable value global variable // following 2 global variables var grid; var mastertable; function gridcreated(sender, args) { grid = sender; // setting values mastertable = sender.get_mastertableview(); // setting values - here mastertable has values in mastertable.selectallitems(true); } function abc() { debugger; var collectionofordernumber = 0; var selectedrows = mastertable.get_selecteditems(); // here unable values mastertable (var = 0; < selectedrows.length; i++) { var row = selectedrows[i]; var cell = mastertable.getcellbycolumnuniquename(row, "ordernumber") collectionofordernumber = collectionofordernumber + "-" + cell.innerhtml; } document.getelementbyid("hdf1").value = collectiono...

content management system - Notifications for Joomla extension updates -

is there extension check whether there newer versions available installed extensions on joomla site, , notify site administrator? ideally, looking similar drupal's "update" module. i understand there no central place keeping these modules , versions joomla, @ least lot of them available on joomla extensions site, along needed information, perhaps wrote tool checks source? aha, looks included in joomla 1.6, according this description (check out "find updates" button, looks great).

SQL Server 2008 Table Partitioning -

i have huge database has several tables hold several million records. it's holding engineering data client , continually grows. impacting performance, optimised indexing. i've been looking @ partitioning. however, looking @ partitioning on version held in table. in it's simplistic form table comprises of:- versionid int sheetid int creationdate datetime somedate nvarchar(255) version int and data like:- 1, 1, 2010-09-01, blah, 1 2, 1, 2010-09-02, more blah, 2 3, 1, 2010-09-04, blah, 3 4, 2, 2010-09-02, more blah, 1 for every new change 'sheet' in system, table has new entry added new version. ideally want partition table have top 2 versions each 'sheet'. table above i'd want versions 2 & 3 sheet id 2, , version 1 sheet id 2, rest moved partition. i've read doesn't seem possible. right or wrong? if i'm wrong, following on have bunch of tables link table. these hold various versions of data entered. can partition...

compression - How to compress files in .NET 1.1 -

i need compress files in [*.zip] format in .net 1.1. don't want use sharpzip compression got random errors - "access denied" - when running in .net 1.1. sharptzip work if put assembly on gac - not option in project. problem. check this: http://forums.asp.net/p/1139901/1839049.aspx#1839049 you can use command-line tool zip. example 7-zip .

html - Issue with positioning a div -

i working on site laid out div s. having trouble 1 in particular: training photo div . if go http://php.wmsgroup.com/eofd6.org/education.html you'll see photo underneath left nav has dropped down. want snap right under nav box. have tried several different things positioning main content div s positioning , can't right. any appreciated. link style sheet http://php.wmsgroup.com/eofd6.org/in.css thanks! float #content right, not left.

javascript - how to replace " char to '? -

i want replace " char ' . use replace method on string str want replace in: str = str.replace(/"/g, "'"); important use regular expression g flag set replace globally. if omit g flag or use string search, replace first occurrence.

php - Strip HTML Tags in Zend Framework -

i trying strip html tags except <p>,<br>,<strong>,<b> input data following: public function init() { parent::init(); $this->fields = array( 'name' => 'name', 'age' => 'age', 'profile' => 'profile', ); $this->mdata = array(); $this->verify = true; } anyone knows how apply zend_filter_striptags in it? if understand problem: $allowedtags = array('p','b','br','strong'); // allowed tags $allowedattributes = array('href'); // allowed attributes $striptags = new zend_filter_striptags($allowedtags,$allowedattributes); // instance of zend filter $sanitizedinput = $striptags->filter($input); //$input input html see answer

cocoa touch - iPhone: Handling touches transparently -

i have uiviewcontroller , associated uiview. uiview has number of subviews. how handle touch event inside specified rectangle in uiviewcontroller subclass? this handling should transparent: uiview , subviews should still receive touch events if intersect specified rectangle. p.s. overriding touchesbegan in view controller doesn't work. inner views doesn't pass events through. adding custom button end of uiview subviews list doesn't work. inner subviews doesn't receive touch events. touchesbegan/touchesmoved/touchesended way go. depending on trying do, uigesturerecognizer may option. to make sure subviews pass events up, set userinteractionenabled yes on subviews. uiview sets yes default, subclasses (notably uilabel) override , set no.

windows vista - Vbscript detect whether UAC-elevated -

how can vbscript detect whether or not running in uac elevated context? i have no problem detecting user, , seeing if user within administrators group. still doesn't answer question of whether process has elevated privs or not, when running under vista or windows 2008. please note, need detect status; not attempt elevate or (err ..) de-elevate. the method settled on depends on fact vista , windows 2008 have whoami.exe utility, , detects integrity level of user owns process. couple of screenshots here: whoami, normal , elevated, on vista http://lh3.ggpht.com/_svunm47buj0/sq6ql4injpi/aaaaaaaaaea/iwbcsrazqrg/whoami%20-%20adminuser%20-%20groups%20-%20cropped.png?imgmax=512 you can see when cmd running elevated, whoami /groups reports "high" mandatory integrity level , different sid when running non-elevated. in pic, top session normal, 1 underneath running elevated after uac prompt. knowing that, here code used. checks os version, , if vista or server 20...

Copy from SQL Server 2005 to SQL Server 2008 causes x2 data space #SQLHelp -

a colleague of mine copying data sql server 2005 sql server 2008. the destination database lives on sql server 2008 instance set compatibility level 90. source database lives on sql server 2005 instance , set compatility level 90. using sql server integration services 2008 perform copy. the source table, data space used (mb) 127,072. however, after copy performed destination table, data space used (mb) 252,942. data, i'm not including index data space. the fill factor on 2 databases may different.

vb.net - Accessing members of the other half of a partial class -

i'm learning work partial classes in vb.net , vs2008. specifically, i'm trying extend linq sql class automatically created sqlmetal. the automatically generated class looks this: partial public class datacontext inherits system.data.linq.datacontext ... <table(name:="dbo.concessions")> _ partial public class concession ... <column(storage:="_country", dbtype:="char(2)")> _ public property country() string ... end property ... end class in separate file, here's i'm trying do: partial public class datacontext partial public class concession public function foo() string return dosomeprocessing(me.country) end function end class end class ... blue jaggies under ' me.country ' , message 'country' not member of 'datacontext.concession' . both halves of partial class in same namespace. so how access properties of automa...

algorithm for index numbers of triangular matrix coefficients -

i think must simple can't right... i have mxm triangular matrix, coefficients of stored in vector, row row. example: m = [ m00 m01 m02 m03 ] [ m11 m12 m12 ] [ m22 m23 ] [ m33 ] is stored coef[ m00 m01 m02 m03 m11 m12 m13 m22 m23 m33 ] now i'm looking non-recursive algorithm gives me matrix size m , coefficient array index i unsigned int row_index(i,m) and unsigned int column_index(i,m) of matrix element refers to. so, row_index(9,4) == 3 , column_index(7,4) == 2 etc. if index counting zero-based. edit: several replies using iteration have been given. know of algebraic expressions? here's algebraic (mostly) solution: unsigned int row_index( unsigned int i, unsigned int m ){ double m = m; double row = (-2*m - 1 + sqrt( (4*m*(m+1) - 8*(double)i - 7) )) / -2; if( row == (double)(int) row ) row -= 1; return (unsigned int) row; } unsigned int column_index( unsigned int i, unsigned...

php - How to add multiple sql queries to paginaiton dynamically? -

i trying add or connect multiple sql queries dynamically. i creating pagination script , trying add filter buttons or links in case when user clicks on links, add id sql query , display results. to better understand saying, show script i'm working on: below see have 3 links; marketing, automotive, , sports. these links represent filter selections, when 1 clicked 'marketing' the sql query insert marketing 'category=$ids'. works fine, except when want add multiple selections picking 'marketing' , 'sports' , not have 'automotive' display. is there easy way add multiple ids sql connection instead of one? i hope makes sense, if need further explanation let me know. on this. <?php $ids=$_get['id']; echo $ids; $pagen = $_get['page']; echo $pagen; ?> <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <htm...

php - Magento Custom Module. Redirect to another module and return to checkout -

magento shopping cart built on zend framework in php. first time i've dealt zend framework , i'm having following difficulty... i'm creating custom module allow users upload images whenever purchase products. i can overload addaction() method whenever user attempts add product cart. can create custom module presents form user , accepts file(s). i'm not sure how insert code run module overloaded method: <?php require_once 'mage/checkout/controllers/cartcontroller.php'; class company_specialcheckout_checkout_cartcontroller extends mage_checkout_cartcontroller { # overloaded addaction public function addaction() { # when user tries add cart, request images them # ********* # *** do in here display custom block ???? ### # *** , allow addaction continue if validated form input ### # ********* parent::addaction(); } } i suspect difficulties come lack of knowledge of zend mvc way of doing ...

java - Does any one use OSGi's OBR? -

is using osgi bundle repository , for? i tried in apache felix, think it's great. can point osgi container number of obrs , when install bundle, container automatically install required dependencies. it's apt-get install application servers.

c# - Problem creating datatable via code and binding to a datagridview -

i trying bind data table inventorytable datagrid viewer.the problem in code when compiles,it says column"make" not belong table make column in code follows: public partial class form1 : form { list<car> listcars = new list<car>(); datatable inventorytable=new datatable(); public form1() { initializecomponent(); listcars.add(new car("chucky", "bmw", "green")); listcars.add(new car("tiny", "yugo", "white")); listcars.add(new car("ami", "jeep", "tan")); listcars.add(new car("pain inducer", "caravan", "pink")); listcars.add(new car("fred", "bmw", "pea soup green")); listcars.add(new car("sidd", "bmw", "black")); listcars.add(new car("mel", "...