Posts

Showing posts from April, 2010

c# - How to send and receive 1024 Bits? -

i'm designing interface using c# windows forms , want send , receive 1024 bits using serial port, number i'm sending in hex-form, did next: private void button2_click(object sender, eventargs e) { int i; int = 0; byte[] mychar; mychar = new byte[128]; string m = textbox1.text; (i = 0; < 127; i++ ) { mychar[i] = convert.tobyte((m.substring(a,2)),16); += 2; } serialport1.write(mychar,0,127); } and check if data correct or not, shorted out both transmitter , receiver can see send textbox1 shown in textbox5, problem textbox shown output ascii, , couldn't tell how convert hex form ,(see attempt commented bellow): private void displaytext(object s, eventargs e) { textbox5.clear(); textbox5.appendtext(rxstring); //int value = convert.toint32(rxstring, 16); //string stringvalue = char.convertfromutf32(value); //textbox4.appendtext(stringvalue); } so summarize problems : 1- code send data correct

statistics - R - print outlier from a datafram -

i want extract outliers data frame. 10 out of 1000 data points possible outliers or doesn't fall in 95% confidence interval. there ways find value largest difference between , sample mean. > <- c(1,3,2,4,5,2,3,90,78,56,78,23,345) > require("outliers") > outlier(a) [1] 345 i don't want remove outliers dataframe or boxplot. want print or subset them. any ideas? given data: a <- c(1,3,2,4,5,2,3,90,78,56,78,23,345) if want values not within 95% confidence. have keep in mind confidence concept of probability of "true mean". in case: > mean(a) [1] 53.07692 first question answer: 53 "normal" value expect? why ask it? because if want print values not within 95%: a[a > mean(a) + qt(0.975, df = length(a) - 1) * mean(a) / sqrt(length(a)) | < mean(a) - qt(0.975, df = length(a) - 1) * mean(a) / sqrt(length(a))] [1] 1 3 2 4 5 2 3 90 345 you might more expect, in case.

xcode SpriteKit New game template -

hi i'm trying learn spritekit tutorials have read game template has gameview.swift file , gameview.sks file , loads hello world click on screen adds sprite of space ship. the 1 xcode 6.2 has no gameview.swift or gameview.sks file i've tried adding these going add new file cocoa touch class subclass of skscene add import spritekit new file resources spritekit scene but can't seem work ? there tutorial i'm missing of how this. hope can point me in right direction cheers

html - Show background image that repeats on y axis? -

this relatively small project i've been working on it's driving me insane... i'm trying port original website (which done in dreamweaver, html) visual studio 2013 asp.net project can add databases, login's etc. assignment have. the main problem have fact css code not want tell in terms of layout. i've tried remaking website entirely step step, making sure each aspect works correctly before moving on next. this original website looks like: http://i.stack.imgur.com/sxfeg.png (original html + css) https://gist.github.com/anonymous/7ed94218f9374d41918e now, used template long time in order design , i've experimented see css code affects layout , found tag main_container (line 13 of html gist) controls white background of website. so if remove tag, happen: http://i.stack.imgur.com/bfnle.png ^ important in problem. when porting on website, copied across code correctly , adapted asp. (see gist: https://gist.github.com/anonymous/9c09befeb8950f4c1

c# - With a UV layout, how can I best modify this function to access any part of my texture? -

i've been trying reduce code used in voxel / planar terrain generator, , wrote function in order call every time need add new set of uv's - representing 4 vertex in texture map: list<vector2> _uvs(list<vector2> uv, int x = 0, int y = 0) { list<vector2> uvreturn = new list<vector2>(); uvreturn = uv; uvreturn.add(new vector2 (0f, 0f) * x); uvreturn.add(new vector2 (0.125f, 0) * y); uvreturn.add(new vector2 (0.125f, 1)* y); uvreturn.add(new vector2 (0f, 1f) * x); return uvreturn; } however, can't seem identify exact spots write in modifiers, seem throw things off every time. have single row of 128x textures in 1024 file. uv layout moment seems exact, except multiplication. remove , shows first texture, perfectly. ways can improved on? goal used 4 vertex plane. you can't multiply that, that's different. uvreturn.add(new vector2 (x * 0.125f, 0f)); uvreturn.add(new vector2 ((x + 1) * 0.125f, 0)); uv

web services - WSDL TO PHP implementation -

i got converted wsdl php script not working trying connect http://www.regcheck.org.uk/api/reg.asmx?wsdl , getting error array ( [regcheckservicecheck::check] => soapfault object ( [message:protected] => system.web.services.protocols.soapexception: server unable process request. ---> system.nullreferenceexception: object reference not set instance of object. @ webtropy.carreg.check(string registrationnumber, string username) in c:\inetpub\wwwroot\regcheck.org.uk\api\reg.asmx:line 26 --- end of inner exception stack trace --- [string:exception:private] => [code:protected] => 0 [file:protected] => c:\xampp\htdocs\check\regcheckservicecheck.php [line:protected] => 32 [trace:exception:private] => array ( [0] => array ( [file] => c:\xampp\htdocs\check\regcheckservicecheck.php [line] => 32 [function] => __call [class] => soapclient [type] => -> [args] => array ( [0] => check [1] => array ( [0] => regcheckstructcheck object ( [

javascript - AngularJS $watch not updating my output -

i have html looks - <div ng-controller="postsctrl"> <ul ng-repeat="post in posts" style="list-style: none;"> <li style="padding: 5px; background-color: #f5f5f5;"> <h4> <a href="#" ng-click="showdetails = ! showdetails">{{post.posttitle}}</a> </h4> <div class="post-details" ng-show="showdetails"> <p>{{post.postcontent}}</p> </div> </li> </ul> </div> now data being populated json based rest url , being displayed. have form adding new post database- <form data-ng-submit="submit()" data-ng-controller="formsubmitcontroller"> <h3>add post</h3> <p> title: <input type="text" data-ng-model="posttitle"> </p&

Android flavors, Gradle sourceSets merging -

i try make application multiple partners , each partner test , prod version. each flavors create specific folder res/values in documentation said. my gradle file : apply plugin: 'com.android.application' android { packagingoptions { exclude 'meta-inf/license' exclude 'meta-inf/notice' } compilesdkversion 14 buildtoolsversion "21.1.2" defaultconfig { versioncode 1 versionname 1 minsdkversion 14 targetsdkversion 19 } productflavors { prodpartner1 { applicationid "com.partner1" } testpartner1 { applicationid "com.partner1.test" } prodpartner2{ applicationid "com.partner2" } testpartner2{ applicationid "com.partner2.test" } } sourcesets { testpartner2 { res.srcdirs = [&quo

mysql - Search order by query string -

i use following working mysql query: select nom_appellations appellations nom_appellations '%saint%' limit 8 and have result : lussac-saint-emilion montagne-saint-emilion puisseguin-saint-emilion saint-emilion saint-emilion grand cru saint-emilion grand cru classé but want order string "saint" pertinence this: saint-emilion saint-emilion grand cru saint-emilion grand cru classé lussac-saint-emilion montagne-saint-emilion puisseguin-saint-emilion how can data order featured string ? you can first appearance of saint in nom_appellations : select nom_appellations appellations nom_appellations '%saint%' order locate('saint', lower(nom_appellations)) limit 8;

django-celery PeriodicTask and eta field -

i have django project in combination celery , need able schedule tasks dynamically, @ point in future, recurrence or not. need ability delete/edit scheduled tasks so achieve @ beginning started using django-celery databasescheduler store periodictasks (with expiration) database described more or less here in way if close app , start again schedules still there my problem though still remains since cannot utilize eta , schedule task @ point in future. possible somehow dynamically schedule task eta ? a second question of mine whether can schedule once off task, schedule run e.g. @ 2015-05-15 15:50:00 (that why i'm trying use eta) finally, scheduling thousants of notifications, celery beat capable handle number of scheduled tasks? of them once-off while others being periodic? or have go more advanced solution such apscheduler thank you i've faced same problem yesterday. ugly temporary solution is: # tasks.py djcelery.models import periodictask, inter

Converting a C++ String Class to a Python String -

i have c++ class able output strings in normal ascii or wide format. want output in python string. using swig (version 3.0.4) , have read swig documentation. believe need use typemap construct achieve goal. have written following: %typemap(out) my_namespace::mystring * { $result = pystring_asstring($1); } with no success. when try access c++ string python, following output: <swig object of type 'mystring *' @ 0x02b6fc68> obviously, i'm doing wrong. can point me in right direction? in advance. i use pyboost c++/python interfaces , amazing , easy that. if can, recommend it. std::string automatically mapped python string. in case, may solution define __str __ method object or directly pass char* (i see in swig docs never followed way).

python - How to cache a small piece of information in Django -

i have website delivers list of questions users. set of questions same users. have these questions stored in text file. content of file not change while server running. i cannot use static page display these questions because have logic decide when show question. i cache these questions in memory (instead of reading file off hard drive every time user connects). using django 1.7. i did read caching django's website, think suggested methods (like memcached , database) heavy need. solution situation? use global variable? thanks! there many caching back-ends can use listed in https://docs.djangoproject.com/en/1.7/topics/cache/ i haven't tried file system or local memory caching myself, needed memcached, looks they're available, , rest piece of cake! from django.core import cache cache_key = 'questions' questions = cache.cache.get(cache_key) # if questions: # use questions fetched cache else: questions = { 'question1': 'how you?

java - Debug JSP using Eclipse and JBoss -

i need debug jsp files using eclipse , jboss. have big project. have made remote debug. configured jboss , created debug configuration in eclipse. if put breakpoint in place inside java class - works , execution stops @ breakpoint. i'm trying same thing inside jsp file execution doesn't stop @ breakpoint. should make jsp breakpoints work? after building , compilation i'm getting ear file. i'm using eclipse luna java ee developers , jboss application server 7.1.1. i'm setting breakpoints on java code inside jsp file. jboss starts with bat file: @echo off rem ------------------------------------------------------------------------- rem jboss bootstrap script windows rem ------------------------------------------------------------------------- rem $id$ @if not "%echo%" == "" echo %echo% @if "%os%" == "windows_nt" setlocal if "%os%" == "windows_nt" ( set "dirname=%~dp0%" ) else ( s

android - Get notified when a third party app is launched for the first time -

i want notified when 3rd party apps opened user first time. my app system app, can request system permissions. i know can polling data such app's cache , seeing larger 0, there other way without polling? (for example, via broadcastreceiver) as per knowledge, don't broadcast when launch application first time. however can check intent.flag_activity_launched_from_history set if application has been launched history. not solve problem case check if in future find way detect first application launch.

How to use Boost with Cocoapods on IOS? -

Image
has succeeded in using cocoapods boost pod ? i not understand not seem install fully. after pod install blank project below. there step missing ? this output install pod install --verbose analyzing dependencies updating spec repositories $ /applications/xcode.app/contents/developer/usr/bin/git rev-parse >/dev/null 2>&1 $ /applications/xcode.app/contents/developer/usr/bin/git rev-parse >/dev/null 2>&1 updating spec repo `master` $ /applications/xcode.app/contents/developer/usr/bin/git pull --ff-only up-to-date. cocoapods 0.36.3 available. update use: `gem install cocoapods` more information see http://blog.cocoapods.org , changelog version http://git.io/bah8pq. inspecting targets integrate using `archs` setting build architectures of target `pods`: (``) using `archs` setting build architectures of target `pods-podboost`: (``) resolving dependencies of `podfile` starting resolution (2015-04-01 15:48:56 +0300) creating possibility stat

lotus notes - Adding days to @Today -

might silly question i'm trying add (for example) 2 days todays date via using @today. there way how without using @adjust in formula language? i don't believe there way in formula language other using @adjust. wonder reason avoid @adjust? in lotusscript there function cdat converts number date/time value. imagine cdbl function convert date/time number. assuming true, convert today's date number (of days since jan 1 1900) , add 2 it, , convert date.

ios - Xcode test target with host application forces wrong target into build section of scheme -

when add test target needs host application in order run xcode adds targets not associated application added. i have 2 schemes (internal & production). want run tests on our internal application. when add internal application host end production target being added builds , cannot delete it. if remove host application goes away tests fail. does know i'm going wrong? we had same problems, fixed them these steps: in testing target, go tab 'general' , set hosting application 'none', go 'build phases' , remove target dependency on former hosting target. (don't know if step necessary) go 'window'->'projects', remove derived data hosting target , close xcode. reopen xcode again, open project/workspace. edit hosting target's scheme, select "build" on left , uncheck "find implicit dependencies" - believe function buggy. in testing target, go tab 'general' , set hosting application pre

javascript - Only getting partial user publication in Meteor Jasmine test -

i have client integration test ensure admin user can change user roles via user management interface in app. however, when query user want change, query comes empty though has been created in fixture. describe('admin users', function() { beforeeach(function(done) { meteor.loginwithpassword('admin@gmail.com', '12345678', function(error) { router.go('/users'); tracker.afterflush(done); }); }); beforeeach(waitforrouter); aftereach(function(done) { meteor.logout(function() { done(); }); }); it('should able change user roles', function(done) { var changeuser = meteor.users.findone({ emails: { $elemmatch: { address: 'user@gmail.com' } } }); console.log('changeuser: ', changeuser); console.log('users: ', meteor.users.find().fetch()); $('#user-' + changeuser._id + '-roles').val('

php - I cannot grab a $_POST value in controller using Yii 2.0 -

using yii 2.0 i'm trying grab $_post values in controller view cannot this. show code , talk through below. models/casesearch.php <?php namespace app\models; use yii; use yii\base\model; use yii\data\activedataprovider; use app\models\cases; /** * casesearch represents model behind search form `app\models\cases`. */ class casesearch extends cases { public $category; public $subcategory; public $childcategory; public $newcategory; /** * @inheritdoc */ public function rules() { return [ [['case_id', 'year'], 'integer'], [['name', 'judgement_date', 'neutral_citation', 'all_er', 'building_law_r', 'const_law_r', 'const_law_j', 'cill', 'adj_lr'], 'safe'], ]; } /** * @inheritdoc */ public function scenarios() { // bypass scenarios() implementation in parent class return model::scenarios(); } /** * creates data provider inst

php - htaccess error when dealing with non-english characters in url, but working without it -

if article title in url written in full english, displayed correctly. if title written in greek, 404 page. without using htaccess rewrite rule, displays page. my question how can make work htaccess? htaccess error when dealing rewriteengine on rewritecond %{request_filename} !-f rewriterule ^article/([a-za-z0-9]+)/?$ article.php?title=$1 [nc,qsa,l] rewriterule ^([^\.]+)$ $1.php [nc,l] 3 scenarios: first (english chars): title: hello url: example.com/article/hello opens page second (greek chars): title: γειά url: example.com/article/γειά requested url article/ÃŽ³ÃŽÂµÃŽ¹ÃŽ¬.php not found on server. third (without using htaccess): /article.php?title=γειά opens page [a-za-z0-9] match english text , numbers. change article rewrite rule to: rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d rewriterule ^article/([^/]+)/?$ index.php?title=$1 [nc,qsa,l] [^/]+ match 1 , more of character till next / matched or end of string reached matchin

python - scikit-learn SelectPercentile TFIDF data feature reduction -

i using various mechanisms in scikit-learn create tf-idf representation of training data set , test set consisting of text features. both data sets preprocessed use same vocabulary features , number of features same. can create model on training data , assess performance on test data. wondering if use selectpercentile reduce number of features in training set after transformation, how can identify same features in test set utilise in prediction? traindensedata = traintransformeddata.toarray() testdensedata = testtransformeddata.toarray() if ( usefeaturereduction== true): reducedtraindata = selectpercentile(f_regression,percentile=10).fit_transform(traindensedata,trainyarray) clf.fit(reducedtraindata, trainyarray) # apply feature reduction test data see code , comments below. import numpy np sklearn.datasets import make_classification sklearn import feature_selection # build classification task using 3 informative features x, y = make_classification(n_samples

javascript - Passing a function with parameters -

i want pass function parameters function without evaluating it. this method doesn't work: function first (id) {...} function second (func) { func(); } second(first(id)); this method can't use because number of parameters not same: function first (id) {...} function second (func, id) { func(id); } second(first, someid); you can use #bind partial application: second( first.bind(null, id) )

javascript - how to make a shadow in HTML canvas -

i need draw canvas rect shadow has shadows on 4 sides of rect , similar div has style "box-shadow":"0px 0px 5px 5px" try this <div style="box-shadow: 0 0 5px 5px red; height: 40px; width:100px;"> test </div>

sql - Specific data types -

i'm trying build database i'm struggling type of data. basicly have behave combobox : have several choices can choose one. unfortunatly can't define in sql database. came idea store different "choices" in table , each entries fill one, leaving 10+ empty field. isn't there method in cleaner way ? enumerated types behave describe.

Insert files into HTML input programmatically via javascript -

is there way put file server file type input tag via javascript? way change value of text type input, want insert file file type input. i tried things like: var _file = new file(); document.getelementbyid('fileinputid').files[0] = _file; but seems filelist property of input protected , cannot change file objects inside it. i want bring file server , load file input. is there way achieve issue? thank y'all!

sql - What is best way to merge 2 select statement? -

i have sql server query statement this: with ( select ( sum(case when (t1.price) > 0 (t1.price) else 0 end) ) pr1 ,( abs(sum(case when (t1.price) < 0 (t1.price) else 0 end)) ) pr2 dbo.price_table t1 ) ,b ( select (when(pr1 - pr2) < 0 abs(pr1 - pr2) else 0 end) res ) select res b in query, use 2 select statement achieve "res" column, want achieve "res" column in 1 select statement. what best way merge 2 select statement 1 select statement query? your calculation seems way complicated. taking sum of positive values. sum of negative values, using abs() make value positive, , subtracting result. guess what? same taking sum() of values in first place. so, think statemen

Using polymorphic type in type family in haskell -

i'm learning type family, it's confusing. when define polymorphic type outside of class definition, works well. {-# language rank2types #-} type t = num => but when polymorphic type defined inside of class definition, {-# language typefamilies #-} {-# language rank2types #-} data d = d class a type t :: * instance d type t d = num => then complier shows error : illegal polymorphic or qualified type: forall a. num => in type instance declaration 't' in instance declaration 'a d' is there way make function in class return type polymorphic, 3(num => a)?

asp.net - 400 Bad Request for OData -

i created .net 4.5 web project using visual studio 2012 test out using odata following this tutorial . however, whenever send following request fiddler: put http://localhost:14116/odata/products(5) http/1.1 host: localhost:14116 accept: application/json content-type: application/json content-length: 67 { "name" : "apple //e", "price" : "1298", "category" : "computer" } i following response: http/1.1 400 bad request cache-control: no-cache pragma: no-cache expires: -1 server: microsoft-iis/8.0 x-aspnet-version: 4.0.30319 x-sourcefiles: =?utf-8?b?yzpcdxnlcnnczgxhdmvsbgvczg9jdw1lbnrzxhzpc3vhbcbzdhvkaw8gmjaxmlxqcm9qzwn0c1xp rgf0yvrlc3qzxe9eyxrhvgvzddncb2rhdgfcuhjvzhvjdhmonsk=?= x-powered-by: asp.net date: wed, 01 apr 2015 14:37:41 gmt content-length: 0 what missing? (stack overflow removing 2 empty lines in http response.) this request works fine: get http://localhost:14116/odata/products?$filter=price+lt+500

javascript - Open several times multiple file input without losing earlier selected files -

i have multiple file input. want customers choose multiple files when click on 'choose files' (i think done) , if forget select files, want code enable selecting new files (done) , add data data have selected before (couldn't solve it). how can append new files list? just give context: goal after send each file ajax php server. $("#upload-form").submit(function(e) { $('#displayfilenames').html(''); console.log('currently in files.'); var files = $('#myfileinput')[0].files; (var = 0; < files.length; i++){ $('#displayfilenames').append(files[i].name + '</br>'); console.log(files[i].name); } // send data ajax. }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id='upload-form' action='' method='post' enctype='multipart/form-data'> <input id='myfi

python - How does one draw the X = 0 plane using matplotlib (mpl3d)? -

Image
here answer lets 1 plot plane using matplotlib , if 1 uses vector [1, 0, 0] , nothing gets plotted! makes sense, because of way code set (meshgrid on x-y plane, , z points determine surface. so, how can plot x = 0 plane using matplotlib? this less generic example linked, trick: import numpy np import matplotlib.pyplot plt mpl_toolkits.mplot3d import axes3d yy, zz = np.meshgrid(range(2), range(2)) xx = yy*0 ax = plt.subplot(projection='3d') ax.plot_surface(xx, yy, zz) plt.show()

linux - Monitor for trigger file and copy all files in that directory -

i'm new unix scripting. sorry if question sounds stupid. i have script copies files landingzone archive directory. now, want write script checks test.txt file (which trigger file), if found copy files arrived before test.txt files landingzone archive. please let me know how this? i'm mentioning script because i've couple more commands apart copying. this should work archive=... # archive directory cd landingzone if [ -f test.txt ]; find . -type f -maxdepth 1 ! -name test.txt ! -newer test.txt -exec cp {} $archive ';' fi explanation: if [ -f ... ]; performed if test.txt exists. call find to search normal files ('-f') exclude subdirectories (-maxdepth 1) exclude test.txt (! -name test.txt) exclude files newer test.txt (! -newer test.txt) copy files found archive directory (-exec ...)

ios - How to access UIButton (or any UIElement) inside UITableViewHeaderFooterView subclass? -

i'm learning uitableview in objective-c. hint me how access uibutton inside uitableviewheaderfooterview subclass uiviewcontroller class? programatically, don't use ib. full code: https://gist.github.com/tomnaz/3d790b308d305af8b98c [[??? btnedit] addtarget:self action:@selector(addnewitem:) forcontrolevents:uicontroleventtouchupinside]; don't in viewdidload, in viewforheaderinsection: have pointer header view. - (uiview *)tableview:(uitableview *)tableview viewforheaderinsection:(nsinteger)section { static nsstring *headerreuseidentifier = @"tableviewsectionheaderviewidentifier"; itemsheaderview *sectionheaderview = [tableview dequeuereusableheaderfooterviewwithidentifier:headerreuseidentifier]; [sectionheaderview.btnedit addtarget:self action:@selector(addnewitem:) forcontrolevents:uicontroleventtouchupinside]; return sectionheaderview; }

C++ Sorted Structure Linked List -

i working on project import data text file linked list in order, output linked list. however, whenever output linked list, last entry in text file repeating on , over. here structure: struct account { int accountnumber; double balance; string firstname; string lastname; account * next; }; this function add node in list: void insertaccountbyaccountnumber(account * & h, account * n) { if (h == null) { h = n; return; } if (h->accountnumber >= n->accountnumber) { n->next = h; h = n; return; } account * t1, *t2; t1 = h; t2 = h->next; while (t2 != null) { if (t2->accountnumber < n->accountnumber) { t1 = t2; t2 = t2->next; } else { n->next = t2; t1->next = n; return; } t1->next = n; } } and here code create node text

java - How to add an external folder to the class path? -

so have following folder structure: project lib (running jar folder) properties (property file load in folder) i trying load property file via x.class.getclassloader().getresource("properties/filename"). method works in eclipse when build jar using maven fails find file, giving file not found exception. i suspect folder not in classpath because if run getclassloader().getresources("") property folder never shows up. tried suggestions in previous questions on stackoverflow none have worked far. i tried running java -cp , -classpath still failed. when using maven, files *.properties , other not-compilable files must lie @ src/main/resources folder, default, available. additionally, recommend use thread.currentthread().getcontextclassloader() proper classloader, in order load resources. anyway, if want have custom folder @ classpath, suggest add resource, @ pom.xml , this: <project> ... <build> ...

ssis - choosing the value of BypassPrepare property -

i know setting "bypassprepare" property true means preparing (parsing) query done database engine i'm connecting to. otherwise preparation done integration services package how matter whether parsing done on ssis side or database engine side. want make best choice. thanks , if set option true preparing (i.e. parsing) done database engine connecting to. if set option false preparation done integration services package. this option available oledb type connections , introduced because pacakge (sql task) cannot prepare/parse sql commands oledb database supports. meaning error in parse phase , not able execute statement valid statement on oledb database cannot prepared/parsed sql task.

java - Using private static nested class to implement Singleton -

i learning singleton pattern. learnt classic way implement create static field of singleton class type, hide constructor using private access modifier, , provide public getinstance() method. however, thought of way of implementing without using private constructors: public class swrapper { private static singleton holder = new singleton(); private static class singleton{ /* implementation without private constructor*/} public static singleton getinstance() { return holder; } question: implementation work? (i think can't sure.) if does, there advantages or disadvantages using implementation? it's singleton, it's eagerly initialized (not lazily initialized), it's not interesting. use of name holder suggests attempting initialization-on-demand holder idiom : public class singleton { private static class holder { static final singleton instance = new singleton (); } public static singleton getinstance() {

java - How to handle multiple parent types with JPA? -

i've inherited system has several tables of form this: create table notes ( id int primary key, note text, parent_id int, parent_type varchar ); basically, idea have several other types, "tickets" , "widgets", , if want add note ticket 123, you'd do: insert notes (note, parent_id, parent_type) values ('blah blah', 123, 'ticket'); is there sensible way have jpa create @onetomany relationships from, say, ticket note schema? or need split notes table out separate ticket_notes, widgets_notes, etc tables? would possible create separate ticketnotes, widgetnotes, etc entities in java using @discriminatorcolumn , perhaps? it seems taking advantage of discriminators , inheritance gets me want. for example: @entity class ticket { @id private integer id; // ... @onetomany(mappedby="ticket", fetch=fetchtype.lazy) private list<ticketnotes> notes; } @entity @inheriten

android - display bitmap setImageBitmap -

in application android, trying receive image server socket, can't display them setimagebitmap(). don't have error, screen stay white. here code : public class communicateurandroid implements runnable { public communicateurandroid(socket s, imageview img) { _imagev = img; try { _din = new datainputstream(s.getinputstream()); _dout = new dataoutputstream(s.getoutputstream()); } catch (ioexception e) { e.printstacktrace(); } new thread(this).start(); } public void run() { int length = 0; byte tmp; while (true) try { length = _din.readint(); byte tab[] = new byte[length]; (int = 0; < length; i++) { tmp = _din.readbyte(); tab[i] = tmp; } _image = bitmapfactory.decodebytearray(tab, 0, tab.length); system.out.println("----------"); if (_im

jquery - pass an javascript object to DOM element data atribute -

if fetch data attributes 1 dom element effective way pass element? example of data attributes needs passed: object {avatar: "...", lname: "...", fname: "...", username: "..."} you can use data method object, set properties in object data values: $('#someelement').data(obj); you can duplicate data 1 element getting data object , use set data: $('#someelement').data($('#sourceelement').data()); demo: $('#div2').data($('#div1').data()); // show in stackoverflow snippet document.write(json.stringify($('#div2').data())); <div id="div1" data-avatar="42" data-lname="pan" data-fname="peter" data-username="peterpan07"></div> <div id="div2"></div> <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>

jsf - Display amount in format $1,560.00 and $ 50.00 -

i have 2 fields in screen need display amounts in format this amount : $1,560.00 tax : $ 10.00 in code using <h:outputtext value="#{mbean.amount}" > <f:convertnumber currencysymbol="$" type="currency" maxfractiondigits ="2" /> </h:outputtext> and output is amount : $1560.00 tax : $10.00 how right align amount , comma (,) these amount fields?

vba - Excel Bar Chart - Same Color and Legend Entry for Same Names -

Image
i chart states of machine on period of time. example may "running" 2 hours , "stopped" 1 hour, , there may several times each state occurs. using stacked bar chart i'd display state , amount of time stays in state. i'm finding excel assigning new color , legend entry each new state instance if state has occurred. how can make same-named states within chart have same color (e.g. every time "running" displayed has same color , single legend entry)? thanks the state name stored series name. there series each stack in chart. possible iterate through series , style them based on series name. possible remove entries legend using legendentries object. combining these loop, can update series color if matches title , remove item legend if not 1 of first 2 series. assumes "running" , "stopped" alternate @ start , entries keep in legend. if not case, more logic spot entries keep. sub style_chart() dim cht chart

python - Paramiko - Running commands in "background" -

i've implemented paramiko using exec_command, however, command i'm running on remote machine(s) can take several minutes complete. during time python script has wait remote command complete , receive stdout. my goal let remote machine "run in background", , allow local python script continue once sends command via exec_command. i'm not concerned stdout @ point, i'm interested in bypassing waiting stdout return script can continue on while command runs on remote machine. any suggestions? current script: def function(): ssh_object = paramiko.sshclient() ssh_object.set_missing_host_key_policy(paramiko.autoaddpolicy()) ssh_object.connect(address, port=22, username='un', password='pw') command = 'command run' try: stdin, stdout, stderr = ssh_object.exec_command(command) stdout.readlines() except: else thank you! use separate thread run command. threads should cleaned join command (the

javascript - Changing link URL after every 5 visits -

what i'm trying accomplish following. i have link on website, want change link after every 5 visits or "page refreshes" user , have loop. so example visit site , download button links site called "www.site1.com". refresh site 5 times , download button link changes "www.site2.com". if refresh 6th time goes original. i have not been able find searching through forums shows i'm trying accomplish here. experimenting window.onload , setinterval function changes link every 5 seconds. anyway transition every 5 seconds every 5 page visits? window.onload = function() { function changeurl(){ document.getelementbyid("link").href = "www.site1.com"; } setinterval(changeurl, 5000); } you want use javascript localstorage or sessionstorage this. below example of code using localstorage example window.onload = function() { if (localstorage.visits) { //if value in local storage increase it'

ruby on rails - Status code 500 Paperclip amazon s3 connection refused - (Connection refused - connect(2) for "bucket.s3.amazonaws.com" port 443 -

paperclip can't seem connect amazon s3 bucket instance gives error - *** exception errno::econnrefused in rack application object (connection refused - connect(2) "bucket-images-test.s3.amazonaws.com" port 443) my production.rb looks this: config.paperclip_defaults = { :storage => :s3, :s3_credentials => { :bucket => 'bucket-images', :access_key_id => 'accesskey', :secret_access_key => 'seceretkey', :host_name => 's3-website-us-east-1' }, :default_url => "/missing.png", :path => "/:attachment/:id/:style/:filename", :url => "/:attachment/:id/:style/:filename" } i'm using: paperclip version 4.2.0 aws-sdk version 1.63 aws-sdk-resources version 2 the problem gems , iptables gemfile gem 'paperclip', '~> 4.2.0' gem 'aws-sdk', '~> 1.5.8' gem

How to get List of IP address inside the LAN connection ( Host name + Ip address) in Java? -

how list of ip address inside lan connection ( host name + ip address) in java ? need example code. enter following code in application. process process = runtime.getruntime().execute("net view"); inputstream in=process.getinputstream(); read lines input stream , list of host names in current lan or wifi network.

ios - Setting an image after retreaving the result of a post request takes 17s -

i making post request server returns string, says if user exist or not nickname, post notification works flawless , prints out returned result in under 1s inside completion handler, takes additional 17 20 set image based on returned result... here code using: - (void)textfielddidbeginediting:(uitextfield *)textfield{ // each textfield selected checkl previous text field formating if (textfield == registeremailaddresstextfield) { //check if nickname @ least 6 charactes if (registernicknametextfield.text.length < 6) { nslog(@"emial text field"); [registernicknamecheckmarklabel setimage:[uiimage imagenamed:@"wrong_checkmark.png"]]; }else{ nslog(@"checking nickname"); //check if nickname exists or not nsurl *url = [nsurl urlwithstring:@"myurl"]; //create session custom configuration nsurlsessionconfiguration *sessi