Posts

Showing posts from May, 2010

c# - How to convert to System.Int32 when doing a select from a DataTable -

i've got datatable i've loaded csv file using kbcsv library . can tell columns numbers in csv file , there aren't null rows. want select on data table query i've created using string.format. here's query: string qry = string.format("gridx = {0} , gridy = {1} , convert([{2}], 'system.int32') {3} {4}", xc, yc, _testdatacolumn, _comparison, _threshold); where xc double, yc double, _testdatacolumn string, _comparison string , _threshold double. table.select() method converts string to: gridx = 0 , gridy = 4 , convert([st devssi(dbm)], 'system.int32') = 5 i put convert in there because before getting a cannot perform '=' operation on system.string , system.int32 error message. i've looked @ this help. don't understand how last column (st devssi) became string. doing conversion correctly? there way take care of such errors? if run code sample csv file should same error when searches coordinates (0, 4) looks

jquery - deleting last character from span text? -

i have span element text. keep on appending based on events. works fine using $("#id").append(txt); . not able delete it. tried using $("#id").slice(0, -1) $("#id").val().slice(0, -1); values displayed on page remain same. should using substr or something? tried google couldn't come this? possible using jquery? you can use this : $(selector).text(function(i,v){ return v.slice(0,-4); });

ios - how to parsing data in JSON to tableview -

i have json http://vmg.hdvietpro.com/ztv/home , how parsing data json in link table view. try code cant data json application.thanks help movies.h @interface movies : nsobject @property (strong,nonatomic) nsstring *moviesid; @property (strong,nonatomic) nsstring *text1; @property (strong,nonatomic) nsstring *thumbnail; #pragma mark - #pragma mark class methods -(id)initwithmoviesname:(nsstring *)ctext1 andthumbnail:(nsstring*) cthum andmoviesid:(nsstring*) cid; @end movies.m @implementation movies @synthesize text1,moviesid,thumbnail; -(id)initwithmoviesname:(nsstring *)ctext1 andthumbnail:(nsstring*) cthum andmoviesid:(nsstring *) cid{ self=[super init]; if (self) { text1=ctext1; thumbnail=cthum; moviesid=cid; } return self; } @end tableviewcontroller #define getdataurl @"http://vmg.hdvietpro.com/ztv/home" -(void) retrievedata{ nsurl *url=[nsurl urlwithstring:getdataurl]; nsdata *data=[nsdata datawi

sql - Difference between NULL and Blank Value in Mysql -

i have check value of particular column named result blank or not. when check if result null , query failed, when checked result='' , worked. what difference between two. please explain. "update rls_tp_2012_03 a, rls_tp_2012_03 b set a.comment=b.comment b.tcode='t1199' , a.groupname='xyz' , a.hlabno=b.hlabno , a.result =''; "; "update rls_tp_2012_03 a, rls_tp_2012_03 b set a.comment=b.comment b.tcode='t1199' , a.groupname='xyz' , a.hlabno=b.hlabno , a.result null; " null absence of value. empty string value, empty. null special database. null has no bounds, can used string , integer , date , etc. fields in database. null isn't allocated memory, string null value pointer pointing in memory. however, empty allocated memory location, although value stored in memory "" .

haskell - Use relative paths for extra-lib-dirs on cabal -

i have c library "myboo" has makefile. want make wrapper of library. don't want install /usr/local since "myboo" not major module. additionally recommended build "myboo" not dynamic library static library. i make custom setup.py build "myboo"; main :: io () main = defaultmainwithhooks simpleuserhooks { prebuild = \a b -> makelib b >> prebuild simpleuserhooks b } makelib :: args -> buildflags -> io () makelib _ flags = let verbosity = fromflag $ buildverbosity flags cflags <- lookupenv "cflags" >>= return . maybe "" id setenv "cflags" $ "-fpic" ++ (' ' : cflags) rawsystemexit verbosity "env" ["make", "--directory=myboo", "libmyboo.a"] and arrange myboo.cabal link haskell codes c library; library exposed-modules: myboo build-depends: base >=4.7 && <4.8 hs-source-

xsd pattern not working with more than two regex separated by OR ( | ) -

i facing problem following xsd pattern ... <xsd:pattern value="\d+(,\d+)*(,[*])|\d+(,\d+)*|\d+(,[*])(,\d+)+" /> in above pattern want allow user enter following patterns only: 1,2,3 1,*,3 1,2,* but when try enter 1,2,* gives me following exception ... unknown exception occurred while updating = input string: "*" i not see wrong expression can improved , doing might prevent error. fault might in way results of regular expression used, not regular expression itself. the regular expression given in question \d+(,\d+)*(,[*])|\d+(,\d+)*|\d+(,[*])(,\d+)+ . testing in notepad++ v6.5.5 shows matches 3 example lines, expression not anchored start , end of line. adding 1 ^ , 1 $ not sufficient because of precedence of | . using expressions matches lines: ^(\d+(,\d+)*(,[*])|\d+(,\d+)*|\d+(,[*])(,\d+)+)$ could use ^\d+(,\d+)*(,[*])$|^\d+(,\d+)*$|^\d+(,[*])(,\d+)+$ seems harder read , understand. within regular expression the [*]

java - JUnit using mockito -

i have a service class named service.class , 2 classes named a.class , b.class service class has method calls methods based on object of classes & b. how can create mockito object of & b can pass mockito object in service class method.which needed junit testing. eg. service.class class service { a; response response; public service(){ } public service(a a, b b){ this.a= a; this.b = b; } public respose test(inputstream i,inputstream i1){ inputstream instreama = a.method1(i,i1); response response= response.method2(instreama); return response; } , in response.class public response method2(inputstream i1)){ return response.ok().build(); } edit: junit class have created both classes mockeda = mock(a.class); response mockedresponse = mock(response.class);

java - Thread lock after opening new EntityManager -

i have weird error working spring jpa transactions. thread locked around 16 minutes , continues without problem. here situation: @transactional(propagation = propagation.requires_new) public class { public string encrypt(string str){ log.debug("encrypting..."); // data base read operations } public string encrypt(string str, string str2){ // read , write database operations. } public string foo(...){ // read , write database operations. } public string bar(...){ // read , write database operations. } } @transactional(propagation = propagation.requires_new) public class b { public string dosomething(...){ log.debug("calling encrypt method..."); string chain1 = this.a.encrypt("whatever"); log.debug("calling encrypt method..."); string chain2 = this.a.encrypt("again"); log.debug("calling e

java - RCP Help Search is not working -

i create 1 sample rcp application view , 1 sample plugin lars tutorial it works if try search thing in sample help. change 1 sample html , add other lines "rcp application". now if tried search "application" "nothing found" previous keyword still giving result. what i'm missing here.?

javascript - How to calculate date difference in html using java script without clicking submit button -

i giving 2 dates manually in form after 1 more empty box there date difference should calculated in terms of days in third box dynamically using java script me working when clicking submit button , using submit button property want should calculated after entering second date second box , should display in third box here code.... please me out here.. script function datediff() { date1 = new date(); date2 = new date(); diff = new date(); date1temp = new date(dateform.firstdate.value); date1.settime(date1temp.gettime()); date2temp = new date(dateform.seconddate.value); date2.settime(date2temp.gettime()); diff.settime(math.abs(date1.gettime() - date2.gettime())); timediff = diff.gettime(); days = math.floor(timediff / (1000 * 60 * 60 * 24)); dateform.difference.value = days; return false; } html <form> <fieldset> <label for="enter leave starting date">enter leave starting date

The conversion of the varchar value overflowed an int column in sql server 2012 -

i'm getting error query data... error message is: msg 248, level 16, state 1, line 1: conversion of varchar value overflowed int column... cant resolve problem, if 1 can me, in advance, here sql: this happens when inserted 3 new joins in query, made them bold, otherwise works perfectly... select distinct acr_art_id, des_texts.tex_text criteria_des_text, coalesce(des_texts2.tex_text, acr_value) criteria_value_text, (des_texts.tex_text + ': ' + coalesce(des_texts2.tex_text, acr_value)) cel_opis inventory.dbo.article_criteria left join inventory.dbo.designations designations2 on designations2.des_id = acr_kv_des_id left join inventory.dbo.des_texts des_texts2 on des_texts2.tex_id = designations2.des_tex_id left join inventory.dbo.criteria on cri_id = acr_cri_id left join inventory.dbo.designations on designations.des_id = cri_des_id left join inventory.dbo.des_texts on des_texts.tex_id = designations.des_tex_id inner joi

php - Transfer data from one field to another adding some symbols between each single one -

title may misguiding explain want achieve here. i have table in database has data. data id's skills. id=3 -> java, id=15 -> php. tbl_skills 3, 15, 28 5, 14, 12, 20 what want give value each skill represent how knows language. i want : tbl_skills_evaluated 3:50, 15:60, 28:45 5:34, 14:80, 12:73, 20:90 i want copy tbl_skills data , add " : " after each id, dont care number after " : " now. i want in php. ideas people?

java - Electronic Medical Record System -

i , team mates developing electronic medical record system pediatric , materny clinic. want develop using java front end, , mysql backend. can 1 suggest or give me hints it? have @ java web frameworks this. quite struts2 simple setup. skeleton app setup have @ appfuse , which'll take lot of hard work out of getting setup. for db interactions, consider using hibernate app, giving java based access db (object relational mapping). so many other things can consider, starting above should give good, solid, start , let focus on app functionality rather framework.

javascript - Raphaeljs hover on each element of the associative array -

i using raphael js draw map , mark cities on it. you can see code here i have set of elements - circles around map, (each circle stands city) want perform specific actions when hovering on. problem is, cant write single function of them, have write same function each element. how solve problem? i tried for (var city in cities) { cities[city].hover(function () { cities[city].attr({"fill": "#ff5b3a"}); }, function () { cities[city].attr({"fill": "none"}); } )}; but after that, when hovering on city - paints last city in red, not city hovering over. please suggest me solution. you need create closure and/or use 'this', created function know element applied, , not last element in loop. there's couple of ways that, 1 of immediate function create function scope of city referring to. or can use 'this' refer correct element. for (var city in cities) { ci

c# - Producer/Consumer pattern with a batched producer -

i'm attempting implement simple producer/consumer style application multiple producers , 1 consumer. research has led me onto blockingcollection<t> useful , allowed me implement long-running consumer task below: var c1 = task.factory.startnew(() => { var buffer = new list<int>(batch_buffer_size); foreach (var value in blockingcollection.getconsumingenumerable()) { buffer.add(value); if (buffer.count == batch_buffer_size) { processitems(buffer); buffer.clear(); } } }); the processitems function submits buffer database , work in batches. solution sub optimal however. in baron production periods time until buffer filled meaning database out of date. a more ideal solution either run task on 30 second timer or short circuit foreach timeout. i ran timer idea , came this: synctimer = new timer(new timercallback(timerelapsed), blockingcollection, 5000, 5000); private static void time

caching - How to disable Operating System(Ubuntu) cache in C program -

as far know, can disable os cache through use open() o_direct. how if willing use fopen() instead of open()? i think due alignment requirements of o_direct flag it's not possible (see that question ). f...() - io family uses internal buffer cache io operation , don't think standard implementation align buffer appropriately. edit for special purposes, think of 2 non-portable solutions: if sure, file system doesn't require special alignment, use fdopen() : int fd = open( ....., o_wronly|o_direct ); file *fp = fdopen( fd, "w" ); if working on linux only, using fopencookie() solution: use cookie transort 'real' fd open() , provide write function copies data appropriately aligned buffer , calls write() (i have never used fopencookie() , think worth trying if using non-standard gnu extension isn't nogo) in both cases aware f-...() i/o functions still internal buffering real write() s may not occur before call fflush() or fclos

sql server - TSQL use joined table data as function parameters -

can briefly explain why not possible use values of table parameters joined function? ;create function "foo" ( @id int ) returns @result table ( "value" int ) begin insert @result select @id * 2 return end; ;with "cte" ( select "id" = 1 union select 2 ) select * cte , "foo"(cte."id") the last line throws error ( ~ cte."id" can not bound ). doesn't matter if it's cte or table. joining result sets coming out table valued function done using cross apply .

Conversion from String to BigDecimal do not with Cucumber on Scala -

i'm writing tests in cucumber scala code. have following step when added product price 10.0 and following step definition: when( """^added product price ([\d\.]*)$""") { (price: bigdecimal) => { //something } } i following error when run test intellij: cucumber.runtime.cucumberexception: don't know how convert "10.0" scala.math.bigdecimal. try writing own converter: @cucumber.deps.com.thoughtworks.xstream.annotations.xstreamconverter(bigdecimalconverter.class) public class bigdecimal {} @ cucumber.runtime.parameterinfo.convert(parameterinfo.java:104) @ cucumber.runtime.stepdefinitionmatch.transformedargs(stepdefinitionmatch.java:70) @ cucumber.runtime.stepdefinitionmatch.runstep(stepdefinitionmatch.java:38) @ cucumber.runtime.runtime.runstep(runtime.java:289) @ cucumber.runtime.model.stepcontainer.runstep(stepcontainer.java:44) @ cucumber.runtime.model.stepcontainer.runsteps(stepcontainer.java:39)

c# - are reads and writes to a variable of type double guaranteed to be atomic on a 64 bit intel processor? -

i have 64 bit machine running 64 bit processor application 32 bit. reading or writing double guaranteed atomic? talking assignment , reading only. how 32 bit process affect process? can reader ever read partial value double when other thread writing in given specs? no. double can straddle l1 cache line boundary, requiring multiple bus cycles glue 2 pieces together. real problem in c#, 32-bit clr provides alignment guarantee of 4. these misaligned accesses not not atomic, expensive due shuffling processor needs do. code uses double can have 3 distinct timings, fast if double happens aligned 8 accident, twice slow when misaligned 4 still inside l1 cache line, on 3 times slower when misaligned across cache line. such program can randomly bump 1 of these modes when garbage collector compacts heap , moves double. very wary of this, synthetic test program can miss failure mode. the perf problem core reason double[] allocated in large object heap sooner normal. loh pr

python - Django social_auth doesn't create models -

i'm using django social auth in project, running manage.py syncdb doesn't create required tables in database. tried making new empty project , adding social_auth installed apps didn't work (to find out if package conflics other apps in project or not). import social_auth works fine means package installed successfully. i tried deleting tables in database , running syncdb on , over, didn't help. after logging in , authorizing app error comes up: programmingerror @ /complete/instagram/ (1146, "table '<my db name>.social_auth_usersocialauth' doesn't exist") which implies required tables not created on database. my installed_apps , result of syncdb: installed_apps = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_auth'

Generic function for calling back every kinds of methods with different arguments in C# -

i want have function able call function , retrieve proper value. these examples of need: var ilist<person> = invokefunction<ilist<person>>(repositoryperson.getallperson); var persion = invokefunction<person>(repositoryperson.getpersonbyid, 10); var int = invokefunction<int>(repositoryperson.runcustomstoreprocedure, 250,"text",521,10); there no syntax allow since there no syntax allow call invokefunction method , pass in method call first parameter that. specifically, type can declare invokefunction have first parameter kind of delegate type, need specify specific delegate type, gets square 1. now, if modified syntax slightly, here's linqpad program demonstrates: void main() { var t = new test(); invokefunction<int>(t, "add", 10, 20).dump(); invokefunction<int>(t, "negate", 10).dump(); invokefunction<int>(t, "semirandom").dump(); } public class test {

winforms - use multiple screens on a window - C# -

Image
i want use multiple screens ( panel or else ) on window! i don't want use mdi child form ... is there way? or our approach create "views" usercontrol s , add/remove them in code to/from panel on form. times share set of common methods (interface iview ) can example check whether view unsaved data, etc.

ios - NSURLSessionTask category method crashes with "Unrecognized selector sent to instance" -

i need add method nsurlsessiontask . here's category supposed that: // nsurlsessiontask+extras.h #import <foundation/foundation.h> @interface nsurlsessiontask (extras) - (void)hellonsurlsessiontask; @end // nsurlsessiontask+extras.m #import "nsurlsessiontask+extras.h" @implementation nsurlsessiontask (extras) - (void)hellonsurlsessiontask { nslog(@"hello nsurlsessiontask!"); } @end everything compiles well, autocomplete works, when call method, application crashes: 2014-06-27 12:32:23.916 test[4333:60b] *** terminating app due uncaught exception 'nsinvalidargumentexception', reason: '-[__nscflocaldatatask hellonsurlsessiontask]: unrecognized selector sent instance 0x109723310' same approach works if add category nsobject , , can't seem understand why doesn't nsurlsessiontask . here's test project reproduces problem me: https://dl.dropboxusercontent.com/u/25100182/test.zip unfortunately doesn

How can I extract "Path to executable" of all services with PowerShell -

get-service *sql* | sort displayname | out-file c:/servicelist.txt i have 1 line powershell script extract list of services running on local machine, now, in addition displaying "status", "name" , "displayname" want display "path executable" i think you'll need resort wmi: get-wmiobject win32_service | ?{$_.name -like '*sql*'} | select name, displayname, state, pathname update if want perform manipulation on selected data, can use calculated properties described here . for example if wanted text within quotes pathname, split on double quotes , take array item 1: get-wmiobject win32_service | ?{$_.name -like '*sql*'} | select name, displayname, @{name="path"; expression={$_.pathname.split('"')[1]}} | format-list

php - Eloquent - join clause with string value rather than column heading -

i have question regarding join clauses in eloquent, , whether can join on string value rather table column. i have code below querying nested set joining parent/child records in table 'destinations' via table 'taxonomy'. the second $join statement in closure 1 causing issue; eloquent assumes column, when join on t1.parent_type = 'destination' - ie, t1.parent_type should = string value, destination . $result = db::connection() ->table('destinations d1') ->select(array('d1.title level1', 'd2.title level2')) ->leftjoin('taxonomy t1', function($join) { $join->on('t1.parent_id', '=', 'd1.id'); $join->on('t1.parent_type', '=', 'destination'); }) ->leftjoin('destinations d2', 'd2.id', '=', 't1.child_id') ->where('d1.slug', '=', $slug) ->get(); is possible force

Mobile Dart workflows in Chrome Dev Editor -

maybe you'll have ideas. so, there articles / tutorial / regarding topic of mobile dart workflows in chrome dev editor develop sandbox google io 2014? i interested on these topics, multi-screen , mobile workflows, , debugging apps directly on phones , tablets. the workflows deploying dart apps (chrome app , web apps) mobile won't land until next release - m14 - on or around end of july. can track bug m14 release: https://github.com/dart-lang/chromedeveditor/issues/2778 .

javascript - Trouble shooting jquery enable/disable text box based on radiobutton again -

after getting piece right, ( trouble shooting jquery enable/disable text box based on radiobutton ) found neede add field form, disabled if radio selection made. seems have broken whole thing , cannot find problem is. i've rewritten code try , make sense of (i don't know javascript @ all) <input type="radio" name="radioknof" value="public" checked/> <label "public">anyone</label> </br> <input type="radio" name="radioknof" value="direct" /> <label for="direct">specific</label> </br> <label for="newmanagerfirstname">manager's firstname :</label> <input type="text" name="newmanagerfirstname" id='newmanagerfirstname' value="1"> </br> <label for="newmanageremail">manager's email address:</label> <input type="text" name="newmanage

MINUS functionality in BigQuery database -

i new bigquery database. like in oracle database minus operator same functionality in bigquery? did not find minus operator in bigquery. oracle --> minus bigquery --> ?? though there no minus function in bigquery, can use left outer join alternative. select name, uid minus select name, uid b can written as: select a.name, a.uid left outer join b on a.name= b.name , a.uid= b.uid b.name null

javascript - Changing CSS property on entering or leaving AngularJS state -

i've got app want change css property on entering/exiting angular state. css property background-color on html , body elements (basically backdrop) gets exposed on transitions between states. i'd change color of backdrop make transitions bit nicer. suggestions how can in angular? ui-router 's $state service broadcasts events on $rootscope states change. listen these events , apply style changes accordingly. following cause body have red background during state transitions , white background after: angular.module('myapp').run(function($rootscope){ $rootscope.$on('$statechangestart', function(event, tostate, toparams, fromstate, fromparams){ //change body background document.body.style.background = 'red'; }); $rootscope.$on('$statechangesuccess', function(event, tostate, toparams, fromstate, fromparams){ //reset body background document.body.style.background = 'white';

java - Loading exported file to view -

i use jasperreports library 5.6.0 i tire programing: viewer (jrviewer) pdf ---> xml ---> pdf viewer (jrviewer) step - export generated raport view xml file step - exported file xml convert pdf , showing jrviewer but have problem step 2, // file variable xml file generated step 1 jasperdesign design = jrxmlloader.load(file); jasperreport report = jaspercompilemanager.compilereport(design); jasperprint print = jasperfillmanager.fillreport(report, new hashmap(), new jrbeancollectiondatasource(b)); jasperprintmanager.printreport(print, false); i got error: java.lang.nullpointerexception @ net.sf.jasperreports.engine.xml.jrxmlloader.loadxml(jrxmlloader.java:323) @ net.sf.jasperreports.engine.xml.jrxmlloader.loadxml(jrxmlloader.java:284) @ net.sf.jasperreports.engine.xml.jrxmlloader.load(jrxmlloader.java:273) @ net.sf.jasperreports.engine.xml.jrxmlloader.load(jrxmlloader.java:218) @ net.sf.jasperreports.engine.xml.jrxmlloader

bash - How do I execute sudo subcommand in background -

i have script should run this: sudo command & othercommand i need password prompt sudo finish before othercommand run, above setup runs sudo in background rather command ie, bash doing: (sudo command) & while i'd sudo (command &) i use sudo -b makes command detatch terminal , makes hard stop since ^c , jobs won't effect it. how can this? to able stop background process when script exits example ctrl - c use trap: trap 'kill $pids' exit [...] sudo command & pids="${pids+$pids }$!" [...] othercommand [...] wait this script exit once sudo command finished or receives terminating signal, @ point kill sudo command before exiting.

javascript - How to populate chart with data from database? -

i'm following railscast create chart of data. recommends following: orders.js jquery -> morris.line element: 'orders_chart' data: $('#orders_chart').data('orders') xkey: 'purchased_at' ykeys: ['price', 'shipping_price', 'download_price'] labels: ['total price', 'shipping price', 'download price'] preunits: '$' and create element in view, table in view fills graph. however, data not $('#orders_chart').data('orders') , rather data directly database table doesn't shown on webpage. how that? step 1: set route in routes files give json data: get '/get_graph_data', to: 'graphs#data_show', as: 'get_graph_data', defaults: {format: 'json'} step 2: write controller class graphscontroller def data_show json data end end write ajax request get_graph_data = -> url = (you can use dat

javascript - Easily manage user input forms in a PHP Web Application -

dear stackoverflowers, i'm writing simple web application in plain html+php. i'm not using framework, content manager or anything. the entry page has few checkboxes, 2 textboxes , series of dropdown menus. once selected, user clicks "search" button , runs php code , returns output. the problem dropdown menus. code following : <form action=$script method=\"get\" name=\"org\"> <select name=\"org\" onchange=\"javascript:document.org.submit();\"> <option value=\"0\">(default all)</option> <option value=\"1\">cars</option> <option value=\"2\">parts</option> </select> </form> then every time user selects option, webpage reloaded , variable set. have 2 problems : 1.- option selected in dropdown menu shown first, user knows has clicked. way put php switch @ beginning of form , echo new dropdown menu depending on variable set in prev

How to open a directory on a networked computer with Java -

i tried this. string userhomepath = "\\mysvr\\project\\my team\\001 test\\001 test\\003 report"; file userhome = new file(userhomepath); try { desktop.getdesktop().open(userhome); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } why can't open? plz explain me. because of white spaces? if so, how can fix it. thanks here's exception: java.io.ioexception: failed open file:////mysvr/project/my%20team/001%20test/001%20test/003%20report/. error message: system cannot find file specified. @ sun.awt.windows.wdesktoppeer.shellexecute(unknown source) @ sun.awt.windows.wdesktoppeer.open(unknown source) @ java.awt.desktop.open(unknown source) @ org.ace.insurance.fire.renewal.test.main(test.java:13) i can open till "\mysvr\project" . use "//mysvr/project/..." or "\\\\mysvr\\project\\..." . of course first try out in windows explorer

delphi - Append formated text from SQL to TRichEdit -

can problem? how append formatted txt database field trichedit ? just clarify: need contents of 2 database fields have formatted text (rtf) , put them in trichedit preserving formatting. use mssql express , field set text in ansi format. ok works nice: tmp := tblcases.fieldbyname('field1').asstring; str := tblcases.fieldbyname('field2').asstring; delete (tmp,lastdelimiter ('}',tmp),1); delete (str,1,1); ms := tstringstream.create (tmp+ ansistring (#13#10)+str); ms.position :=0; dbdx.lines.loadfromstream(ms); ms.free; to merge 2 rtf fields removed last closing } of first , first bracket of second creating 1 string. use tstringstream paste in trichedit. see updated code above.

PHP - split array by key -

i've got following array, containing ordered non consecutive numerical keys: array ( [4] => 2 [5] => 3 [6] => 1 [7] => 2 [8] => 1 [9] => 1 [10] => 1 ) i need split array 2 arrays, first array containing keys below 5, , other array consisting of keys 5 , above. please note keys may vary (e.g. 1,3,5,10), therefore cannot use array_slice since don't know offset. do know simple function accomplish this, without need of using foreach ? just found out array_slice has preserve_keys parameter. $a = [ 4 => 2, 5 => 3, 6 => 1, 7 => 2, 8 => 1, 9 => 1, 10 => 1 ]; $desired_slice_key = 5; $slice_position = array_search($desired_slice_key, array_keys($a)); $a1 = array_slice($a, 0, $slice_position, true); $a2 = array_slice($a, $slice_position, count($a), true);

android - How to create a custom check box by inflating a layout -

i want create custom check box view, inflating layout, want manipulate views in layout based on check box status (checked/unchecked), want add custom xml attributes view. take on creating view class , custom components

c# - invoke causes Cannot access a disposed object -

i have form in load page create thread , delegate show position every time updated : private delegate void updatelistboxdelegate(); private updatelistboxdelegate updatelistbox = null; private void frmmain_load(object sender, eventargs e) { pictureboxonlinetrain.parent = pictureboxmetromap; updatelistbox = new updatelistboxdelegate(this.updatestatus); // initialise , start worker thread workerthread = new thread(new threadstart(this.getonlinetrain)); workerthread.start(); } so in load form called thread: private bool stop = false; public void getonlinetrain() { try { while (stop!=true) { timetablerepository objtimetablerepository = new timetablerepository(); onlinetrainlist = objtimetablerepository.getall().tolist(); objtimetablerepository = null; if(stop!=true) i

php - mysql special date output format -

as part of live chat script uses php/mysql on serverside , js/jquery on clientside want output date of each message in special format. if message send today this(for example): today 22:30 , if sent yesterday : yesterday 12:30 , if send before yesterday should output date format: dd.mm.yy h:i (for example 28.05.14 22:19) . of course know php easily, better performance want using sql. i´ve read lot in mysql documentation altough found lot of date formating, couldn´t find this. now want know if possible sql? the date of each message stored timestamp in db. use query below. must fulfill requirements(with or without modifications). select if(date_format(`created`, '%y-%m-%d') = date(now()), 'today ' + date_format(`created`, '%k:%i'), (select if(date_format(`created`, '%y-%m-%d') < date(now()), (select if(date_format(`created`, '%y-%m-%d') = (date(now() - interval 1 day)), 'yesterday ' +

date - How can Joda or Java returns true if day is the first day of the month? -

how in joda or java can write method returns boolean value if today first day of current month ? if today's date first day of month, return true . it this: public static boolean isfirstdayofthemonth( date datetoday ){ boolean isfirstday = false; //code check if datetoday first day of current month. returns isfirstday; } thank in advance! with java se 8: public static boolean isfirstdayofthemonth(localdate datetoday ){ return datetoday.getdayofmonth() == 1; }

c# - Custom MapReduce Hive not Java -

is possible add mapper and/or reducer scripts written in else java hive query? i prefer c# if possible. cheers, joe check out hadoop streaming . while won't efficient using java: the utility allows create , run map/reduce jobs executable or script mapper and/or reducer.

Genymotion 2.2.2 issues with gapps -

i have downloaded , installed genymotion 2.2.2 (which cane virtualbox) , downloaded gapps 4.4 problem have after flashing armt v1.1, error message saying "oops, flashing gapps encountered , error , unable perform." kinda message when want flash gapps. there can me issue because i'm lost here. simply cant install wrong gapps version 4.4 in emulator device running 2.2.2 , must match to fix :- 1- first thing download "genymotion-arm-translation_v1.1 " can download here or mirrors 2- second download proper gapps android version(genymotion emulator) this link contain versions

sql - Import CSV File into a SQLite Database via PHP -

i want import table csv file sqlite db via php script can manually run update data. heres list of want achieve: rename old table (which called "produkte") product-currentdate (or drop table) then import files csv file ( ; separated , iso 8859-1 charset / first row of csv-file contains table header) save date in table "product" i've found script reason not work: <?php $dir = 'sqlite:test.sqlite'; $dbh = new pdo($dir) or die("cannot open database"); $query = <<<eof load data local infile 'produkte.csv' table produkte fields terminated ';' optionally enclosed '"' lines terminated '\n' ignore 1 lines (id, hauptmenue, produktgruppe, beschreibung, text, bild, shop, info) eof; $dbh->query($query); ?> i hope knows how solve problem... best regards dave federico cingolani has posted php script @ github meets needs <?php function import

algorithm - find longest subsequence with non-negative sum -

let's have array of n real numbers. want find longest contiguous subsequence in array it's sum greater or equal zero. it has done in linear time. we have no idea how start answering this. thanks in advance. for this, create subsequence (here designated ibeg , iend , , length len ) , march along sequence, extending subsequence @ end or shrinking @ beginning maintain >0. since inner loop constrained length of current sequence still o(n). var ibeg = 0; var iend = 0; var len = 0; var best_len = -1, best_ibeg = 0, best_iend = 0; var acc = 0; var = 0; var n = length(sequence); while i<n acc += sequence(i); len++; iend++; if acc>0 if len>best_len best_len = len; best_ibeg = ibeg; best_iend = iend; end else while ibeg<=iend acc -= sequence(ibeg); ibeg++; if acc>0, break; end end end end then best_len length of longest sequence, , best_ibeg ,

ios - Kill another running (background) application -

i want create app has sole purpose of quitting waze app. the app launched when in car automatically (bluetooth connect trigger activator). annoyance have go menu , press power button icon within waze make go sleep mode. in opinion should offer option go sleep mode if press 'home', don't. i'd create app launched bluetooth disconnect trigger activator , closes waze , closes itself. know how code second part, i've no idea how can close running/background application. i tried killall waze or killall com.waze.iphone without success. note: it's jailbreak only.

php - Get parameters value from another url -

in .cgi file set $http_proxy= '192.168.1.1:80' how can 192.168.1.1:80 text file on host or url (for example line 4 data.txt in http://url.com/data.txt ). if want read contents of file can use $raw = file_get_contents('http://urlcom/data.txt'); $file = explode("\n", $raw); echo $file[3]; // read line 3 the file must accessible (by host/system/etc).

c# - FileSystemWatcher changed event not firing for recently opened file -

i implemented filesystemwatcher in windows forms application. changed event working when open file (say pdf-1) first time. when open same file second time within short span of time, changed event not firing. firing when open file (say pdf-2). again changed event firing first file (pdf-1) if open after time (say 1 or 2 hours). i set internalbuffersize 16kb , notifyfilters used lastaccess , lastwrite , filename , directoryname . i unable find out issue. can me out? i have seen similar results filesystemwatcher raid controller disks, scsi disks , regular ide disks write cache enabled . i experienced lot of other errors may have been caused thread synchronization problems . here description of problem .

angularjs - Angular directive link function with 4 arguments? -

in angular developer guide find example: var integer_regexp = /^\-?\d+$/; app.directive('integer', function() { return { require: 'ngmodel', link: function(scope, elm, attrs, ctrl) { ctrl.$parsers.unshift(function(viewvalue) { if (integer_regexp.test(viewvalue)) { // valid ctrl.$setvalidity('integer', true); return viewvalue; } else { // invalid, return undefined (no model update) ctrl.$setvalidity('integer', false); return undefined; } }); } }; }); q) fourth argument in link function, , bind to? thought link function take 3 arguments. it's controller or array of controllers, specified in required property of directive definition object. in particular case it's controller of ngmodel directive on same element more info here

android - How to set custom EmptyView for listview in Navigation Drawer -

i want show custom view empty view in list view in drawer layout! create view in xml , called view_custom_empty.xml: <?xml version="1.0" encoding="utf-8"?> <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffff0000"> <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerhorizontal="true" android:layout_centervertical="true" android:text="no result" android:textcolor="#ffffffff" /> </relativelayout> in activity set list view emptyview this: view emptyview = getlayoutinflater().inflate(r.layout.view_custom_empty, null); viewgroup viewgroup = (viewgroup) drawerlayout.getparent(); viewgroup.addview(emptyview

java - How to set column width of Jtable equal to a checkbox -

Image
below picture. i using following code it's not setting width size of checkbox tablecolumn column = null; column = table.getcolumnmodel().getcolumn(0); column.setpreferredwidth(1); i want remove spaces around checkbox the tablecolumn has 3 widths, minimum, preferred , maximum. setting width 1 makes no sense since checkbox won't paint in 1 pixel, guess minimum value being used. also, depending on auto resize property value overridden make sure column widths fill table view. try setting minimum , preferred sizes same (reasonable) value. a better approach not guess @ width since change different laf's. instead can use renderer determine appropriate width column. see table column adjuster basic example code can use , more complex class provides complete solution.

web applications - Web archive file with non compiled java code -

i have .war file has directory structure below: root |_meta-inf |_theme (css files) |_web-inf |_lib |_src (java source code) as can see above, there no classes folder. searched throughout root directory , didnt find .class files. does know if .class files generated during application server runtime? if so, how done. to more specific i'm encountering problem sap business objects sdk - jsfplatform.war file. i'm trying reverse engineering unable understand how process working.

ios - How to write array data into excel file (CSV) in objective c -

i trying write array data excel (actually csv, opened in excel). used following code that: nsmutablearray *list; list = [[nsmutablearray alloc] init]; nsstring *string = [list componentsjoinedbystring:@","]; nsdata *data = [string datausingencoding:nsutf8stringencoding]; nsarray *paths = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes); nsstring *documentsdirectory = [paths objectatindex:0]; nsstring *appfile = [documentsdirectory stringbyappendingpathcomponent:@"yourfilename.csv"]; [data writetofile:appfile atomically:yes]; it works fine, problem have 20 objects in 'list' array , 20 objects written in side side cells. want write first 4 objects in 1 line , move new line , again write next 4 objects in line till objects in list array completed. can me issue? nsmutablearray *list = ... nsmutablestring *buffer = [nsmutablestring string]; (nsuinteger = 0; < list.count; i++) { nsstring *value = lis

postgresql - PL/pgSQL : Does DISTINCT ON passes through with it's result onto next CTE? -

my code looks (schema), because it's pretty huge: something ( select distinct on (x1,x2,x3,x4) ... ), something2 (xx.*, ... xx left join ...), something3 (xx.*, ... something2 xx left join ...) select ... something3 so imagine situation: after using distinct on (x1,x2,x3,x4) in something , then select * (ignoring something2 , something3 here) : i 1700 results. but the problem is not expected result (yet), because need use more cte leftjoin information so when have same distinct on in something , select * something3 (which final expected result should return 1700 rows) i 4000 results values wanted distinct earlier on in something . it seems i'm losing distinct i've typed in something , because when put same syntax: distinct on (x1,x2,x3,x4) ... in 3 something's 1700 results - it's not i'm looking for. time means me. could me out solution , better understanding of problem here? this happens, because : ctes can th

grails - How to use optionKey and optionValue on g:select when passing a map -

i have list of key value pairs in controller, list instances= [ 'xxxxx':'yyyyy', 'aaaaa':'bbbbb',' ] [instances:instances] and in gsp <g:select name = "sinstance" from="${instances}" optionkey="key" optionvalue ="value" /> but resulting error error processing groovypageview: error executing tag : error executing tag : no such property: key class: java.lang.string i'm looking for: <option: value='xxxxx'> yyyyy like joshua moore mentioned, passing map, not list. should either fix in controller, or can call .entryset() tag: <g:select name="sinstance" from="${instances.entryset()}" optionkey="key" optionvalue="value" />

c# - Linq to entities with raw stored procedure returns duplicate copies of data -

interfacing sql server 2008r2: i have linq expression: iqueryable<xxx> xxxresult = (from t in _context.xxxx.asnotracking().include("yyy") t.zzz >= lownumber && t.zzz <= highnumber && t.qqq == somevalue select t); (it doesn't matter on exact query, it's there in case does.) linq generated sql sql server generated terrible plan, and, since can't add index/join hints, created stored procedure wrapped sql above linq expression generated. i know should able access stored procedure through entity framework, i'm using previous project used light code-first implementation (no .edmx file, instance) , i'm kinda new whole ef thing , didn't know how tie new procedure ef. know can done, trying call procedure directly. i worked out: iqueryable<xxx> xxxresult = _context.xxxx.sqlquery("getdata @p0, @p1, @p2", somevalue, lownumber, highnumber)

c# - How to write text to a file in Windows Phone 8? -

i found example of how write data file in windows phone 8: https://stackoverflow.com/a/15625701/181771 public async task writedatatofileasync(string filename, string content) { byte[] data = encoding.unicode.getbytes(content); var folder = applicationdata.current.localfolder; var file = await folder.createfileasync(filename, creationcollisionoption.replaceexisting); using (var s = await file.openstreamforwriteasync()) { await s.writeasync(data, 0, data.length); } } this works, text encoded. i'm attempting write json file i'd save raw text. what need accomplish this? use streamwriter automatically deal encoding. public async task writedatatofileasync(string filename, string content) { var folder = applicationdata.current.localfolder; var file = await folder.createfileasync(filename, creationcollisionoption.replaceexisting); using (var s = await file.openstreamforwriteasync()) { using (var writer = new streamwriter(s)) { await writ

database partitioning - MySQL Partition by Month not working -

i create table by create table `part_tab` ( `id` int not null, `use_time` datetime not null ) engine=innodb default charset=utf8 partition hash(month(use_time)) partitions 12; then use explain partions syntax, seems mysql didn't use partition, still scans whole table: mysql> explain partitions select * part_tab use_time < '2013-02-01' \g *************************** 1. row *************************** id: 1 select_type: simple table: part_tab partitions: p0,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11 type: possible_keys: null key: null key_len: null ref: null rows: 12 extra: using 1 row in set (0.00 sec) if change condition equal,the partition used: mysql> explain partitions select * part_tab use_time = '2013-02-01' \g *************************** 1. row *************************** id: 1 select_type: simple table: part_tab partitions: p2 typ

php - Two different actions in a form cakephp -

i using cakephp 2.4 , want form 2 buttons each button should have own action don't know how can redirect submit-a action1 , submit-b action2. <div class="form information"> <?php echo $this->form->create('soya', array('action' => 'reportecompravsprod')); ?> <?php // here goes forms ?> <div class="submit"> <?php echo $this->form->submit('vista', array('class' => 'form-submit', 'name' => 'submit-a')); echo $this->form->submit('reporte', array('class' => 'form-submit', 'name' => 'submit-b')); ?> </div> </div> using javascript, there many ways accomplish you're trying do. the easiest make onclick() on button, , change "action" of form before submitting.

java - Simplify DAO Layer with Resteasy / Hibernate / Spring -

i'm looking cleaner code dao layer : i have generic dao interface : public interface genericdao<t> { t save(t entity); t merge(t entity); void delete(t entity); t findfromid(int id); list<t> findall(); } an abstract implementation : public abstract class abstractgenericdaoimpl<t> implements genericdao<t> { [...] } for each database entity, have 2 files : an interface : public interface userdao extends genericdao<userpe> { } a concrete class : @repository public class userdaoimpl extends abstractgenericdaoimpl<userpe> implements userdao { [ no code entities ] } i'm using spring injection : @autowired private userdao userdao; i'd use generic dao common entities, : @autowired private genericdao<myentity> myentitydao; but spring doesn't want inject (nosuchbeandefinitionexception) , don't know how configure hibernate queries (which needs entity classes). i'm usi

uiview - Layout subviews not working properly -

i have troubles custom view im designing. table display 12 labels, upper left label , lower left label has width*5 of other views. have added views , adjusted frame in layout subviews, labels not appear in view (already checked new views debugger of xcode override func layoutsubviews() { super.layoutsubviews() let width = self.frame.size.width let height = self.frame.size.height let normalwidth = width/10 let normalheight = height/2 var currentorigin = cgpoint(x: 0, y: 0) let namesize = cgsize(width: normalwidth * 5 - 3, height: normalheight) labels[0][0].frame = cgrect(origin: currentorigin, size: namesize) currentorigin.x += normalwidth j in labels[0]{ j.frame = cgrect(origin: currentorigin, size: cgsize(width: normalwidth - 3, height: normalheight)) currentorigin.x += normalwidth } currentorigin.y = normalheight currentorigin.x = 0 labels[1][0].frame = cgrect(origin: currentorigin, size: namesiz

haskell - Finding a value in ByteString (which is actually JSON) -

a web service returns response bytestring req <- parseurl "https://api.example.com" res <- withmanager $ httplbs $ configreq req case (hashmap.lookup "result" $ responsebody res) of .... -- error - responsebody returns bytestring configreq r = --...... to more specific, responsebody returns data in bytestring , although it's valid json. need find value in it. obviously, easier find if json , not bytestring . if that's case, how convert json? update: decode $ responsebody resp :: io (either string aeson.value) error: couldn't match expected type `io (either string value)' actual type `maybe a0' you'll find several resources converting bytestring json. simplest use cases on hackage page itself, , rest can infer using type signatures of entities involved. https://hackage.haskell.org/package/aeson-0.7.0.6/docs/data-aeson.html but here's super quick intro json aeson: in langu