Posts

Showing posts from April, 2014

java - How to make JVM hang for a given time period? -

i trying simulate gc in local environment. there way can make jvm hang 5 mins? if on linux system (most other unixes have this), can do pkill -stop java; sleep $(( 5 * 60 )); pkill -cont java to pause java process 5 minutes. pkill -tstp java; sleep $(( 5 * 60 )); pkill -cont java is less agressive. but nowhere garbage collector break .

sql - How to get the values of comma delimited string into a table? -

i have string @str =11,22 in variable. how can insert table like, id num ------------- 1 11 2 22 here's simple way you're looking although dependent on values being split comma , having no spaces (although can use trim if believe happen): declare @str varchar(10) = '11,22,33' declare @foobar table (id int identity (1,1), num int) while (charindex(',', @str) > 0) begin insert @foobar (num) select left(@str, charindex(',', @str) - 1) set @str = (select substring(@str, charindex(',', @str) + 1, len(@str))) end if len(@str) > 0 insert @foobar (num) select @str select * @foobar and here sql fiddle: http://www.sqlfiddle.com/#!6/0e240/2/0

yacc - execute action in PLY Python before the symbol are parsed -

i'm making parser parse tokens 3 address code. generate correct tac code when calling function need call function "givetac" before , after tokens parsed. my problem can't find way call function before parses token. in documentation of ply there section 6.11 embedded actions claims can add empty rule this: def p_foo(p): "foo : seen_a b c d" print("parsed foo", p[1],p[3],p[4],p[5]) print("seen_a returned", p[2]) def p_seen_a(p): "seen_a :" print("saw = ", p[-1]) # access grammar symbol left p[0] = some_value # assign value seen_a but if try in code "syntax error in input!" error. code: def p_fun_declaration_type_formal_pars_block(p): 'fun_declaration : before type name lpar formal_pars rpar block' def p_fun_before_fun(p): 'before :' givetac("function",none,none,'main') p[0]=p[1] if remove "before...

matlab - How to select rows from a matrix -

i beginner in matlab. saving file using, eval(['save(''results/loc_', num2str(location) ,''',''values'')']); i have 54 locations. in case save 54 files named loc_1,loc_2...loc_54 in new folder named 'results'. size of each file 15x7. in case number of columns remain same. number of rows change. if take 1 trial,then 'loc_1' give 3x7 values. if take 2 trials, 'loc_1' give 6x7 values , on. in case want take 'trial' variable , value 5. each file named loc_1,loc_2,..,loc_54 give me 15x7 values. now want separate first 5 rows (and 7 columns) loc_1 , need save them in 3 different files , size of each file 5x7. have save loc_numstr(location) files (that total of 54 files) , separate them this. have 3 sets of 54 files of each size 5x7. in case taking 5 trials, separating 5x7 size of each file. 4 trials, need consider 4x7 , on. any kind of appreciated. thanks. i think made bit complicated. can explain m...

java - Why can't a thread-unsafe class work while using just getter and setter? -

i have class follow: public class boolflag { boolean flag; public boolflag() { flag=false; } public synchronized void setflag(boolean flag) { this.flag=flag; } public synchronized boolean getflag() { return flag; } } if don't set getter , setter synchronized,it cause problem follow: when set object of boolflag called imageready in 1 buttonclick listiner: if (status == jfilechooser.approve_option) { try { system.out.println("file chosen"); imgfile=chooser.getselectedfile(); image.setimg( imageio.read(imgfile) ); imageready.setflag(true); } catch(exception e) { system.out.println("file not opened"); } } then in thread: public void run() { boolean running=true; while(running) { // system.out.println(...

javascript - Get database if combobox is selected in data table -

i've created functionality can databases listed view. after loop through documents , can display them accordingly in data table using computedfields. here's code have: try { var viewdocs:java.util.vector = new java.util.vector(); var relcol = database.search("form='dbpick_kappa'"); var bazu_skaits= relcol.getcount(); var doc:notesdocument = relcol.getfirstdocument(); var alldocs:java.util.vector = new java.util.vector(); (j=1;j<bazu_skaits+1;j++) { viewdocs.add(doc); var serveris = doc.getitemvaluestring("server_p"); var datubaze = doc.getitemvaluestring("filename_p"); var db:notesdatabase = session.getdatabase(serveris, datubaze,false); var sender = getcomponent("senderbox").getvalue(); var allrelevant:notesdocumentcollection = db.search("statusflag='" + sender + "'"); var skaits = allrelevant.getcount(); var tmpdoc = allrelevant.getfirstdocument(); ...

data structures - List manipulation performance in Haskell -

i learning haskell , curious following: if add element list in haskell, haskell returns (completely?) new list, , doesn't manipulate original one. now let's have list of million elements , append 1 element @ end. haskell "copy" whole list (1 million elements) , adds element copy? or there neat "trick" going on behind scenes avoid copying whole list? and if there isn't "trick", process of copying large lists not expensive think is? it depends on data structure you're using. if you're using normal haskell lists, these analogous typical linked list implementation in c or c++. structure, appends o(n) complexity, while prepends o(1) complexity. if try append million elements, take o(500000500000) time (o(1) + o(2) + o(3) + ... + o(1000000)) approximately 500000500000 operations. regardless of language you're using, haskell, c, c++, python, java, c#, or assembler. however, if use structure data.sequence.seq , use...

objective c - iOS How to check if valueForKey exist or not? -

i have question checking existence of valueforkey. here's code: id _jsonid = [nsjsonserialization jsonobjectwithdata:[_json datausingencoding:nsutf8stringencoding] options:0 error:&_error]; monday = [[nsmutablearray alloc] init]; if ([_jsonid valueforkey:@"mon"]!= nil) { _keymon = [_jsonid valueforkey:@"mon"]; [monday addobject:@"monday"]; (int i=0; i<5; i++) { if ([_keymon objectatindex:i]!=[nsnull null]) { [monday addobject:[_keymon objectatindex:i]]; } } } else { [_keytues addobject:@"no class today"]; [monday addobject:[_keymon objectatindex:1]]; } the idea is, if _jsonid valueforkey came nothing, can add nsstring addobject:@"no class today incase xcode tells me that: *** terminating app due uncaught exception 'nsinvalidargumentexception', reason: '*** -[__nsarraym insertobject:atindex:]: object cannot nil' like has been telling me now. have sol...

java - What is the correct way to compare two throwables? -

i using junit rule re-run failed tests. requirement is, if re-run fails, determine whether failed same reason. to i've adapted code this answer keep record of failures , compare them. however, comparison (.equals) evaluates false despite them failing same reason. best way go this? private statement statement(final statement base, final description description) { return new statement() { @override public void evaluate() throws throwable { (int = 0; < retrycount; i++) { try { base.evaluate(); return; } catch (throwable t) { system.err.println(description.getdisplayname() + ": run " + (i + 1) + " failed"); // compare error 1 before it. if (errors.size() > 0) { if (t.equals(errors.get(errors.size() - 1))) { system.out.println("the error same previous one!"); } else { system.ou...

ios - Is there a way to know if a user taps on a WKInterfaceMap? -

on watchkit, map component wkinterfacemap object. this ui component default, loads main map app on apple watch when user taps on it. i can keep track of controller's diddeactivate() event, have no idea if because user stopped using watch, tapped map or went somewhere else. unfortunately, there no method or event in watchkit determine if user tapped on wkinterfacemap . closest technique use diddeactivate , , you've enumerated challenges approach.

asp.net web api - OAuth JWT access token expiration depending on type of client -

i created jwt token implementation based on taiseer's tutorial . the following code added owin startup class: oauthauthorizationserveroptions oauthserveroptions = new oauthauthorizationserveroptions() { allowinsecurehttp = httpcontext.current.isdebuggingenabled, tokenendpointpath = new pathstring("/oauth2/token"), accesstokenexpiretimespan = timespan.fromminutes(90), provider = new customoauthprovider(), accesstokenformat = new customjwtformat("http://example.com/") }; now there different types of apps use api. web clients, 90 minute expiration enough, mobile apps far short. is there way mobile apps token expiration 1 year now? use custom http headers differentiate between types of apps. tried extend expiration in protect method of customjwtformat class, indeed allows larger expiration in jwt. public class customjwtformat : isecuredataformat<authenticationticket> { public string protect(authenticationticket data) { ...

angularjs - Leaflet click event not working on iPad -

i'm using angular leaflet directive. working on laptop. on ipad, double click working click event not working @ all. have 1 event handler click doesn't triggered. $scope.events = { map: { enable: ['mousedown', 'dblclick', 'click'], logic: 'broadcast' } }; $scope.$on('leafletdirectivemap.mousedown', function(event) { alert('click'); }); $scope.$on('leafletdirectivemap.click', function(event) { alert('click'); }); $scope.$on('leafletdirectivemap.dblclick', function(event) { alert('dbclick'); }); double click event gets triggered other ones not. can try debug this? checkout https://github.com/angular/material/issues/1300 . having below code fixed issue us, $mdgestureprovider.skipclickhijack();

java string Constant : hex value for a single character - how? -

i need replicate character in unix file, looks this: cat myfile | xxd -ps | sed 's/[[:xdigit:]]\{2\}/\\x&/g' result -> ... \xa4 ... how can put character, looks hex a4 string literal in java? i tried this, doesn't work: public final static string separator = "\ua4"; (it's same me if constant string or char...) thanks help! strings encoded in utf-16 in java. try this; public final static string separator = "\u00a4"

python 3.x - No module named 'django.templates' -

i using python 3.4, django 1.8. using pycharm developing. while running program ,i getting 'no module named 'django.templates'' error. settings.py """ django settings dj project. generated 'django-admin startproject' using django 1.8.1. more information on file, see https://docs.djangoproject.com/en/1.8/topics/settings/ full list of settings , values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # build paths inside project this: os.path.join(base_dir, ...) import os base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # quick-start development settings - unsuitable production # see https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # security warning: keep secret key used in production secret! secret_key = 'uhqkhi7h_w48bz*gnr+_!roaa8@c_)087a(!ees)mn2=n=lv-r' # security warning: don't run debug turned on in production! debug = true allowed_hosts = [] # a...

java - Spring REST best practice for method types -

i building spring restfull service , have following method retrieves place object based on given zipcode: @requestmapping(value = "/placebyzip", method = requestmethod.get) public place getplacebyzipcode(@requestparam(value="zipcode") string zipcode) { place place = placeservice.placebyzip(zipcode); return place; } is best practice have return type of "place"? imagine difficult error handling? using latest versions of spring restfull web service believe returning 'object' practise allows simplify code , specific on returning. see typing api response. a practise error handling use controller advice utility supplied spring. have read of: https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc this allows throw exceptions @ of service layers , produce nice helpful error response.

http headers - How to set Etag for a url in play framework? -

i have searched set etag in playframework. got are 1) https://www.playframework.com/documentation/2.0/assets 2) https://www.playframework.com/documentation/2.0/javaresponse first option works asset or files. second option not work. added 3 given in example. actually usage of etag described in play's doc assets (that linked first) , in wikipedia typical usage section . at beginning of action need determine if requested resource has been changed since previous generation of etag, if yes, need generate new content new etag, otherwise return 304 notmodified response. of course depends on kind of requested resource, anyway quite clean sample may database entity, id , field date/time of last modification: public static result etaggedfoo(long id) { foo foo = foo.find.byid(id); if (foo == null) return notfound("given foo not found"); string etag = digestutils.md5hex(foo.id + foo.lastmodification.tostring()); string ifnonematch = reques...

mysql - NULL values in where condition is not working -

i have encountered weird problem in mysql query. following query returning me 0 result whereas there many rows should returned. query is select distinct sku, ean, url, cid tab_comp_data status ='' and in many rows there null values in status column returns me no rows. i have tried other way round. select distinct sku, ean, url, cid tab_comp_data status <>'inact' this returns me no rows. p.s. status column can null or 'inact' i want query null values, should use is null operator. so, query should like: select distinct sku, ean, url, cid tab_comp_data status null

Powershell execute file with path in parameters -

i trying run sqlpackage.exe powershell using variable string sourcefile parameter: $fileexe = "c:\program files (x86)\microsoft sql server\120\dac\bin\sqlpackage.exe" & $fileexe /action:publish /sourcefile:$outputvariable\file.dacpac /profile:c:\sql\file.sqldatabase.publish.xml where $outputvariable folder containing full path unfortunately following error: sqlpackage.exe : *** illegal characters in path. @ c:\powershell\test.ps1:20 char:6 + & $fileexe /action:publish /sourcefile:$outputvariable\file.dacpac /profile:c ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + categoryinfo : notspecified: (*** illegal characters in path.:string) [], remoteexception + fullyqualifiederrorid : nativecommanderror i tried surrounding quotes , splitting parameters did not solution. idea? thanks in advance! apparently trimming $outputvariable $outputvariable.trim() the problem fixed.

ios - Local HTML Cache policy in UIWebView -

i have walked through various solution clear local image cache in uiwebview, while trying load image in html atomically displays previous image(i using same name replace image in template). [[nsurlcache sharedurlcache] removeallcachedresponses]; nsmutableurlrequest *request = [[nsmutableurlrequest alloc]initwithurl:[nsurl fileurlwithpath:[[customfunctions getfilespath] stringbyappendingpathcomponent:obj]] cachepolicy:nsurlrequestreloadignoringlocalcachedata timeoutinterval:30.0]; [webview1 loadrequest:request]; [webview1 reload]; this code , can 1 please suggest me this. in advance. sorry english. //to prevent internal caching of webpages in application nsurlcache *sharedcache = [[nsurlcache alloc] initwithmemorycapacity:0 diskcapacity:0 diskpath:nil]; [nsurlcache setsharedurlcache:sharedcache]; //[sharedcache release]; sharedcache = nil; try using this. clear url cache memory of application.

wpf - C# OpenFileDialog - exception when no files are chosen -

i trying work out on error, when no files chosen program goes next step although shouldn't. have tried: if (filetocheck != null) but didn't work. other suggestions? private void mail(object sender, routedeventargs e) { openfiledialog openfiledialog = new openfiledialog(); openfiledialog.filter = "text files (*.txt)|*.txt|all files (*.*)|*.*"; if (openfiledialog.showdialog() == true) { spamtext.text = file.readalltext(openfiledialog.filename); } string[] filetocheck = { openfiledialog.filename }; splitter(filetocheck); mail = tempdict; } you on right track. but checking if (filetocheck != null) not enough, since when no file selected, openfiledialog.filename contains empty string, not null. so can use if (!string.isnullorempty(filetocheck)) check. another way - put code around filetocheck outside of openfiledialog.showdialog() == true condition inside of it. looks more logical,...

Which is the fastest way to get a slice of an array in c? -

i this: char in[] = {'a','b','c','d','f','r','t','b','h','j','l','i'}; char out[3]; out = &in; and first 3 characters but error of incompatible types out array name , can't modified. there's no straight forward way slice of array in c. can use memcpy : memcpy(out, in, sizeof out); and need take in has sufficient elments copy from.

Memory decline when use drools stream mode -

i use drools 6.2.final fusion cep, , have set event @expires (1d), found memery have been declining few days later. every day total of event data not much.i doubt event in working memery after expiration not clear.so want confirm something: 1.fusion cep stream mode stateful session must dispose() after fireallrules()? in code ksession create once @ init method, , use insert event , fire rules, never use dispose() method after fire. i'm worried not did not use method caused event has been kept in memory. 2.the event after expiration automatically removed memory? fear event not cleared, resulting in memory has been declining. @org.kie.api.definition.type.role(org.kie.api.definition.type.role.type.event) @org.kie.api.definition.type.typesafe(true) @org.kie.api.definition.type.timestamp("begintime") @org.kie.api.definition.type.expires("1d") public class event{ private long begintime; // ...other fields, set , method.. } -- poublic void initks...

windows phone 8.1 - Long-running task performed in foreground is suspended when app goes to background -

when user first opens app, need download , install content server before can begin using app. problem takes around 5 minutes on wifi, during time app goes background , download suspended. is there way either: prevent windows app entering background while perform download or continue peforming task in background (i.e. perform task irrespective of whether app in foreground or background) also, don't want use backgrounddownloadmanager thanks when app being suspended, processes stopped , and background task cancelled. last chance suspending event - see more @ msdn . in case, when need download big file in background - mentioned backgrounddownloader best option - it's designed such tasks. in other cases have convince user leave app in foreground (a message?), take care lockscreen (see displayrequest class). i'm not sure maybe able use backgroundtask (separate process), triggered maintancetrigger - user able download file in specific circumstances , ...

multithreading - Java - Close a thread with 'return' not working -

i have following code in class contains main method executorservice executor = executors.newfixedthreadpool(1); runnable formatconcentration = new formatconcentration(87); executor.execute(formatconcentration); system.out.println("called instance of formatconcentration"); while (!executor.isterminated()) { //stay alive thread.sleep(1000); system.out.println("still alive"); } system.out.println("program finished"); return; this creates instance of formatconcentration class. code following (i've taken of functionality out sake of example). public class formatconcentration extends thread{ private int numberofnewrows; formatconcentration(int rows) { this.numberofnewrows = rows; } public void run() { system.out.println("running formatting script"); final int numberofnewregistered = this.numberofnewrows; try { system.out.println("finished formatt...

ios - Detect tap on child bones -

i have dae object bones. want detect tap on specific bone method : - (nsarray *)hittest:(cgpoint)thepoint options:(nsdictionary *)options; this method returns parent node, wherever tap on object. how can handle ? thanks in advance. this not possible bones not have geometry hit. one trick can use creating simple invisible box on every bone. combine boxes , apply skelleton it. then, check hit test's geometryindex . another way create simple mesh in 3d software, follows bones no details make invisible , bind skeleton well. make note of position of each polygon , check against faceindex of te hit test.

ruby on rails - ng-token-auth $rootscope.user object changes on page refresh -

i'm getting issues using ng-token-auth devise-token-auth. sign in, sign , sign out working well. when refresh page while user signed in, $rootscope.user object gets updated value of signed in user. when clear cookies after each sign out, works fine. auth_headers being updated on each sign in/page refresh. config.change_headers_on_each_request set true in devise_token_auth.rb. i have same problem (i think). opened issue , apparently related pull request .

angularjs - Protractor removes element from the dom -

i'm stucked in test protractor, because of strange (and not cool) behaviour of template using. on page load, template has on overlay going hidden after 1 second in way: $(document).ready(function(config){ settimeout(function(){ $('.page-loading-overlay').addclass('loaded'); $('.load_circle_wrapper').addclass('loaded'); },1000); }); *that feel terrible me (don't want comment this) anyway test broken because of run faster second , throw error: unknownerror: unknown error: element not clickable @ point (463, 625). other element receive click: <div class="page-loading-overlay loaded">...</div> because overlay receive click. i found workaround setting timeout in test, slow down suite , ci/cd process. , make test code messy. here code: it('should test something', function(){ settimeout(function(){ // test code }, 1000); }); i wondering if there way remove elemen...

c# - How to resolve list of dependencies in Autofac? -

i want register type, resolve type, , register instance using resolved values. this: //register type: builder.registertype<validateimportmandatorycolumns>().named<ivalidateimport>("mandatorycolumn").as<ivalidateimport>(); builder.registertype<validateimportnonmandatorycolumns>().named<ivalidateimport>("nonmandatorycolumns").as<ivalidateimport>(); //resolve var t1 = container.resolvenamed<ivalidateimport>("mandatorycolumn"); var t2 = container.resolvenamed<ivalidateimport>("nonmandatorycolumns"); //create list resolved values: list<ivalidateimport> allvalidators = new list<ivalidateimport>(){t1,t2}; //register instance: builder.registerinstance(allvalidators).as<list<ivalidateimport>>(); this not working. can't resolve , register again. know how autofac? maybe approach wrong, please tell me if have better idea. goal inject list of validators different types us...

cordova - android keyboard changes layout of phonegap application -

Image
i create quiz application android using phonegap framework, first page of application contains sign form, want user information. code is <table class="m"> <tr> <td class="left">name:</td> <td class="right"><input class="t" type="text"/></td> </tr> <tr> <td class="left">image:</td> <td class="right"><input class="t" type="text"/></td> </tr> <tr> <td class="left">email:</td> <td class="right"><input class="t" type="text"/></td> </tr> <tr> <td class="left">phone:</td> <td class="right"><input class="t" type="text"/></td> </tr> </table> when click on text field android keyboard appears o...

php - Exceeding Maximum File Size Is Not Showing An Error -

i have written code should check whether file size exceeds 8.5 mb or not & if does, should produce , error , prohibit post entering db. code prohibiting post enter db not showing error stating file size exceeds. ( p.s: check unknown file format working.) here code have written: //$session id define ("max_size","9000"); function getextension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } $valid_formats = array("jpg", "png", "gif", "bmp","jpeg"); if(isset($_post) , $_server['request_method'] == "post") { $uploaddir = "uploads/"; //a directory inside foreach ($_files['photos']['name'] $name => $value) { $filename = stripslashes($_files['photos']['name'][$name]); $size=file...

android - App showing contact numbers three times -

i have created app in when button clicked activity opens , user has select contact. numbers contact has displayed on screen. working fine contact having more 3 numbers. when contact selected has 1 number , app instead of showing number 1 time shows same numbers 3 times. here code string contactnumber = ""; if(integer.parseint(cursor.getstring(cursor.getcolumnindex(contactscontract.contacts.has_phone_number))) > 0 ){ cursor phonecursor = getcontentresolver().query(contactscontract.commondatakinds.phone.content_uri,null, contactscontract.commondatakinds.phone.contact_id + " = " + indexid, null,null); while(phonecursor.movetonext()){ if(phonecursor.getcount() > 1){ contactnumber = contactnumber + "," + phonecursor.getstring(phonecursor.getcolumnindex(contactscontract.commondatakinds.phone.number)); contact_num = (textview) findviewbyid(r.id.contact_number); conta...

How to copy multiple files in one layer using a Dockerfile? -

the following dockerfile contains 4 copy layers: copy readme.md ./ copy package.json ./ copy gulpfile.js ./ copy __build_number ./ how copy these files using 1 layer instead? following tried: copy [ "__build_number ./", "readme.md ./", "gulpfile ./", "another_file ./", ] copy readme.md package.json gulpfile.js __build_number ./ or copy ["__build_number", "readme.md", "gulpfile", "another_file", "./"] you can use wildcard characters in sourcefile specification. see docs little more detail . directories special! if write copy dir1 dir2 ./ that works like copy dir1/* dir2/* ./ if want copy multiple directories (not contents) under destination directory in single command, you'll need set build context source directories under common parent , copy parent.

python - Convert argument to string -

never work struct before. when hire developer work, used this, doesn't work. , developer doesn't answer... please, can problem? from views.py , can see below, got error struct() argument 1 must string, not unicode in 'invid': str(struct.unpack('=h', urandom(2))[0]), . so, how convert string? @login_required def userprofile(request, username): extra_context = dict() if request.post: user_form = userform(request.post, instance=request.user) user_profile = userprofileform(request.post, request.files, instance=request.user.profile) if user_form.is_valid(): user_form.save() if user_profile.is_valid(): user_profile.save() else: user_form = userform( instance=request.user, initial={ 'first_name': request.user.first_name, 'last_name': request.user.last_name, ...

html - List items not correctly aligning with an ng-repeat -

Image
i have simple ng-repeat <li> . each <li> consumes 33.33% of width 3 items per row. however, reason items in second row not line up. after big of digging, if apply min-width of say, 400px , works. but, can not description text length dynamic. html: <ul class="grid-wrap"> <li class="grid-col one-third" ng-repeat="job in jobs" ng-init="descriptionlimit = 20"> <div>{{ job.jobtitle }}</div> <div>{{ job.location }}</div> <div>{{ job.jobdescription | limitto:descriptionlimit }} <span ng-click="descriptionlimit = job.jobdescription.length"> >> </span></div> </li> </ul> css: ul, ol { list-style: none; padding: 0; margin: 0; } .grid-wrap { margin-left: -3em; /* same gutter */ overflow: hidden; clear: both; } .grid-col { float: left; padding-left: 3em; /* gutter between columns */ ...

c# - How to display a ComboBox in a DataGrid if the DataTable it is bound to has a list of items? -

i have dataset. don't know contents of set. have display table of set in datagrid. i'm able using following code. able work it, have created own dataset. customerdataprovider class have created has method returns dummy dataset. customerdataprovider provider = new customerdataprovider(); dataset ds = new dataset(); datatable table = new datatable(); dataview view = new dataview(); public mainwindow() { initializecomponent(); ds = dataset.getdataset(); table = ds.tables[0]; view = table.asdataview(); this.datacontext = view; } <grid> <datagrid x:name="dynamicgrid" itemssource="{binding path=., mode=twoway}" columnwidth="*" /> </grid> now, if datatable contains bool value, datagrid automatically displays checkbox. want able automatically display combobox if datatable contains list of items. how go achieving this? instead of auto-generating columns, set aut...

mysql - Get biggest value of group after join -

i have 2 tables in db: conversation: conversationid | persone | perstwo | timestamp 1 | 1 | 3 | 1431680294000 2 | 3 | 8 | 1431680407000 message: messageid | conversationid | senderid | receiverid | message | timestamp | seen 1 1 1 3 xyz! 1431680294000 0 2 2 3 8 hi x! 1431680405000 0 3 2 3 8 allt bra? 1431680407000 0 now want find latest message of each conversation. my approach right find conversations of user , try group conversationid: select distinct conversationid, senderid, receiverid, message, timestamp message conversationid in (select conversationid conversation persone = 3 or perstwo = 3) group conversationid order timestamp desc unfortunately these results: 2 3 8 hi x! 1431680405000 1 1 3 xyz! 1431680294000 even though need ...

javascript - jquery simple onclick event -

<a aria-expanded="false" data-toggle="tab" href="#pictures"> <i class="pink ace-icon fa fa-gift bigger-120"></i> pictures </a> i want wire on click #picture event alert message add $(document.ready(function() { $("#pictures").click(function(){ alert('clicked!'); }); }) but doesnt work, i've got no error messages inside firebug console. jquery loaded before correctly. in html there no element id pictures , change it, $("#pictures").click(function(){ alert('clicked!'); }); // or use selector this, if can't change html $('a[href="#pictures"').click(function(){ alert('clicked!'); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a aria-expanded="false" data-t...

I want to change key value getting bt json from Server in iOS -

Image
[server] array_push($msg,array("finished"=>@"1", . . .) array_push($msgs,$msg); $response = array("msgs"=>$msgs); echo json_encode($response); [client ] nsdictionary *responsedict = [nsjsonserialization jsonobjectwithdata:data options:0 error:&jsonparseerror]; nsmutablearray * umsgsinfoarray = [responsedict mutablearrayvalueforkey:@"msgs"]; } i want change client's "finished" key value(="1") in client. should do? i little bit confuse , if want how change "finished" key values please use below - [[[umsgsinfoarray objectatindex:0] objectatindex:1] setobject:@"1" forkey:@"finished"]];

regex - Match nth number by regular expression(QRegularExpression) -

i trying match nth number in string. ex : 0000_1111_2222_3333 the string[0] should 0000, string[1] should 1111 , on following solution qstring find_nth_match(qregularexpression const &reg, qstring const &input, int nth) { auto = reg.globalmatch(input); qregularexpressionmatch match; int count = 0; while(it.hasnext()){ match = it.next(); if(count == nth){ return match.captured(1); } ++count; } return "no match"; } i use following qdebug()<<"nth match == "<<find_nth_match(qregularexpression("(\\d+)"), "0000_1111_2222_3333", 2); it print "nth match == 2222" it possible match nth number regular expression?

css - Media Queries content adaptation -

i cannot handle correctly #main-wrapper behaviour @media screen , (min-width: 1400px) what trying #main-wrapper has 100% width resolution <1400px , >1400 width set 1336px now #menu-section overflows #content-section live example: http://solutionsmvo.nazwa.pl/nell-ogrody/o-nas/ code: #main-wrapper { width: 100%; overflow:hidden; } #menu-section { width: 25%; float: left; height:100vh; position: fixed; } #content-section { width: 75%; float:right; min-height: 100vh; } @media screen , (min-width: 1400px) { #main-wrapper {width: 1336px; margin: 0 auto;} } <div id="main-wrapper"> <div id="menu-section"> </div> <div id="content-section"> </div> </div> because #menu-section in <1400px has position: fixed; property, it's okay in case, when width > 1400px, problem occur. remove position: ...

How to find the difference between two rows of data consisting of date and time in R -

i working data file consisting of 1 column of date , time df time_stamp 1 2003-09-06t20:21:51z (2003-09-06--> year-month-days-hours-mintutes-seconds) 2 2003-09-06t20:22:36z 3 2003-09-06t20:22:51z 4 2003-09-06t20:23:06z 5 2003-09-06t20:24:56z 6 2003-09-06t20:25:06z i want find difference between 2 rows based on unit of minutes. have applied code 1st convert data date format, gives me error like: x<-as.date(df,format='%d/%b/%y:%h:%m:%s') error in as.date.default(datew, format = "%d/%b/%y:%h:%m:%s") : not know how convert 'datew' class “date” while mode(df) shows results of "list" any highly appreciated. output should as: df time_stamp time_duration 1 2003-09-06t20:21:51z 0 2 2003-09-06t20:22:36z 1 3 2003-09-06t20:22:51z 0.25 4 2003-09-06t20:23:06z 0.25 5 2003-09-06t20:24:56z 1.8 6 2003-09-06t20:25:06z 0.17 thanks, i...

java - The attribute value is undefined for the annotation type Produces for "MediaType.APPLICATION_JSON" -

i getting weird warning (while hovering red line in eclipse) simple restful service code: (eclipse draws red line under "mediatype.application_json") import java.util.list; import java.util.logging.logger; import javax.enterprise.inject.produces; import javax.persistence.entitymanager; import javax.persistence.entitymanagerfactory; import javax.ws.rs.core.mediatype; import javax.ws.rs.get; import javax.ws.rs.path; import com.mycompany.annotation.restfulserviceaddress; import com.mycompany.myproject.middleware.api.myservice; @restfulserviceaddress("/mycompany-middleware") public class myserviceimpl implements myservice { private entitymanagerfactory entitymanagerfactory; @get @path("/getstuff") @produces(mediatype.application_json) public list<object> getstuff() { entitymanager entitymanager = entitymanagerfactory .createentitymanager(); try { return entitymanager.createquery( "select s stuf...

swift - How to get current view from other view controller? -

i doing sign in/sign out feature app.when try sign out,i want called current view controller viewdidappear().because want refresh view lock label available sign in user.so need know current view controller displaying in app. help? if in navigation controller, can vc on top. self.navigationcontroller?.topviewcontroller will return viewcontroller on top of stack. you can check this other options. to point few: var topviewcontroller: uiviewcontroller? view controller @ top of navigation stack. var visibleviewcontroller: uiviewcontroller? view controller associated visible view in navigation interface. var viewcontrollers: [uiviewcontroller] view controllers on navigation stack.

twitter bootstrap - Symfony2 + Bootstrap3: customization of "block form_label" causes flipped form -

Image
i wanted place icons links on right part of labels. it's 100% solved (read here full story) in summary overrode block {%- block form_label -%} in template follows (i added "added part" below): {% extends "bootstrap_3_horizontal_layout.html.twig"%} {%- block form_label -%} {% if label not sameas(false) -%} {% if not compound -%} {% set label_attr = label_attr|merge({'for': id}) %} {%- endif %} {% if required -%} {% set label_attr = label_attr|merge({'class': (label_attr.class|default('') ~ ' required')|trim}) %} {%- endif %} {% if label empty -%} {%- if label_format not empty -%} {% set label = label_format|replace({ '%name%': name, '%id%': id, }) %} {%- else -%} {% set label = name|humanize %} {%- endif -%} ...

php - How to include select query for javascript? -

i have developed jvector map.now working fine.its showing details well.now want show country details database.its file javascript.finally have decided , create php database file database.php <?php content-type: application/json; $dbhost = "localhost"; $dbuser = "root"; $dbpass = ""; $dbname = "mydatabase"; $link = mysql_connect($dbhost, $dbuser, $dbpass) or die('could not connect: ' . mysql_error()); mysql_select_db($dbname) or die('could not select database'); $query = "select countryid,country,pdogcoregion,comments,ccl,category countrydetails country='canada'; "; $result = mysql_query($query) or die('query failed: ' . mysql_error()); $all_recs = array(); while ($line = mysql_fetch_array($result, mysql_assoc)) { $all_recs[] = $line; } echo json_encode($all_recs); mysql_free_result($result); mysql_close($link); ?> i have created simpl...

javascript - Ignoring task dependencies in gulp.js -

i have following task gulp.task('sass-build', ['clean-build'], function () { // stuff }); which requires clean-build finished before starting. however, use task gulp.watch without clean-build dependency. i'm aware solve helper task suggested in skipping tasks listed dependencies in gulp , require using gulp.run (which deprecated) or gulp.start (which isn't documented because it's considered bad practise). what better way of doing this? or way use gulp.run or gulp.start ? the approach showed in linked question not bad. instead of gulp.run can use simple functions same: var sassfunction = function() { return gulp.src('blahbla') .pipe(bla()) } gulp.task('sass-build', ['clean-build'], function () { return sassfunction() }); gulp.task('sass-dev', function () { return sassfunction(); }); gulp.task('watch', function() { gulp.watch('your/sass/files/**/*.scss...

json - Unable to the the Image to the desired position in android's custom listview -

recently, i've managed make custom listview in android displays image in list. however, have 1 problem cannot solve. tried simple, 1. display blinking icon list item has same date json data via web. 2. display image 2nd , 3rd position of listview. 3. , rest of list items, there no images shown. i have simple codition in custom adapter's getview method compares current date date gets retreived json data via web. i've set function i'm using below. if current date equal date json data, display image blinks(for testing purposes i'm using 2015/05/14). if position equal 2nd or 3 rd position display icon. else show nothing. however, images shows @ random positions of listview. there bug in code? how possible not show icons doesn't meet conditions ? if (days.get(position).trim().tostring().equals("2015/05/14")||days.get(position).trim().tostring()=="2015/05/14") { holder.left.setbackgroundresource(r.drawable.blinker); animationdr...

java - Clear file name when enter directory name and enter -

i'm working on opening file using jfilechooser here code jfilechooser filechooser = new jfilechooser(); filechooser.setacceptallfilefilterused(false); filenameextensionfilter filter = new filenameextensionfilter("ff files", "ff"); filechooser.addchoosablefilefilter(filter); int result = filechooser.showdialog(null, "pp"); on button click event these code running, normal code guess. when click it, jfilechooser dialog appears. if enter directory name in file name field (ex. sam) , hit enter , enters directory, text field still shows entered text i.e 'sam' tried same flow in notepad , in eclipse, in phase, 'sam' getting cleared can provide directory name , hit enter. correct me if code wrong, if problem duplicate, apology wasted time. notepad , eclipse use different implementation jfilechooser . that´s why might behave different , don´t think can make work expecting (instead of using custom library or making own implem...

java - Is it possible to generate an inner class of a class to compile with an annotation processor? -

i wondering if possible generate class, via annotation processor, inner class of class compiled. for instance, while compiling class a , generate class a$foo . wonder if there trick used or not. got feeling might possible generate source compiled in same byte code inner class would. and, @ compile/runtime, jvm take inner class, , allow accessing outer class private fields. the idea behind question, not noobie question, though may more or less technical, able use private visibility modifier annotated fields dagger, butterknife, etc. private modifier allowing detect unused fields more easily, whereas package private protection hides them. or there workaround, way best of both words ? given use case, no. an inner class normal java class, living in different .class file. when compiled, hidden constructor param added inner class constructor. private fields in outer class made accessible adding hidden accessor methods in outer class. of happens @ compile time. the jvm ...

android - How to Configure Listview with more than 16 Items in GetView with holder -

i have problem getview adding items in listview baseadapter. when store "0 15 items " " if(position == 0 ) if(position == 15) " displays listview items in sequence. when try adding 1 more (16th) item listview (like if(position == 16) ), displays first item in listview , doesn't show 16th item have added array. i using custom listview row , each row has own function interacts users. don't know how add more 16 items in getview using 'position'. i have listview of 21 items can not implement more 16 items. any 1 have solution of pls tell me getview code public view getview(int position, view convertview, viewgroup parent) { // todo auto-generated method stub holder holder; textview tv1; imageview img; textview desc; layoutinflater inflater = context.getlayoutinflater(); if(convertview == null){ convertview = inflater.inflate(r.layout.screenlock_addapter, parent,false); holder = new holder(); if...