Flask Framework

All

Intro

I’m a Django guy, well, at least a bit. More python than Django, as some people say. But recently I started to play with Flask[1], quite simple and very appropriate for building small reliable api’s.

Flask

Several tutorials online can be found, the one I really like is this [2], Miguel Grinberg is quite didatict and explains the practical part very well.

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

Example

I did an small example with Flask and Google API connection and it’s on my git.

 

Tips

1. For releasing the API not in localhost, please change the last line:

app.run(debug) --> app.run(host='0.0.0.0')

2. Use POSTMAN to do the tests and export the tests as collections

3. You can use a AWS or Google Cloud/Azure for the tests. Google is pretty nice actually, AWS too.

4. Be patience cause it might happen a little delay on the deployment in the instances.

REFs

[1] http://flask.pocoo.org

[2] https://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask

[3] https://github.com/FranciscoMeloJr/Python-Tests

 

Debugging by Hypothesis

All

Intro

When bugs arrive there are many things that might have cause them, and actually we spend more time trying to find the bugs than coding [1].

If we would put in one sentence, debugging It is a two step process, first the location of the failure and then the fixing of the issue. The debugging process relies on developers questions but also relies on tools and approaches.

Modern debugging tools employ sophisticated mechanisms to help answering this question, however sometimes, actually most of the times, it is not enough just to use tools to find answers, it’s actually necessary to use several approach/more than one sometimes, to find the causes of issues.

1.Try and fail approach

For small development problems, the try and fail approach is effiencient and ok. However, to bigger problems we need to change the way to solve them actually.

2.Questions

1. Why? Chain of failure.
2. What? Related to entity level.
3. Whether? Set of events on the

3.Hypothesis thesis

The questions can be used combined with hypothesis testing, which is a quite interesting and reliable approach to solve problems on code that you know and code that you don’t know.

REFs

[1] How Did the Failure Come to Be? Mohammadreza Azadmanesh and Matthias Hauswirth. CoCos’17, October 23, 2017, Vancouver, Canada.

 

 

 

 

Turtle in Python

All

2Intro

I was playing a bit on python, as usual, and I came again with the Turtle built-in module. That’s an amazing module that remembers me the good days of Logo, Rip Seymont Paper.

Turtle

Such a cool module, it’s totally underrated. Well, at least on my side. Make sure to not name the module turtle, As I did, it won’t work obviously.

import turtle

silly = turtle.Turtle()

silly.forward(50)
silly.right(90)     # Rotate clockwise by 90 degrees

silly.forward(50)
silly.right(90)

silly.forward(50)
silly.right(90)

silly.forward(50)
silly.right(90)

turtle.done()

The references can be found here [1] and some codes I’ve done can be found here [2]. It’s very simple, pretty much like logo.

Simple things like square and circles are done with just one line.

REFs

[1] https://docs.python.org/2/library/turtle.html

[2]https://github.com/FranciscoMeloJr/Python-Tests

 

Python asserts

All

Intro

I was doing some python tests recently I came to use python asserts again, np_asserts, python asserts and unittest framework. All very very useful, but I think the original assert is so clever and easy to use, we should apply them in everyday life.

asserts

  I was comparing the name of a bank (string) with the calculated value of a function that returns it.
   assert get_from_id_name_bank(‘004’) == ‘TD’
  Similar to the example in [1]

np library

Np is also so straightforward, just need to do import numpy as np and it’s done! Put the comparison, and done!

Comparing arrays for example:

      np.testing.assert_array_equal(expected,banks)
    All the supported functions are here [2].

unittest

That’s a complete framework for testing and it’s very simple and has set_up, and tear_down. All in it.

    python -m unittest -v test_module

You can add some verbosity via v while doing the execution

Source

https://github.com/FranciscoMeloJr/Python-Tests/tree/master/

REFs

[1]https://code-maven.com/slides/python-programming/pytest-compare-strings

[2]https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.testing.html

[3] https://docs.python.org/3/library/unittest.html (for python 3)

 

 

Little python exercise

All

Intro

Recently I did an interview with the following problem:

You have a list of strings, on our list, some of the strings were corrupted on the reading process. You want to avoid duplications so do an algorithm to solve this.

List example: ttoo, toto, oott.

Example output: toto.

List example 2:  xt, tx.

Example output 2: xt.

Solutions

There are several ways to solve the problem and basically, you can understand it as a sort algorithm, a kind of special sort, but a sort. Therefore a bubble sort or insertion sort can be applied.

Solution 1

My second solution was to come back to a dict and try to use it to optimize the size comparison. However, since I’m using a dict (i.e. an encoding operation) I will need therefore an operation for translate it in a list (i.e. decoding operation).

Part A – encoding:

for each_word in words:
    key = len(each_word)
    if key not in result:
        result[key] = [each_word]
    else:
        list_values = result[key]
        list_values.append(each_word)
        result[key] = list_values

Part A2: I use an aux function to end correctly in the dict

def create_new_list(list_values):
    #['ot', 'to', 'tt']
    #['to', 'tt']
    sorted(list_values)

    list_new = [list_values[0]]
    flag = True
    for i in range(1, len(list_values)):
        flag = True
        for each in list_new:
            if set(list_values[i]) == set(each):
                flag = False
        if flag:
            list_new.append(list_values[i])
    return list_new

Solution 2

This was actually my first solution on the head, but second to be implemented. And its more or less based on the insertion sort algorithm and basically inserts an element on the final list if and only if the set of this element not there.  [I mean based on insertion because you will get the elements on the list and compare with the final list.] + the survival flag for each element.

However, you still need to do the size comparison to avoid tt in ttoo problems:

flag = True
for i in range(1, len(words)):
    flag = True
    for each in final:
        if len(words[i]) == len(each) and set(words[i]) == set(each):
            flag = False
    if flag:
        final.append(words[i])
return final

The solution can be improved by using the sorted using len option (i) + the comparison is first done on the length and then on the set, avoiding unnecessary comparisons.

(i) sorted(xs, key=len)

Solution 3

Solution 3 would use a dict comprehension on the first solution. But after thinking about it, it just too noisy and unclear for the reader.

(i) I’m creating the values of the Dict on the fly, so I don’t need an extra function to do it for me (encoding).

(ii) I just put a list comprehension in the end (for the decoder operation).

(i)for each_word in words:
    key = len(each_word)
    if key not in result:
        result[key] = [each_word]
    else:
        list_values = result[key]
        # 2:[cra] - car
        for each in list_values:
            if set(each) != set(each_word):
                list_values.append(each_word)
                result[key] = list_values
(ii) return [result.get(each_key)[0] for each_key in result.keys()]

 

Solution 4

It’s totally possible to do it in just one list comprehension, though it would be very long though, basically because one would need to condense the survival code within the list comprehension. I don’t think it worth though.

Source

All the solutions are there.

https://github.com/FranciscoMeloJr/Python-Tests/tree/master/banks

REFs

[1] https://www.datacamp.com/community/tutorials/python-dictionary-comprehension

 

Reward System Studies of Video-Game Playing / Neuroscience study

All

Intro

At SMU, back in Halifax, I studied Video-games and neuroscience doing a small EEG experiment in the end. The experiment was not conclusive therefore it was not published.

Content

The full content can be found here [1], which is a report for the class in Cognitive Neuroscience 1, from Prof Jason Ivanoff.

Abstract

This review covers several studies that have measured the influence of games through
the functional Magnetic Resonance Interference – fMRI – method as a key in the effort to
understand cognitive act of game play. The reward system is the key for the understanding of videogame play, so after explaining it several studies are summarized in details with the highlights and main concepts preserved for the understanding of the current relations with games. The activations areas vmPFC, dorsal striatum, dorsal parts of the ACC, rTP, striatum, midbrain (including VTA/SN) and ventral visual stream. Moreover, several of the deactivations areas during game play are discussed: OFC, caudate nucleus, putamen and nucleus accumbens, NAc that can be very important in a cognitive perspective. Also the lack of emphasis in the NAc which plays an key role in reward system and in the impulsivity and aggression is discussed. It will also discuss tendencies considering the limitations reveled.
Keywords: fMRI, Video-Game, FPS, Reward System

REFs

[1] https://drive.google.com/file/d/0B-ZRkXDVghb6QzYxZ21jQzBGaVk/view?usp=sharing

 

PyCharm

All

Intro

My training at the bachelor level was always to avoid external help and program basically with a paper and a pen, later passing it to the computer! Mainly to avoid a lot to use unnecessary tools to do things they don’t require, trying to learn and improve yourself in a language is NOT HELPED if your IDE continue to solving all your issue.

But for improving the speed and IN REAL LIFE some tools really help, and this is the case for PyCharm! totally. Or even Microsoft VS PVT! microsoft cof cof 

PyCharm

You can find PyCharm here [1] and the download straight from the link [2]. I remember in the previous versions, back some years, it was kind of basic, nowadays though, it’s very powerful with many tools and stuff, it’s like a VS for python developers.
Remember to download/install python first, since it doesn’t come with the IDE.

I’m currently using version 2018.1.4, which is quite simple and basically plug and play. Install and run in 5 minutes.

REFs

[1] https://www.jetbrains.com/pycharm

[2] https://www.jetbrains.com/pycharm/download/download-thanks.html?platform=windows&code=PCC