Posts

Showing posts from June, 2011

java - JavaCC not going to next possible token -

i have 2 tokens < import> , <\import>, , need capture data inside tag. i've tried code: < codigo_java_import_open: "<import>" > < codigo_java_import_close: "<\\import>" > void insertimportjavacode():{} { < codigo_java_import_open > insertimportjavacoderecursiva() } void insertimportjavacoderecursiva(): { token t; } { ( lookahead(2) t = < codigo_java_import_close > | t = < ~[] > { // code use information of token t } insertimportjavacoderecursiva() ) } but, javacc goes in first option of insertimportjavacoderecursiva() ex.: if have import code this: <import> import there. <\import> javacc throw error token "import there." not <\import>.

django haystack - Elasticsearch - how to fuzzy match phrase when search keyword has no spaces? -

i want match document field title has value brown fox searching keyword brownfox . when trying fuzzy query no results: curl -xget 'http://localhost:9200/haystack/_search?pretty' -d '{ "query" : { "fuzzy" : { "title": { "value": "brownfox", "fuzziness": 2, "prefix_length": 0, "max_expansions": 10000 } } } }' i tried match query fuzziness , operator and : curl -xget 'http://localhost:9200/haystack/_search?pretty' -d '{ "query": { "match": { "title": { "query": "brownfox", "fuzziness": "auto", "operator": "and" } } } }' this returns results similar keywords, not document title brown fox consi

How to restrict users from creating new organization on Grafana -

Image
on grafana deployment if create user editor role can't perform administrative tasks can create new organization , gain administrative privileges on organization. there way prevent roles creating new organizations? bellow can see snapshot of user editor role viewing "new organization" action on main menu on grafana 3.1.0 there global switch (all users affected, admin) in grafana's config file - allow_org_create , default it's enabled.

javascript - Binding dynamic form values with vue.js -

i've built dynamic set of form inputs using vue.js , form inputs generated external list of inputs. my problem don't see how can bind input values vue model, vue instance can access / interact form values. i've created basic fiddle give idea here: https://jsfiddle.net/gzprj5ef/ is possible update vue instance form values? you have remove double brackets when using v-model . here updated jsfiddle

Polymorphic uncurried method calls (adhoc polymorphism) in Java -

let me start example. say have abstract vehicle class. public abstract class vehicle { public vehicle() {} public abstract void ride(); } and classes car , bicycle inherit abstract class. public class car extends vehicle { public car() {} @override public void ride() { system.out.println("riding car."); } } public class bicycle extends vehicle { public bicycle() {} @override public void ride() { system.out.println("riding bicycle."); } } when apply ride() method object of type vehicle actual type can determined @ runtime, jvm apply correct version of ride() . that is, in curried method call of sort v.ride() , polymorphism works expected way. but if have external implementation in form of method accepts subtype of vehicle argument? so, if have repair(bicycle b) , repair(car c) methods? uncurried polymorphic method call repair(v) won't work. example: import java.util.a

Reading a multibyte text file in Windows - how does it detect newlines? (Python 2) -

Image
i thought caveat of unicode world -> cannot correctly process byte stream writing without knowing encoding is. if assume encoding, might valid - incorrect - characters showing up. here's test - file writing: hi1 hi2 stored on disk 2-byte unicode encoding: windows newline characters \r\n stored 4 byte sequence 0d 00 0a 00 . open in python 2 default encodings, think it's expecting ascii 1-byte-per-character (or stream of bytes), , reads: >>> open('d:/t/hi2.txt').readlines() ['\xff\xfeh\x00i\x001\x00\r\x00\n', '\x00h\x00i\x002\x00'] it's not decoding 2 bytes 1 character, yet 4 byte line ending sequence has been detected 2 characters, and file has been correctly split 2 lines . presumably, then, windows opened file in 'text mode', described here: difference between files writen in binary , text mode and fed lines python. how did windows know file multibyte encoded, , four-bytes of newlines, without being tol

WooCommerce - Apply coupon of discounts of a given payment method -

i'm integrating solution woocommerce coupon of discount given depending on payment method customer chooses. so, it, coupon needs created/applyed in checkout page, when customer selecting payment method wants. possible? how should this? there 2 free plugins allow set discount codes based on payment methods: https://wordpress.org/plugins/woocommerce-auto-added-coupons/ - on 5k+ active installs, 1 seems right choice. https://wordpress.org/plugins/woocommerce-payment-discounts/ - although 1 has 3k+ active installs, meant give discounts based on payment methods. looking for. try out both plugins, preferrably 2nd 1 first.

WebGL: fade drawing buffer -

i've set preservedrawingbuffer true . doing results in drawn on buffer seen @ once, however, wondering if there way somehow fade buffer time goes on old elements drawn disappear on time, , newest drawn elements appear relatively high opacity until fade away. is there better way achieve such effect? i've tried render previous elements again lowering opacity until reaches 0 didn't seem efficient way of fading once drawn don't plan on changing it. thanks! it's common redraw stuff went on here webgl: smoothly fade lines out of canvas redrawing stuff means can keep things not fading out. example if you're making space shooting game , want explosions , missile trails fade out don't want spaceships , asteroids fade out need redrawing , manually fading stuff out drawn them while decreasing alpha if want fade out can use post processing type effect. you make 2 textures , attach them 2 framebuffers. blend/fade first framebuffer fadefb1 se

How to avoid the L in Python -

>>> sum(range(49999951,50000000)) 2449998775l is there possible way avoid l @ end of number? the l you. (so know long ) , nothing worry about. >>> = sum(range(49999951,50000000)) >>> 2449998775l >>> print 2449998775 as can see, printed value (actual value) not have l repr (representation) displays l consult this post

ios - Resizing UICollectionViewCells on rotation changes currently visible cells -

Image
this question has answer here: keeping contentoffset in uicollectionview while rotating interface orientation 22 answers i have paginated, horizontally scrolling uicollectionview each cell takes size of view/device screen, , 1 cell appears @ time. i'm experiencing issue on device rotation, cells transition correct new size, position of cells off. before rotation: after rotation: on rotation, how can not resize collection view cells ensure current cell stays visible? i've boiled problem down simple example without custom flow layout. setting size of cells collectionview frame's size (the collection view size of view controller holding it): func collectionview(collectionview: uicollectionview, layout collectionviewlayout: uicollectionviewlayout, sizeforitematindexpath indexpath: nsindexpath) -> cgsize { return collectionview.frame.

pyspark - Download, install, configure, use spark packages -

i new spark/pyspark. trying read csv , attempted use spark-csv package keep seeing referenced finding .jar files, downloading, running "spark-submit --jars jarfile pythoncode.py", took forever run , in end after df.show(), displayed headers sans data. compared function wrote, it's slow , doesn't work (i'm sure it's mistake on end). tried use spark-ts package in sort of similar way, cannot run. there pip install spark and/or kind of baby step instructions general spark package installation/usage?

node.js - setEncoding Error when Serving OpenFin on MAC -

i seeing fatal error: cannot read property 'setencoding' of undefined on mac when running through openfin tutorial here => https://openfin.co/create-your-first-application/ it's happening when calling > grunt serve . this bug fixed on latest version of openfin-launcher, please re-install package: npm install openfin-launcher@1.3.3 additionally change version form "stable" "beta" mac support still experimental.

pyspark program throwing name 'spark' is not defined -

below program throwing error name 'spark' not defined traceback (most recent call last): file "pgm_latest.py", line 232, in <module> sconf =sparkconf().set(spark.dynamicallocation.enabled,true) .set(spark.dynamicallocation.maxexecutors,300) .set(spark.shuffle.service.enabled,true) .set(spark.shuffle.spill.compress,true) nameerror: name 'spark' not defined spark-submit --driver-memory 12g --master yarn-cluster --executor-memory 6g --executor-cores 3 pgm_latest.py code #!/usr/bin/python import sys import os datetime import * time import * pyspark.sql import * pyspark import sparkcontext pyspark import sparkconf sc = sparkcontext() sqlctx= hivecontext(sc) sqlctx.sql('set spark.sql.autobroadcastjointhreshold=104857600') sqlctx.sql('set tungsten=true') sqlctx.sql('set spark.sql.shuffle.partitions=500') sqlctx.sql('set spark.sql.inmemorycolumnarstorage.compressed=true&

core data - Non-optional to-many relationship allows nil or empty set -

Image
i have sample data structure: table "groups" , table "items". groups can contains 0 or more items , item must linked minimum 1 or more groups: groups |--------- to-many, optional ---------->>|items ---------|<<------- to-many, non-optional! -------|-------- groupname| |itemname items | |groups i create nsmanagedobject subclasses. both trivial here items: class items:nsmanagedobject { @nsmanaged var itemname:string @nsmanaged var groups:set<groups> //attention: there no ! or ? } in code below expecting catch error: var item = items() item.itemname = "aaaa" { try items.moc.save() //moc - static field in items "linked" managedobjectcontext } catch { print(error) } but there no errors! item saves coredata empty groups. can't figure out why? but if make items groups relation non-optional to-one (in class items groups

rails db:migrate vs rake db:migrate -

i'm new rails. noticed when generating data migration in rails 5, people use rails db:migrate on rake db:migrate . can explain difference between rails vs rake command in database migration? mean rake command obsolete in rails 5? many thanks rails core team decided have consistency enabling rails command support rake does. for example in rails 5 commands db:migrate, setup, test etc part of rake command in rails 4 being supported rails command. can still choose use rake run commands similar how run in rails 4. because rails community has introduced rake proxy instead of moving command options rake rails. what happens internally when rails db:migrate command executed, rails checks if db:migrate rails natively supports or not. in case db:migrate not natively supported rails, rails delegates execution rake via rake proxy. if want see commands supported rails in rails 5 can long list of options executing rails --help.

spring - Where should I put the login logic? DispatcherServlet or a Filter? -

the following 2 things both implement front controller pattern : dispatcherservlet defined spring filter defined servlet spec i think login logic should placed in front controller . 1 should use in spring mvc web application? instead of implementing own, recommend use spring-security . btw: way spring-security hooks http-request handling process (the "entry"-point), based on servlet filter ( org.springframework.web.filter.delegatingfilterproxy ).

android - Calling a method upon exiting Geofence -

i want call method in when user has exited geofence radius, i'm not entirely sure how go that. seems have work geofencetransitionsintentservice(), i'm finding outdated code the api docs have full fledged example on how this. use conditional check geofencetransition == geofence.geofence_transition_exit in onhandleintent of geofence service: developer.android.com/training/location/geofencing.html –

Python metaclass conflict/Type error -

i'm debugging python script (python isn't go language), , first time i'm working metaclass's in python. i'm getting metaclass conflict error when run code below. typeerror: error when calling metaclass bases metaclass conflict: metaclass of derived class must (non-strict) subclass of metaclasses of bases in attempting solve commented out metaclass declaration in mysqlmsoftware , thinking it's redundant inherits class same metaclass declaration, leads to: typeerror: error when calling metaclass bases module.__init__() takes @ 2 arguments (3 given) any insight, guidance or direction appreciated. i've been reading python's metaclass implementation , issue isn't popping out far. msoftware.py from abc import abcmeta, abstractmethod class msoftware(object) : __metaclass__ = abcmeta def __init__(self,name,spark=none,mysql=none): self.name = name ... mysqlmsoftware.py from mouse import mouse, msoftware ab

html - AngularJS function unable to be called in ng-view -

using following code, able use angularjs carousel. <!doctype html> <html ng-app="app"> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-animate.js"></script> <script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-1.2.1.js"></script> <link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"> <script type="text/javascript"> var app = angular.module('app', ['ui.bootstrap']); app.controller('carouseldemoctrl', carouseldemoctrl); function carouseldemoctrl($scope){ $scope.myinterval = 3000; $scope.nowrapslides = false; $scope.activeslide = 0; $scope.slides = [ { image: 'http://lorempixel.com/400/200/' }, { image:

php - How to search value for a condition inside an array -

given array: array ( [0] => array ( [footer] => array ( [id] => 1 [field] => [fvalue] => dream change our country. nmnmn ) ) [1] => array ( [footer] => array ( [id] => 2 [field] => contact [fvalue] => <h2>our contacts</h2> <address class="margin-bottom-40"> shekertek, road: #3 <br> dhaka, bangladesh<br> phone: 01673050495<br> email: <a href="jegeachi24@gmail.com">jegeachi24@gmail.com</a><br> skype: <a href="skype:jegeachi.support">jegeachi.support</a> </address>

testing - Looking for a test string with a char from all languages -

for i18n testing, i'm looking test string have representation of commonly used languages (supported utf-8) , have special chars of these languages have issues in display. will use test string keep sure our system process these languages correctly , have correct font can display these languages correctly. e.g. sample text should have chars latin languages, far east languages, right left languages... there no clear answer question, full of ambiguous terms, instance "commonly used languages" or "normally have issues in display". highly dependent on os, os version, text engine used display text, fonts installed. pretty whole tech stack. sprinkling "all" in question (all special chars, ... languages) make answer useless. looking @ string of tens thousands of characters. have lot of combining marks, , ligatures. want check of combinations too? might have "issues in display" if want check application works in (most) languages, t

javascript - How do I make a TextGeometry multiline? How do I put it inside a square so it wraps like html text does inside a div? -

i'm making 3d text using webgl , three.js , , three.textgeometry . it's working fine far. i'm able create single line of 3d text. now want create multiline text, short paragraph. preferably, i'd wrap naturally when reaches border of box/rectangle placed in. want similar behavior standard html text has when it's inside of div, wrapping multiple lines when reaches edge of it's parent div. here's how i'm creating single line: textgeo = new three.textgeometry( 'hello there. paragraph? hope so.', 'size': 30 'height': 2 'font': 'helvetiker' 'weight': 'normal' 'style': 'normal' bevelthickness: 0.1 bevelsize: 0 bevelenabled: true material: 0 extrudematerial: 1 ) materialarray = [ new three.meshbasicmaterial( { color: 0xffffff } ) new three.meshbasicmaterial( { color: 0x666666, shading: three.smoothshading } ) ] textma

html - How to use bootstrap to create responsive two-column layout with left column really narrow -

i have been using bootstrap responsive 12 column grid layout website. i have layout follows (stripped down version example purpose) <div class='container-fluid'> <div class='row'> <div class='col-md-1'> left side contents go here </div> <div class='col-md-11'> right side contents go here </div> </div> </div> what need now, left side column wider want. how can make fixed-length narrow , still use bootstrap layout? any appreciated! a clean solution customizing bootstrap have more columns, answer: how use bootstrap 16 or 24 columns other alternative using nested rows, end problems unused space, suggestion customizing bootstrap.

reporting services - Nested Cursor based update -

so ssrs report i'm using temp tables. have 2 tables, 1 transactions i'm using pull account , amounts. second amortized delinquency information i'm trying adjust based on transaction i'm running syntax issues. case statements not allowed used cursors or updates? --example transaction:account 123456 principal 500.00 interest 250.00 delinquent 5 months of 200 principal each month, transaction had principal amount of 500, first 2 left alone, third reduced 100 match total transaction amount, leaving remaining amount of 0 --delinquent data -- 11/2015 prin 200 int 80 -> prin 0 int 0 (running total prin 500 int 250) -- 10/2015 prin 200 int 80 -> prin 0 int 10 (running total prin 500 int 250) -- 9/2015 prin 200 int 80 -> prin 100 int 80 (running total prin 500 int 240) -- 8/2015 prin 200 int 80 -> prin 200 int 80 (running total prin 400 int 160) -- 7/2015 prin 200 int 80 -> prin 200 int 80 (running total prin 200 int 80) <- process starts o

.net - Insert delay/wait in code c# -

public void openupform(object sender, eventargs e) { if (forms.count == numberoftimes) { forms.foreach(f => { f.close(); f.dispose(); }); forms.clear(); //need delay here return; } forms.add(new form1()); forms.last().show(); } hello have code, need add delay after forms.clear(); im new coding couldnt figure out. have tryed task.delay , thread.sleep locks user interface. possible add delay dosent lock application? thank you. you can mark method async , use this: await task.delay(2000); will not block ui thread public async void openupform(object sender, eventargs e) { if (forms.count == numberoftimes) { forms.foreach(f => { f.close(); f.dispose(); }); forms.clear(); await task.delay(2000); return; } forms.add(n

c - return makes pointer from integer without a cast [enabled by default] -

does know how can resolve warning:return makes pointer integer without cast [enabled default] when return new_cost? int *cost(int num_nodes, edge new_solution[][10]) { int new_cost = 0; int num_edges = 1; //set number of edges default int x, y, weight; (x = 1; x <= num_nodes; x++) //print out new_solution { weight =0;//find largest tx on each node (y = 1; y <= num_nodes; y++) if (new_solution[x][y].label == 1) { printf("\n edge %d:(%d %d) energy:%d", num_edges++, x, y, new_solution[x][y].weight); if (weight < new_solution[x][y].weight) //find highest energy used per node { weight = new_solution[x][y].weight; //printf("\n weight:%d accum:%d", weight, new_cost); } } new_cost += weight; //find total weight } printf("\n total cost %d\n\n&

Forking the streaming flow in haskell-pipes -

i'm having trouble directing flow though pipeline haskell-pipes. basically, analyze bunch of files , have either print results terminal in human-friendly way encode results json the chosen path depends upon command line option. in second case, have output opening bracket, every incoming value followed comma , closing bracket. insertcommas never terminates, closing bracket never outputted. import pipes import data.bytestring.lazy b import data.aeson (encode) insertcommas :: consumer b.bytestring io () insertcommas = first <- await lift $ b.putstr first cat $ \obj -> lift $ putstr "," b.putstr obj jsonexporter :: consumer (filepath, analysisresult) io () jsonexporter = lift $ putstr "[" p.map encode >-> insertcommas lift $ putstr "]" exportstream :: config -> consumer (filepath, analysisresult) io () exportstream conf = case outputmode conf of json -> jsonexporter

java - JOptionPane no button text with custom LNF -

Image
i tried styling custom-made dialog allows user create new folder. until loaded custom , feel, looked fine: now tried setting , feel , texts of buttons disappeared. i set sscce demonstrates behaviour. please note lnf class nothing except loading values uimanager.getdefaults() . if helps, i'm using debian 8 (jessie) gnome 3.18.1 , global dark theme toggled on. why happen , how can fix disappearing of button texts? another common way use uidefaults#addresourcebundle(...) method: //@see javax/swing/plaf/basic/basiclookandfeel.java @override public uidefaults getdefaults() { uidefaults defaults = new uidefaults(); defaults.putall(uimanager.getdefaults()); //defaults.addresourcebundle("com.example.swing.plaf.light.resources.light"); defaults.addresourcebundle("com.sun.swing.internal.plaf.basic.resources.basic"); return defaults; } test2.java import java.awt.*; import java.io.file; import java.util.*; import javax.swing.*; imp

ios - Can't set relationship object to another object in CoreData -

i have 2 entities: goal , category. added relationship "category" goal entity. want user can choose category list , category added relation goal object. getting error: -[__nssingleobjectseti managedobjectcontext]: unrecognized selector sent instance 0x138a22fa0 my code: - (bool)save { // category object nsmanagedobject *objcategory = [self getcategoryobjectwithid:@"1"]; if (!objcategory) { nslog(@"error objcategory fetching!"); return; } nsentitydescription *entity = [nsentitydescription entityforname:@"goal" inmanagedobjectcontext:[coredatawrapper mymanagedcontext]]; nsmanagedobject *goal = [[nsmanagedobject alloc] initwithentity:entity insertintomanagedobjectcontext:[coredatawrapper mymanagedcontext]]; [goal setvalue:strid forkey:@"id"]; [goal setvalue:[nsset setwithobject:objcategory] forkey:@"category"]; // here error r

java - Largest palindrome product -

i've written program calculate largest palindrome product of 2 3 digit number. i've solved problem @ project euler, solving same in hackerrank fails test cases. wonder what's wrong. input : first line contains t denotes number of test cases. followed t lines, each containing integer, n. constraints: 1≤t≤100 101101<n<1000000 public class solution { static boolean ispalin ( int i){ int low = 0; string = string.valueof(i); int high = a.length() - 1; while(low<high){ if(a.charat(low) == a.charat(high)){ low++; high--; }else{ return false; } } return true; } public static void main(string[] args) { scanner in = new scanner(system.in); int noofcases = in.nextint(); int currmax = 0, result = 0; int no_one, no_two; int largest = -1; for(int i=0; i<noofcases; i++){ currmax = in.nextint(); for(no_one = 100; no_one<=999; n

SSL Handshake Error using Java -

i trying connect java client jmx server using ssl certificate. but unfortunately connection gives ssl handshake error. when tried debug this, using -djavax.net.debug=all flag, following error message on java client. 2016-07-15t13:29:50.02-0700 [app/0] out rmi renewclean-[10.200.0.27:44445,javax.rmi.ssl.sslrmiclientsocketfactory@305a99f7], read: tlsv1.2 alert, length = 2 2016-07-15t13:29:50.02-0700 [app/0] out rmi renewclean-[10.200.0.27:44445,javax.rmi.ssl.sslrmiclientsocketfactory@305a99f7], recv tlsv1 alert: fatal, handshake_failure 2016-07-15t13:29:50.02-0700 [app/0] out rmi renewclean-[10.200.0.27:44445,javax.rmi.ssl.sslrmiclientsocketfactory@305a99f7], called closesocket() 2016-07-15t13:29:50.02-0700 [app/0] out rmi renewclean-[10.200.0.27:44445,javax.rmi.ssl.sslrmiclientsocketfactory@305a99f7], handling exception: javax.net.ssl.sslhandshakeexception: received fatal alert: handshake_failure when change client else, jconsole, conn

This thing is giving me error. C Language -

how can fix this? want scanf() value d, how can it? need please. appreciate that. #include <stdio.h> #include <stdlib.h> void lerdeputados(int d) { printf("indique o número de deputados repartir: "); scanf("%d",&d); } int main(void) { int d; lerdeputados(d); printf("%d",d); return 0; } the problem here when pass variable d lerdeputados function, it's passed by value , means copied. value changed inside function, it's changing copy , , changing copy of course not change original. what need here pass variable by reference . unfortunately c doesn't have that, can emulated using pointer. in other words, need pass pointer variable d lerdeputados function. like void lerdeputados(int *d) { ... } then call address-of operator: lerdeputados(&d);

actionscript 3 - error 1024+1023 with buttons(AS3 Action script 3) -

here code: package { import flash.display.simplebutton; public class button extends simplebutton { public function button() { } public function addlisteners():void { button.addeventlistener(mouseevent.click, downstate); } public function downstate(event:mouseevent):void { trace('test'); } } } the button made has correct types(up, down, hit, over) errors say: 1023 incompatible override line 16 column 19 1024: overriding function not marked override line 16 column 19 thank helping if want to! since button class extending simplebutton , public , protected functions , properties simplebutton available in button . the simplebutton class has property called downstate , when try declare function called downstate in button class, error because it's clashing existing entity called downstate . to fix error, use name doesn't exist yet in scope ( clickhandler in example below) package { import fl

jquery - JavaScript- How to change "message" div to yellow -

i'd know how change "message" div yellow. below js, html, , css files. also, i'd know how make data validations work. word male doesn't print out, letter m. javascript: // assignment 7 javascript , jquery alert ("this test."); //1.) dom ready $(document).ready(function() { alert("the dom ready."); //2.) submitform function var submitform = function() { //alert("this second test."); var first_name = ""; var last_name = ""; var gender = ""; var experience = ""; var firstname = document.getelementbyid("first_name").value; var lastname = document.getelementbyid("last_name").value; //from stack overflow (mar '12) var gender = $('input[name=gender]:checked').val(); /*var m = male; var f = female; var male; var female; var gender = $('input[name=gender]:checked').val(); if (gender = m)

java - Null Pointer Exception when filling a 2d array -

this question has answer here: what nullpointerexception, , how fix it? 12 answers i'm building small game in applet. whenever try run it, following error on line buttons[i][k] = new activesquare(k); error: java.lang.nullpointerexception @ com.proj3.renee.clickaid.<init>(clickaid.java:21) @ sun.reflect.nativeconstructoraccessorimpl.newinstance0(native method) @ sun.reflect.nativeconstructoraccessorimpl.newinstance(nativeconstructoraccessorimpl.java:57) @ sun.reflect.delegatingconstructoraccessorimpl.newinstance(delegatingconstructoraccessorimpl.java:45) @ java.lang.reflect.constructor.newinstance(constructor.java:526) @ java.lang.class.newinstance(class.java:379) @ sun.applet.appletpanel.createapplet(appletpanel.java:795) @ sun.applet.appletpanel.runloader(appletpanel.java:724) @ sun.applet.appletpanel.run(appletpanel.java:380) @ java.lang.thread.run(t

java - Concerns with asynchronous opening of JDialog with owner frame -

i have read of java swing not thread safe. i loading data remote site asynchronously , displaying in dialog once has loaded. concern if swing not thread-safe claims, i'm afraid cause issue when set dialog's owner frame, in different thread. if correct in concern, can open dialog synchronously , avoid issues? swing component must created , updated on event dispatch thread (edt). when load data using separate thread can use swingutilities.invokelater(...) create dialog , components. or option use swingworker . when background processing of worker finished code can automatically executed on edt. read section swing tutorial on concurrency more information , working examples.

mule - NullPayload for Database Query only when wrapped in a Transaction -

i have flow returns nullpayload when wrapped in multi-transaction. when remove multi-transaction tag expected results. why that? here code snippet <flow name="successful-flow" processingstrategy="synchronous"> <vm:inbound-endpoint exchange-pattern="request-response" path="order-process.in" doc:name="vm"/> <ee:multi-transactional action="always_begin" doc:name="transactional" > <foreach collection="#[message.payload]" doc:name="for each" rootmessagevariablename="original"> <jms:outbound-endpoint queue="orders.queue" connector-ref="jmsconnector" doc:name="jms - send order processing queue"> <jms:transaction action="join_if_possible"/> </jms:outbound-endpoint> </foreach> <db:insert config-ref="order_db" doc

javascript - Sending URLs to server from Chrome Extension background.js -

i'm building simple chrome extension url of each of users browser pages when opened , send server. can url appear in alert box, ajax returning blank value database. alerts work fine though(?) any ideas/thoughts? see script below.. popup.html: <html> <head> <title>facebook connect chrome extension</title> <script type="text/javascript" src="index.js"></script> </head> <body> <h1>facebook connect chrome extension</h1> <p><a target="_blank"href="https://www.facebook.com/dialog/oauth?client_id=my-app- id&response_type=token&scope=email&redirect_uri=http://www.facebook.com">facebook connect</a></p> </body> </html> updated background.js: chrome.tabs.onupdated.addlistener(function (tabid, changeinfo, tab) { if (changeinfo != undefined) { var http = new xmlhttprequest(); http.o

javascript - Manipulating DOM of a specific socket using jQuery -

i'm trying make chat application socket.io , have 2 forms set up. 1 form username , other messages. first, page show username form until receives input. username form disappear when user submits information. able access form using jquery $(this). however, make message form appear using show() after retrieve user connection. the function looks this: socket.on('user connected', function(msg){ $('#messages').append($('<li>').text(msg + " has connected")); console.log($(this)) }); but noticed $(this) return socket node. how go retrieving message form of specific socket? if write $('form#message').show(), sockets reveal message form, not want. this html body <ul id="messages"></ul> <form id="user" action=""> <input id="user" autocomplete="off" /> <button>enter</button> </input> </form&g

python - Creating a function which reverses iterator -

i'm doing in attempt better understand iter() , next() methods better. so understand can done using built-ins: >>>animal = 'cat' >>>print(list(reversed(animal))) ['t','a','c'] but can done creating class iterable: class reverselist(): def __init__(self, data): self.data = data self.index = len(data) def __iter__(self): return self def __next__(self): if self.index == 0: raise stopiteration self.index =self.index -1 return self.data[self.index] def intolist(self): self.test = [i in self] return self.test rev = reverselist('cat') print(rev.intolist()) ['t','a','c'] however, i'm having trouble doing same thing using functions instead of going ooo route. is there way functions using iter() , next() methods without having resort comprehensions , loops? you can generator function

php - Mysql query on SQL file -

how can use mysql querys on sql file on custom path? file contain db or table. for example this: // file contain db $mysqli = new mysqli('../myfolder/mydb.sql', 'user', 'pass'); $mysqli -> query("select * table"); // file contain table $mysqli = new mysqli('../myfolder/mytable.sql', 'user', 'pass'); $mysqli -> query("select * table"); the .sql file contains sql commands; need run create database, , can use mysqli connect database.

python:organising a text file of users scores into a list -

i have text file containing this: john = 10 lucy = 2 tom = 4, hardy = 7 tom = 5 tom = 3 hardy = 7 christoper = 4 kim = 9 tom = 4 john = 5 john = 7 john = 6 i need read file , organize list using last 3 scores of users. have been trying hours cant working, please thankyou this might help: dic={} open("demo.txt","r") f: line in f: a,b=line.strip().replace(" ","").split("=") if a.lower() in dic: dic[a.lower()].append(b) else: dic[a.lower()]=[] dic[a.lower()].append(b) d in dic: dic[d]= dic[d][-3:] print dic output: {'christoper': ['4'], 'lucy': ['2'], 'hardy': ['7', '7'], 'kim': ['9'], 'tom': ['5', '3', '4'], 'john': ['5', '7', '6']}

javascript - Do something after var reaches certain value with setinterval? -

i have bootstrap loading bar updates setinterval every 250ms looks it's making progress. trying show alert , redirect when loading bar reaches 100%. <div class="progress" style="border-radius:0px;"> <div class="progress-bar progress-bar-success progress-bar-striped active" style="border-radius:0px;" id="loading" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" style="width: 0%"> </div> </div> i've tried adding window.location before end of function not work. how can this? maybe if statement? var percentl = 10; setinterval(function () { percentl = percentl + 2; document.getelementbyid("loading").style.width = percentl + "%"; }, 250); you can stop timer using clearinterval , add if statement check if % has reached 100

python - Different encodings used in in "print s" vs "print [s]"? -

when following in ipython notebook s='½' s print s print [s] i see '\xc2\xbd' ½ ['\xc2\xbd'] what's going on here? how print list of unicode strings? (ie want see ['½']) edit comments, looks difference "print s" uses s.__str__ , "s", "print [s]" uses it's s.__repr__ you can use repr function create string containing printable representation of list, decode string string-escape encoding returns byte string of string. printing byte string terminal encode automatically it's default encoding (usually utf8) : >>> print repr([s]).decode('string-escape') ['½'] but note since in python 3.x have unicode, don't need use trick : python 3.4.3 (default, oct 14 2015, 20:28:29) [gcc 4.8.4] on linux type "help", "copyright", "credits" or "license" more information. >>> >>> s='½' >>> prin

python - PyCharm: Unresolved reference -

Image
i using pycharm , got following red warnings in from ... import ... . didn't ask me install requirement. why happening , how rid of red thing. thanks! does code run? if not, want install pyspark , add python environment. otherwise, if code run , want remove red inspection warning, try adding pyspark list of unresolved references want ignore in file | settings | inspections - python - unresolved references. taken reference: pycharm - resollving references

android - Default Alpha value of navigation bar in Lollipop -

Image
if set android:windowtranslucentnavigation true in theme in lollipop navigation bar won't translucent in kitkat. instead it's dark semi-transparant background. here know alpha value of background? i've made test navigation bar , found alpha of navbar when android:windowtranslucentnavigation = true 40% of black color. so color in hex be: #66000000 here steps how calculated value: i made screenshot presented below then open in gimp image editor , take rgb values of each color white (255,255,255), white under navbar (153,153,153) grey (150,150,150), grey under navbar (90,90,90) then calculate next: 255 100% 153 x x = 153 * 100 / 255 = 60% so calculated invert value of alpha channel, true value of alpha channel 100 - 60 = 40% argb value of 40% (102,0,0,0) in hex it's #66000000