Posts

Showing posts from September, 2011

google reflections - Java - determine where an object is instantiated from object's class -

say have class called myclass , within class, want find out class name instantiated object of myclass , example: class myclass { final string whocreatedme; public myclass() { whocreatedme = ??? } } public class driver { public static void main(string[] args) { system.out.println(new myclass().whocreatedme); // should print driver } } this not advisable, , breaks in unexpected (and expected) ways. hope you're not going use in production code. public class temp { static class testclass { public final string whocreatedme; public testclass() { stacktraceelement ste = thread.getallstacktraces().get(thread.currentthread())[3]; whocreatedme = ste.getclassname(); } } public static void main(string[] args) throws exception { system.out.println(new testclass().whocreatedme); } }

Read camera permission for iOS in Xamarin -

i have ios app developed in xamarin. when app not have permission access microphone, if user tries access microphone app, check settings using avaudiosession.sharedinstance().requestrecordpermission (delegate(bool granted)) , display message. now need same if app not have permission access camera. need check if permission granted camera , display message accordingly. how can this? did checked answer? detect permission of camera in ios think that's solution looking :). edit: here highest voted answer's code ported c# // replace media type whatever want avauthorizationstatus authstatus = avcapturedevice.getauthorizationstatus(avmediatype.video); switch (authstatus) { case avauthorizationstatus.notdetermined: break; case avauthorizationstatus.restricted: break; case avauthorizationstatus.denied: break; case avauthorizationstatus.authorized: break; default: throw new argumentoutofrangeexception(); }

php - Array shows values but print_r(array_values) is empty -

i'm getting response service , print_r() shows array seems different usual arrays. if print array_values it's empty. php: print_r($token); //result: array ( [{"access_token":"123","token_type":"bearer"}] => ) print_r(array_values($token)); //result: array ( [0] => ) why access_token , token_type values not listed in array_values ? the answer not json, it's not because have json type array. because there no value in array. //result: array ( [{"access_token":"123","token_type":"bearer"}] => ) that array has 1 index no value, hence array_values shows nothing. have created array incorrectlly :)

githooks - Git Hook to detect branch creation -

we need write client-side git hook detect new branch creation master. whenever new branch created, folder needs deleted branch. i not sure hook best place check or how identify if branch has been created. a client hook tricky, as: it can bypassed client, , is not deployed on clients. a server hook easier ( update hook ), since receives 0 sha new refs. same hook can list content of commit git diff-tree --no-commit-id --name-only -r <sha1> # or git ls-tree -d --name-only -r <sha1> if specific folder still there, can reject push helpful message.

Pass generic type in c++ method as parameter -

i trying implement c++ method , want pass generic parameter in it. want assign parameter object's property. here example: class myclass { public: unsigned long long var1; unsigned short var2; signed short var3; } now have global object of myclass in someotherclass , method says: void someotherclass::updatemyclassvalue(int paramtype, <generic> value) { switch(paramtype) { case1: objmyclass.var1 = value; case2: objmyclass.var2 = value; case3: objmyclass.var3 = value; } } how pass such type, because if use fixed type e.g unsigned long long parameter type, won't able assign var2 & var3. don't want loose data, e.g signed data may have -ve value. please me overcome situation, have no experience working in c++. not sure if can achieve using templete<> in c++, if yes how? thanks pass parameter pointer: void someotherclass::updatemyclassvalue(int paramtype, v

How can i verify if the text on the button is correct in selenium using C# -

i need verify if text on button correct? how can text on button in selenium using c#. thanks hi answer using method. public static t getattributeastype<t>(this iwebelement element, string attributename) { string value = element.getattribute(attributename) ?? string.empty; return (t)typedescriptor.getconverter(typeof(t)).convertfromstring(value); }

javascript - How ready for Web Development will you be after you complete Codeacademy's web developer program? -

i'm beginner programmer decided work computers in order fulfill lifetime passion have had them. many others, stumbled across codeacademy , have embarked on "web developer skills" program start off with. my question is, prepare web development point paid professional, or best supplement in-depth html, java, angularjs etc.. courses? aspirations, naive may be, cutting edge in computer systems , programming, pushing forward rather making career based on selling templates. any feedback regarding appreciated! it not prepare point paid professional. , courses on html, js, angularjs beforehand if have no experience @ all. codecademy solid start, that's is. start. covers absolute basics of various languages/development methods contains, , includes basic projects work on idea of do. however, point enough people pay develop them, need show project work have done. whether it's did on own, or group project worked on, people see finished product. by means

The maximum number of element in a list when generate all the permutations of a list in Python -

i using itertools generate permutations of python list import itertools lt = [0,1,2,3] print list(set(itertools.permutations(lt))) it works when length of list less 7, when length of list grater 7 ([0,1,2,3,4,5,6,7]), takes lot of time generate permutations, , program frozen. wondering if there way generate permutations big list, thank you! itertools return generator in ns time. it's slow conversion set() . 8! >>> lt = [i in xrange(8)] >>> %timeit itertools.permutations(lt) 1000000 loops, best of 3: 547 ns per loop >>> %timeit set(itertools.permutations(lt)) 100 loops, best of 3: 13.4 ms per loop >>> %timeit list(set(itertools.permutations(lt))) 10 loops, best of 3: 19.1 ms per loop >>> %timeit list(itertools.permutations(lt)) 100 loops, best of 3: 4.9 ms per loop 9! = 362880 >>> lt = [i in xrange(9)] >>> %timeit itertools.permutations(lt) 1000000 loops, best of 3: 557 ns per loop >

C++ can't implement default constructor -

i have following class: class fraction { private: int x; int y; public: // constructors fraction(long x = 0, long y = 1); fraction(const fraction&)=default;//here problem virtual ~fraction(); }; i'm trying disable default c++ constructor implement own (i intend use copy). so, declared default. but, when i'm trying implement it: fraction::fraction(const fraction&){} compiler throws following error @ me: ./src/fraction.cpp:16:1: error: definition of explicitly-defaulted ‘fraction::fraction(const fraction&)’ fraction::fraction(const fraction&){ ^ in file included ../src/fraction.cpp:8:0: ../src/fraction.h:22:2: error: ‘fraction::fraction(const fraction&)’ explicitly defaulted here fraction(const fraction&)=default; is there way fix it? i'm doing wrong ? found articles defaults, nothing can me fix these errors. = default tells compiler use default implementatio

python - django extended built in user model not allowing to login in admin -

i using django 1.8 app , using postgresql.i have created super user , can login admin panel after configuring postgresql settings in settings.py file.but after i have decided extend django built in user model , thats why have created new app namely authentication , wrote model from django.db import models django.contrib.auth.models import abstractbaseuser django.contrib.auth.models import baseusermanager class accountmanager(baseusermanager): def create_user(self, email, password=none, **kwargs): if not email: raise valueerror('users must have valid email address.') if not kwargs.get('username'): raise valueerror('users must have valid username.') account = self.model( email=self.normalize_email(email), username=kwargs.get('username') ) account.set_password(password) account.save() return account def create_superuser(self, email, password, **

ios - How to vary impulse/velocity based on screen size/device -

i building game swift have sprites moving around screen have avoid. when test game on iphone 5, objects harder avoid on 6 or 6+. think because had velocity same across board (i adjusting sizes based on screen size). changed original impulse try , vary based on screen size matching numbers had cgvectors let gonex = screenwidth/6 let goney = screenheight/9 let gtwox = screenwidth/6 let gtwoy = screenheight/9 ghostone.physicsbody?.applyimpulse(cgvectormake(gonex, -goney)) ghosttwo.physicsbody?.applyimpulse(cgvectormake(-gtwox, gtwoy)) i did this, , helped enough notice difference between devices, still not acceptable. objects still harder or easier avoid based on device. is there other way can vary impulse?

php - Homestead + Symfony 2.7 Installation -

i'm having problems trying install symfony2 on laravel homestead vagrant box.. i repeatedly keep getting 403 response when entering url. i have in homestead.yaml , have added test.dev hosts file. folders: - map: ~/code to: /home/vagrant/code sites: - map: test.dev to: /home/vagrant/code/symfony-test # tried /home/vagrant/code/symfony-test/web any ideas? your variant: # tried /home/vagrant/code/symfony-test/web right. point in browser http://test.dev/app.php because default homestead looking index.php or rename app_dev.php index.php! if need dev mode comment in app_dev.php lines 12-18

c++ - Reading and displaying UTF-8 encoded Chinese characters -

i trying read chinese characters utf-8 encoded text file , storing them in variables. when try print them in console, shows question marks in place of characters. while(!fin.eof()) { fin.get(c); appendcharactertoword(currentword, c); } (i working in windows , code in c++)

php - how to post Guzzle 6 Async data -

i trying post data async using guzzle 6(latest ver) $client = new client(); $request = $client->postasync($url, [ 'json' => [ 'company_name' => 'update name' ], ]); but not getting request form guzzle post request on terminal have tried send request? http://guzzle.readthedocs.org/en/latest/index.html?highlight=async $client = new client(); $request = new request('post', $url, [ "json" => [ 'company_name' => 'update name'] ]); $promise = $client->sendasync($request)->then(function ($response) { echo 'i completed! ' . $response->getbody(); }); $promise->wait();

javascript - Practice for Routing Handler in MEAN Stack? -

i have application on express 4.x integrated twilio api , dependent on input users' phone, respond different xml files may or may not created dynamically. where supposed put theoretical route conditional? i.e. exports.handle = function(req, res) { if(req.body.digits == 1){ //pass first option handler } if (req.body.digits == 2) { //create xml file dynamically //for second option } else { //handle else } }; it seems bit heavy putting routes file. in such mvc structure typical put conditional controller? or stuff routes? or there option i'm unaware of? i'd rather have code pass requests single handler. i.e. exports.handle = function(req, res) { if (req.body.digits) //send handler }; where go? called? in scenario, router "single handler". channeling input through routing mechanism , letting decide appropriate handler (or controller) is. commonly referred "front co

jquery - Make an ajax call after form checking -

i have form this: <form id="update_form_password"> <label for="text-input">nouveau mot de passe</label> <input type="password" id="customer_new_password" name="customer_new_password" class="form-control"> <label for="text-input">répétez le mot de passe</label> <input type="paswword" id="customer_repeat_password" name="customer_repeat_password" class="form-control"> <button type="submit" class="btn btn-primary"> enregistrer</button> </form> i'm using jquery validation plugin check forms correctly filled. my problem submit form after check. so have actually: <script> $('#update_form_password').validate({ rules: { customer_new_password: "required", customer_repeat_password: { equalto: "#customer_new_pass

javascript - I am using the Angular "Date" filter, but what is this numerical expression? -

in angular tutorial there example of date filter being used this: {{ 1304375948024 | date }} --> may 2, 2011` what notation of expression 1304375948024 ? that unix timestamp , measure of number of seconds have elapsed since unix epoch , defined 00:00:00 utc on 1 january 1970 check out epoch converter shows 1304375948024 represents mon, 02 may 2011 22:39:08 gmt as pointed out @psl in comment - type of value receive standard javascript date.prototype.gettime() . note in javascript, value in milliseconds , not seconds.

python 3.x - How can I get python3.4 to find the PySDL2 module I downloaded on win7? -

i downloaded pysdl2 (from https://bitbucket.org/marcusva/py-sdl2/downloads ) , unzipped sdl2 package folder c:\python34\lib\site-packages\pysdl2-0.9.3, has subfolder sdl2 has subfolder ext. i copied 'hello world' program same folder, using header: import os os.environ["pysdl2_dll_path"] = "/python34/lib/site-packages/pysdl2-0.9.3" import sys import sdl2.ext i ran same folder, , said couldn't find sdl2. (i used os.environ line, since had 'set' environment variable, didn't help) importerror: not find library sdl2 (pysdl2_dll_path: /python34/lib /site-packages/pysdl2-0.9.3/sdl2) so ran pip install pysdl2, , said: c:\python34\lib\site-packages\pysdl2-0.9.3>pip install pysdl2 requirement satisfied (use --upgrade upgrade): pysdl2 in c:\python34\ lib\site-packages cleaning up... so, have package in python library, have pointed in environment, , pip says there, somehow python can't find import. what should doing? pys

validation - Parsley.js - Display errors near fields AND in a combined list above form -

is possible configure parsley.js display error messages both... a) next individual fields, , b) in combined list elsewhere on page ...at same time? also, possible render error messages hyperlink field generated error? thanks. update: the accepted answer fantastic example (thanks milz!) needed bit more refining. for benefit of other readers, here's updated code in which... error messages no longer duplicate after failing first validation (in original example, try generating error repeatedly pressing backspace in field - new message added list every keystroke) error message take text of label in same form-group (handy radios , checkboxes don't have individual labels meaningful) error messages removed list on fly when they're fixed user. entire error panel has title, , hidden/shown depending on whether has content or not. boostrap styling, layout & parsley config provided. // 1. configure parsley bootstrap 3 forms // window.parsleyconfig =

c# - Appending query params to relative Uri -

i have relative uri string, sometimes query parameters. instance /?abc . task append l=a query. tried use methods of uri , uribuilder , seems both of them not support relative uris. ideas?

node.js - Errors Installing Ionic Framework on Mac -

when trying install ionic framework on mac via node.js using command $ npm install -g cordova ionic getting following errors npm err! darwin 14.3.0 npm err! argv "node" "/usr/local/bin/npm" "install" "-g" "cordova" "ionic" npm err! node v0.12.5 npm err! npm v2.12.0 npm err! attempt unlock /usr/local/lib/node_modules/cordova, hasn't been locked npm err! npm err! if need help, may report error at: npm err! <https://github.com/npm/npm/issues> npm err! darwin 14.3.0 npm err! argv "node" "/usr/local/bin/npm" "install" "-g" "cordova" "ionic" npm err! node v0.12.5 npm err! npm v2.12.0 npm err! attempt unlock /usr/local/lib/node_modules/ionic, hasn't been locked npm err! npm err! if need help, may report error at: npm err! <https://github.com/npm/npm/issues> npm err! please include following file support request: npm err! /users/k

python - scikit KernelPCA unstable results -

Image
i'm trying use kernelpca reducing dimensionality of dataset 2d (both visualization purposes , further data analysis). i experimented computing kernelpca using rbf kernel @ various values of gamma, result unstable: (each frame different value of gamma, gamma varying continuously 0 1) looks not deterministic. is there way stabilize it/make deterministic? code used generate transformed data: def pca(x, gamma1): kpca = kernelpca(kernel="rbf", fit_inverse_transform=true, gamma=gamma1) x_kpca = kpca.fit_transform(x) #x_back = kpca.inverse_transform(x_kpca) return x_kpca kernelpca should deterministic , evolve continuously gamma. it different rbfsampler have built-in randomness in order provide efficient (more scalable) approximation of rbf kernel. however can change in kernelpca order of principal components : in scikit-learn returned sorted in order of descending eigenvalue, if have 2 eigenvalues close each other order changes gamma

arrays - Interpolation without specifying indices in Python -

i have 2 arrays of same length, array x , array y. want find value of y corresponding x=0.56. not value present in array x. python find closest value larger 0.56 (and corresponding y value) , closest value smaller 0.56 (and corresponding y value). interpolate find value of y when x 0.56. this done when find indices of 2 x values , corresponding y values myself , input them python (see following bit of code). there way python find indices itself? #interpolation: def effective_height(h1,h2,g1,g2): return (h1 + (((0.56-g1)/(g2-g1))*(h2-h1))) eff_alt1 = effective_height(x[12],x[13],y[12],y[13]) in bit of code, had find indices [12] , [13] corresponding closest smaller value 0.56 , closest larger value 0.56. now looking similar technique tell python interpolate between 2 values of x x=0.56 , print corresponding value of y when x=0.56. i have looked @ scipy's interpolate don't think in case, although further clarification on how can use in case helpful too.

(new) python questions about user input -

okay have question on user input, simple , i'm new so..i'm using python 3.3 , if type input("enter name , age: ") how put if statement records name , age , tells user: print("your name , age that") with values inserted, ps, i'm using notepad++ ide , cmd enter input code. no python shells. in advance, please explain in detail how answers work because i'm new python, i've been scripting on actionscript before outdated know few things or 2 loops never scripted input data can recorded. thanks in advance . name, age = input("enter name , age: ").split() print("your name {this} , age {that}".format(this=name, that=age))

Adding Javascript with php -

i typed code php let me if click 'delete' delete user database i need put javascript code asks me when click on delete 'are sure !? ' <?php if(!isset($_get['id'])) { die('bad access'); } $_id = (int)$_get['id']; // avoid injection , typing codes in url if ($_id == 0) { die('bad access'); } require_once('usersapi.php'); $user = tinyf_users_get_by_id($_id); if($user == null){ tinyf_db_close(); die('wrong user id'); } $result = tinyf_users_delete($_id); tinyf_db_close(); if($result){ die('success'); } else{ die('falied'); } ?> the file showusers.php <html> <body> <?php require_once('usersapi.php'); error_reporting(e_all); ini_set('display_errors', 1); /* function tinyf_users_get($extra ='') { global $tf_handle; $query = sprintf("select * `users` %s",$extra ); $qresult = mysqli_query($tf_handle

r - Remove row-specific items from list -

i create last column ('desired_result') 3 prior columns ('group', 'animal', , 'full'). below code reproducible example. library(data.table) data = data.table(group = c(1,1,1,2,2,2), animal = c('cat', 'dog', 'pig', 'giraffe', 'lion', 'tiger'), desired_result = c('dog, pig', 'cat, pig', 'cat, dog', 'lion, tiger', 'giraffe, tiger', 'giraffe, lion')) data[, full := list(list(animal)), = 'group'] data = data[, .(group, animal, full, desired_result)] data group animal full desired_result 1: 1 cat cat,dog,pig dog, pig 2: 1 dog cat,dog,pig cat, pig 3: 1 pig cat,dog,pig cat, dog 4: 2 giraffe giraffe,lion,tiger lion, tiger 5: 2 lion giraffe,lion,tiger giraffe, tiger 6: 2 tiger giraffe,lion,tiger giraffe, lion basically, modify 'full

javascript - AJAX xmlhttp.responseText -

i've been racking brain few hours , can't figure out why string comparison won't work. in following code, xmlhttp call , response text. php file call returning proper response string "noad" , , noad being displayed when appropriate in testing. however, when call returned noad want identify it, reason within call below xmlhttp.responsetext == comparisontext not comparing two. why xmlhttp.responsetext printout noad can't use within comparator? function loadxmladimage1doc(currentscenariotime) { var returntext = "not here"; var comparisontext = "noad"; var xmlhttp; if (window.xmlhttprequest) {// code ie7+, firefox, chrome, opera, safari xmlhttp=new xmlhttprequest(); } else {// code ie6, ie5 xmlhttp=new activexobject("microsoft.xmlhttp"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readystate==4 && xmlhttp.status==200) { if (xmlhttp.responsetext == comparisontext) {

Java - Write hashmap to a csv file -

i have hashmap string key , string value. contains large number of keys , respective values. for example: key | value abc | aabbcc def | ddeeff i write hashmap csv file such csv file contains rows below: abc,aabbcc def,ddeeff i tried following example here using supercsv library: http://javafascination.blogspot.com/2009/07/csv-write-using-java.html . however, in example, have create hashmap each row want add csv file. have large number of key value pairs means several hashmaps, each containing data 1 row need created. know if there more optimized approach can used use case. thanks in advance! as question asking how using super csv, thought i'd chime in (as maintainer of project). i thought iterate on map's entry set using csvbeanwriter , name mapping array of "key", "value" , doesn't work because hashmap 's internal implementation doesn't allow reflection key/value. so option use csvlistwriter follows. @ least way d

ios - touchesBegan on local variable -

i have function gets called repeatedly every 2 seconds, bringing ball top of screen random texture each time. want able work ball in touchesbegan can't because local variable. i've tried making global variable gave me error saying tried add skspritenode has parent. appreciated. here's code used bring down balls. override func didmovetoview(view: skview) { var create = skaction.runblock({() in self.createtargets()}) var wait = skaction.waitforduration(2) var waitandcreateforever = skaction.repeatactionforever(skaction.sequence([create, wait])) self.runaction(waitandcreateforever) } func createtargets() { let randomx = int(arc4random_uniform(170) + 290) var ball = skspritenode(imagenamed: "blueblue") ball.zposition = 0 ball.physicsbody = skphysicsbody(circleofradius: ball.size.width / 11) ball.physicsbody?.dynamic = true ball.size = cgsize(width: ball.size.width / 1.5, height: b

c++ - Principle range of object orientation using image moments -

i trying extract angle of shape in image using moments in opencv/c++. able extract angle, issue principal range of angle 180 degrees. makes orientation of object ambiguous respect 180 degree rotations. code using extract angle is, findcontours(frame, contours, cv_retr_external, cv_chain_approx_simple); vector<vector<point2i> > hull(contours.size()); int maxarea = 0; int maxi = -1; int m20 = 0; int m02 = 0; int m11 = 0; (int = 0; < contours.size(); i++) { convexhull(contours[i], hull[i], false); approxpolydp(hull[i], contourvertices, arclength(hull[i], true)*0.1, true); shapemoments = moments(hull[i], false); if(shapemoments.m00 <= areathreshold || shapemoments.m00 >= max_area) continue; if(contourvertices.size() <= 3 || contourvertices.size() >= 7) continue; if(shapemoments.m00 >= maxarea) { maxarea = shapemoments.m00; maxi = i; } } if(maxi == -1) return false; fabriccontour

oauth - How to authenticate using Twitter in Windows phone 8.1? -

i have following code login authentication via twitter in windows phone 8.1 application: user = app.mobileservice.loginasync(mobileserviceauthenticationprovider.twitter); but in wp8.1 loginasync method requires 2 parameters , second parameter should be: jobject token token provider specific object existing oauth token log in with what should enter second parameter? object of jobject class twitter access keys? if so, how assign keys object? the token object needs formatted depending on specific provider. these examples of formats based on providers: microsoftaccount {"authenticationtoken":"<authentication_token>"} facebook {"access_token":"<access_token>"} google {"access_token":"<access_token>"} azure active directory {"access_token":"<access_token>"} i took information from: https://msdn.microsoft.com/en-us/library/dn296411.aspx so maybe like user = app.

iOS Swift Barcode Reading -

i have barcode scanning working in app. after barcode detected stop capture session allow processing of barcode. however, after barcode processed want scanning controller stay , next barcode scanned. had assumed starting capture session (startrunning()) image stays frozen. how can start capture session again? to stop session use code self.session.stoprunning() to begin agian, use code self.session.startrunning() here code implement barcode scanner... import uikit import avfoundation class viewcontroller: uiviewcontroller, avcapturemetadataoutputobjectsdelegate { let session : avcapturesession = avcapturesession() var previewlayer : avcapturevideopreviewlayer! var highlightview : uiview = uiview() override func viewdidload() { super.viewdidload() // allow view resize freely self.highlightview.autoresizingmask = uiviewautoresizing.flexibletopmargin | uiviewautoresizing.flexi

php - I was hoping someone could give m advice on the best way to this solution? -

i updating website client. web site has store locator page, there around 65,000 store locations in store location page. stored within mysql database inthe storelocation table. this feature works great, fine, however, clients wants give ability users filter store locations locations carry products. so have 7 total products used filters. thinking using kind of mapping table, maybe 1 many....one store location can hold many products. trying think of quick way link locations table new mapping table. the solution have came far making table , having go through each store adding products carry. able query against kind of order history table has product names store ordered, allow me create php script link tables. have not found said table, however. i not sure client impressed 65,000 stores carry products, kudos! i following: stores 65,000 entries of stores unique id each one products 7 entries of unique products unique id , product name store_products

arrays - C# Trouble instanciating controls -

i'm attempting make array of control in c# visual studio express doesn't cooperate. i'm getting message @ run time: object reference not set instance of object. the error occurs @ arrow below. how make work? public partial class protocoltool : form { // ... other stuff // doesn't seem make instances expect // class string_entry defined lower public string_entry[] pt_entries = new string_entry[nb_entries]; // constructor class protocol tool public protocoltool() { initializecomponent(); // tried make instances here still doesn't work //pt_entries = new string_entry[nb_entries]; // add supposedly instanciated control in tablelayoutpanel entriesguiadd(); // ... other stuff } private void entriesguiadd() { (int = 0; < nb_entries; i++) { // tried make instances here still doesn't work //pt_entries[i].create();

How does one populate a pre-designed spreadsheet with Java? -

i may going wrong way, here's goal: i want populate specific fields (that color keyed) in spreadsheet both figures input user , solutions made inputs. spreadsheet not have interactive. essentially, (without being able find solution) trying pass variable specific cell in spreadsheet. achieve access or excel, small part of larger application. if helps, ultimately, user inputs , calcs need stored in database , organized/keyed date; there new inputs , calculations entered daily. here's test program: /* test program generate spreadsheet , populate specific cells scanner inputs user , solution derived scanner inputs */ import java.util.scanner; class testrecord { string name; double a; double b; double calc_average() { double x = (a+b) / 2; system.out.println("the average " + x); return x; } } class sheetgenerator { public static void main(string[] args) { testrecord dingdong = new testrecord()

shell - Error: Could not find command 'git' with Boxen -

i've installed git installer , , works fine. i've got command line tools git (see below prove), seems when run boxen broken. does knows git isn't found boxen while installed? i've tried install git through homebrew, didn't fix issue either. boxen refuses find git. hope can help. stefan.vermaas @ macbook in ~ ○ git --version git version 2.4.3 stefan.vermaas @ macbook in ~ ○ git /usr/local/git/bin/git stefan.vermaas @ macbookx in ~ ○ git /usr/local/heroku/bin:/usr/local/git/bin/git:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/x11/bin stefan.vermaas @ macbook in /opt/boxen/repo on master ± ./script/boxen --> preparing auto-update... --> complete! nothing new upstream. fact file /opt/boxen/repo/facts.d/example.yaml parsed returned empty data set notice: compiled catalog macbook in environment production in 2.39 seconds error: not find command 'git' i've tried extend path thorbjørn ravn andersen suggested, it's still saying: &quo

java - Is it possible to unexpose a Rule in Drools? -

let's i've drools file this, rule "test rule 1" salience 10 when $data : map( this["amount"] >= 1000 && this["quantity"] >=3 ) system.out.println("you've met criteria"); end =========================================================================================== rule "test rule 2" salience 9 when $data : map( this["amount"] >= 1000 ) system.out.println("quantity criteria not met"); end =========================================================================================== rule "test rule 3" salience 8 when $data : map( this["quantity"] >= 3 ) system.out.println("amount criteria not met"); end all these present in single .drl file. in rule, order of rule based on highest salience number. need like, 1) if test rule 1 satisfied, dont want further rules executed. 2) if test rule 1 not satisfied, dont have wo

java - HTTPS Post request (not) using certificate/hash print? -

i admit there possibility not informed subject, i've done loads of reading , still can't answer question. from have learnt, make communication secure https need using sort of public key (reminds me of pgp-encryption). my goal make secured post request java application (which i, in moment starts working, rewrite android app, if matters) php application accessible via https address. naturally did google research on topic , got lot of results how make ssl connection. non of results used sort of certificate/hash prints. use httpsurlconnection instead of httpurlconnection , else identical. right now, copy paste of found here this: string httpsurl = "https://xx.yyyy.zzz/requesthandler.php?getparam1=value1&getparam2=value2"; string query = "email=" + urlencoder.encode("abc@xyz.com", "utf-8"); query+="&"; query+="password="+urlencoder.encode("tramtarie","utf-8"); ur

java code of my calculator app made in android studio. It got crashed -

package com.example.android.mycalculator; import android.os.bundle; import android.support.v7.app.actionbaractivity; import android.view.view; import android.widget.edittext; import android.widget.textview; public class mainactivity extends actionbaractivity { int qty = 0; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); string val = ((edittext)findviewbyid(r.id.input1)).gettext().tostring(); int num1 = integer.valueof(val); string val1 = ((edittext)findviewbyid(r.id.input2)).gettext().tostring(); int num2 = integer.valueof(val1); } private void display(int number) { textview quantitytextview = (textview) findviewbyid( r.id.quantity_text_view); quantitytextview.settext("" + number); } /*for getting input value

apache zookeeper - Kafka unrecoverable if broker dies -

This summary is not available. Please click here to view the post.

regex - CSS animation speed regular expressions (PHP) -

i need regular expressions extract time elements css: e.g. 4000ms or 4s all i've got this: preg_match_all('/([0-9]{1-10}(ms|s)/i', $css, $timevalues); thanks in advance. you're incorrectly using range quantifier {min, max} , , missing closing parenthesis. you can modify regular expression follows: preg_match_all('/([0-9]{1,10})m?s/i', $css, $timevalues); print_r($timevalues[1]);

Need to reorder list and make a sentence in python -

i need rearranging list alphabetically list= ['z', 'a', 'b', 'y', 'c', 'x', 'd', 'w', 'e', 'v', 'f', 'g', 'u', 'h', 'i', 'j', 't' ,'k', 'l', 's', 'm', 'n', 'r', 'o', 'p', 'q', ' '] into "hello world" indexing array. how do that? i'm beginner , i'm doing in python 2.7. as has been mentioned, list can sorted alphabetically using sort() function follows: mylist = ['z', 'a', 'b', 'y', 'c', 'x', 'd', 'w', 'e', 'v', 'f', 'g', 'u', 'h', 'i', 'j', 't' ,'k', 'l', 's', 'm', 'n', 'r', 'o', 'p', 'q', ' '] mylist.sort() print mylist whi

numpy - Why are non-integer exponents causing nan's to show up in Python? -

i trying numerically solve lane-emden equation in python using scipy.integrate.ode class. for reason, code works integer values of n (the polytropic index) such 3, not non-integer values such 2.9 , 3.1. i getting runtime warning, "7: runtimewarning: invalid value encountered in double_scalars" , print statement "print f0, f1" shows several values nan's when n not integer. from scipy.integrate import ode import numpy np def rhs(zet, u, n): x = u[0] # theta y = u[1] # phi f0 = -u[1]/(zet**2) f1 = (u[0]**(n))*(zet**2) print f0, f1 return np.array([f0,f1]) r = ode(rhs).set_integrator("vode", method="adams", atol=1.e-13, rtol=1.e-13, nsteps=15000, order=12) y0 = np.array([1.,0.]) zeta0 = 0.000001 r.set_initial_value(y0, zeta0) n=3.1 r.set_f_params(n) dzeta = 0.000001 zeta = [zeta0] theta = [y0[0]] while r.successful() , r.y[0] > 0.0: r.integrate(r.t + dzeta) zeta.append(r.t) theta.append(r.y[0

java - Is it possible to repair this class to make it Immutable -

i'm trying repair following class become immutable: public class immutablelist<e> implements iterable<e> { private list<e> internal; public immutablelist(list<e> l) { this.internal = l; } public int size() { return this.internal.size(); } public e get(int i) { return this.internal.get(i); } public iterator<e> iterator() { return this.internal.iterator(); } } but @ moment i'm not successful, problem don't know type of e don't know how deep copy it. wanted know if possible make class immutable? thanks in advance your class nearly "as immutable possible." there's no general way deal arbitrary generic types, should not worry it. two remaining issues: you need copy l -- shallow copy suffice. this.internal = new arraylist<e>(l) do. if internal.iterator() supports remove() , consumers of list type can remove elements. make class

@Configurable-Beans not working with JPA-EntityListeners in Spring Boot -

i having strange problem custom jpa-entity listener i've created in spring boot application. i'm trying use springs @configurable mechanism configure entitylistener (as seen in springs auditingentitylistener ) spring refuses recognize listener used in @entitylisteners -annotation on jpa entity. if not configured on jpa entity, listener gets wired/configured spring should. i've created example project junit-test demonstrate problem: https://github.com/chrisi/aopconfig/find/master @springbootapplication @enablespringconfigured @enableloadtimeweaving public class application { public static void main(string[] args) throws exception { springapplication.run(application.class, args); } } the entitylistener: /** * bean not instanciated spring should configured spring * because of {@link configurable}-annotation. * <p> * configuration works if <code>unmanagedbean</code> not used <code>entitylistener</code> * via {@link javax.

java - getArguments() is returning null -

i'm having problem using fragments. indeed, i'm trying pass arguments fragment activity. problem getarguments() call returns null. here code: albumuser.java : public class albumuser extends appcompatactivity { @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_album_user); string albumid = getintent().getstringextra("albumid"); string albumname = getintent().getstringextra("albumname"); string albumauthor = getintent().getstringextra("albumauthor"); string coverurl = getintent().getstringextra("coverurl"); getfragmentmanager().begintransaction().replace(r.id.fragmentalbum, album.newinstance(albumid,albumname,albumauthor,coverurl)).commit(); } } album.java : public class album extends fragment { private string albumid; private string albumname; private string albuma

java - Injections in guice don't work everywhere -

this question has answer here: how avoid having injector.createinstance() on place when using guice? 3 answers i'm trying inject service google guice @inject annotation: @inject service service; this inject working not in places. when doesn't work catch null pointer. can problem ? obviously, attemps within single project if not create instances .getinstance() nothing injected. annotation not magic. you have use requeststaticinjection() on static references annotated @inject . this explained in extreme detail in guice documentation.

c# - How to programmatically count the occurrence of regular expression as quickly as text editor -

i have written c# program opens particular directory. opens each file in directory , counts every occurrence of following regular expression @"^clm". program returns regular expression count each file , places count separate cell in spreadsheet. code using below: list<string> linespost = system.io.file.readalllines(dipostfiles + curpostfile).tolist(); int y = 0; (int = linespost.count - 1; >= 0; i--) { string pattern = @"^clm"; match m = regex.match(linespost[i], pattern); while (m.success) { y++; break; } (xlrange.cells[startrow + x, 3] excel.range).value2 = y; } this work, takes long time. if open given file in notepad++, example, , put in same regular expression hit count button, result quickly. is there more efficient way count instances of regular expression? anticipating 5,000 occurrence per text file. overall size of each text file 5 mb. any appreciated. first , foremos

c++ - Missing faces when displaying STL data -

Image
i wrote simple parser ascii stl format. when try render triangles supplied normals, resulting object missing many faces: this how should like: what tried: explicitly disabled backface culling (though shouldn't have been active before) ensured depth buffer enabled here minimal sample program reproduces error: #include <sdl2/sdl.h> #include <sdl2/sdl_main.h> #include <sdl2/sdl_render.h> #include <sdl2/sdl_opengl.h> int main(int argc, char **argv) { sdl_init(sdl_init_video); int screen_w=1280,screen_h=720; sdl_window * win = sdl_createwindow("test", 20, 20, screen_w, screen_h, sdl_window_opengl); sdl_glcontext glcontext = sdl_gl_createcontext(win); stlparser stlparser; std::ifstream file(".\\logo.stl"); stlparser.parseascii(file); const auto& ndata = stlparser.getndata(); const auto& vdata = stlparser.getvdata(); std::cout << "number of facets:

c# - TestStack White with a tray window -

i need interact application, that resides in tray . i'm currenty using teststack white way: processstartinfo processstartinfo = new processstartinfo("myprog.exe"); application application = application.attachorlaunch(processstartinfo); _window = application.getwindows()[0]; everything works if application not running before call, since launching it, visible. instead, if application running, , in tray, white not find window, , can see in console following log: could not find windows application ...and, after retries, fails exception. now, best solution found kill application , relaunch it: application.kill(); application = application.launch("myprog.exe"); and works. guess there better solution this. open application want automate , print running process names, find stands application. the add following code... application myapp; myapp = application.attach("processname"); hope helps...

java - Using class extending asynctask to check internet connection in android activity -

by checking questions on here have managed create below class in order check whether user has active internet connection. want use in android activities check connection before load data internet. ask if suitable way of checking user's internet connection , provide example of how called within activity (how pass context , how obtain true/false response in android activity. public class connectionstatus { private context context; public connectionstatus(context context){ this.context=context; } public static boolean isnetworkavailable(context c) { networkinfo netinfo = null; try { connectivitymanager cm = (connectivitymanager) c .getsystemservice(context.connectivity_service); netinfo = cm.getactivenetworkinfo(); } catch (securityexception e) { e.printstacktrace(); } return netinfo != null && netinfo.isconnectedorconnecting(); } public boolean checkconnection() { if (isnetworkavailable(context)) {