Posts

Showing posts from September, 2015

javascript - Why jQuery Select box change event is now working? -

i working on product filters user select select box according his/her preference not getting selected value user in jquery. html code:- <select name="product_filter" id="product_filter"> <option value="price_low_first">price : low high</option> <option value="price_high_first">price : high low</option> <option value="latest">latest</option> <option value="popular">most popular</option> </select> jquery code: $(function () { $("#product_filter").change(function () { alert("hi") var selectedtext = $(this).find("option:selected").text(); var selectedvalue = $(this).val(); alert("selected text: " + selectedtext + " value: " + selectedvalue); }); }); hi believe code perfect. once please check jquery.min.js

sql - MySQL - Finding Empty relations -

i trying work out how full list of team leaders , team members our tables. including team leaders have no team. we have basic data structure have table person contains our basic person object. people extend table in details table. one of extended pieces of information have team_leader status. have 2 relevant details define this: detail_isteamleader , detail_teamleader . first boolean , defines short list of team leaders. second defines persons team leader (ideally subset). _person table_ person_id person_name _detail table_ detail_id detail_person_id detail_isteamleader detail_teamleader i can team leaders have team using following query: select tl.person_id tlref, tl.person_name tlname, per.person_id perref, per.person_name pername detail left outer join person per on detail.person = per.person_id left outer join person tl on detail_teamleader = tl.person_id order tlname, psname however, fails team_leaders detail.isteamleader true not occur in detail_teamleader

tcl - array allowed not allowed -

i have script "proc backup". have each directory many words allowed or not allowed. thought integrade array. not ahead ... or there simpler? bind pubm - "*fertig*" backup proc backup {nick host handle channel text} { set name[lindex [split [stripcodes bcru $text]] 2] set dir[lindex [split [stripcodes bcru $text]] 4] if {[catch {exec sh backup.sh $dir $name} error]} { putlog $error } putnow "privmsg $channel :backup $name done"; } array set allowed { "dir1" "to rar" "dir2" "backupserver1 " "dir3" "2016 2017" } array set not_allowed { "dir1" "test crap" "dir2" "old backupserver2 jpg zip" "dir3" "2015 2014 2013 2012 2011 2010 209 19" } edit : line irc: ( lindex 2 , 4) run backup.sh when word in name is word0 word1

date - Java 8 - Trying to convert String to LocalDateTime -

this question has answer here: java string date conversion 13 answers i trying convert below string localdatetime , somehow not working. val formatter = datetimeformatter.ofpattern("yyyy-mm-dd hh:mm:ss.sss"); val datetime = localdatetime.parse("2016-09-21 13:43:27.000", formatter); it seems there problem in pattern. you have problem pattern, should use 'h' hours(0-23). type formatter , datetime wrong. work correctly: datetimeformatter formatter = datetimeformatter.ofpattern("yyyy-mm-dd hh:mm:ss.sss"); localdatetime datetime = localdatetime.parse("2016-09-21 13:43:27.000", formatter);

html - Flexbox grid: two equal length rows, top row split into two columns -

Image
i'm trying make layout following image using css flexbox. but i'm not familiar flexbox can me make this? here i'm trying: .row.flex { display: flex; } .row [class=^"col-"] { width: 200px; height: 100%; } <div class="row flex"> <div class="col-xs-12 col-sm-6"> </div> <div class="col-xs-12 col-sm-6"> </div> <div class="col-xs-12 col-sm-12"> </div> </div> thanks :) option 1 set flex container wrap . make each flex item take 50% of space. adjust margins calc . the third item, forced wrap, gets flex-grow: 1 , consumes remaining space. .row.flex { display: flex; flex-wrap: wrap; } .row [class^="col-"] { flex: 0 0 calc(50% - 10px); height: 100px; margin: 5px; background-color: lightgreen; } .row [class^="col-"]:last-child { fle

core data - NSBatchDeleteRequest with NSPredicate in swift -

how delete rows coredata using nsbatchdeleterequest nspredicate. i want delete records older 30 days. i dont want data in memory , compare , delete, want use nsbatchdeleterequest, in nsbatchupdaterequest. here code far have written let date = nsdate(); let yesterday = date.datebyaddingtimeinterval(-24*60*60); let predicate = nspredicate(format: "date > %@", yesterday); let fetchrequest = nsfetchrequest(entityname: "notification"); let batchdelete = nsbatchdeleterequest(fetchrequest: fetchrequest) please give answers in swift this simple example. possible rich using of nspredicate filter request. let calendar = nscalendar.currentcalendar() let thirtydaysago = calendar.datebyaddingunit(.day, value: -30, todate: nsdate(), options: []) let fetchrequest = nsfetchrequest(entityname: "notification") fetchrequest.predicate = nspredicate(format: "(date >= %@)", thirtydaysago) let deleterequest = nsbatchdeletere

c - Android and JNI real time clock -

i got problem mini android application , use of real time clock signals in c (jni) function. it seems android ui doesn't real time signals timers instanced in c function. in following poc , timer trigger signal 5 times per second , if signal triggered while ui updating, application crashes. if don't start timer => no crash if don't put on ui => no crash i wrote little poc evidence behaviour. java part call jni function , put button on screen. public class mainactivity extends appcompatactivity { button bt; static { system.loadlibrary("testtimer-jni"); } /* jni ingresso */ public native void jnistarttimer(); @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); jnistarttimer(); /* load button */ bt = new button(getbasecontext()); setcontentview(bt); } } and main.c file content. timer instanced , starte

html - Bootstrap/CSS: Clearfix affects even/odd index -

i'm using clearfix prevent bootstrap grid breaking when use columns of different heights. however, once clearfix div added document, columns appear after in source behave if have different even/odd index do. i have created relevant demo . can see, removing clearfix div, makes colors of divs change if index has changed. do know may causing , can correct it? if @ nth-of-type definition specifies the :nth-last-of-type(an+b) pseudo-class notation represents element has an+b-1 siblings same expanded element name after in document tree, 0 or positive integer value of n, , has parent element. see :nth-child() pseudo-class syntax of argument. the key thing here states: the same expanded element name so taking quite literally, css selector targets specific element , odd , matched on specific element name , not elements matched using specific selector. this why replacing div with span work never matched different element.

java - "String cannot be converted to int" -

this question has answer here: how convert string int in java? 31 answers i have textfile temperatures 12 months. when try find average temperature, error "string cannot converted int" line temp[counter] = sc.nextline(); someone sees what's wrong? scanner sc = new scanner(new file("temperatur.txt")); int[] temp = new int [12]; int counter = 0; while (sc.hasnextline()) { temp[counter] = sc.nextline(); counter++; } int sum = 0; for(int = 0; < temp.length; i++) { sum += temp[i]; } double snitt = (sum / temp.length); system.out.println("the average temperature " + snitt); you need convert sc.nextline int scanner sc = new scanner(new file("temperatur.txt")); int[] temp = new int [12]; int counter = 0; while (sc.hasnextline()) { string line = sc.nextline();

symfony - Symfony2 Doctrine use wrong alias in SQL, login fails with "Authentication request could not be processed [...]" -

i trying make own user bundle, , struggling @ login phase, error message : authentication request not processed due system problem. i'm kinda new symfony , doing best learn many aspects possible, please forgive me if took wrong path in defining stuff. structure i have 2 bundles, 1 app called scoreboardbundle, , 1 dedicated authenticating mechanic called pulsahr\userbundle. intend make bundle reusable in of projects. user entity want use scoreboardbundle\entity\user, , inherits pulsahr\userbundle\entity\user, implements userinterface, \serializable. log info i looked dev.log, , found intriguing line : [2016-09-22 14:16:19] security.info: authentication request failed. {"exception":"[object] (symfony\component\security\core\exception\authenticationserviceexception(code: 0): exception occurred while executing 'select t1.id id_2, t1.username username_3, t1.password password_4, t1.roles roles_5, t1.email email_6, t1.config config_7, t1.name name_

DRm support for html5 player -

i trying run angular js application on mobile device html5 player video playback. i know whether html5 supports drm default or there way support drm in html5. regards, raj dugar html5 supports drm through encrypted media extensions (eme) mechanism, in turn relies on media source extensions (mse) mechanism. essentially, drm system provides content decryption module (cdm) built or added browser , accessed html5/javascript via eme decrypt , possibly playback encrypted media. not browser support cdms - in general chrome supports widevine cdm, ms edge supports playready cdm , safari supports fairplay cdm. firefox supports adobe primetime , widevine cdm, although momentum seems latter. you can read more eme here: https://www.html5rocks.com/en/tutorials/eme/basics/ and spec here: https://www.w3.org/tr/2016/cr-encrypted-media-20160705/

html - Regex scrape of the same form_id name but different values -

i know using either regex or xpath how can scrape form id value html page has same form_id names example below, scrape value 2nd form_id name advice best way achieve using regex or xpath? thanks <input type="hidden" name="form_id" value="search_block_form" /> i scrape value form_id below: "webform_client_form_" <input type="hidden" name="form_id" value="webform_client_form_" /> targeting second input xpath: (//input[@name='form_id']/@value)[2] using utilities work on dom structure preferable choice here.

row - apply() vs. sweep() in R -

i writing notes compare apply() , sweep() , discovered following strange differences. in order generate same result, sweep() needs margin = 1 while apply wants margin = 2. argument specifying matrix uppercase x in apply() lowercase in sweep(). my.matrix <- matrix(seq(1,9,1), nrow=3) row.sums <- rowsums(my.matrix) apply.matrix <- apply(x = my.matrix, margin = 2, fun = function (x) x/row.sums) sweep.matrix <- sweep(x = my.matrix, margin = 1, stats = rowsums(my.matrix), fun="/") apply.matrix - sweep.matrix ##yup same matrix isn't sweep() "apply-type" function? r quirk or have lost mind? note apply , if each call ‘fun’ returns vector of length ‘n’, ‘apply’ returns array of dimension ‘c(n, dim(x)[margin])’ if ‘n > 1’ in example, margin can (and should) set 1 in both cases; returned value apply should transposed. easiest see if original matrix not square: my.matrix <- matrix(seq(1,12,1), nrow=4) apply.matrix <- t(app

jquery - DataTables numbers_length = 3 change pagination buttons -

Image
by setting numbers_length property 3, able produced this is there way can 3 page numbers (previous, current , next) : solution you can use our plug-in simple numbers - no ellipses . $(document).ready(function() { $('#example').datatable({ 'pagingtype': 'simple_numbers_no_ellipses' }); }); however plug-in shows "previous" , "next" buttons. overcome use modified code below. $.fn.datatable.ext.pager.numbers_no_ellipses = function(page, pages){ var numbers = []; var buttons = $.fn.datatable.ext.pager.numbers_length; var half = math.floor( buttons / 2 ); var _range = function ( len, start ){ var end; if ( typeof start === "undefined" ){ start = 0; end = len; } else { end = start; start = len; } var out = []; ( var = start ; < end; i++ ){ out.push(i); } return out; }; if ( pages <= buttons ) {

c# - Visual Studio 2015 Xamarin.Android - limit fling in Image Gallery to just one item per fling -

when swipe gallery, multiple images go right left, depending on swipe speed. can please tell me how limit swipe 1 image @ time, no matter how fast swipe? [activity(label = "app3", mainlauncher = true, icon = "@drawable/icon")] public class mainactivity : activity { protected override void oncreate(bundle bundle) { base.oncreate(bundle); // set our view "main" layout resource setcontentview (resource.layout.main); gallery gallery = (gallery)findviewbyid<gallery>(resource.id.gallery); gallery.adapter = new imageadapter(this); gallery.itemclick += delegate (object sender, android.widget.adapterview.itemclickeventargs args) { toast.maketext(this, args.position.tostring(), toastlength.short).show(); }; } } try override gallery onfling() method , don't call superclass onfling() method. in way

rest - RESTful API and real life example -

we have web application (angularjs , web api) has quite simple functionality - displays list of jobs , allows users select , cancel selected jobs. we trying follow restful approach our api, that's gets confusing. getting jobs easy - simple get: /jobs how shall cancel selected jobs? bearing in mind operation on jobs need implement. easiest , logical approach (to me) send list of selected jobs ids api (server) , necessary procedures. that's not restful way. if following restful approach seams need send patch request jobs , json similar this: patch: /jobs [ { "op": "replace", "path": "/jobs/123", "status": "cancelled" }, { "op": "replace", "path": "/jobs/321", "status": "cancelled" }, ] that require generating json on client, mapping model on server, parsing "path" property job id , ac

javascript - Unable to read properly from JSON file with php -

i trying read json file php array , echo array's content, can fetch info ajax in javascript , convert array in javascript array of json objects. here how json file looks like. [["{\"id\":1474541876849,\"name\":\"d\",\"price\":\"12\"}"],["{\"id\":1474541880521,\"name\":\"dd\",\"price\":\"12\"}"],["{\"id\":1474541897705,\"name\":\"dddgg\",\"price\":\"124\"}"],["{\"id\":1474541901141,\"name\":\"faf\",\"price\":\"124\"}"],["{\"id\":1474543958238,\"name\":\"tset\",\"price\":\"6\"}"]] here php : <?php $string = file_get_contents("products.json"); $json_a = json_decode($string, true); $arr = array(); foreach ($json_a $key) { array_push($arr,$key[0]); } foreach (

elasticsearch - Multiline logstash "next" not grouping -

short: having troubles multiline. tag "multiline" on log doesn't put them together. explanation: logs receive september 22nd 2016, 13:43:52.738 [0m[[31merror[0m] [0mtotal time: 368 s, completed 2016-09-22 13:43:52[0m september 22nd 2016, 13:43:51.738 [0m[[0minfo[0m] [0m[36msuites: completed 29, aborted 0[0m[0m september 22nd 2016, 13:43:51.738 [0m[[31merror[0m] [0mfailed: total 100, failed 4, errors 0, passed 96[0m september 22nd 2016, 13:43:51.737 [0m[[0minfo[0m] [0m[36mrun completed in 1 minute, 24 seconds.[0m[0m september 22nd 2016, 13:43:51.737 [0m[[0minfo[0m] [0mscalatest[0m the line " total time: %{number} s " repeated multiple time , i'm interested in these total time coming after " total, failed, error " line. between first , second line none or several logs. my configuration is: grok { #1 match => {"message" => "\[.m\[\u001b\[3.m%{notspace:level}\u001b\[0m\] \u001b\[0m%{notspace:status}:

exception - SocketTimeoutException - "timeout" "read timed out" -

i writing tests run okhttp/retrofit requests against mockwebserver. among other things i'm testing timeouts . here noticed, of timeout tests do not produce same kind of exception time : while exception thrown sockettimeoutexception , exception message differs between 2 possibilities. get "timeout" , sometimes "read timed out" . there seems no clear pattern (it's same test produces 1 or other of these exception messages). i assume different constellations/causes lead differing messages... can explain me difference between these 2 cases? here corresponding stack traces: "read timed out" caused by: java.net.sockettimeoutexception: read timed out @ java.net.socketinputstream.socketread0(native method) @ java.net.socketinputstream.socketread(socketinputstream.java:116) @ java.net.socketinputstream.read(socketinputstream.java:170) @ java.net.socketinputstream.read(socketinputstream.java:141) @ okio.okio$2.read(

c# - How to get value of string created in resources Xamarin.android -

i developing android application in xamarin studios , want make text of button underlined. created string in strings.xml following <string name="advanced_search"><u>advanced search</u></string> i succesfully able reference string in xml file desginer, want access in code set button's text. tried following doesn't work: advancedsearchbutton.text = resource.string.advanced_search.tostring(); when try reference string integer value string, want text string holds. how can access string in xamarin using c#? you need use resources.getstring : advancedsearchbutton.text = resources.getstring(resource.string.advanced_search); this assuming code contained within activity , otherwise need have reference android context .

java - Open new tab in swt browser after button click -

i used swt browser. opened page , there button verify browser have option open new browser window. standard swt browser have problem it. above how button defined. <button class="btn btn-action btn-slim size-w-90pct" data-e2e="opendealerbtn" ng-if="igdefaultrowcontroller.account.ispdsupported" ng-class="{'btn-disabled': igdefaultrowcontroller.shoulddisableopenplatformbutton}" ng-disabled="igdefaultrowcontroller.shoulddisableopenplatformbutton" ng-click="igdefaultrowcontroller.opendealer()" ig-click-tracking="puredealbtn-cfd" id="opendealerbutton-xq7ji"> <span class="btn-label" ig-i18n="" key="accountoverview.opendealer"><span ng-bind-html="value">open classic platform</span></span> </button> [solved!] how expand swt browser open more 1 tab ? i used tabfolder more tabs. it possible catch url after click on b

vba - Excel ActiveX textbox - count characters or change case -

two days of continual failure. using barcode system has barcode scanner scans barcode of alpha-numeric text , places activex textbox. enters text 1 letter @ time, , upon completion of entire barcode, matches case selection, deletes text in box ready next scan. the issue happen facing inside of textbox. whatever reason, text goes textbox , ~ (1 time in 1 hour or 0 times in 8 hours) not complete case. exact text inside of textbox matches 1 of cases not counted , stays inside box. @ point, future scans appended end of text inside of box. below sample of variables, case, , 1 of events occuring based on case selection. variables private sub textbox1_change() dim ws worksheet, v, n, t, b, c, e, f, h, j, k, i1, i2, i3, i4 set ws = worksheets("sheet1") v = textbox1.value n = 0 t = 0 b = 0 c = 0 e = 0 f = 0 h = 0 j = 0 k = 0 i1 = 0 i2 = 0 i3 = 0 i4 = 0 case select case v case "2 in x 16 ft r -1": n = 9 t = 1 b = 10 c = 1 e = 11 f = 6 g = "2

ios - How to create different instance for SDWebImageManager -

i have many controllers download images using sdwebimage library. using following code [[sdwebimagemanager sharedmanager] downloadimagewithurl:[nsurl urlwithstring:_urltodownloadfrom] options:0 progress:nil completed:^(uiimage *image, nserror *error, sdimagecachetype cachetype, bool finished, nsurl *imageurl) { _productinfo.isdownloading = false; _productinfo.isimagedownloadedscuessfully = finished; if (image) { [_productinfo setmainimg:image]; canshowlistview ? [self.listcollectionview reloaddata] : [self.gridcollectionview reloaddata]; } }]; as seen in code using sdwebimagemanager shared instance download data, because of these downloading operation go inside queue in fifo series. example have controller downloading 10 images, push controller above downloads more 5 images. these new images top controller have wait till previous controller download 10 images. how can solve problem? possible solution c

docker - Error response from daemon: network myapp not found -

i trying create container in multihost network while creating getting error: error response daemon: network myapp not found here myapp name of overlay network have created. command using is: sudo docker run --rm -it --name=test_cont --net=myapp ubuntu bash docker networks scoped different access. myapp network overlay network scoped swarm. that means can use @ swarm level - docker service create --network myapp work fine, because services @ swarm level too. you can start container docker run on swarm, run locally on node run command on, can't see swarm networks.

qooxdoo - Include Library (jQuery) -

i want include 2 libraries (jquery, highcharts). tried add them additional-js in config.json file: "additional-js" : { "add-script" : [ { "uri" : "script/jquery-3.1.0.min.js" }, { "uri" : "script/highcharts.js" } ] }, the problem is, sequence of includes changed build. after build highcharts.js first included one. how can manage sequence? and here direct answer question: i've tested fresh created app , sequence given in config.json preserved. first have place files of additional libraries in right path of app (here called myapp) in myapp/source/resource/scripts/jquery.js myapp/source/resource/scripts/highcharts.js then add folling entry in job section of myapp/config.json "jobs" : { "common" : { "add-script" : [ { "uri" : "resource/scripts/jquery.js" }, { "uri" : "re

c# - Export DataGridView SelectedRows to a DataTable -

i want transfer multiple selected rows of datagridview datatable set datasource crystal report. first load data came database through stored procedure. datagridview1.datasource = clspayroll.view_employee(); then put code below in print selected button multiselection not restricted. foreach(datagridviewcolumn column in datagridview1.columns) table.columns.add(column.name, typeof(string)); (int = 0; < datagridview1.selectedrows.count; i++) { table.rows.add(); (int j = 0; j < datagridview1.columns.count; j++) { table.rows[i][j] = datagridview1[j, i].value; } } rpt.setdatasource(table); i have entries on database here: emp_id emp_name gender emp-000013 dummy male emp-000014 teresa female emp-000015 dutcry male when select rows emp-000014 , emp-0000015. i expect crystalreport viewer list instead shows emp-000013 , emp-000014 thanks posted answers , i'm sorry not update whether i've fixed

javascript - Highcharts reflow all charts at once / trigger resize event in Angular? -

we have angular app has several dozens of highcharts/highstock instances across many different views. we doing app-wide button setting wider screen width setting toggling css max-width rule. problem highcharts instances ain't doing reflow/redraw after elder parent container has been resized. , triggering reflows @ higher level of scope arduous, keeping list possible chart instance containers... i did not manage invoke reflow triggering resize event programmatically, tried several different syntaxes i.e. settimeout(function() { angular.element(window).triggerhandler('resize'); }, 900); is there way trigger reflow all highcharts instances without specifying container elements ? or proper syntax programmatically triggering window resize event in angular? update: seems calling window resize has stopped working in hc version 4.2.1 https://github.com/highcharts/highcharts/issues/5051

reactjs - Redirect to another route after submission success -

i'm using redux-form , react-router. redux-form provides method called onsubmitsuccess called after successful submission. however, don't have access router in method. how can redirect new route using react-router after successful submission? i suggest use container component this. once form submitted, dispatch action , in action use browserhistory change or replace route. //container code function mapdispatchtoprops(dispatch){ return{ onsubmit : () =>{ dispatch(updatedata()) } } } //action code function updatedata(){ //update state if needed browserhistory.push(//changed route) }

python - How do I extract attributes from xml tags using Beautiful Soup? -

i trying use beautiful soup in django extract xml tags. sample of tags i'm using: <item> <title> title goes here </title> <link> link1 goes here </link> <description> description goes here </description> <media:thumbnail url="image url goes here" height="222" width="300"/> <pubdate>thu, 15 sep 2016 13:24:48 edt</pubdate> <guid ispermalink="true"> link2 goes here </guid> </item> i have obtained strings of title,link , description tags. i'm having trouble obtaining url media:thumbnail tag. this snippet got values of rest of tags: soup=beautifulsoup(urlopen(xmllink),'xml') items in soup.find_all('item'): listtitle.append(items.title.get_text()) listurl.append(items.link.get_text()) listdescription.append(items.description.get_text()) help the issue because not every item has media:thumbnail need check first: i

Displaying HTML and Web Pages consecutivelyin VB.net using Web Browser conctrol -

i have array of web pages , local html files want display using web browser control in vb.net application. set navigate property first file in array , ok. want stay there interval, display next one. set timer after navigate first 1 want navigate second 1 after timer pop flashes first 1 second one. there method can use hold first 1 interval, display second, third etc? thanks bill

html5 - How to use WebRTC without an answer? -

in absence of signalling server coordinating initial exchange, webrtc provide way allow responder send information freely caller, if responder has received offer , has no other methods of communication caller? (there's no signalling server because web app must useable offline. method establish connection 1 exchange of information useful.) sorry, it's long , weird question. webrtc needs signalling system establishing peer peer connection. thing notice why needs signalling. in process of establishing peer connection 2 parties exchange sdp contains information such ip , port @ both ends @ media/data packets exchanged. contains encoding/decoding or codec used plus many other useful things.thus without exchange of these packets between both parties communication can't possible. that why not possible @ least in case of webrtc without communication both sides peer connection can established.

Elasticsearch Highlight -

i have elasticsearch 2.4.0 installation. use highlight information. following query result list hits, no highlights. idea? regards cl { "query": { "query_string" : { "query": "harley" } }, "highlight" : { "pre_tags" : ["<tag1>"], "post_tags" : ["</tag1>"], "fields" : { "givenname" : {}, "familyname" : {} } } }

swift - Could not cast value of type 'SCNView' to 'SKView' -

i'm following tutorial create "tetris" game in swift xcode 7. followed every single step in tutorial, i'm getting runtime error: could not cast value of type 'scnview' (0x106c19778) 'skview' (0x1068fcad0). my gameviewcontroller.swift follows: import uikit import scenekit import spritekit class gameviewcontroller: uiviewcontroller { var scene: gamescene! var swiftris:swiftris! override func viewdidload() { super.viewdidload() //configure view let skview = view as! skview skview.multipletouchenabled = false //create , configure scene scene = gamescene(size: skview.bounds.size) scene.scalemode = .aspectfill scene.tick = didtick swiftris = swiftris() swiftris.begingame() //presente scene. skview.presentscene(scene) scene.addpreviewshpaetoscene(swiftris.nextshape!){ self.swiftris.nextshape?.moveto(startingcolumn, r

c++ - Template and constexpr deduction at compiletime dependent on compiler and optimization flags -

the following question condensed larger code. therefore expressions seem overkill or unnecessary, crucial original code. consider having struct, contains compile time constants , simple container class: template<typename t> struct const { static constexpr t one() { return static_cast<t>( 1 ); } }; template<typename t> class container { public: using value_type = t; t value; }; now having template function, has "specialization" types offering value_type : template<typename t> void dosomething( const typename t::value_type& rhs ) {} now expect, should work: template<typename t> class tester { public: static constexpr t 1 = const<t>::one(); void test() { dosomething<container<t>>( 1 ); } }; the interesting point is, compiler not complain definition of tester<t>::one , usage. further not complain, if use const<t>::one() or static_cast<t>(

android - Java: BouncyCastle - SpongyCastle and Conditional Compiling -

thanks android shipping own, outdated versions of bouncycastle crypto libraries i'm in ugly situation. i've built library talks rest our own webservice data encrypted , decrypted on fly client. client can either mobile application on android or desktop/server computer running oracle java. for android need spongycastle , desktop/server need bouncycastle because spongycastle jars not signed , oracle runtime won't allow crypto stuff. the thing is, code same, regardless of library beingused. imports different because of package names. in c i'd use conditional compiling include platform specific headers, not in java, know. still, there way without effort can achieve similar, create 2 builds same source? i'd hate have 2 .java files same have different imports. that's maintainance nightmare.

javascript - JSON Array Value Returns "[{" -

i writing jsp web app , have converted list of java objects json array, , set attribute. right trying use jquery parse array , make separate json objects, have hit big snag , can't find online else has dealt it. servlet creates formatted json array when access value of array so: orders[0].value; i returned "[{" in javascript console. when access object orders[0]; which hidden input holds array, find value looks this: value="[{" firstname" : "john", "lastname" : "doe", ..... as can see, looks there newline after "[{" , recognizing value. in javascript console, rest of array highlighted differently well. i totally stumped on how solve issue. advice appreciated. here's code servlet sets attribute: object orders = request.getsession().getattribute("orders"); string json = new gson().tojson(orders); try { arraylist<string> jsonlis

c# - Get Namespace from InvocationExpressionSyntax in Roslyn Analyzer -

Image
i'm attempting create analyzer roslyn prevent use of asserts within given namespace (to ensure project design standard maintained). i've been able point can verify if assert, unsure how namespace context. public override void initialize(analysiscontext context) { context.registersyntaxnodeaction(analyzemethod, syntaxkind.invocationexpression); } private static void analyzemethod(syntaxnodeanalysiscontext context) { var expression = (invocationexpressionsyntax)context.node; var memberaccessexpression = expression.expression memberaccessexpressionsyntax; if (memberaccessexpression == null) return; var membersymbol = modelextensions.getsymbolinfo(context.semanticmodel, memberaccessexpression).symbol imethodsymbol; if (!membersymbol?.tostring().contains("assert") ?? true) return; //check if we're inside page namespace. //this assert, lets fail it. var diagnostic = diagnostic.create(rule, memberaccessexpression.getloc

python - Create mask from skimage contour -

Image
i have image found contours on skimage.measure.find_contours() want create mask pixels outside largest closed contour. idea how this? modifying example in documentation: import numpy np import matplotlib.pyplot plt skimage import measure # construct test data x, y = np.ogrid[-np.pi:np.pi:100j, -np.pi:np.pi:100j] r = np.sin(np.exp((np.sin(x)**2 + np.cos(y)**2))) # find contours @ constant value of 0.8 contours = measure.find_contours(r, 0.8) # select largest contiguous contour contour = sorted(contours, key=lambda x: len(x))[-1] # display image , plot contour fig, ax = plt.subplots() ax.imshow(r, interpolation='nearest', cmap=plt.cm.gray) x, y = ax.get_xlim(), ax.get_ylim() ax.step(contour.t[1], contour.t[0], linewidth=2, c='r') ax.set_xlim(x), ax.set_ylim(y) plt.show() here contour in red: but if zoom in, notice contour not @ resolution of pixels. how can create image of same dimensions original pixels outside (i.e. not crossed contour line) maske

c# - Increasing a field In an array of structures -

i have found in many places c# structures should treated immutable, me understand behavior of following code: public partial class form1 : form { private struct socsearchdomains { public string urlname; public datetime lastrequeststampdate; public int errorscount; public socsearchdomains(string urlname, datetime requeststampdate) { urlname = urlname; lastrequeststampdate = requeststampdate; errorscount = 1; } } private static socsearchdomains[] searchdomain { get; set; } private static socsearchdomains searchdomain1 { get; set; } public form1() { initializecomponent(); searchdomain = new socsearchdomains[1]; searchdomain[0] = new socsearchdomains("192.168.1.81", datetime.now); searchdomain1 = new socsearchdomains("192.168.1.81", datetime.now); } private void button1_click(object sender, eventargs e) {

Design: Background thread with a Spring service -

i have spring service after performing tasks,initiates background async tasks. task have defined component. now, if have use method belonging service initiated thread. can autowire service in thread(component) , work. problem is...the design. brings in kind of circular dependency? how can tackle such issue? servicea-> starts threada component->threada needs call method in servicea. what using @async annotated method described here a non tested example: @service public class myservice { private final resttemplate resttemplate; public string mysyncmethod(){ return "hello world"; } @async public future<string> myasyncmethod() throws interruptedexception { return new asyncresult<>(mysyncmethod()); } }

java - Dagger 2 cycle injection -

i have 2 singletone classes i'd inject them fragments, activites, ect., i've inject them each other well. , @ point allways error. public class adverticumchecker implements iadverticumchecker { @inject bannermanager bannermanager; public adverticumchecker(context context) { indexapplication.getapplication().getappcomponent().inject(this); } } public class bannermanager { @inject iadverticumchecker adverticumchecker; public bannermanager(){ indexapplication.getapplication().getappcomponent().inject(this); } } these modules @module public class bannermanagermodule { @singleton @provides bannermanager providebannermanager(){ return new bannermanager(); } } @module public class adverticumcheckermodule { private context context; public adverticumcheckermodule(context context){ this.context = context; } @singleton @provides iadverticumchecker prov

java - ObjectOutputStream not writing to file -

i'm trying serialize object file following: // fill test data arraylist<transaction> transactions = new arraylist<>(); transactions.add(new transaction("internet", "2016-09-20", -28)); transactions.add(new transaction("groceries", "2016-09-20", -26)); //serialize transactions try { // file f = new file("transactions.ser"); // outputstream file = new fileoutputstream(f); // outputstream buffer = new bufferedoutputstream(file); // objectoutput output = new objectoutputstream(buffer); file f = new file("transactions.ser"); fileoutputstream fos = new fileoutputstream(f); objectoutputstream out = new objectoutputstream(fos); out.writeobject(transactions); out.flush(); out.close(); fileinputstream fis = new fileinputstream(f); objectinputstream in = new objectinputstream(fis); object o = in.readobject(); system.out.println(o); }

Can CKAN stream GeoJSON? -

i have uploaded several spatial datasets ckan repository , stream geojson them. have used datastore api like: datastore_search?resource_id=d6fa3911-ae95-4100-8c4f-78aa388c97c9 ...but returns attributes, not geometry. know geometry available because have put dataset in geojson format , when select explore->preview shows features on map. possible? thanks jim i think can want changing link this: https://yourckanurl/dataset/dataset_id/resource/resource_id/download/anything_you_want.geojson the datastore stores tabular data , not geojson data, trying geojson file resource uploaded ckan won't work. if need database storage of geo data might want @ ckanext-mapstore: https://github.com/geosolutions-it/ckanext-mapstore

ios - Handle non-JSON response from POST request with Alamofire -

i'm using alamofire 3 , end point i'm calling (i don't own server) accepts post request , returns html response. i able html response when using curl in command line , alamofire doesn't return response body, header. this code: let headers = [ "referer": "someurl" ] alamofire.request(.post, url, headers: headers) .validate() .response { request, response, data, error in // response } response is: optional(<nshttpurlresponse: 0x7f9ba3759760> { url: someurl } { status code: 200, headers { connection = "keep-alive"; "content-encoding" = gzip; "content-type" = "text/html"; date = "thu, 22 sep 2016 15:19:20 gmt"; server = nginx; "transfer-encoding" = identity; vary = "accept-encoding"; } }) and data is: optional<nsdata> - : <> any thoughts?

javascript - Embedded Youtube videos not playing in mobile iOS Safari -

recently we've found bug exists only in safari on iphone(s) cannot pinpoint source of issue. when pressing play button video appears load closes immediately. all answers i've found far aren't recent and/or don't solve problem. testing in browserstack giving me error: invalid css property declaration at: * www-embed-player-sprite-mode-vfl9mhoab.css file served youtube. i'm open optional ways of handling embedded videos avoid issue. the code: #set($showvideo = $request.getparameter("showvideo")) #set($howitworksid = $placeholder.getattributevaluegroup().getattributevalue('product_howitworks', $sesshoppingcart.getlocale())) #set($embeddedurl = "https://www.youtube.com/embed/" + $howitworksid + "?rel=0") #set($hasvideoid = false) #if( $howitworksid && $howitworksid != "" ) #set( $hasvideoid = true ) #end <div id="howitworksmodal" class="modal-howitworks modal fade"> &l