Posts

Showing posts from August, 2010

go - Init function breaking unit tests -

in package want test, have init function loads configuration file containing stuff want use run application. however, don't want trigger init function while running unit tests. is there way skipping or preventing init function called during unit tests? some snippets illustrate question: func init() { var err error // necessary prevent config variable shadowing config, err = loadconfig("./client/config.yml") if err != nil { log.fatal(err) } } func loadconfig(filepath string) (*config, error) { viper.setconfigfile(filepath) if err := viper.readinconfig(); err != nil { return nil, fmt.errorf("error loading config file: %s", err) } (...) } // new returns config value(!) func new() config { return *config } a test case: func testnew(t *testing.t) { expected := &config{} observed := new() if !reflect.deepequal(observed, expected) { t.errorf("observed %+v. expecting %+v\n&quo

selenium webdriver - Error when executing testng.xml using pagefactory -

i running 2 classes using testng.first class running second class failing error: "org.testng.testngexception:can't invoke public void testscripts.newaccountcreation.accountcreation1(): either make static or add no-args constructor class" if add non argument constructor getting null pointer exception. i using pagefactory design test cases. eclipse version:kepler testng:6.9.9 chrome version: 57.0.2987.133 chrome driver: 2.27 any suggestions appreciated. please find below code: page factory code login page: /** * */ package pages; import org.openqa.selenium.webdriver; import org.openqa.selenium.webelement; import org.openqa.selenium.support.findby; import pages.loginpage; public class loginpage { webdriver driver; public loginpage(webdriver ldriver) { this.driver = ldriver; } @findby(xpath = "//input[contains(@id,'username-inputel')]") public webelement username; @findby(xpath = &

node.js - Request sent is taking too long. why would that be? -

Image
"request sent" taking 3+ seconds. client code: jq.ajax({ url: '/test', type: 'post', contenttype: 'application/json', data: jsondata, success: function(response) { console.log('done'); } }); server code: app.post('/test', function(req, res){ res.send(req.body) }); datalength 865853 ( seen headers ) server running nginx behind nodejs server running. want understand why happening , ways reduce it. its post request. adding headers image: request sent taking long. why be? it anything. want understand why happening , ways reduce it. there may lots of reasons. without seeing single line of code it's impossible tell what's wrong it. may using blocking functions, may calling external services, may work in main process, may blocking event loop, may forget handle errors, may doing number of things wrong in application , may have misconfigured reverse proxy, may using wrong ports,

Testing Recurring payment in paypal sandbox -

i have integrated paypal sandbox how can use paypal recurring payment procedure. parameter required recurring , how can use web hook recurring.if suggest me how use paypal sandbox recurring , provide best solution. which type of recurring being used? if implementing recurring using nvp/soap api, kindly refer below. kindly note webhook not compatible nvp/soap api a. using express checkout - https://developer.paypal.com/docs/classic/api/merchant/createrecurringpaymentsprofile_api_operation_nvp/ b. using paypal buttons- https://developer.paypal.com/docs/classic/api/button-manager/bmcreatebutton_api_operation_nvp/ for notifications, can use ipn notifications every time payment made https://developer.paypal.com/docs/classic/ipn/integration-guide/ipnintro/ if implementing using rest api, webhook used receiving notifications. refer links below a. https://developer.paypal.com/docs/api/payments.billing-agreements b. https://developer.paypal.com/docs/api/webhooks/

LUA replace instances of string -

i have string x = "a b c d e f g e b" , trying replace every instance of x b x character letter z let's say, above should x = z c d e f g z . have looked in examples mention specific characters replacement string.gsub , how can above done? you may use string.gsub(x, "%a b", "z") where %a matches letter. see more on lua pattern here . lua demo : x = [[a b c d e f g e b]] res, _ = string.gsub(x, "%a b", "z") print(res) -- z c d e f g z

xml - Android:Background in styles lets elements disappear -

i changed android:background in style: <style name="theme.app.base" parent="theme.appcompat.light.darkactionbar"> <item name="colorcontrolnormal">#747474</item> <item name="colorcontrolactivated">@color/coloraccenttrans</item> <item name="colorcontrolhighlight">@color/coloraccenttrans</item> <item name="colorprimary">@color/colorprimary</item> <item name="colorprimarydark">@color/colorprimarydark</item> <item name="coloraccent">@color/coloraccent</item> <item name="android:background">@color/background</item> </style> and elements material calendar view seemed have lot visibility , can't figure out why. here xml of fragment layout: <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.andr

ios - UIViewController view's frame changes after present(viewController: animated: completion: ) -

i have uiviewcontroller set size in viewdidload that: //setting view's frame let width = uiscreen.main.bounds.size.width - 10 let height = (43 * uiscreen.main.bounds.height) / 100 //%43 of screen self.view.frame = cgrect(x: 5, y: 80, width: width, height: height) it works great until try present viewcontroller that: //presenting autocompletevc self.autocompletevc = gmsautocompleteviewcontroller() self.autocompletevc.delegate = self self.present(self.autocompletevc, animated: true, completion: nil) after dismiss view ( self.autocompletevc.dismiss(animated: true, completion: nil) ) frame of first viewcontroller 's view changes full screen's frame. any idea how fix it? thanks! set frame in viewwillappear if doesn't work in viewwilllayoutsubviews this: public override func viewwilllayoutsubviews() { super.viewwilllayoutsubviews() //setting view's frame let width = uiscreen.main.bounds.size.width - 10 let height = (43 * uiscr

django - Constraints when writing Python class -

i`m using python 3.5.2 , django 1.11 using sqlite i faced situation want name model class name, different names different results in manage.py migration regarding foreignkeys example shell: modules.py from django.db import models class place(models.model): question_text = models.charfield(max_length=200) class choice(models.model): question = models.foreignkey(place, on_delete=models.cascade) running python3 manage.py makemigrations post migrations 'post': post/migrations/0001_initial.py - create model choice - create model place - add field question choice' when renaming class choice in example "rating": from django.db import models class place(models.model): question_text = models.charfield(max_length=200) class rating(models.model): question = models.foreignkey(place, on_delete=models.cascade) output of migration attempt: migrations 'post': post/migrations/0001_initial.py - create

YouTube Live Streaming and Timezone Information (GMT) in Creator Studio -

we making live broadcasting software youtube. following livestream api guide, broadcast our live event. one issue encountered, however, never correct gmt information event. example, though on live from south korea, gmt+9, according creator studio's page, live events broadcasted gmt-7. currently we’re using following api: snippet.scheduledstarttime https://developers.google.com/youtube/v3/live/docs/livebroadcasts the usage snippet.scheduledstarttime(1997-07-16t19:20:30.45+01:00) guided in http://www.w3.org/tr/note-datetime is there issue google's api timezone setting? thanks.

Excel, maximum value based on date range -

i have excel spreadsheet 2 columns, first dates , second values. dates span on several years. want write function retrieves maximum value each year. for example, in following data set: june 3, 2009 3 june 5, 2009 5 january 1, 2010 7 july 7, 2010 1 april 1, 2013 12 may 2, 2013 77 the function year 2009 return value 3 function year 2010 return value 7 function year 2013 return value 77 all of dates in column of values in column e in column j have list of years needed, i.e. j1 = 2009, j2 = 2010, j3 = 2011, etc. the function each year located in column k corresponding year in column j, i.e. maximum value 2009 in cell k1, maximum value 2010 in cell k2, etc. i believe function should like: =max(some type of function gives me range of dates per year) thanks help you can use: =max(if(year($a$2:$a$9)=j1,$e$2:$e$9,0)) array formula press ctrl + shift + enter @ same time can drag it $a$2:$a$9 column of date $ absolute references change last row

how to hide selected item from spinner list in android -

i want hide selected item list of spinner questions hide selected item custom spinner list didn't answer. want question in link code is.... toolbar.xml <android.support.v7.widget.toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?attr/colorprimarydark" android:minheight="?attr/actionbarsize" app:popuptheme="@style/themeoverlay.appcompat.light" > <spinner android:id="@+id/spinner_nav" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </android.support.v7.widget.

css3 - Bootstrap 4 unable to pull col to right -

i using bootstrap v4.0.0-alpha.6 i have 3 columns displayed in 1 row, need swap first column last column while in md not while in sm/xs. i want view in desktop mode: [c][b][a] and in mobile view: [a] [b] [c] i tried this: <div class="row pt-2"> <div class="col-12 col-md-4 float-md-right"> <img src="assets/img/3-delivery.jpg"> </div> <div class="col-12 col-md-4"> <img src="assets/img/arrow.png"> </div> <div class="col-12 col-md-4 float-md-left"> <img src="assets/img/4-served.jpg"> </div> </div> it doesn't work @ all. use push pull classes.. http://www.codeply.com/go/dhurlsa6u4 <div class="row pt-2"> <div class="col-12 col-md-4 push-md-8"> </div> <div class="col-12 col-md-4">

scope - When is a copy constructor called in C++? - Function return -

i'm working through chapter 18 of stroustrup's principles , practice , stuck on 1 part related copy constructors. i have copy constructor defined as: x(const x& x) { out("x(x&)"); val = x.val; } x struct. val int value of x. 'out' is: void out(const string& s) { cerr << << "->" << s << ": " << val << "\n"; } i have following 2 functions defined: x copy(x a) { return a; } and x copy2(x a) { x aa = a; return aa; } in main have: x loc(4); x loc2 = loc; loc2 = copy(loc); loc2 = copy2(loc); when call copy, copy constructor called twice: once copy's parameter scope , once return call. makes sense me. however, when call copy2, copy constructor still called twice: once function argument , once 'x aa = a.' why isn't called return? there's no guarantee copy constructors called in c++. in case of return, it'

c++ - Better way to determine which shell is being used at runtime (Windows)? -

i have function clears terminal screen. it's supposed work on windows , *nix based os. if function detects caller's os windows, check see if caller using cmd.exe or else ( git-bash or cygwin ). is there better way this? don't fact need rely on home variable. compiler: g++ #include <cstdlib> void clearscreen() { #ifdef _win32 if (std::getenv("home")) // git-bash & cygwin home var called home std::system("clear"); // cmd's home var called homepath else std::system("cls"); #else // assume posix std::system("clear"); #endif } note : function has been tested in cmd.exe , git-bash , , wsl . has not been tested in cygwin .

android - Service is running in multiple instance -

i have created background service work if application killed. in service getting data sensor. seems service returning sensors value multiple times in second resulting of application getting hanged. here service: public class stepcounterservice extends service { private static final string log_tag = "foregroundservice"; public static boolean flag = false; private sensormanager msensormanager; private stepdetector detector; private powermanager mpowermanager; private wakelock mwakelock; @override public ibinder onbind(intent intent) { // todo auto-generated method stub return null; } @override public int onstartcommand(intent intent, int flags, int startid) { /* msensormanager = (sensormanager) this.getsystemservice(sensor_service); msensormanager.registerlistener(detector, msensormanager.getdefaultsensor(sensor.type_accelerometer), sensormanager.sensor_delay

Convert array of arrays into multidimensional array in Typescript -

i'm trying convert array of arrays requested http service. have following code below: this array http service have number of arrays: [object array] > [0] > make: "toshiba", model: "h2000" ..[n] this needs converted multidimensional array this: [{make:"toshiba"},{model:"h2000"}, {make:"hp"},{model:""}]; i have looked loop having no luck: create method converts object array function objtoarray(obj) { return object.keys(obj).reduce(function(arr, key) { arr.push({ [key] : obj[key] }); return arr; }, []); } and run array through it: var formattedarray = arr.map(x => objtoarray(x)); demo: https://jsfiddle.net/41d3p6zx/

python 3.x - In a while loop changeing "<" to "<= " in the same code draws a different turtle graphic -

question using while loops. i notice if use "<" condition in while loop draw different picture if use "<=" condition same code. below see 2 different code sets , associated pictures render reference. any or feed appreciated! for given code use while loop start draw circle squares: import turtle def draw_square(some_turtle): count =0 while count <4 : some_turtle.forward(100) some_turtle.right(90) count += 1 def draw_circle(): win = turtle.screen() win.bgcolor("red") nic = turtle.turtle() nic.shape("turtle") nic.color("blue") nic.speed(2) count = 0 while count <4: draw_square(nic) nic.right(10) count += 1 win.exitonclick() draw_circle() draw_square("1") it renders following image: turtle drawing i change < <= such: import turtle def draw_square(some_turtle): count =0 while count <=4 : some_turtle.forward(100) s

amazon web services - delphi: TAmazonConnectionInfo.RequestProxy* with username and password -

tamazonconnectioninfo has requestproxy* settings use amazon web services (aws) through proxy. however tamazonconnectioninfo allow set: .requestproxyhost .requestproxyport but don't allow set: .requestproxyusername .requestproxypassword there practical issue? or emarcadero has forgotten implement these properties? i use delphi berlin update 2

java - Make GSON accept single objects where it expects arrays -

i have bunch of model classes have fields of type list<x> x 1 of many things (e.g. string , integer , of own types). i'm using gson parse json represenations of these models. problem server i'm deal (which beyond control) somehow removed singleton arrays , replaces them contained object. example, instead of returning: { "foo": [ "bar"], "bleh": [ { "some": "object" } ] } it returns: { "foo": "bar", "bleh": { "some": "object" } } now assume java model class this: public class model { private list<string> foo; private list<someobject> bleh; } currently causes gson throw exception because finds begin_string or begin_object expects begin_array . for arrays or lists of strings solved using typeadapter<list<string>> . problem have list s many different element types , don't want write separate typeadapter each case.

android - How to intent From Catch Block if exception is occurs -

Image
i trying intent catch block if exception occurs.it not intent. when have enter wrong ip gives "malformedurlexception" purpose need change ip address activity please me. the log file: the code: protected class asynclogin extends asynctask<string, jsonobject, boolean> { string username = null; @override protected boolean doinbackground(string... params) { restapi api = new restapi(); boolean userauth = false; try { // call user authentication method in api jsonobject jsonobj = api.userauthentications(params[0], params[1]); jsonparser parser = new jsonparser(); userauth = parser.parseuserauth(jsonobj); username = params[0]; //parse json object boolean } catch (exception e) { // todo auto-generated catch block intent openstartingpoint

android - Cannot resolve method for SparseArray<TextBlock> -

this piece of script has recognize text camera through textrecognizer , search word inside text. if word present, system has save in string found word after. the problem have 2 errors: cannot resolve method 'contains(java.lang.string)' cannot resolve method 'getvalue(int)' how can solve errors? haven't found similar method sparsearray<textblock> . public void receivedetections(detector.detections<textblock> detections) { string search = "palabra"; final sparsearray<textblock> items = detections.getdetecteditems(); //is detection of textrecognizer of camera (int i=0; i<items.size(); ++i) { if(items.get(i).contains(search)) { string found = items.getvalue(i+1); log.i("current lines ", found); } } } you can find sparsearray documentation here . as can see, there no getvalue() method on sparsearray, calling getvalue(int) on sparsearray items variable not valid

c++ - Algorithm to draw a sphere using quadrilaterals -

i attempting draw sphere scratch using opengl. function must defined void drawsphere(float radius, int nsegments, int nslices) , must centred @ (0, 0, 0) origin , must created using gl_quads . firstly, "slices" sort of tapered cylinder shapes stacked on top of each other create sphere, , "segments" quads generated in circle generate wall/side of each of these tapered cylinder slices? secondly, cannot seem find algorithms or examples of how make calculations generate sphere using quadrilaterals - example seem generated triangles instead. edit here have tried, in right direction, coordinate calculations off somewhere: void drawsphere(float radius, int nsegments, int nslices) { /* * todo * draw sphere centered @ origin using gl_quads * compute , set normal vectors each vertex ensure proper shading * set texture coordinates */ (float slice = 0.0; slice < nslices; slice += 1.0) { float lat0 = m_pi * (((slice - 1) / nslices) -

swift - Porous Boundary -

i set boundary game seems working alright until forced, in make character run towards several seconds, , character go straight through. explanations , how can fix it? edit: here code boundary func createscenecontents() { self.backgroundcolor = .black self.physicsbody = skphysicsbody(edgeloopfrom: self.frame) } createscenecontents() ship.physicsbody = skphysicsbody(rectangleof: ship.size) ship.physicsbody?.affectedbygravity = false ship.physicsbody?.isdynamic = true ship.name = "ship" ship.physicsbody?.categorybitmask = physicscategory.ship ship.physicsbody?.collisionbitmask = physicscategory.ship try setting precise collision detection ship : ship.physicsbody?.usesprecisecollisiondetection = true you might consider adding physics category boundary.

Difference between declaring methods in php 5.3 and 5.6 -

i working on codebase runs on live environment php version 5.3.29. i've tried moving on test environment uses php version 5.6.28. i noticed loadconfig method doesn't invoked if declare private keyword. is breaking change between version 5.3 , 5.6 methods need declared with, private, public, protected etc? this partial example class: class baseconfig { var $dao = null; var $appconfig = array(); var $frameworkbootstrap = null; var $reserved = array(cmd_param, 'go', 'submit', 'xsubmit'); function baseconfig() { register_shutdown_function(array(&$this, '_doshutdown')); $this->frameworkbootstrap = parse_ini_file(dirname(__file__) . '/' . framework_bootstrap_config); $this->loadconfig(); } function loadconfig() { require_once(dirname(__file__) . '/configdao.class.php'); $dao = new configdao(); $this->appconfig = $dao->getall

sql - How do I ensure integrity between unrelated tables? -

i started learning database design, , i'm working oracle 11g , sql developer. i have these 3 business rules db: each officer must enroll in 1 , 1 insurance companies. each insurance company may enroll 1 or more officers each insurance company must provide @ least 5 different types of insurance types. each type of insurance may provided 4 insurance companies or none @ all each insurance type may subscribed 1 or more officers. each officer may subscribe 5 different insurance covers provided same company. . . . so far, good, came 5 tables ( ins_coy, offr, ins_type, provide, , subscribe ). provide , subscribe came composite tables since relationships between ins_coy , ins_type, , offr , ins_type both m:m relationships. pk , fk attributes each of table below: ins_coy table coy_id - pk offr table offr_id - pk coy_id - (fk referencing ins_coy.coy_id)) ins_type table type_id - pk provide coy_id , type_id - (composite pk) coy_id - (fk referencing coy.

r - Calculating SD of compass directions using Circular -

my goal calculate mean , standard deviation series of compass degrees. since may cross 360/ 0 mark, can't use standard mean or sd calculation. i've been using circular packing in r, seems give me correct means (though negative values used when crossing 360 mark opposed positive). sd values way small. thoughts on might wrong, or better way calculate mean , sd compass directions? the below code attempt test calculations of mean , sd on various compass directions, , compare standard mean , sd calculation (they should agree unless cross 360/ 0 mark) library(circular) tester<-c(20,40,60) tester<-c(340,360,20) tester<-c(340,0,20) tester<-c(300,320,340) tester<-c(160,180,200) tocirc<- circular(tester, type="angles", units="degrees",rotation="clock") mean(tocirc) sd(tocirc) mean(tester) sd(tester) when load circular , has separate sd function calculates standard deviation circular data differently. #data tester<

spring mvc - Failed to convert property value of type 'com.siri.espc.dao.Point' to required type 'java.awt.Point' for property 'pointA'; -

apr 14, 2017 7:42:19 pm org.springframework.context.support.classpathxmlapplicationcontext preparerefresh info: refreshing org.springframework.context.support.classpathxmlapplicationcontext@3d71d552: startup date [fri apr 14 19:42:19 ist 2017]; root of context hierarchy apr 14, 2017 7:42:19 pm org.springframework.beans.factory.xml.xmlbeandefinitionreader loadbeandefinitions info: loading xml bean definitions class path resource [spring.xml] apr 14, 2017 7:42:19 pm org.springframework.context.support.classpathxmlapplicationcontext refresh warning: exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.beancreationexception: error creating bean name 'triangle' defined in class path resource [spring.xml]: initialization of bean failed; nested exception org.springframework.beans.conversionnotsupportedexception: failed convert property value of type 'com.siri.espc.dao.point' required type 'java.awt.point

java - Eclipse changes my font size back to 10 after I changed it to 12 -

i use preference dialog change editor text 12. when quit eclipse , restart it, text drawn @ size 12, after second or two, gets drawn @ size 10 , have change again. there way change text size stays @ size? one way goto windows-> preference -> general -> color , fonts and other cltr , = increase font size cltr , - decrease font size.

angularjs - Using Angular ng-attr for the disabled attribute -

i trying use ng-attr conditionally add attribute element. code this: <label for="theid" ng-attr-disabled="{{true || undefined}}" class="control-label"> label </label> what inspecting element this: <label translate="" for="theid" ng-attr-disabled="{{true || undefined}}" class="control-label ng-scope" disabled="disabled"> label </label> but expectation is: <label translate="" for="theid" ng-attr-disabled="{{true || undefined}}" class="control-label ng-scope" disabled> label </label> am wrong altogether how works? thanks i don't think should care it, in case. when value falsy, disabled not present. when value truthy, present - , it's presence in html attributes (like required on inputs, validation care presence required="false"