Monday, October 2, 2017

Ruby on Rails 5.1 & Vue.js 2.4.x – Testing with Karma, Jasmine – How to install?

Leave a Comment

I have Rails 5.1.x and Vue.js 2.4.x; I do not mix Rails and Vue.js in the frontend – only Vue.js is used

I added the following packages:

package.json

... "devDependencies": {     "jasmine": "^2.8.0",     "karma": "^1.7.1",     "karma-chrome-launcher": "^2.2.0",     "karma-jasmine": "^1.1.0",     "webpack-dev-server": "^2.6.1"   }, ... 

Q1: Where do I do the configuration? In webpack/test.js or some karma.conf.js file

Q2: What is in this conf file?

Q3: Do I need to install karma-webpack?


EDIT 1

I was able to install karma, jasmine and es6 support, BUT it's still not correctly integrated in the RoR ecosystem

/package.json

... "devDependencies": {     "jasmine": "^2.8.0",     "karma": "^1.7.1",     "karma-cli": "^1.0.1",     "karma-jasmine": "^1.1.0",     "karma-phantomjs-launcher": "^1.0.4",     "karma-webpack": "^2.0.4",     "standard": "^10.0.3",     "webpack-dev-server": "^2.6.1"   }, ... 

/karma.conf.js

module.exports = function(config) {   config.set({     basePath: 'app/javascript/',      browsers: ['PhantomJS'],      files: [       { pattern: 'test/*.spec.js', watched: false },       { pattern: 'test/**/*.spec.js', watched: false }     ],      frameworks: ['jasmine'],      preprocessors: {       'test/*.spec.js': ['webpack'],       'test/**/*.spec.js': ['webpack'],     },      webpack: {       module: {         loaders: [           { test: /\.js/, exclude: /node_modules/, loader: 'babel-loader' }         ]       },       watch: true     },      webpackServer: {       noInfo: true     }   }) } 

/app/javascript/test/my_test.spec.js

describe("A suite", () => {   it("contains spec with an expectation", () => {     expect(true).toBe(true)   }) }) 

$ karma start

25 09 2017 15:45:02.199:WARN [watcher]: All files matched by "/home/ubuntu/workspace/app/javascript/test/**/*.spec.js" were excluded or matched by prior matchers. 25 09 2017 15:45:02.217:WARN [watcher]: All files matched by "/home/ubuntu/workspace/app/javascript/test/**/*.spec.js" were excluded or matched by prior matchers. 25 09 2017 15:45:03.147:WARN [karma]: No captured browser, open http://0.0.0.0:8080/ 25 09 2017 15:45:03.156:WARN [karma]: Port 8080 in use 25 09 2017 15:45:03.156:WARN [karma]: Port 8081 in use 25 09 2017 15:45:03.157:INFO [karma]: Karma v1.7.1 server started at http://0.0.0.0:8082/ 25 09 2017 15:45:03.157:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency 25 09 2017 15:45:03.173:INFO [launcher]: Starting browser PhantomJS 25 09 2017 15:45:03.310:ERROR [phantomjs.launcher]: Fontconfig warning: ignoring C.UTF-8: not a valid language tag  25 09 2017 15:45:03.837:INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket 1lM4B1iRIygqSYz3AAAA with id 19034471 PhantomJS 2.1.1 (Linux 0.0.0): Executed 1 of 1 SUCCESS (0.043 secs / 0.001 secs) 

Q1: Where do I do the configuration? In webpack/test.js or some karma.conf.js file

A1: karma.conf.js is working, but I don't think my approach is best

Q2: What is in this conf file?

A2: Still not sure

Q3: Do I need to install karma-webpack?

A3: Yes, I think so


Q4: What do I have to change to do the following (in RoR 5.1.x)?

From: https://vuejs.org/v2/guide/unit-testing.html

/app/javascript/test/components/my_component.spec.js

// Import Vue and the component being tested import Vue from 'vue' import MyComponent from 'path/to/MyComponent.vue'  // Here are some Jasmine 2.0 tests, though you can // use any test runner / assertion library combo you prefer describe('MyComponent', () => {   // Inspect the raw component options   it('has a created hook', () => {     expect(typeof MyComponent.created).toBe('function')   })    // Evaluate the results of functions in   // the raw component options   it('sets the correct default data', () => {     expect(typeof MyComponent.data).toBe('function')     const defaultData = MyComponent.data()     expect(defaultData.message).toBe('hello!')   })    // Inspect the component instance on mount   it('correctly sets the message when created', () => {     const vm = new Vue(MyComponent).$mount()     expect(vm.message).toBe('bye!')   })    // Mount an instance and inspect the render output   it('renders the correct message', () => {     const Ctor = Vue.extend(MyComponent)     const vm = new Ctor().$mount()     expect(vm.$el.textContent).toBe('bye!')   }) }) 

1 Answers

Answers 1

I'd used a custom Webpack configurations in Karma earlier but that's just redundant Webpack and preprocessors logic I had. So I came up with this approach which seems correct to me.

I would recommend this: https://github.com/rails/webpacker/blob/master/docs/testing.md#karma-setup-for-typescript

P.S. I'm intentionally not copy-pasting the code snippets since the existing doc may change in future.

Read More

Can Spring be directed to take a parameter from either the body or the URL?

Leave a Comment

An argument to a Spring MVC method can be declared as RequestBody or RequestParam. Is there a way to say, "Take this value from either the body, if provided, or the URL parameter, if not"? That is, give the user flexibility to pass it either way which is convenient for them.

2 Answers

Answers 1

You can make both variables and check them both for null later on in your code like this :

@RequestMapping(value = GET_SOMETHING, params = {"page"}, method = RequestMethod.GET) public @ResponseBody JSONObject getPromoByBusinessId(         @PathVariable("businessId") String businessId, @RequestParam("page") int page,         @RequestParam("valid") Boolean valid,         @RequestParam("q") String promoName) throws Exception {} 

and then use a series if if-else to react to requests. I wrote it to work with any of the three params be null or empty, react to all different scenarios.

To make them optional, see : Spring Web MVC: Use same request mapping for request parameter and path variable

Answers 2

HttpServletRequest interface should help solve this problem

@RequestMapping(value="/getInfo",method=RequestMethod.POST) @ResponseBody public String getInfo(HttpServletRequest request) {     String name=request.getParameter("name");     return name;  } 

Now, based on request data coming from body or parameter the value will be picked up

C:\Users\sushil λ curl http://localhost:8080/getInfo?name=sushil-testing-parameter sushil-testing-parameter C:\Users\sushil λ curl -d "name=sushil-testing-requestbody" http://localhost:8080/getInfo sushil-testing-requestbody C:\Users\sushil λ 
Read More

Debugging CoffeeScript in VSCode goes to .js files

Leave a Comment

I am trying to debug a CoffeeScript file in vs code. It works and I can step through the compiled.js files. However, I can't step through the actual CoffeeScript files.

Here is my launch.json file:

{     "type": "node",     "request": "launch",     "name": "Launch Meeting",     "program": "${workspaceRoot}/lib/meeting/meeting-service.coffee",     "cwd": "${workspaceRoot}",     "env": {         "NODE_ENV": "local"     },     "sourceMaps": true } 

And in another window, I am running:

./node_modules/.bin/coffee -mc --watch lib/activity/note-activity-model.coffee \                                        lib/activity/note-activity-publisher.coffee \                                        lib/app-event-queue.coffee \                                        lib/meeting/meeting-api.coffee \                                        lib/meeting/meeting-service.coffee \                                        lib/meeting/meeting-socket-service.coffee \                                        lib/meeting/meeting-util.coffee 

When I set a breakpoint in the coffee file, the debugger halts on the compiled js file. I need it on the coffee file.

1 Answers

Answers 1

Did you try to use

"stopOnEntry": true, "smartStep": false 

as described in https://github.com/Microsoft/vscode/issues/5963 ?

Read More

Numpy dtype - data type not understood

Leave a Comment

I have a dataframe that I am looking at the data types associated with each column.

When I run:

In [23]: df.dtype.descr  Out [24]: [(u'date', '<i8'), (u'open', '<f8'), (u'high', '<f8'), (u'low', '<f8'), (u'close', '<f8'), (u'volume', '<f8'), (u'dividend', '<f8'), (u'adj_factor', '<f8'), (u'split_factor', '<f8'), (u'liq', '<f8'), (u'currency', '|O')] 

I want to set the currency dtype to S7. I am doing:

In [25]: dtype_new[-1] = (u'currency', "|S7") In [26]: print dtype_new Out [27]: [(u'date', '<i8'), (u'open', '<f8'), (u'high', '<f8'), (u'low', '<f8'), (u'close', '<f8'), (u'volume', '<f8'), (u'dividend', '<f8'), (u'adj_factor', '<f8'), (u'split_factor', '<f8'), (u'liq', '<f8'), (u'currency', '|S7')] 

It looks to be the correct format. So I try to put it back to my df:

In [28]: df = df.astype(np.dtype(dtype_new)) 

And I get the error:

TypeError('data type not understood',) 

What should I be changing? Thank you. This was working before I recently updated anaconda and I am not aware of the issue. Thanks.

ADJUSTMENT:

df.dtype is

In [23]: records.dtype Out[23]: dtype((numpy.record, [(u'date', '<i8'), (u'open', '<f8'), (u'high',     '<f8'), (u'low', '<f8'), (u'close', '<f8'), (u'volume', '<f8'), (u'dividend', '<f8'), (u'adj_factor', '<f8'), (u'split_factor', '<f8'), (u'liq', '<f8'), (u'currency', 'O')])) 

How can I change the '0' to a string less than 7 characters?

How can I change the last dtype from 'O' to something else? Specifically a string less than 7 characters.

LASTLY - is this a unicode issue? With Unicode:

In [38]: np.dtype([(u'date', '<i8')])      ...:      --------------------------------------------------------------------------- TypeError                                 Traceback (most recent call     last) <ipython-input-38-8702f0c7681f> in <module>() ----> 1 np.dtype([(u'date', '<i8')])  TypeError: data type not understood 

No Unicode:

In [39]: np.dtype([('date', '<i8')]) Out[39]: dtype([('date', '<i8')]) 

1 Answers

Answers 1

It seems you have centered the point about unicode and, actually, you seem to have touched on a sore point.

Let's start from the last numpy documentation.

The documentation dtypes states that:

[(field_name, field_dtype, field_shape), ...]

obj should be a list of fields where each field is described by a tuple of length 2 or 3. (Equivalent to the descr item in the __array_interface__ attribute.)

The first element, field_name, is the field name (if this is '' then a standard field name, 'f#', is assigned). The field name may also be a 2-tuple of strings where the first string is either a “title” (which may be any string or unicode string) or meta-data for the field which can be any object, and the second string is the “name” which must be a valid Python identifier. The second element, field_dtype, can be anything that can be interpreted as a data-type. The optional third element field_shape contains the shape if this field represents an array of the data-type in the second element. Note that a 3-tuple with a third argument equal to 1 is equivalent to a 2-tuple. This style does not accept align in the dtype constructor as it is assumed that all of the memory is accounted for by the array interface description.

So the doc doesn't seem to really specify whether the field name can be unicode, what we can be sure from the doc is that if we define a tuple as the field name, e.g. ((u'date', 'date'), '<i8'), then using unicode as the "title" (notice, still not for the name!), leads to no errors.
Otherwise, also in this case, if you define ((u'date', u'date'), '<i8') you will get an error.

Now, you can use unicode names in Py2 by using the encode("ascii")

(u'date'.encode("ascii"))   

and this should work.
One big point is that for Py2, Numpy does not allow to specify dtype with unicode field names as list of tuples, but allows it using dictionaries.

If I don't use unicode names in Py2, I can change the last field from |0 to |S7 or you have to use the encode("ascii") if you define the name as unicode string.


And the bugs involved...

To understand why it happens what you see, it is useful to have a look at the bugs/issues reported in Numpy and Pandas and the relative discussions.

Numpy
https://github.com/numpy/numpy/issues/2407
You can notice in the discussion (which I do not report here) mainly a couple of things:

  • the "issue" has been going on for a while
  • one trick people used was to use encode("ascii") on the unicode string
  • remember that the 'whatever' string has different defaults (bytes/unicode) in Py2/3
  • @hpaulj himself commented beautifully in that issue report that "If the dtype specification is of the list of tuples type, it checks whether each name is a string (as defined by py2 or 3) But if the dtype specification is a dictionary {'names':[ alist], 'formats':[alist]...}, the py2 case also allows unicode names"

Pandas
Also on the pandas side an issue has been reported which relates to the numpy issue: https://github.com/pandas-dev/pandas/pull/13462
It seems to have been fixed not that long ago.

Read More

Widgets lead to DeadObjectException - Transaction failed on small parcel

Leave a Comment

I'm getting following exception as soon as I want to show a widget and start listening:

// the relevant stack trace, the rest is comming from my code  // before the code line I posted below java.lang.RuntimeException: system server dead?     at android.appwidget.AppWidgetHost.startListening(AppWidgetHost.java:189)     at com.my.app.utils.WidgetUtil.a(SourceFile:231)     ...     android.os.DeadObjectException: Transaction failed on small parcel; remote process probably died     at android.os.BinderProxy.transactNative(Native Method)     at android.os.BinderProxy.transact(Binder.java:503)     at com.android.internal.appwidget.IAppWidgetService$Stub$Proxy.startListening(IAppWidgetService.java:481)     at android.appwidget.AppWidgetHost.startListening(AppWidgetHost.java:185)     at com.my.app.utils.WidgetUtil.a(SourceFile:231)     ... 

The source in my code is following code line:

 mAppWidgetManager = AppWidgetManager.getInstance(context);  mAppWidgetHost = new AppWidgetHost(context, R.string.app_name);  mAppWidgetHost.startListening(); // <= this line leads to the crash 

Observations

  • my app is working normally on a lot of phones (all but one actually)
  • above crash only happens on one users device (SM-N910C (Samsung Note 4), Android 6.0.1)
  • the user says, those widgets work fine in his launcher

Does anyone has an idea what could cause this? Is this something I can solve in my app? The user says widgets are working fine in his launcher...

2 Answers

Answers 1

DeadObjectException : 

The object you are calling has died, because its hosting process no longer exists.

Possible Solutions:

1) Override your service's onDestroy() method and watch what event flow leads to it. If you catch DeadObjectException without going through this method, your service should have been killed by the OS.

2) by removing Typeface , this might be because of ttf which i was using from assets folder Please try comment the typeface and test it hope it will work for sure

3) put all your code inside the onCreate. From there you will see what is the culprit like a NullPointerException for example but your code will run smoothly already.

Answers 2

So, a simple Google search led me to this definition of a DeadObjectException :-

The object you are calling has died, because its hosting process no longer exists.

From this, it is obvious that you're getting this error because the process that's hosting mAppWidgetHost has been killed off.

The question now is that why are you getting this error. Overriding and logging onDestroy() to monitor it could be useful, and definitely is worth a shot. But, since its working on all devices except for one, its more than likely that there's nothing wrong with the onDestroy() method. Instead, the OS is killing the process off before you can access the object.

So, now why is the OS doing that? This question had me balled up for the longest time. I still do not have a clear answer or solution to this despite a bevy of Google searches with all kinds of related to the problem. But, after spending a considerable amount of time searching, I noticed a peculiarity - most of the issues with this exception, such as this, this and yours happen with Samsung devices.

My guess is that Samsung's underlying architecture leads to this problem. And, while I do not have a reason why this happens or a plausible solution even after a lot more searching, this could still be a start to find a work around targeting Samsung devices.

UPDATE

I searched a bit more and came across this answer. Take a look at the last comment by the question author on the question :-

Finally it is working fine just by a line of code in manifest file, here it is android:hardwareAccelerated="false" If anybody get the following kind of errors please try by adding the above line signal 11 (SIGSEGV), code 1 (SEGV_MAPERR)

I don't know the logic behind this or if it would work or not. Just sharing it with the hope that it could help you - even in the minutest form.

Read More

Angular sending access token to Asp.net Web API not working if the email address has a '+' in it

Leave a Comment

I have security working fine in an application, except when a user tries to login with a '+' in their email.

The access token looks fine (when the email contains a + it looks like this):

Bearer 8BGpt_KkEp-_6U5tUdKqK1xLCQBaWzHcxDT9RRKkbzoF2fHCUNhRL3U-fpLdQIuSXm8RcTOH4ZY3a0UZH6-6IgXxx_ojgyL26179JovRm5xQSZD7ANxLvvdU3ubfcpzSr4tw-sza37UaJh7xDFB8eH0NA9Djt7Ik8Ebxdin7u-n76InCulRAV6xMWgXfF9bwoU8MsV3lrh_zhnxYGnx3O7QUNQ740NUJLHJYH12rBth16CA1AXSF86rA5rUB7vJ7yK09k_FJTifyuldTeFHJHsyscnEIQxGozbf3x1cmZowkiK4Q1r8W0M8uz25m8j_tuMrWawTqYJNZiTuI9afW38WWQ4BRLkQF7TwoMOgZQ-f1K_3W8Zy3x-OsKdQS4i9CapvKe1utCscZVroByvyD9SvpILGiZGTjGD_zCAm8KerMPT5GNOb07kPGV_167PHEXm0TGaJbCelb5gLgXbMXv3GxBQLnYIfPUXCBaKx4UFkY8kFMPs9MxFcGY81p67rfnjeswBZ3PW6fDFTf9U_I8g 

However, when I try to send a secure request with this access token, I get the response:

status: 401 "{"Message":"Authorization has been denied for this request."}" 

As said above, it works without any issue if I remove the plus. This seems to be a Wep API issue rather than an Angular issue.

I found that the methods encodeUrl and decodeUrl to not stop the space from being change to a plus. I have tried the following in the c# code to switch the space to a plus:

var registerEmail = model.email.Replace(' ', '+'); 

This is used in both the login and register actions.

Perhaps it is not possible to use a + in an email in OAuth in Web API 2?

1 Answers

Answers 1

It seems to be a bug in asp.net roles. I am not sure of a clear solution. However, for the time being, encoding the username as follows before storing it on register and when logging in:

public static class UsernameEncodingService {     public static string returnEncodedUsername(string email)     {         var emailAsLower = email.ToLowerInvariant();         var encodedEmail = Base64Encode(emailAsLower);         var encodedEmailWithoutEquals = encodedEmail.Replace("=", "213");         var encodedEmailWithoutPlus = encodedEmailWithoutEquals.Replace("+", "214");         return encodedEmailWithoutEquals;     }      private static string Base64Encode(string plainText)     {         var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);         return System.Convert.ToBase64String(plainTextBytes);     } } 
Read More

Sunday, October 1, 2017

How to set individual line widths in network-style Plotly figure (Python 3.6 | plot.ly)?

Leave a Comment

I'm working on a plot.ly wrapper for my networkx plots adapted from https://plot.ly/python/network-graphs/. I can't figure out how to change the width for each connection based on the weights. The weights are in the attr_dict as weight. I tried setting go.Line objects but it wasn't working :(. Any suggestions? (and links to tutorials if possible :) ). Attaching an example of the network structure from a plot I made in matplotlib.

How can I set individual line widths for each connection in plotly?

enter image description here

import requests from ast import literal_eval import plotly.offline as py from plotly import graph_objs as go py.init_notebook_mode(connected=True)  # Import Data pos = literal_eval(requests.get("https://pastebin.com/raw/P5gv0FXw").text) df_plot = pd.DataFrame(pos).T df_plot.columns = list("xy") edgelist = literal_eval(requests.get("https://pastebin.com/raw/2a8ErW7t").text) _fig_kws={"figsize":(10,10)}  # Plotting Function def plot_networkx_plotly(df_plot, pos, edgelist, _fig_kws):     # Nodes     node_trace = go.Scattergl(                          x=df_plot["x"],                          y=df_plot["y"],                          mode="markers",     )     # Edges     edge_trace = go.Scattergl(                          x=[],                           y=[],                          line=[],                          mode="lines"     )      for node_A, node_B, attr_dict in edgelist:         xA, yA = pos[node_A]         xB, yB = pos[node_B]         edge_trace["x"] += [xA, xB, None]         edge_trace["y"] += [yA, yB, None]         edge_trace["lines"].append(go.Line(width=attr_dict["weight"],color='#888'))      # Data     data = [node_trace, edge_trace]     layout = {                 "width":_fig_kws["figsize"][0]*100,                 "height":_fig_kws["figsize"][1]*100,      }     fig = dict(data=data, layout=layout)      py.iplot(fig)     return fig plot_networkx_plotly(df_plot, pos, edgelist, _fig_kws)  # --------------------------------------------------------------------------- # PlotlyDictValueError                      Traceback (most recent call last) # <ipython-input-72-4a5d0e26a71d> in <module>() #      46     py.iplot(fig) #      47     return fig # ---> 48 plot_networkx_plotly(df_plot, pos, edgelist, _fig_kws)  # <ipython-input-72-4a5d0e26a71d> in plot_networkx_plotly(df_plot, pos, edgelist, _fig_kws) #      25                          y=[], #      26                          line=[], # ---> 27                          mode="lines" #      28     ) #      29   # ~/anaconda/lib/python3.6/site-packages/plotly/graph_objs/graph_objs.py in __init__(self, *args, **kwargs) #     375         d = {key: val for key, val in dict(*args, **kwargs).items()} #     376         for key, val in d.items(): # --> 377             self.__setitem__(key, val, _raise=_raise) #     378  #     379     def __dir__(self):  # ~/anaconda/lib/python3.6/site-packages/plotly/graph_objs/graph_objs.py in __setitem__(self, key, value, _raise) #     430  #     431         if self._get_attribute_role(key) == 'object': # --> 432             value = self._value_to_graph_object(key, value, _raise=_raise) #     433             if not isinstance(value, (PlotlyDict, PlotlyList)): #     434                 return  # ~/anaconda/lib/python3.6/site-packages/plotly/graph_objs/graph_objs.py in _value_to_graph_object(self, key, value, _raise) #     535             if _raise: #     536                 path = self._get_path() + (key, ) # --> 537                 raise exceptions.PlotlyDictValueError(self, path) #     538             else: #     539                 return  # PlotlyDictValueError: 'line' has invalid value inside 'scattergl'  # Path To Error: ['line']  # Current path: [] # Current parent object_names: []  # With the current parents, 'line' can be used as follows:  # Under ('figure', 'data', 'scattergl'):  #     role: object 

Update with Ian Kent's Answer:

I don't think the code below can change the weights for all of the lines. I tried making all of the widths 0.1 with the weights list and got the following plot: enter image description here

but then when I did width=0.1 it worked for all of the lines: enter image description here

1 Answers

Answers 1

I think the issue is in the following line of your code:

edge_trace["lines"].append(go.Line(width=attr_dict["weight"],color='#888')) 

Try it with "line" instead of "lines". This is a bit of a confusing aspect of the Plotly API, but in scatter plots, the mode is plural and the argument name to change attributes of the trace is singular. So,

trace = go.Scatter(mode = 'markers', marker = dict(...)) trace = go.Scatter(mode = 'lines', line = dict(...)) 

Edit: Okay so there turned out to be more issues than just the "lines" now that I've sat down with it:

You have the line argument as a list of dict-like objects, whereas plotly expects it to be a single dict-like. Building a list of weights then adding all the weights to the line attribute at once seems to work:

edge_trace = go.Scattergl(                      x=[],                      y=[],                      mode="lines" )  weights = [] for node_A, node_B, attr_dict in edgelist:     xA, yA = pos[node_A]     xB, yB = pos[node_B]     edge_trace["x"] += [xA, xB, None]     edge_trace["y"] += [yA, yB, None]     weights.append(attr_dict["weight"])  edge_trace['line'] = dict(width=weights,color='#888') 

Also, you are plotting the lines in front of the nodes and thus obstructing them. You should change

data = [node_trace, edge_trace] 

to

data = [edge_trace, node_trace] 

to avoid this.

Read More