Skip to content

Instantly share code, notes, and snippets.

@elena-roff
elena-roff / test_proxy.py
Created March 12, 2019 13:12
Test examples to test API
import requests
from custom_module import api_get_data
uri = 'http://<.....>'
def fail(*args, **kwargs):
raise requests.exceptions.RequestException()
@elena-roff
elena-roff / api_get_data.py
Created March 12, 2019 13:21
Get data from the api with an offset update and limit extended
def api_get_data() -> List[Mapping]:
""" Gets data from the API. """
url = "{}/v1/booking".format(os.environ['CT_BOOKING_API_URI'])
params: Dict = {
...
'limit': 1000,
'offset': 0,
}
@elena-roff
elena-roff / get_obj_key.py
Created March 12, 2019 13:24
Creates a hash for an object
import hashlib
def get_obj_key(obj: Type) -> str:
""" Creates and returns a unique object id."""
obj_key = '+'.join(
[
obj.attr1, str(obj.num_attr1), obj.attr2, ...
])
return hashlib.md5(obj_key.encode('utf8')).hexdigest()
@elena-roff
elena-roff / test_examples_pytest.py
Created March 12, 2019 13:33
Pytest unit test examples
def test_format_to_dict():
""" Tests formatting to a dictionary. """
data_to_transform = defaultdict(lambda: defaultdict(lambda: {}))
assert isinstance(format_to_dict(data_to_transform), dict)
def test_valid():
valid_data = {'valid_key': 1}
assert function_to_test(valid_data) == 1
@elena-roff
elena-roff / conftest.py
Created March 12, 2019 13:36
Setups the client fixture
import pytest
from <service> import app
# ex: app = flask.Flask(__name__, static_url_path='/static')
@pytest.fixture
def client():
app.app.config['TESTING'] = True
client = app.app.test_client()
yield client
@elena-roff
elena-roff / test_endpoints.py
Created March 12, 2019 13:42
Test example with client
headers = {
'Content-Type': 'application/json',
'Authorization': ('...'),
'accept': 'application/json'
}
def test_post(client):
response = client.post('/endpoint',
data=json.dumps(payload),
@elena-roff
elena-roff / recursive_file_search.py
Last active March 20, 2019 19:41
Find files recursively
import globt
# if you need a list, just use glob.glob instead of glob.iglob
for filename in glob.iglob('src/**/*.c', recursive=True):
pprint(filename)
# ----- OR -----
from pathlib import Path
@elena-roff
elena-roff / get_url_link.py
Created March 29, 2019 10:34
Creates a clickable URL from two fields of the pandas DataFrame
@elena-roff
elena-roff / precision_recall_plot.py
Created March 29, 2019 10:38
Precision / Recall curve
from sklearn.metrics import precision_score, recall_score, precision_recall_curve
import matplotlib.pyplot as plt
def plt_prc(recall, precision, label=None):
plt.step(recall, precision, label=label)
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.ylim([0.0, 1.05])
plt.xlim([0.0, 1.0])
@elena-roff
elena-roff / mask_train.py
Created March 29, 2019 10:58
Mask for filters on train feature set
filters = {
'field_1': <threshold value for the field1>,
'field_2': <threshold value for the field2>,
}
# creates a matrix of True's
mask = np.ones(features.shape[0], dtype=bool)
for field, threshold_value in filters.items():
# updates the matrix with