content
stringlengths 0
894k
| type
stringclasses 2
values |
---|---|
# !/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
# -------------------------------------------#
# author: sean lee #
# email: [email protected] #
#--------------------------------------------#
"""MIT License
Copyright (c) 2018 Sean
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE."""
import sys
if sys.version_info[0] == 2:
reload(sys)
sys.setdefaultencoding('utf8')
range = xrange
import re
from .textrank import TextRank, KeywordTextRank
from .. import postag
def keyword(txt, k=10, stopword=[], allowPOS=[]):
words = []
for word, flag in postag.tag(txt):
if word not in stopword:
if len(allowPOS) > 0:
if flag in allowPOS:
words.append(word)
else:
words.append(word)
ktr = KeywordTextRank(words)
return ktr.topk(k)
def keyphrase(txt, k=10, stopword=[]):
def get_sents(doc):
re_line_skip = re.compile('[\r\n]')
re_delimiter = re.compile('[,。?!;]')
sents = []
for line in re_line_skip.split(doc):
line = line.strip()
if not line:
continue
for sent in re_delimiter.split(line):
sent = sent.strip()
if not sent:
continue
sents.append(sent)
return sents
sents = get_sents(txt)
docs = []
for sent in sents:
words = []
for word, flag in postag.tag(sent):
if word not in stopword:
words.append(word)
docs.append(words)
tr = TextRank(docs)
res = []
for idx in tr.topk(k):
res.append(docs[idx])
return res
|
python
|
import flask
class RequestDictionary(dict):
def __init__(self, *args, default_val=None, **kwargs):
self.default_val = default_val
super().__init__(*args, **kwargs)
def __getattr__(self, key):
# Enable rd.key shorthand for rd.get('key') or rd['key']
return self.get(key, self.default_val)
def create(default_val=None, **route_args) -> RequestDictionary:
request = flask.request
# Allow views to not care where data came from:
# Put all data sources in one unified dict,
# in ascending order of priority
# e.g. URL route has higher priority than the URL query string
data = {
**request.args, # The key/value pairs in the URL query string
**request.headers, # Header values
**request.form, # The key/value pairs in the body, from a HTML post form
**route_args # And additional arguments the method access, if they want them merged.
}
return RequestDictionary(data, default_val=default_val)
|
python
|
# library
import pandas as pd
import matplotlib.pyplot as plt
import datetime
import gif
import seaborn as sns
import warnings
warnings.filterwarnings("ignore")
# 関数化する
## git.frameデコレターを使用する
@gif.frame
def my_plot(df, date, x_min, x_max, y_min, y_max):
# 可視化するデータ
d = df[df["date"] <= date]
# グラフ設定
sns.set()
sns.set_style("whitegrid", {'grid.linestyle': '--'})
sns.set_context('talk')
sns.despine(left=True)
# グラブ描画
fig = plt.subplots(1, 1, figsize=(15, 8))
plt.subplots_adjust(bottom=0.2, top=0.925)
ax= sns.lineplot(
data=d,
x=d['date'],
y=d['weight'],
color='green',
marker='o',
linestyle='dashed',
linewidth=2,
)
# title
ax.set_title(
'test gif' ,
fontsize=24,
fontweight=16)
# X軸Y軸ラベル
ax.set_xlabel('')
ax.set_ylabel(
'Body Weight [kg]',
color='tab:green',
fontsize=16,
labelpad=20,
weight='bold')
# X軸値回転
# うまく行かないのでコメントアウトで回避
# datetime型のseriesでありほしいのはYMDだけ、編集する
# dtアクセッサを利用するのは定番、覚えておく
ax.set_xticklabels(
d['date'].dt.strftime('%Y-%m-%d'),
#d['date'],
rotation=75)
# 目標値
th = 63.0
ax.set_xlim(x_min, x_max)
ax.set_ylim(y_min, y_max)
ax.hlines(
y=th,
xmin=x_min,
xmax=x_max,
color='red',
linestyle="--",
lw=3)
ax.text(
x=df["date"].mean(),
#x=d["date"].mean(),
y=th+0.5,
s="Target Level",
color="red",
ha='center',
va='center',
fontsize=16)
# ダイエットできなかった期間を描く
# ダイエットしなかった日のdf
bad_df = d[d["ringfit"]==0]
# 期間描画
for bad_day in bad_df["date"]:
start = bad_day - datetime.timedelta(hours=12)
end = bad_day + datetime.timedelta(hours=12)
ax.axvspan(
xmin=start,
xmax=end,
alpha=0.3,
color='#F933FF')
ax.text(
x=bad_day,
y=d["weight"].max()+0.5,
s='I did not play "Ring Fit"',
color="red",
ha='center',
va='center',
fontsize=16)
####################################################
# test
####################################################
# データ
START = pd.Timestamp("2020-01-05")
END = pd.Timestamp("2020-01-16")
weights = [66.7, 66.7, 65.8, 65.6, 67.0, 66.5, 65.9, 65.1, 64.7, 64.5, 64.8, 66.1]
ringfit = [1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1] # リングフィットした:1, してない:0
# データフレーム化
df = pd.DataFrame(
{
"date": pd.date_range(start=START, end=END),
"weight": [wi for wi in weights],
"ringfit": [fi for fi in ringfit],
}
)
print(df.head())
x_min = df["date"][0]
x_max = df["date"][len(df)-1]
y_min = 60
y_max = 70
# グラフのアニメーション作成
frames = []
for date in df["date"]:
frame = my_plot(df, date, x_min, x_max, y_min, y_max)
frames.append(frame)
#gifを保存
## loop=0により1回だけのループ描画
gif.save(
frames,
path='./weight-log.gif',
duration=7.5,
loop=0,
unit="s",
between="startend",
)
|
python
|
from collections import defaultdict
from collections.abc import MutableMapping
from copy import deepcopy
from pathlib import Path
from typing import (Any, Dict, List, Literal, Mapping, NamedTuple, Sequence,
Tuple, Union)
import yaml
from more_itertools import unique_everseen
from .md import merge_settings
from .utils import snake_to_text
class NavEntry(NamedTuple):
"""
An entry in the navigation tab.
Args:
hierarchy (Sequence[str]): List of navigation entries.
file (Path): Path to the page, relative to report docs folder.
"""
hierarchy: Sequence[str]
loc: Union[Path, str]
NavList = List[NavEntry]
MkdocsNav = List[Union[str, Mapping[str, Union[str, "MkdocsNav"]]]]
def path_to_nav_entry(path: Path) -> NavEntry:
"""
Turn a file path into a NavEntry.
The path is split, each part of the path used as an element of the
hierarchy. Snake-case are split into words with first letters
capitalized.
Args:
path (Path): The path relative to the report docs folder to turn
into a nav-entry.
Returns:
NavEntry: The NavEntry object representing the path and
the hierarchy of navigation entries.
"""
return NavEntry(
tuple(
[snake_to_text(x) for x in path.parent.parts] + [snake_to_text(path.stem)]
),
path,
)
def _check_length_one(
x: Mapping[str, Union[str, "MkdocsNav"]]
) -> Tuple[str, Union[str, MkdocsNav]]:
assert len(x) == 1
return list(x.items())[0]
def mkdocs_to_navlist(mkdocs_nav: MkdocsNav) -> NavList:
"""
Convert an mkdocs nav to a list of NavEntry.
Args:
mkdocs_nav: A python representation of the nav-entry
in the mkdocs.yml file.
"""
res = []
for entry in mkdocs_nav:
if isinstance(entry, str):
res.append(NavEntry([], Path(entry)))
elif isinstance(entry, Mapping):
key, val = _check_length_one(entry)
if isinstance(val, str):
res.append(NavEntry([key], Path(val)))
elif isinstance(val, List):
res = res + [
NavEntry((key,) + tuple(h), p) for (h, p) in mkdocs_to_navlist(val)
]
else:
raise Exception("Not expected type")
else:
raise Exception("Not expected type")
return res
def split_nav(x: NavList) -> Tuple[List[str], Dict[str, NavList]]:
"""
Split the navigation entry into top level list of items and dict of Navs.
Given a nav-entry, each top-level item that is not a hierarchy itself is
added to the return list. Every hierarchy will have its top level
removed and entered into a dict, with the top-level hierarchy name as the
key and the sub-nav as the value.
Args:
x (Nav): The list of NavEntry to process
Returns:
Tuple[List[str], Dict[str, Nav]]: Structure as explained above.
"""
res_nav = defaultdict(list)
res_list = []
for (h, p) in x:
if len(h) == 0:
res_list.append(p)
else:
res_nav[h[0]].append((h[1:], p))
return (res_list, res_nav)
def navlist_to_mkdocs(nav_list: NavList) -> MkdocsNav:
"""
Convert a list of nav-entries into mkdocs format.
Args:
nav (Nav): The list of NavEntry to convert to mkdocs.yml format
Returns:
Python object of the mkdocs.yml nav entry.
"""
split_nokey, split_keys = split_nav(nav_list)
res: MkdocsNav = [str(p) for p in split_nokey]
for key, val in split_keys.items():
mkdocs_for_key = navlist_to_mkdocs(val)
# if it is a list of length 1 with a string, treat it special
if len(mkdocs_for_key) == 1 and isinstance(mkdocs_for_key[0], str):
res.append({key: mkdocs_for_key[0]})
else:
res.append({key: mkdocs_for_key})
return res
def add_nav_entry(mkdocs_settings, nav_entry: NavEntry) -> Any:
"""
Add an additional entry to the Nav in mkdocs.yml
Args:
mkdocs_settings (): The mkdocs settings to update.
nav_entry (NavEntry): The NavEntry to add
Returns:
The updated mkdocs_settings
"""
mkdocs_settings = deepcopy(mkdocs_settings)
nav = mkdocs_to_navlist(mkdocs_settings["nav"]) + [nav_entry]
# we need to deduplicate
nav = list(unique_everseen(nav))
mkdocs_nav = navlist_to_mkdocs(nav)
mkdocs_settings["nav"] = mkdocs_nav
return mkdocs_settings
def load_yaml(file: Path) -> Any:
"""
Load a yaml file, return empty dict if not exists.
Args:
file (Path): File to load
Returns:
The value in the file, empty dict otherwise.
"""
if file.exists():
with file.open("r") as f:
res = yaml.load(f, Loader=yaml.Loader)
else:
res = {}
return res
def save_yaml(obj: Any, file: Path) -> None:
"""
Save object to yaml file.
Args:
obj (Any): The object to save.
file (Path): Filename to save it into.
"""
with file.open("w") as f:
yaml.dump(obj, f, default_flow_style=False)
def _merge_nav_lists(
nav_list_source: List[NavEntry],
nav_list_target: List[NavEntry],
nav_pref: Literal["S", "T"] = "T",
) -> List[NavEntry]:
nav_list_source_dict = {item.loc: item for item in nav_list_source}
nav_list_target_dict = {item.loc: item for item in nav_list_target}
# should files in Self or Other have preference
if nav_pref == "T":
for key, value in nav_list_source_dict.items():
if key not in nav_list_target_dict:
nav_list_target_dict[key] = value
elif nav_pref == "S":
nav_list_target_dict.update(nav_list_source_dict)
else:
raise ValueError(f"Unknown preference {nav_pref}. Has to be 'S' or 'O'")
return list(nav_list_target_dict.values())
class ReportSettings(MutableMapping):
def __init__(self, file: Path):
self._file = file
self._dict = load_yaml(file)
def __getitem__(self, key: Any) -> Any:
return self._dict[key]
def __setitem__(self, key: Any, value: Any):
"""Assign key to value, but also save to yaml-file."""
self._dict[key] = value
save_yaml(self._dict, self._file)
def __delitem__(self, key: Any):
del self._dict[key]
def __iter__(self):
return self._dict.__iter__()
def __len__(self):
return len(self._dict)
@property
def nav_list(self) -> List[NavEntry]:
return mkdocs_to_navlist(self._dict["nav"])
@nav_list.setter
def nav_list(self, nav_list: List[NavEntry]):
self["nav"] = navlist_to_mkdocs(nav_list)
def append_nav_entry(
self,
nav_entry: Union[Path, NavEntry],
nav_pref: Literal["S", "T"] = "T",
) -> None:
if isinstance(nav_entry, Path):
nav_entry = path_to_nav_entry(nav_entry)
self.nav_list = _merge_nav_lists([nav_entry], self.nav_list, nav_pref=nav_pref)
@property
def dict(self):
return self._dict
@dict.setter
def dict(self, value):
self._dict = value
save_yaml(self._dict, self._file)
def merge(
self,
source: Union[Dict[str, Any], "ReportSettings"],
nav_pref: Literal["S", "T"] = "T",
):
if isinstance(source, self.__class__):
source = source._dict
# make a copy so we can manipulate it
source = deepcopy(source)
source_nav = source.get("nav", None)
if "nav" in source:
del source["nav"]
# now we want to merge the content; but nav items have to be
# treated differently
merged_dict = merge_settings(self._dict, source)
if source_nav is not None:
# now we merge the navs; for this we access them as lists
nav_list_target = self.nav_list
nav_list_source = mkdocs_to_navlist(source_nav)
combined_nav = _merge_nav_lists(
nav_list_source=nav_list_source,
nav_list_target=nav_list_target,
nav_pref=nav_pref,
)
merged_dict["nav"] = combined_nav
self.dict = merged_dict
|
python
|
from secml.array.tests import CArrayTestCases
import numpy as np
import copy
from secml.array import CArray
from secml.core.constants import inf
class TestCArrayUtilsDataAlteration(CArrayTestCases):
"""Unit test for CArray UTILS - DATA ALTERATION methods."""
def test_round(self):
"""Test for CArray.round() method."""
self.logger.info("Test for CArray.round() method.")
def _round(array):
array_float = array.astype(float)
array_float *= 1.0201
self.logger.info("a: \n{:}".format(array))
round_res = array_float.round()
self.logger.info("a.round(): \n{:}".format(round_res))
self.assert_array_equal(round_res, array.astype(float))
round_res = array_float.round(decimals=2)
self.logger.info("a.round(decimals=2): \n{:}".format(round_res))
array_test = array * 1.02
self.assert_array_equal(round_res, array_test)
round_res = array_float.round(decimals=6)
self.logger.info("a.round(decimals=6): \n{:}".format(round_res))
self.assert_array_equal(round_res, array_float)
_round(self.array_sparse)
_round(self.row_sparse)
_round(self.column_sparse)
_round(self.array_dense)
_round(self.row_sparse)
_round(self.column_dense)
def test_clip(self):
"""Test for CArray.clip() method."""
self.logger.info("Test for CArray.clip() method.")
def _check_clip(array, expected):
self.logger.info("Array:\n{:}".format(array))
intervals = [(0, 2), (0, inf), (-inf, 0)]
for c_limits_idx, c_limits in enumerate(intervals):
res = array.clip(*c_limits)
self.logger.info("array.min(c_min={:}, c_max={:}):"
"\n{:}".format(c_limits[0], c_limits[1], res))
res_expected = expected[c_limits_idx]
self.assertIsInstance(res, CArray)
self.assertEqual(res.isdense, res_expected.isdense)
self.assertEqual(res.issparse, res_expected.issparse)
self.assertEqual(res.shape, res_expected.shape)
self.assertEqual(res.dtype, res_expected.dtype)
self.assertFalse((res != res_expected).any())
# array_dense = CArray([[1, 0, 0, 5], [2, 4, 0, 0], [3, 6, 0, 0]]
# row_flat_dense = CArray([4, 0, 6])
_check_clip(self.array_dense,
(CArray([[1, 0, 0, 2], [2, 2, 0, 0], [2, 2, 0, 0]]),
CArray([[1., 0., 0., 5.],
[2., 4., 0., 0.],
[3., 6., 0., 0.]]),
CArray([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])))
_check_clip(self.row_flat_dense, (CArray([2, 0, 2]),
CArray([4., 0., 6.]),
CArray([0., 0., 0.])))
_check_clip(self.row_dense, (CArray([[2, 0, 2]]),
CArray([[4., 0., 6.]]),
CArray([[0., 0., 0.]])))
_check_clip(self.column_dense, (CArray([[2], [0], [2]]),
CArray([[4.], [0.], [6.]]),
CArray([[0.], [0.], [0.]])))
_check_clip(self.single_flat_dense,
(CArray([2]), CArray([4.]), CArray([0.])))
_check_clip(self.single_dense,
(CArray([[2]]), CArray([[4.]]), CArray([[0.]])))
# Check intervals wrongly chosen
with self.assertRaises(ValueError):
self.array_dense.clip(2, 0)
self.array_dense.clip(0, -2)
self.array_dense.clip(2, -2)
def test_sort(self):
"""Test for CArray.sort() method."""
self.logger.info("Test for CArray.sort() method")
def _sort(axis, array, sorted_expected):
self.logger.info("Array:\n{:}".format(array))
array_isdense = array.isdense
array_issparse = array.issparse
for inplace in (False, True):
array_copy = copy.deepcopy(array)
array_sorted = array_copy.sort(axis=axis, inplace=inplace)
self.logger.info("Array sorted along axis {:}:"
"\n{:}".format(axis, array_sorted))
self.assertEqual(array_issparse, array_sorted.issparse)
self.assertEqual(array_isdense, array_sorted.isdense)
self.assertFalse((sorted_expected != array_sorted).any())
# Value we are going to replace to check inplace parameter
alter_value = CArray(100, dtype=array_copy.dtype)
if array_copy.ndim < 2:
array_copy[0] = alter_value
if inplace is False:
self.assertTrue(array_sorted[0] != alter_value[0])
else:
self.assertTrue(array_sorted[0] == alter_value[0])
else:
array_copy[0, 0] = alter_value
if inplace is False:
self.assertTrue(array_sorted[0, 0] != alter_value[0])
else:
self.assertTrue(array_sorted[0, 0] == alter_value[0])
# Sparse arrays
_sort(-1, self.array_sparse,
CArray([[0, 0, 1, 5], [0, 0, 2, 4], [0, 0, 3, 6]],
tosparse=True))
_sort(0, self.array_sparse,
CArray([[1, 0, 0, 0], [2, 4, 0, 0], [3, 6, 0, 5]],
tosparse=True))
_sort(1, self.array_sparse,
CArray([[0, 0, 1, 5], [0, 0, 2, 4], [0, 0, 3, 6]],
tosparse=True))
_sort(-1, self.row_sparse, CArray([0, 4, 6], tosparse=True))
_sort(0, self.row_sparse, CArray([4, 0, 6], tosparse=True))
_sort(1, self.row_sparse, CArray([0, 4, 6], tosparse=True))
_sort(-1, self.column_sparse, CArray([[4], [0], [6]], tosparse=True))
_sort(0, self.column_sparse, CArray([[0], [4], [6]], tosparse=True))
_sort(1, self.column_sparse, CArray([[4], [0], [6]], tosparse=True))
# Dense arrays
_sort(-1, self.array_dense,
CArray([[0, 0, 1, 5], [0, 0, 2, 4], [0, 0, 3, 6]]))
_sort(0, self.array_dense,
CArray([[1, 0, 0, 0], [2, 4, 0, 0], [3, 6, 0, 5]]))
_sort(1, self.array_dense,
CArray([[0, 0, 1, 5], [0, 0, 2, 4], [0, 0, 3, 6]]))
_sort(-1, self.row_dense, CArray([0, 4, 6]))
_sort(0, self.row_dense, CArray([4, 0, 6]))
_sort(1, self.row_dense, CArray([0, 4, 6]))
_sort(-1, self.column_dense, CArray([[4], [0], [6]]))
_sort(0, self.column_dense, CArray([[0], [4], [6]]))
_sort(1, self.column_dense, CArray([[4], [0], [6]]))
# Bool arrays
_sort(-1, self.array_dense_bool,
CArray([[False, True, True, True],
[False, False, False, False],
[True, True, True, True]]))
_sort(0, self.array_dense_bool,
CArray([[False, False, False, False],
[True, False, True, True],
[True, True, True, True]]))
_sort(1, self.array_dense_bool,
CArray([[False, True, True, True],
[False, False, False, False],
[True, True, True, True]]))
_sort(-1, self.array_sparse_bool,
CArray([[False, True, True, True],
[False, False, False, False],
[True, True, True, True]], tosparse=True))
_sort(0, self.array_sparse_bool,
CArray([[False, False, False, False],
[True, False, True, True],
[True, True, True, True]], tosparse=True))
_sort(1, self.array_sparse_bool,
CArray([[False, True, True, True],
[False, False, False, False],
[True, True, True, True]], tosparse=True))
# Check sort() for empty arrays
self.empty_flat_dense.sort()
self.assertTrue((self.empty_flat_dense == CArray([])).all())
self.empty_sparse.sort()
self.assertTrue((self.empty_sparse == CArray([])).all())
def test_argsort(self):
"""Test for CArray.argsort() method."""
self.logger.info("Test for CArray.argsort() method.")
def _argsort(axis, matrix):
self.logger.info("array: {:}".format(matrix))
sorted_idx = matrix.argsort(axis=axis)
self.logger.info("array.argsort(axis={:}): {:}".format(axis, sorted_idx))
self.assertFalse(sorted_idx.issparse, "sorted method don't return a cndarray")
np_matrix = matrix.todense().tondarray()
np_matrix = np.atleast_2d(np_matrix)
np_sorted_idx = np.argsort(np_matrix, axis=axis)
self.assertTrue((sorted_idx.tondarray() == np_sorted_idx).all())
# Sparse arrays
_argsort(None, self.array_sparse)
_argsort(0, self.array_sparse)
_argsort(1, self.array_sparse)
_argsort(None, self.row_sparse)
_argsort(0, self.row_sparse)
_argsort(1, self.row_sparse)
_argsort(None, self.column_sparse)
_argsort(0, self.column_sparse)
_argsort(1, self.column_sparse)
# Dense arrays
_argsort(None, self.array_dense)
_argsort(0, self.array_dense)
_argsort(1, self.array_dense)
_argsort(None, self.row_dense)
_argsort(0, self.row_dense)
_argsort(1, self.row_dense)
_argsort(None, self.column_dense)
_argsort(0, self.column_dense)
_argsort(1, self.column_dense)
# Check argsort() for empty arrays
sorted_matrix = CArray([], tosparse=False).argsort()
self.assertTrue((sorted_matrix == CArray([])).all())
sorted_matrix = CArray([], tosparse=True).argsort()
self.assertTrue((sorted_matrix == CArray([])).all())
def test_shuffle(self):
"""Test for CArray.shuffle() method."""
self.logger.info("Test for CArray.shuffle() method")
def _shuffle(array):
array_copy = array.deepcopy() # In-place method
self.logger.info("Array:\n{:}".format(array))
array_shape = array_copy.shape
array_isdense = array_copy.isdense
array_issparse = array_copy.issparse
array.shuffle()
self.logger.info("Array shuffled:\n{:}".format(array))
self.assertEqual(array_shape, array.shape)
self.assertEqual(array_issparse, array.issparse)
self.assertEqual(array_isdense, array.isdense)
array_list = array.tolist()
array_copy_list = array_copy.tolist()
# For vector-like arrays we shuffle the elements along axis 1
if array.ndim == 2 and array.shape[0] == 1:
array_list = array_list[0]
array_copy_list = array_copy_list[0]
for num in array_copy_list:
# Return num position and remove it from the list
# Not need of asserts here... .index() raises error
# if num not in array_list
array_list.pop(array_list.index(num))
_shuffle(self.array_dense)
_shuffle(self.array_sparse)
_shuffle(self.row_sparse)
_shuffle(self.column_sparse)
_shuffle(self.row_flat_dense)
_shuffle(self.row_dense)
_shuffle(self.column_dense)
_shuffle(self.array_dense_allzero)
_shuffle(self.array_sparse_allzero)
_shuffle(self.array_dense_bool)
_shuffle(self.array_sparse_bool)
_shuffle(self.empty_flat_dense)
_shuffle(self.empty_sparse)
if __name__ == '__main__':
CArrayTestCases.main()
|
python
|
from setuptools import setup
setup(
name='__dummy_package',
version='0.0.0',
install_requires=['html-linter==0.1.9'],
)
|
python
|
import json, glob
FILES = glob.glob('download/*/*/*/*.json')
good = {}
dups = 0
total = 0
for f in FILES:
with open(f, 'r') as fi:
j = json.load(fi)
for post in j['data']['children']:
i = post['data']['id']
if i == '4hsh42':
continue
if i not in good:
good[i] = post
with open('posts.json', 'w') as f:
f.write(json.dumps(good, indent=4, separators=(',', ': ')))
|
python
|
import torch
import matplotlib.pyplot as plt
import imageio
import numpy as np
# Create data, 100 points evenly distributed from -2 to 2
# Use unsqueeze to add one more dimension, torch needs at least 2D input (batch, data)
x = torch.unsqueeze(torch.linspace(-2,2,100), dim=1)
# y = x^2 + b
y = x.pow(2) + 0.5 * torch.rand(x.size())
# Plot data
# plt.scatter(x.data.numpy(), y.data.numpy())
# plt.show()
# Define NN class
class Net(torch.nn.Module):
# 官方必備步驟
def __init__(self, n_feature, n_hidden, n_output):
super(Net, self).__init__()
self.hidden = torch.nn.Linear(n_feature, n_hidden)
self.predict = torch.nn.Linear(n_hidden, n_output)
def forward(self,x):
x = torch.relu(self.hidden(x))
x = self.predict(x)
return x
# Construct a NN
net = Net(1, 10, 1)
# Can use print to see the structure of the network
# print(net)
# Stochastic gradient descent (SGD)
optimizer = torch.optim.SGD(net.parameters(), lr = 0.2)
# Mean squared error
loss_func = torch.nn.MSELoss()
# Continuously plot
plt.ion()
f = plt.figure()
gif = []
for t in range(200):
prediction = net(x)
loss = loss_func(prediction, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if t % 5 == 0:
# Plot and show learning process
plt.cla()
plt.scatter(x.data.numpy(), y.data.numpy())
plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=5)
plt.text(0.5, 0, 'Loss=%.4f' % loss.data.numpy(), fontdict={'size': 20, 'color': 'red'})
plt.pause(0.1)
f.canvas.draw()
image = np.frombuffer(f.canvas.tostring_rgb(), dtype='uint8')
image = image.reshape(f.canvas.get_width_height()[::-1] + (3,))
gif.append(image)
imageio.mimsave('./regression.gif', gif, fps=5)
plt.ioff()
plt.show()
|
python
|
import logging
import re
import nltk
from django.utils.text import slugify
from oldp.apps.backend.processing import ProcessingError, AmbiguousReferenceError
from oldp.apps.cases.models import Case
from oldp.apps.cases.processing.processing_steps import CaseProcessingStep
from oldp.apps.laws.models import LawBook
from oldp.apps.references.models import CaseReferenceMarker, ReferenceMarker
logger = logging.getLogger(__name__)
class ExtractRefs(CaseProcessingStep):
description = 'Extract references'
law_book_codes = None
def __init__(self, law_refs=True, case_refs=True):
super(ExtractRefs, self).__init__()
self.law_refs = law_refs
self.case_refs = case_refs
def process(self, case: Case) -> Case:
"""
Read case.content, search for references, add ref marker (e.g. [ref=1]xy[/ref]) to text, add ref data to case:
case.refs {
1: {
section: ??,
line: 1,
word: 2,
id: ecli://...,
}
2: {
line: 2,
word: 123,
id: law://de/bgb/123
}
}
Ref data should contain position information, for CPA computations ...
:param case_refs:
:param law_refs:
:param case:
:return:
"""
all_refs = []
# print(case.get_sections())
content = ReferenceMarker.remove_markers(case.content)
if self.law_refs:
content, refs = self.extract_law_refs(case, content, key=len(all_refs))
all_refs.extend(refs)
logger.debug('Extracted law refs: %i' % len(refs))
if self.case_refs:
content, refs = self.extract_case_refs(case, content, key=len(all_refs))
all_refs.extend(refs)
logger.debug('Extracted case refs: %i' % len(refs))
case.content = content
case.reference_markers = all_refs
if not case._state.adding:
case.save_reference_markers()
else:
logger.warning('Reference markers not saved (case is not saved)')
# print(case.references)
# if len(not_found_refs) > 0:
# raise ValueError('Some refs still in the content...')
return case
def test_ref_extraction(self, value):
# (.+?)\\[/ref\\]
value = re.sub(r'\[ref=([0-9]+)\](.+?)\[/ref\]', '______', value)
if re.search(r'§', value, re.IGNORECASE):
return value
else:
return None
def get_law_book_codes(self):
if self.law_book_codes is None:
# Fetch codes from db
# State.objects.values_list(
self.law_book_codes = list(LawBook.objects.values_list('code', flat=True))
logger.debug('Loaded law book codes from db: %i' % len(self.law_book_codes))
# Extend with pre-defined codes
self.law_book_codes.extend(['AsylG', 'VwGO', 'GkG', 'stbstg', 'lbo', 'ZPO', 'LVwG', 'AGVwGO SH', 'BauGB',
'BauNVO', 'ZWStS', 'SbStG', 'StPO', 'TKG'])
return self.law_book_codes
# Returns regex for law book part in reference markers
def get_law_book_ref_regex(self, optional=True, group_name=True, lower=False):
# law_book_codes = list(json.loads(open(self.law_book_codes_path).read()).keys())
law_book_codes = self.get_law_book_codes()
law_book_regex = None
for code in law_book_codes:
if lower:
code = code.lower()
if law_book_regex is None:
# if optional:
# law_book_regex = '('
# else:
# law_book_regex = '('
law_book_regex = ''
# if group_name:
# law_book_regex += '?P<book>'
law_book_regex += code
else:
law_book_regex += '|' + code
# law_book_regex += ')'
# if optional:
# law_book_regex += '?'
return law_book_regex
def get_law_ref_regex(self):
# TODO Regex builder tool? http://regexr.com/
# https://www.debuggex.com/
# ((,|und)\s*((?P<nos>[0-9]+)+)*
# regex += '(\s?([0-9]+|[a-z]{1,2}|Abs\.|Abs|Satz|S\.|Nr|Nr\.|Alt|Alt\.|f\.|ff\.|und|bis|\,|'\
#regex = r'(§|§§|Art.) (?P<sect>[0-9]+)\s?(?P<sect_az>[a-z]*)\s?(?:Abs.\s?(?:[0-9]{1,2})|Abs\s?(?:[0-9]{1,2}))?\s?(?:Satz\s[0-9]{1,2})?\s' + law_book_regex
regex = r'(§|§§|Art\.)\s'
regex += '(\s|[0-9]+|[a-z]|Abs\.|Abs|Satz|S\.|Nr|Nr\.|Alt|Alt\.|f\.|ff\.|und|bis|\,|' \
+ self.get_law_book_ref_regex(optional=False, group_name=False) + ')+'
regex += '\s(' + self.get_law_book_ref_regex(optional=False, group_name=False) + ')'
regex_abs = '((Abs.|Abs)\s?([0-9]+)((,|und|bis)\s([0-9]+))*)*'
regex_a = '(([0-9]+)\s?([a-z])?)'
regex_a += '((,|und|bis)\s*(([0-9]+)\s?([a-z])?)+)*'
# f. ff.
regex_a += '\s?((Abs.|Abs)\s?([0-9]+))*'
# regex_a += '\s?(?:(Abs.|Abs)\s?(?:[0-9]{1,2})\s?((,|und|bis)\s*(([0-9]+)\s?([a-z])?)+)*)?'
# regex_a += '\s?((Satz|S\.)\s[0-9]{1,2})?'
# regex_a += '\s?(((Nr|Nr\.)\s[0-9]+)' + '(\s?(,|und|bis)\s[0-9]+)*' + ')?'
# regex_a += '\s?(((Alt|Alt\.)\s[0-9]+)' + '(\s?(,|und|bis)\s[0-9]+)*' + ')?'
regex_a += '\s'
regex_a += '(' + self.get_law_book_ref_regex(optional=True, group_name=False) + ')'
# regex += regex_a
# regex += '(\s?(,|und)\s' + regex_a + ')*'
#
# logger.debug('Law Regex=%s' % regex)
return regex
def get_law_ref_match_single(self, ref_str):
# Single ref
regex_a = '(Art\.|§)\s'
regex_a += '((?P<sect>[0-9]+)\s?(?P<sect_az>[a-z])?)' # f. ff.
regex_a += '(\s?([0-9]+|[a-z]{1,2}|Abs\.|Abs|Satz|S\.|Nr|Nr\.|Alt|Alt\.|und|bis|,))*'
# regex_a += '\s?(?:(Abs.|Abs)\s?(?:[0-9]{1,2})\s?((,|und|bis)\s*(([0-9]+)\s?([a-z])?)+)*)?'
# regex_a += '\s?((Satz|S\.)\s[0-9]{1,2})?'
# regex_a += '\s?(((Nr|Nr\.)\s[0-9]+)' + '(\s?(,|und|bis)\s[0-9]+)*' + ')?'
# regex_a += '\s?(((Alt|Alt\.)\s[0-9]+)' + '(\s?(,|und|bis)\s[0-9]+)*' + ')?'
regex_a += '\s(?P<book>' + self.get_law_book_ref_regex(optional=False) + ')'
return re.search(regex_a, ref_str)
def get_law_ref_match_multi(self, ref_str):
pattern = r'(?P<delimiter>§§|,|und|bis)\s?'
pattern += '((?P<sect>[0-9]+)\s?'
# pattern += '(?P<sect_az>[a-z])?)'
# (?!.*?bis).*([a-z]).*)
# pattern += '(?P<sect_az>(?!.*?bis).*([a-z]).*)?)'
# (?!(moscow|outside))
# pattern += '(?P<sect_az>(([a-z])(?!(und|bis))))?)'
pattern += '((?P<sect_az>[a-z])(\s|,))?)' # Use \s|, to avoid matching "bis" and "Abs", ...
pattern += '(\s?(Abs\.|Abs)\s?([0-9]+))*'
pattern += '(\s?(S\.|Satz)\s?([0-9]+))*'
# pattern += '(?:\s(Nr\.|Nr)\s([0-9]+))'
# pattern += '(?:\s(S\.|Satz)\s([0-9]+))'
# pattern += '(?:\s(f\.|ff\.))?'
pattern += '(\s?(f\.|ff\.))*'
# pattern += '(\s(Abs.|Abs)\s?([0-9]+)((,|und|bis)\s([0-9]+))*)*'
# pattern += '\s?(?:(Abs.|Abs)\s?(?:[0-9]{1,2})\s?((,|und|bis)\s*(([0-9]+)\s?([a-z])?)+)*)?'
pattern += '\s?(?:(?P<book>' + self.get_law_book_ref_regex() + '))?'
# print('MULTI: ' + ref_str)
# print(pattern)
# logger.debug('Multi ref regex: %s' % pattern)
return re.finditer(pattern, ref_str)
def get_law_id_from_match(self, match):
# print(match.groups())
return 'ecli://de/%s/%s%s' % (
match.group('book').lower(),
int(match.group('sect')),
match.group('sect_az').lower()
)
def extract_law_refs(self, referenced_by: Case, content: str, key: int=0):
"""
§ 3d AsylG
§ 123 VwGO
§§ 3, 3b AsylG
§ 77 Abs. 1 Satz 1, 1. Halbsatz AsylG
§ 3 Abs. 1 AsylG
§ 77 Abs. 2 AsylG
§ 113 Abs. 5 Satz 1 VwGO
§ 3 Abs. 1 Nr. 1 i.V.m. § 3b AsylG
§ 3a Abs. 1 und 2 AsylG
§§ 154 Abs. 1 VwGO
§ 83 b AsylG
§ 167 VwGO iVm §§ 708 Nr. 11, 711 ZPO
§ 167 VwGO i.V.m. §§ 708 Nr. 11, 711 ZPO
§§ 167 Abs. 2 VwGO, 708 Nr. 11, 711 ZPO
§§ 52 Abs. 1; 53 Abs. 2 Nr. 1; 63 Abs. 2 GKG
§ 6 Abs. 5 Satz 1 LBO
§§ 80 a Abs. 3, 80 Abs. 5 VwGO
§ 1 Satz 2 SbStG
§ 2 ZWStS
§ 6 Abs. 2 S. 2 ZWStS
TODO all law-book jurabk
:param referenced_by:
:param key:
:link https://www.easy-coding.de/Thread/5536-RegExp-f%C3%BCr-Gesetze/
:param content:
:return:
"""
logger.debug('Extracting law references')
refs = []
results = list(re.finditer(self.get_law_ref_regex(), content))
marker_offset = 0
logger.debug('Current content value: %s' % content)
logger.debug('Law refs found: %i' % len(results))
for ref_m in results:
ref_str = str(ref_m.group(0)).strip()
law_ids = []
# Handle single and multi refs separately
if re.match(r'^(Art\.|§)\s', ref_str):
law_ids = self.handle_single_law_ref(ref_str, law_ids)
elif re.match(r'^§§\s', ref_str):
law_ids = self.handle_multiple_law_refs(ref_str, law_ids)
else:
raise ProcessingError('Unsupported ref beginning: %s' % ref_str)
ref = CaseReferenceMarker(referenced_by=referenced_by,
text=ref_str,
start=ref_m.start(),
end=ref_m.end(),
line=0) # TODO
ref.set_uuid()
ref.set_references(law_ids)
refs.append(ref)
content, marker_offset = ref.replace_content(content, marker_offset, key + len(refs))
return content, refs
def handle_multiple_law_refs(self, ref_str, law_ids):
# Search for multiple refs
mms = self.get_law_ref_match_multi(ref_str)
ids_tmp = []
prev_sect = None
prev_book = None
logger.debug('Multi refs found in: %s' % ref_str)
# Loop over all results
for m in mms:
# If book is not set, use __placeholder__ and replace later
if m.group('book') is not None:
book = m.group('book').lower()
else:
book = '__book__'
# Section must exist
if m.group('sect') is not None:
sect = str(m.group('sect'))
else:
raise ProcessingError('Ref sect is not set')
if m.group('sect_az') is not None:
sect += m.group('sect_az').lower()
law_id = {
'book': book,
'sect': sect,
'type': 'law'
}
logger.debug('Law ID found: %s' % law_id)
# Check for section ranges
if m.group('delimiter') == 'bis':
logger.debug('Handle section range - Add ids from ' + prev_sect + ' to ' + sect)
# TODO how to handle az sects
prev_sect = re.sub('[^0-9]', '', prev_sect)
sect = re.sub('[^0-9]', '', sect)
for between_sect in range(int(prev_sect)+1, int(sect)):
# print(between_sect)
ids_tmp.append({
'book': prev_book,
'sect': between_sect,
'type': 'law'
})
else:
prev_sect = sect
prev_book = book
ids_tmp.append(law_id)
# law_ids.append('multi = ' + ref_str)
# handle __book__
logger.debug('All law ids found: %s' % ids_tmp)
ids_tmp.reverse()
book = None
for id_tmp in ids_tmp:
if id_tmp['book'] != '__book__':
book = id_tmp['book']
elif book is not None:
id_tmp['book'] = book
else:
raise ProcessingError('Cannot determine law book (Should never happen): %s' % ref_str)
law_ids.append(id_tmp)
return law_ids
def handle_single_law_ref(self, ref_str, law_ids):
logger.debug('Single ref found in: %s' % ref_str)
# Single ref
mm = self.get_law_ref_match_single(ref_str)
# Find book and section (only single result possible)
if mm is not None:
# mm.groupdict()
if mm.group('book') is not None:
# Found book
book = mm.group('book').lower()
else:
raise ProcessingError('Ref book is not set: %s ' % ref_str)
if mm.group('sect') is not None:
# Found section
sect = str(mm.group('sect'))
else:
raise ProcessingError('Ref sect is not set')
if mm.group('sect_az') is not None:
# Found section addon
sect += mm.group('sect_az').lower()
law_id = {
'book': book,
'sect': sect,
'type': 'law'
}
logger.debug('Law ID: %s' % law_id)
law_ids.append(law_id)
else:
law_ids.append({'book': 'not matched', 'sect': 'NOT MATCHED (single) %s ' % ref_str})
logger.warning('Law ID could not be matched.')
return law_ids
def clean_text_for_tokenizer(self, text):
"""
Remove elements from text that can make the tokenizer fail.
:param text:
:return:
"""
def repl(m):
return '_' * (len(m.group()))
def repl2(m):
# print(m.group(2))
return m.group(1) + ('_' * (len(m.group(2)) + 1))
# (...) and [...]
text = re.sub(r'\((.*?)\)', repl, text)
# Dates
text = re.sub(r'(([0-9]+)\.([0-9]+)\.([0-9]+)|i\.S\.d\.)', repl, text)
# Abbr.
text = re.sub(r'(\s|\(|\[)([0-9]+|[IVX]+|[a-zA-Z]|sog|ca|Urt|Abs|Nr|lfd|vgl|Rn|Rspr|std|ff|bzw|Art)\.', repl2, text)
# Schl.-Holst.
text = re.sub(r'([a-z]+)\.-([a-z]+)\.', repl, text, flags=re.IGNORECASE)
return text
def get_court_name_regex(self):
"""
Regular expression for finding court names
:return: regex
"""
# TODO Fetch from DB
# TODO generate only once
federal_courts = [
'Bundesverfassungsgericht', 'BVerfG',
'Bundesverwaltungsgericht', 'BVerwG',
'Bundesgerichtshof', 'BGH',
'Bundesarbeitsgericht', 'BAG',
'Bundesfinanzhof', 'BFH',
'Bundessozialgericht', 'BSG',
'Bundespatentgericht', 'BPatG',
'Truppendienstgericht Nord', 'TDG Nord',
'Truppendienstgericht Süd', 'TDG Süd',
'EUGH',
]
states = [
'Berlin',
'Baden-Württemberg', 'BW',
'Brandenburg', 'Brandenburgisches',
'Bremen',
'Hamburg',
'Hessen',
'Niedersachsen',
'Hamburg',
'Mecklenburg-Vorpommern',
'Nordrhein-Westfalen', 'NRW',
'Rheinland-Pfalz',
'Saarland',
'Sachsen',
'Sachsen-Anhalt',
'Schleswig-Holstein', 'Schl.-Holst.', 'SH',
'Thüringen'
]
state_courts = [
'OVG',
'VGH'
]
cities = [
'Baden-Baden',
'Berlin-Brbg.'
'Wedding',
'Schleswig'
]
city_courts = [
'Amtsgericht', 'AG',
'Landgericht', 'LG',
'Oberlandesgericht', 'OLG',
'OVG'
]
pattern = None
for court in federal_courts:
if pattern is None:
pattern = r'('
else:
pattern += '|'
pattern += court
for court in state_courts:
for state in states:
pattern += '|' + court + ' ' + state
pattern += '|' + state + ' ' + court
for c in city_courts:
for s in cities:
pattern += '|' + c + ' ' + s
pattern += '|' + s + ' ' + c
pattern += ')'
# logger.debug('Court regex: %s' % pattern)
return pattern
def get_file_number_regex(self):
return r'([0-9]+)\s([a-zA-Z]{,3})\s([0-9]+)/([0-9]+)'
def extract_case_refs(self, referenced_by: Case, content: str, key: int=0):
"""
BVerwG, Urteil vom 20. Februar 2013, - 10 C 23.12 -
BVerwG, Urteil vom 27. April 2010 - 10 C 5.09 -
BVerfG, Beschluss vom 10.07.1989, - 2 BvR 502, 1000, 961/86 -
BVerwG, Urteil vom 20.02.2013, - 10 C 23.12 -
OVG Nordrhein-Westfalen, Urteil vom 21.2.2017, - 14 A 2316/16.A -
OVG Nordrhein-Westfalen, Urteil vom 29.10.2012 – 2 A 723/11 -
OVG NRW, Urteil vom 14.08.2013 – 1 A 1481/10, Rn. 81 –
OVG Saarland, Urteil vom 2.2.2017, - 2 A 515/16 -
OVG Rheinland-Pfalz, Urteil vom 16.12.2016, -1A 10922/16 -
Bayrischer VGH, Urteil vom 12.12.16, - 21 B 16.30364
OVG Nordrhein-Westfalen, Urteil vom 21.2.2017, - 14 A 2316/16.A -
Bayrischer VGH, Urteil vom 12.12.2016, - 21 B 16.30372 -
OVG Saarland, Urteil vom 2.2.2017, - 2 A 515/16 -
OVG Rheinland-Pfalz, Urteil vom 16.12.2016, -1A 10922/16 -
VG Minden, Urteil vom 22.12.2016, - 1 K 5137/16.A -
VG Gießen, Urteil vom 23.11.2016, - 2 K 969/16.GI.A
VG Düsseldorf, Urteil vom 24.1.2017, - 17 K 9400/16.A
VG Köln, Beschluss vom 25.03.2013 – 23 L 287/12 -
OVG Schleswig, Beschluss vom 20.07.2006 – 1 MB 13/06 -
Schleswig-Holsteinisches Verwaltungsgericht, Urteil vom 05.082014 – 11 A 7/14, Rn. 37 –
Entscheidung des Bundesverwaltungsgerichts vom 24.01.2012 (2 C 24/10)
EuGH Urteil vom 25.07.2002 – C-459/99 -
TODO all court codes + case types
- look for (Entscheidung|Bechluss|Urteil)
- +/- 50 chars
- find VG|OVG|Verwaltungsgericht|BVerwG|...
- find location
- find file number - ... - or (...)
TODO
Sentence tokenzier
- remove all "special endings" \s([0-9]+|[a-zA-Z]|sog|Abs)\.
- remove all dates
:param key:
:param content:
:return:
"""
refs = []
original = content
text = content
# print('Before = %s' % text)
# Clean up text; replacing all chars that can lead to wrong sentences
text = self.clean_text_for_tokenizer(text)
# TODO
from nltk.tokenize.punkt import PunktParameters
punkt_param = PunktParameters()
abbreviation = ['1', 'e', 'i']
punkt_param.abbrev_types = set(abbreviation)
# tokenizer = PunktSentenceTokenizer(punkt_param)
offset = 0
marker_offset = 0
for start, end in nltk.PunktSentenceTokenizer().span_tokenize(text):
length = end - start
sentence = text[start:end]
original_sentence = original[start:end]
matches = list(re.finditer(r'\((.*?)\)', original_sentence))
logger.debug('Sentence (matches: %i): %s' % (len(matches), sentence))
logger.debug('Sentence (orignal): %s' % (original_sentence))
for m in matches:
# pass
# print('offset = %i, len = %i' % (offset, len(sentence)))
#
# print('MANGLED: ' + sentence)
logger.debug('Full sentence // UNMANGLED: ' + original_sentence)
# focus_all = original[start+m.start(1):start+m.end(1)].split(',')
focus_all = original_sentence[m.start(1):m.end(1)].split(',')
# print(m.group(1))
logger.debug('In parenthesis = %s' % focus_all)
# Split
for focus in focus_all:
# Search for file number
fns_matches = list(re.finditer(self.get_file_number_regex(), focus))
if len(fns_matches) == 1:
fn = fns_matches[0].group(0)
pos = fns_matches[0].start(0)
logger.debug('File number found: %s' % fn)
# Find court
court_name = None
court_pos = 999999
court_matches = list(re.finditer(self.get_court_name_regex(), original_sentence))
if len(court_matches) == 1:
# Yeah everything is fine
court_name = court_matches[0].group(0)
elif len(court_matches) > 0:
# Multiple results, choose the one that is closest to file number
for cm in court_matches:
if court_name is None or abs(pos - cm.start()) < court_pos:
court_name = cm.group(0)
court_pos = abs(pos - cm.start())
else:
# no court found, guess by search query
# probably the court of the current case? test for "die kammer"
pass
# Find date
# TODO
logger.debug('Filename = %s' % fn)
logger.debug('Courtname = %s' % court_name)
ref_start = start + m.start(1) + pos
ref_end = ref_start + len(fn)
if court_name is None:
# raise )
# TODO Probably same court as current case (use case validation)
logger.error(AmbiguousReferenceError('No court name found - FN: %s' % fn))
# logger.debug('Sentence: %s' % (fn, original_sentence)))
continue
ref_ids = [
{
'type': 'case',
'ecli': 'ecli://de/' + slugify(court_name) + '/' + slugify(fn.replace('/', '-'))
}
]
# TODO maintain order for case+law refs
ref = CaseReferenceMarker(referenced_by=referenced_by,
text=focus,
start=ref_start,
end=ref_end,
line=0) # TODO line number
ref.set_uuid()
ref.set_references(ref_ids)
refs.append(
ref
)
content, marker_offset = ref.replace_content(content, marker_offset, key + len(refs))
pass
elif len(fns_matches) > 1:
logger.warning('More file numbers found: %s' % fns_matches)
pass
else:
logger.debug('No file number found')
return content, refs
|
python
|
num = int(input("Digite um número inteiro de 0 a 9999: "))
u = num // 1 % 10
d = num // 10 % 10
c = num // 100 % 10
m = num // 1000 % 10
print(f"O numero {num} possui {u} unidades.")
print(f"O numero{num} possui {d} dezenas.")
print(f"O numero{num} possui {c} centenas.")
print(f"O numero{num} possui {m} milhares.")
|
python
|
facts=[
'Mumbai was earlier known as Bombay.',
'Mumbai got its name from a popular goddess temple - Mumba Devi Mandir, which is situated at Bori Bunder in Mumbai.',
'On 16 April 1853, Mumbai witnessed the first train movement in India. \
With 14 carriages and 400 passengers, the first train left Bori Bunder, now called Chhatrapati Shivaji Terminal, \
for Thane in Maharashtra.',
'Mumbai is the hub of Hindi film industry in India, popularly known as Bollywood.',
'Mumbai sea link, officially known as Rajiv Gandhi Sea Link has a length of around 5.6 km. \
It is an architectural-wonder as it was made with 90,000 tons of cement and steel wire comparable to the girth of the earth.',
'Ganesh Chaturthi is the most popular 10 day festival in Mumbai which brings the whole city together, celebrating on the street.',
'Flamingos usually migrate from Afro-Eurasian parts to Mumbai between October to March.',
'Located in the Andheri West, Gilbert Hill is a 200 ft hill of black basalt rock built around 66 million years ago. \
It’s unique because only the US has a hill with the same composition.',
'Mumbai is often referred to as the financial capital of India, as it is the home of the Bombay Stock Exchange \
and the National Stock Exchange, the main stock exchanges of India.'
'Way back in 1863, Alice Tredwell, wife of Solomon Tredwell built the railway line from Mumbai to Pune.',
'The first post office in Mumbai was opened at the house of the Junior Magistrate in 1832.'
]
|
python
|
# Copyright (c) ZenML GmbH 2021. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing
# permissions and limitations under the License.
from typing import TYPE_CHECKING, Any, ClassVar, Dict, Type
from zenml.logger import get_logger
logger = get_logger(__name__)
if TYPE_CHECKING:
from zenml.materializers.base_materializer import BaseMaterializer
class SpecMaterializerRegistry(object):
"""Matches spec of a step to a materializer."""
def __init__(self):
"""Materializer types registry."""
self.materializer_types: ClassVar[
Dict[str, Type["BaseMaterializer"]]
] = {}
def register_materializer_type(
self, key: str, type_: Type["BaseMaterializer"]
):
"""Registers a new materializer.
Args:
key: Name of input or output parameter.
type_: A BaseMaterializer subclass.
"""
self.materializer_types[key] = type_
logger.debug(f"Registered materializer {type_} for {key}")
def get_materializer_types(
self,
) -> Dict[str, Type["BaseMaterializer"]]:
"""Get all registered materializers."""
return self.materializer_types
def get_single_materializer_type(
self, key: str
) -> Type["BaseMaterializer"]:
"""Gets a single pre-registered materializer type based on `key`."""
if key in self.materializer_types:
return self.materializer_types[key]
logger.debug(
f"Tried to fetch {key} but its not registered. Available keys: "
f"{self.materializer_types.keys()}"
)
def is_registered(self, key: Type[Any]) -> bool:
"""Returns true if key type is registered, else returns False."""
if key in self.materializer_types:
return True
return False
|
python
|
import os
SQLALCHEMY_DATABASE_URI = os.environ.get('FLASK_DATABASE_URI', 'postgres://user:pass@host/db')
SQLALCHEMY_ENGINE_OPTIONS = {'pool_pre_ping':True}
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = b'\xb0\xe2\x16\x16\x15\x16\x16\x16'
|
python
|
# Copyright (c) 2014, 2020, Oracle and/or its affiliates.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2.0, as
# published by the Free Software Foundation.
#
# This program is also distributed with certain software (including
# but not limited to OpenSSL) that is licensed under separate terms,
# as designated in a particular file or component or in included license
# documentation. The authors of MySQL hereby grant you an
# additional permission to link the program and your derivative works
# with the separately licensed software that they have included with
# MySQL.
#
# Without limiting anything contained in the foregoing, this file,
# which is part of MySQL Connector/Python, is also subject to the
# Universal FOSS Exception, version 1.0, a copy of which can be found at
# http://oss.oracle.com/licenses/universal-foss-exception.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License, version 2.0, for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""Implementing support for MySQL Authentication Plugins"""
from base64 import b64encode, b64decode
from hashlib import sha1, sha256
import hmac
import logging
import struct
from uuid import uuid4
from . import errors
from .catch23 import PY2, isstr, UNICODE_TYPES, STRING_TYPES
from .utils import (normalize_unicode_string as norm_ustr,
validate_normalized_unicode_string as valid_norm)
_LOGGER = logging.getLogger(__name__)
class BaseAuthPlugin(object):
"""Base class for authentication plugins
Classes inheriting from BaseAuthPlugin should implement the method
prepare_password(). When instantiating, auth_data argument is
required. The username, password and database are optional. The
ssl_enabled argument can be used to tell the plugin whether SSL is
active or not.
The method auth_response() method is used to retrieve the password
which was prepared by prepare_password().
"""
requires_ssl = False
plugin_name = ''
def __init__(self, auth_data, username=None, password=None, database=None,
ssl_enabled=False):
"""Initialization"""
self._auth_data = auth_data
self._username = username
self._password = password
self._database = database
self._ssl_enabled = ssl_enabled
def prepare_password(self):
"""Prepares and returns password to be send to MySQL
This method needs to be implemented by classes inheriting from
this class. It is used by the auth_response() method.
Raises NotImplementedError.
"""
raise NotImplementedError
def auth_response(self):
"""Returns the prepared password to send to MySQL
Raises InterfaceError on errors. For example, when SSL is required
by not enabled.
Returns str
"""
if self.requires_ssl and not self._ssl_enabled:
raise errors.InterfaceError("{name} requires SSL".format(
name=self.plugin_name))
return self.prepare_password()
class MySQLNativePasswordAuthPlugin(BaseAuthPlugin):
"""Class implementing the MySQL Native Password authentication plugin"""
requires_ssl = False
plugin_name = 'mysql_native_password'
def prepare_password(self):
"""Prepares and returns password as native MySQL 4.1+ password"""
if not self._auth_data:
raise errors.InterfaceError("Missing authentication data (seed)")
if not self._password:
return b''
password = self._password
if isstr(self._password):
password = self._password.encode('utf-8')
else:
password = self._password
if PY2:
password = buffer(password) # pylint: disable=E0602
try:
auth_data = buffer(self._auth_data) # pylint: disable=E0602
except TypeError:
raise errors.InterfaceError("Authentication data incorrect")
else:
password = password
auth_data = self._auth_data
hash4 = None
try:
hash1 = sha1(password).digest()
hash2 = sha1(hash1).digest()
hash3 = sha1(auth_data + hash2).digest()
if PY2:
xored = [ord(h1) ^ ord(h3) for (h1, h3) in zip(hash1, hash3)]
else:
xored = [h1 ^ h3 for (h1, h3) in zip(hash1, hash3)]
hash4 = struct.pack('20B', *xored)
except Exception as exc:
raise errors.InterfaceError(
"Failed scrambling password; {0}".format(exc))
return hash4
class MySQLClearPasswordAuthPlugin(BaseAuthPlugin):
"""Class implementing the MySQL Clear Password authentication plugin"""
requires_ssl = True
plugin_name = 'mysql_clear_password'
def prepare_password(self):
"""Returns password as as clear text"""
if not self._password:
return b'\x00'
password = self._password
if PY2:
if isinstance(password, unicode): # pylint: disable=E0602
password = password.encode('utf8')
elif isinstance(password, str):
password = password.encode('utf8')
return password + b'\x00'
class MySQLSHA256PasswordAuthPlugin(BaseAuthPlugin):
"""Class implementing the MySQL SHA256 authentication plugin
Note that encrypting using RSA is not supported since the Python
Standard Library does not provide this OpenSSL functionality.
"""
requires_ssl = True
plugin_name = 'sha256_password'
def prepare_password(self):
"""Returns password as as clear text"""
if not self._password:
return b'\x00'
password = self._password
if PY2:
if isinstance(password, unicode): # pylint: disable=E0602
password = password.encode('utf8')
elif isinstance(password, str):
password = password.encode('utf8')
return password + b'\x00'
class MySQLCachingSHA2PasswordAuthPlugin(BaseAuthPlugin):
"""Class implementing the MySQL caching_sha2_password authentication plugin
Note that encrypting using RSA is not supported since the Python
Standard Library does not provide this OpenSSL functionality.
"""
requires_ssl = False
plugin_name = 'caching_sha2_password'
perform_full_authentication = 4
fast_auth_success = 3
def _scramble(self):
""" Returns a scramble of the password using a Nonce sent by the
server.
The scramble is of the form:
XOR(SHA2(password), SHA2(SHA2(SHA2(password)), Nonce))
"""
if not self._auth_data:
raise errors.InterfaceError("Missing authentication data (seed)")
if not self._password:
return b''
password = self._password.encode('utf-8') \
if isinstance(self._password, UNICODE_TYPES) else self._password
if PY2:
password = buffer(password) # pylint: disable=E0602
try:
auth_data = buffer(self._auth_data) # pylint: disable=E0602
except TypeError:
raise errors.InterfaceError("Authentication data incorrect")
else:
password = password
auth_data = self._auth_data
hash1 = sha256(password).digest()
hash2 = sha256()
hash2.update(sha256(hash1).digest())
hash2.update(auth_data)
hash2 = hash2.digest()
if PY2:
xored = [ord(h1) ^ ord(h2) for (h1, h2) in zip(hash1, hash2)]
else:
xored = [h1 ^ h2 for (h1, h2) in zip(hash1, hash2)]
hash3 = struct.pack('32B', *xored)
return hash3
def prepare_password(self):
if len(self._auth_data) > 1:
return self._scramble()
elif self._auth_data[0] == self.perform_full_authentication:
return self._full_authentication()
return None
def _full_authentication(self):
"""Returns password as as clear text"""
if not self._ssl_enabled:
raise errors.InterfaceError("{name} requires SSL".format(
name=self.plugin_name))
if not self._password:
return b'\x00'
password = self._password
if PY2:
if isinstance(password, UNICODE_TYPES): # pylint: disable=E0602
password = password.encode('utf8')
elif isinstance(password, str):
password = password.encode('utf8')
return password + b'\x00'
class MySQLLdapSaslPasswordAuthPlugin(BaseAuthPlugin):
"""Class implementing the MySQL ldap sasl authentication plugin.
The MySQL's ldap sasl authentication plugin support two authentication
methods SCRAM-SHA-1 and GSSAPI (using Kerberos). This implementation only
support SCRAM-SHA-1.
SCRAM-SHA-1
This method requires 2 messages from client and 2 responses from
server.
The first message from client will be generated by prepare_password(),
after receive the response from the server, it is required that this
response is passed back to auth_continue() which will return the
second message from the client. After send this second message to the
server, the second server respond needs to be passed to auth_finalize()
to finish the authentication process.
"""
requires_ssl = False
plugin_name = 'authentication_ldap_sasl_client'
def_digest_mode = sha1
client_nonce = None
client_salt = None
server_salt = None
iterations = 0
server_auth_var = None
def _xor(self, bytes1, bytes2):
if PY2:
xor = [ord(b1) ^ ord(b2) for b1, b2 in zip(bytes1, bytes2)]
xor = b"".join([chr(i) for i in xor])
return xor
else:
return bytes([b1 ^ b2 for b1, b2 in zip(bytes1, bytes2)])
def _hmac(self, password, salt):
digest_maker = hmac.new(password, salt, self.def_digest_mode)
return digest_maker.digest()
def _hi(self, password, salt, count):
"""Prepares Hi
Hi(password, salt, iterations) where Hi(p,s,i) is defined as
PBKDF2 (HMAC, p, s, i, output length of H).
"""
pw = password.encode()
hi = self._hmac(pw, salt + b'\x00\x00\x00\x01')
aux = hi
for _ in range(count - 1):
aux = self._hmac(pw, aux)
hi = self._xor(hi, aux)
return hi
def _normalize(self, string):
norm_str = norm_ustr(string)
broken_rule = valid_norm(norm_str)
if broken_rule is not None:
raise errors.InterfaceError("broken_rule: {}".format(broken_rule))
char, rule = broken_rule
raise errors.InterfaceError(
"Unable to normalice character: `{}` in `{}` due to {}"
"".format(char, string, rule))
return norm_str
def _first_message(self):
"""This method generates the first message to the server to start the
The client-first message consists of a gs2-header,
the desired username, and a randomly generated client nonce cnonce.
The first message from the server has the form:
b'n,a=<user_name>,n=<user_name>,r=<client_nonce>
Returns client's first message
"""
cfm_fprnat = "n,a={user_name},n={user_name},r={client_nonce}"
self.client_nonce = str(uuid4()).replace("-", "")
cfm = cfm_fprnat.format(user_name=self._normalize(self._username),
client_nonce=self.client_nonce)
if PY2:
if isinstance(cfm, UNICODE_TYPES): # pylint: disable=E0602
cfm = cfm.encode('utf8')
elif isinstance(cfm, str):
cfm = cfm.encode('utf8')
return cfm
def auth_response(self):
"""This method will prepare the fist message to the server.
Returns bytes to send to the server as the first message.
"""
# We only support SCRAM-SHA-1 authentication method.
_LOGGER.debug("read_method_name_from_server: %s",
self._auth_data.decode())
if self._auth_data != b'SCRAM-SHA-1':
raise errors.InterfaceError(
'The sasl authentication method "{}" requested from the server '
'is not supported. Only "{}" is supported'.format(
self._auth_data, "SCRAM-SHA-1"))
return self._first_message()
def _second_message(self):
"""This method generates the second message to the server
Second message consist on the concatenation of the client and the
server nonce, and cproof.
c=<n,a=<user_name>>,r=<server_nonce>,p=<client_proof>
where:
<client_proof>: xor(<client_key>, <client_signature>)
<client_key>: hmac(salted_password, b"Client Key")
<client_signature>: hmac(<stored_key>, <auth_msg>)
<stored_key>: h(<client_key>)
<auth_msg>: <client_first_no_header>,<servers_first>,
c=<client_header>,r=<server_nonce>
<client_first_no_header>: n=<username>r=<client_nonce>
"""
if not self._auth_data:
raise errors.InterfaceError("Missing authentication data (seed)")
passw = self._normalize(self._password)
salted_password = self._hi(passw,
b64decode(self.server_salt),
self.iterations)
_LOGGER.debug("salted_password: %s",
b64encode(salted_password).decode())
client_key = self._hmac(salted_password, b"Client Key")
_LOGGER.debug("client_key: %s", b64encode(client_key).decode())
stored_key = self.def_digest_mode(client_key).digest()
_LOGGER.debug("stored_key: %s", b64encode(stored_key).decode())
server_key = self._hmac(salted_password, b"Server Key")
_LOGGER.debug("server_key: %s", b64encode(server_key).decode())
client_first_no_header = ",".join([
"n={}".format(self._normalize(self._username)),
"r={}".format(self.client_nonce)])
_LOGGER.debug("client_first_no_header: %s", client_first_no_header)
auth_msg = ','.join([
client_first_no_header,
self.servers_first,
"c={}".format(b64encode("n,a={},".format(
self._normalize(self._username)).encode()).decode()),
"r={}".format(self.server_nonce)])
_LOGGER.debug("auth_msg: %s", auth_msg)
client_signature = self._hmac(stored_key, auth_msg.encode())
_LOGGER.debug("client_signature: %s",
b64encode(client_signature).decode())
client_proof = self._xor(client_key, client_signature)
_LOGGER.debug("client_proof: %s", b64encode(client_proof).decode())
self.server_auth_var = b64encode(
self._hmac(server_key, auth_msg.encode())).decode()
_LOGGER.debug("server_auth_var: %s", self.server_auth_var)
client_header = b64encode(
"n,a={},".format(self._normalize(self._username)).encode()).decode()
msg = ",".join(["c={}".format(client_header),
"r={}".format(self.server_nonce),
"p={}".format(b64encode(client_proof).decode())])
_LOGGER.debug("second_message: %s", msg)
return msg.encode()
def _validate_first_reponse(self, servers_first):
"""Validates first message from the server.
Extracts the server's salt and iterations from the servers 1st response.
First message from the server is in the form:
<server_salt>,i=<iterations>
"""
self.servers_first = servers_first
if not servers_first or not isinstance(servers_first, STRING_TYPES):
raise errors.InterfaceError("Unexpected server message: {}"
"".format(servers_first))
try:
r_server_nonce, s_salt, i_counter = servers_first.split(",")
except ValueError:
raise errors.InterfaceError("Unexpected server message: {}"
"".format(servers_first))
if not r_server_nonce.startswith("r=") or \
not s_salt.startswith("s=") or \
not i_counter.startswith("i="):
raise errors.InterfaceError("Incomplete reponse from the server: {}"
"".format(servers_first))
if self.client_nonce in r_server_nonce:
self.server_nonce = r_server_nonce[2:]
_LOGGER.debug("server_nonce: %s", self.server_nonce)
else:
raise errors.InterfaceError("Unable to authenticate response: "
"response not well formed {}"
"".format(servers_first))
self.server_salt = s_salt[2:]
_LOGGER.debug("server_salt: %s length: %s", self.server_salt,
len(self.server_salt))
try:
i_counter = i_counter[2:]
_LOGGER.debug("iterations: {}".format(i_counter))
self.iterations = int(i_counter)
except:
raise errors.InterfaceError("Unable to authenticate: iterations "
"not found {}".format(servers_first))
def auth_continue(self, servers_first_response):
"""return the second message from the client.
Returns bytes to send to the server as the second message.
"""
self._validate_first_reponse(servers_first_response)
return self._second_message()
def _validate_second_reponse(self, servers_second):
"""Validates second message from the server.
The client and the server prove to each other they have the same Auth
variable.
The second message from the server consist of the server's proof:
server_proof = HMAC(<server_key>, <auth_msg>)
where:
<server_key>: hmac(<salted_password>, b"Server Key")
<auth_msg>: <client_first_no_header>,<servers_first>,
c=<client_header>,r=<server_nonce>
Our server_proof must be equal to the Auth variable send on this second
response.
"""
if not servers_second or not isinstance(servers_second, bytearray) or \
len(servers_second)<=2 or not servers_second.startswith(b"v="):
raise errors.InterfaceError("The server's proof is not well formated.")
server_var = servers_second[2:].decode()
_LOGGER.debug("server auth variable: %s", server_var)
return self.server_auth_var == server_var
def auth_finalize(self, servers_second_response):
"""finalize the authentication process.
Raises errors.InterfaceError if the ervers_second_response is invalid.
Returns True in succesfull authentication False otherwise.
"""
if not self._validate_second_reponse(servers_second_response):
raise errors.InterfaceError("Authentication failed: Unable to "
"proof server identity.")
return True
def get_auth_plugin(plugin_name):
"""Return authentication class based on plugin name
This function returns the class for the authentication plugin plugin_name.
The returned class is a subclass of BaseAuthPlugin.
Raises errors.NotSupportedError when plugin_name is not supported.
Returns subclass of BaseAuthPlugin.
"""
for authclass in BaseAuthPlugin.__subclasses__(): # pylint: disable=E1101
if authclass.plugin_name == plugin_name:
return authclass
raise errors.NotSupportedError(
"Authentication plugin '{0}' is not supported".format(plugin_name))
|
python
|
from target import TargetType
import os
import re
import cv2
import time
import subprocess
import numpy as np
TARGET_DIR = './assets/'
TMP_DIR = './tmp/'
SIMILAR = {
'1': ['i', 'I', 'l', '|', ':', '!', '/', '\\'],
'2': ['z', 'Z'],
'3': [],
'4': [],
'5': ['s', 'S'],
'6': [],
'7': [],
'8': ['&'],
'9': [],
'0': ['o', 'O', 'c', 'C', 'D']
}
class UIMatcher:
@staticmethod
def match(screen, target: TargetType):
"""
在指定快照中确定货物的屏幕位置。
"""
# 获取对应货物的图片。
# 有个要点:通过截屏制作货物图片时,请在快照为实际大小的模式下截屏。
template = cv2.imread(target.value)
# 获取货物图片的宽高。
th, tw = template.shape[:2]
# 调用 OpenCV 模板匹配。
res = cv2.matchTemplate(screen, template, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
rank = max_val
# 矩形左上角的位置。
tl = max_loc
# 阈值判断。
if rank < 0.82:
return None
# 这里,我随机加入了数字(15),用于补偿匹配值和真实位置的差异。
return tl[0] + tw / 2 + 15, tl[1] + th / 2 + 15, rank
@staticmethod
def read(filepath: str):
"""
工具函数,用于读取图片。
"""
return cv2.imread(filepath)
@staticmethod
def write(image):
"""
工具函数,用于读取图片。
"""
ts = str(int(time.time()))
return cv2.imwrite(f'{TARGET_DIR}{ts}.jpg', image)
@staticmethod
def image_to_txt(image, cleanup=False, plus=''):
# cleanup为True则识别完成后删除生成的文本文件
# plus参数为给tesseract的附加高级参数
image_url = f'{TMP_DIR}tmp.jpg'
txt_name = f'{TMP_DIR}tmp'
txt_url = f'{txt_name}.txt'
if not os.path.exists(TMP_DIR): os.mkdir(TMP_DIR)
cv2.imwrite(image_url, image)
subprocess.check_output('tesseract --dpi 72 ' + image_url + ' ' +
txt_name + ' ' + plus, shell=True) # 生成同名txt文件
text = ''
with open(txt_url, 'r') as f:
text = f.read().strip()
if cleanup:
os.remove(txt_url)
os.remove(image_url)
return text
@staticmethod
def normalize_txt(txt: str):
for key, sim_list in SIMILAR.items():
for sim in sim_list:
txt = txt.replace(sim, key)
txt = re.sub(r'\D', '', txt)
return txt
@staticmethod
def cut(image, left_up, len_width=(190, 50)):
sx = left_up[0]
sy = left_up[1]
dx = left_up[0] + len_width[0]
dy = left_up[1] + len_width[1]
return image[sy:dy, sx:dx]
@staticmethod
def plain(image):
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
erode = cv2.erode(image, kernel)
dilate = cv2.dilate(erode, kernel)
return dilate
@staticmethod
def fill_color(image):
copy_image = image.copy()
h, w = image.shape[:2]
mask = np.zeros([h + 2, w + 2], np.uint8)
cv2.floodFill(copy_image, mask, (0, 0), (255, 255, 255), (100, 100, 100), (50, 50, 50),
cv2.FLOODFILL_FIXED_RANGE)
return copy_image
@staticmethod
def pre(image):
image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
lower_blue = np.array([103, 43, 46])
upper_blue = np.array([103, 255, 255])
image = cv2.inRange(image, lower_blue, upper_blue)
return image
@staticmethod
def pre_building_panel(image):
image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
mask_orange = cv2.inRange(image, (10, 40, 40), (40, 255, 255))
mask_blue = cv2.inRange(image, (80, 40, 40), (140, 255, 255))
image = cv2.bitwise_or(mask_orange, mask_blue)
return image
|
python
|
from horse import Horse
import random
import os
money = 100
colours = [
"red",
"blue",
"yellow",
"pink",
"orange",
]
def race_horses(horses):
return random.choice(horses)
while money > 0:
print(f"Welcome to the race! You have £{money:.2f}. Your horses are: ")
horses = [Horse.random(colour) for colour in colours]
for number, horse in enumerate(horses):
print(f"{number} - {horse} - {horse.info()}")
which_horse = int(input("What horse do you want to gamble on?"))
which_howmuch = float(input("How much do you want to throw away?"))
money = round(money - which_howmuch, 2)
winner = race_horses(horses)
os.system('clear')
print(f"You bet on {horses[which_horse].name}, the winner is {winner.name}")
if horses[which_horse] == winner:
print("Your horse won the race!")
winnings = round(which_howmuch + (which_howmuch * winner.odds),2)
money = round(money + winnings,2)
print(f"The odds were {horses[which_horse].odds}, and you bet £{which_howmuch:.2f}"
f", so you win £{winnings:.2f}")
if horses[which_horse] != winner:
print("Better luck next time, loser!")
print (f"You have no money!")
|
python
|
"""
Django settings for sandbox project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import sys
# sys.path.append()
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
sys.path.append(os.path.dirname(BASE_DIR))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "53(upox#u=f-0#5ue!)owq&-h#u)7z(z-nel&#(*tqhr@e3-u9"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.sites",
"django.contrib.messages",
"django.contrib.staticfiles",
"testapp",
"django_pesapal",
)
MIDDLEWARE_CLASSES = (
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
)
ROOT_URLCONF = "sandbox.urls"
WSGI_APPLICATION = "sandbox.wsgi.application"
# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": os.path.join(BASE_DIR, "db.sqlite3"),
}
}
# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/dev/howto/static-files/
STATIC_URL = "/static/"
# Pesapal API configuration
# Obtain test keys by creating a merchant account here http://demo.pesapal.com/
TEMPLATES = [
{
# See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATES-BACKEND
"BACKEND": "django.template.backends.django.DjangoTemplates",
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs
"DIRS": [os.path.join(BASE_DIR, "templates")],
"OPTIONS": {
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug
"debug": DEBUG,
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders
# https://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types
"loaders": [
"django.template.loaders.filesystem.Loader",
"django.template.loaders.app_directories.Loader",
],
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.template.context_processors.i18n",
"django.template.context_processors.media",
"django.template.context_processors.static",
"django.template.context_processors.tz",
"django.contrib.messages.context_processors.messages",
],
},
}
]
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"handlers": {"console": {"level": "DEBUG", "class": "logging.StreamHandler"}},
"loggers": {
"django_pesapal": {"handlers": ["console"], "level": "DEBUG", "propagate": True}
},
}
PESAPAL_DEMO = True
PESAPAL_OAUTH_CALLBACK_URL = "transaction_completed"
PESAPAL_OAUTH_SIGNATURE_METHOD = "SignatureMethod_HMAC_SHA1"
PESAPAL_TRANSACTION_DEFAULT_REDIRECT_URL = "payment"
PESAPAL_DEMO = True
PESAPAL_OAUTH_CALLBACK_URL = "transaction_completed"
PESAPAL_OAUTH_SIGNATURE_METHOD = "SignatureMethod_HMAC_SHA1"
PESAPAL_TRANSACTION_FAILED_REDIRECT_URL = ""
PESAPAL_ITEM_DESCRIPTION = False
PESAPAL_TRANSACTION_MODEL = "django_pesapal.Transaction"
PESAPAL_CONSUMER_KEY = "INSERT_YOUR_KEY"
PESAPAL_CONSUMER_SECRET = "INSERT_YOUR_SECRET"
# Override pesapal keys
try:
from local_config import *
except ImportError:
pass
|
python
|
from django.contrib.auth import password_validation, get_user_model
from rest_framework import serializers
from rest_framework.generics import get_object_or_404
from rest_framework.exceptions import ValidationError
from rest_framework.validators import UniqueValidator
from rest_framework_simplejwt.exceptions import InvalidToken, TokenError
from .profile import ProfileSerializer
from eworkshop.tasks.tasks import request_reset_password_email
from ..tokens import EmailToken
from ..models import Profile
Staff = get_user_model()
class ListStaffSerializer(serializers.ModelSerializer):
class Meta:
model = Staff
fields = ('id', 'first_name', 'last_name', 'username', 'is_active')
class ShowStaffSerializer(serializers.ModelSerializer):
username = serializers.CharField(
min_length=4,
max_length=20,
validators=[UniqueValidator(queryset=Staff.objects.all())])
profile = ProfileSerializer(read_only=True)
class Meta:
model = Staff
fields = (
'id',
'username',
'first_name',
'last_name',
'email',
'phone_number',
'cellphone_number',
'address',
'ci',
'profile',
'groups'
)
def create(self, validated_data):
instance = super().create(validated_data)
instance.set_password('1234')
instance.save()
Profile.objects.create(staff=instance)
return instance
class PasswordSerializer(serializers.Serializer):
password = serializers.CharField(
max_length=64, min_length=8, required=True)
password_confirmation = serializers.CharField(
max_length=64, min_length=8, required=True)
def validate(self, data):
if data['password'] != data['password_confirmation']:
raise serializers.ValidationError("Password does not match.")
password_validation.validate_password(data['password'])
return data
def save(self):
password = self.validated_data['password']
self.instance.set_password(password)
self.instance.change_password()
self.instance.save()
class StaffResetPasswordConfirm(PasswordSerializer):
token = serializers.CharField(required=True)
def validate_token(self, token):
try:
self.token_instance(token)
except TokenError as e:
raise InvalidToken(e.args[0])
return token
def token_instance(self, token):
return EmailToken(token=token)
def get_token_user(self):
user_id = self.token_instance(
self.validated_data['token']).payload['user_id']
return get_object_or_404(Staff, **{'id': user_id, 'is_active': True})
def save(self):
self.instance = self.get_token_user()
super().save()
class StaffChangePasswordSerializer(PasswordSerializer):
old_password = serializers.CharField()
def validate_old_password(self, value):
invalid_password_conditions = (
self.instance,
not self.instance.check_password(value)
)
if all(invalid_password_conditions):
msg = "Your old password was entered incorrectly. Please enter it again."
raise serializers.ValidationError(msg)
return value
class StaffResetPasswordSerializer(serializers.Serializer):
email = serializers.EmailField(required=True)
@classmethod
def get_token(cls, user):
return EmailToken.for_user(user)
def validate_email(self, value):
query = Staff.objects.filter(is_active=True).filter(
profile__is_password_changed=True).filter(email__iexact=value)
if not query:
return ValidationError('There is no active user associated with this e-mail address or the password can not be changed')
else:
self.user = query[0]
def save(self):
token = self.get_token(self.user)
request_reset_password_email.delay(self.user.email, str(token))
|
python
|
import math
import cmath
import cairo
from random import randint
IMAGE_SIZE = (5000, 5000)
NUM_SUBDIVISIONS = 6
def chooseRatio():
return randint(0, 6)
colors = [(1.0, 0.35, 0.35), (0.4, 0.4, 1.0), (0.1, 1.0, 0.2), (0.7, 0.1, 0.8)]
def chooseColor():
return colors[randint(0, len(colors) - 1)]
Ratio = chooseRatio()*0.1 + 1.4
def subdivide(triangles):
result = []
for color, A, B, C in triangles:
if color == 0:
# Subdivide red triangle
P = A + (B - A) / Ratio
result += [(0, C, P, B), (1, P, C, A)]
else:
# Subdivide blue triangle
Q = B + (A - B) / Ratio
R = B + (C - B) / Ratio
result += [(1, R, C, A), (1, Q, R, B), (0, R, Q, A)]
return result
# Create wheel of red triangles around the origin
triangles = []
for i in xrange(10):
B = cmath.rect(1, (2*i - 1) * math.pi / 10)
C = cmath.rect(1, (2*i + 1) * math.pi / 10)
if i % 2 == 0:
B, C = C, B # Make sure to mirror every second triangle
triangles.append((0, 0j, B, C))
# Perform subdivisions
for i in xrange(NUM_SUBDIVISIONS):
triangles = subdivide(triangles)
# Prepare cairo surface
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, IMAGE_SIZE[0], IMAGE_SIZE[1])
cr = cairo.Context(surface)
cr.translate(IMAGE_SIZE[0] / 2.0, IMAGE_SIZE[1] / 2.0)
wheelRadius = 1.2 * math.sqrt((IMAGE_SIZE[0] / 2.0) ** 2 + (IMAGE_SIZE[1] / 2.0) ** 2)
cr.scale(wheelRadius, wheelRadius)
# Draw first triangles
for color, A, B, C in triangles:
if color == 0:
cr.move_to(A.real, A.imag)
cr.line_to(B.real, B.imag)
cr.line_to(C.real, C.imag)
cr.close_path()
chosen = chooseColor()
colors.remove(chosen)
cr.set_source_rgb(*chosen)
cr.fill()
# Draw second triangles
for color, A, B, C in triangles:
if color == 1:
cr.move_to(A.real, A.imag)
cr.line_to(B.real, B.imag)
cr.line_to(C.real, C.imag)
cr.close_path()
chosen = chooseColor()
colors.remove(chosen)
cr.set_source_rgb(*chosen)
cr.fill()
# Determine line width from size of first triangle
color, A, B, C = triangles[0]
cr.set_line_width(abs(B - A) / 10.0)
cr.set_line_join(cairo.LINE_JOIN_ROUND)
# Draw outlines
for color, A, B, C in triangles:
cr.move_to(C.real, C.imag)
cr.line_to(A.real, A.imag)
cr.line_to(B.real, B.imag)
cr.set_source_rgb(0.2, 0.2, 0.2)
cr.stroke()
# Save to PNG
surface.write_to_png('penrose.png')
|
python
|
from preprocess.load_data.data_loader import load_hotel_reserve
customer_tb, hotel_tb, reserve_tb = load_hotel_reserve()
# 本书刊登内容如下
# 将iloc函数二维数组的第一维度指定为“:”,提取所有行
# 将iloc函数二维数组的第二维度指定为由列号组成的数组,提取相应的列
# 0:6和[0, 1, 2, 3, 4, 5]表示相同的意思
reserve_tb.iloc[:, 0:6]
|
python
|
"""
@authors:
# =============================================================================
Information:
The purpose of this script is to serve as the main code for the user.
Use the user's guide that still has not been written to find out how to use
this tool.
Use your python skills to understand how this tool has been coded.
Change your variables, do your maths, and do your science.
Let's go to space, y'all
Process :
1. Generate the acceleration values (from orbit data or raw simulation)
using GH_generate
2. Solve for the coefficients using the functions in this script
using GH_solve
3. Generate a Geoid map from solved coefficients
using GH_displayCoef
4. Compare Geoids or coefficients
using GH_displayCoef
5. Plot Satellite positions and accelerations in space
using GH_displaySat
todo: replace "acc" by "geopot" lol
future stuff:
earth rotation
approx drag and shit (solar radiation, tidal effects)
Instruction after executing the code : here are the commands to execute on the terminal :
- A = getMat(n), with n a natural integer : we advise n=7.
- res = np.linalg.lstsq(A, acc)
- acc_solved = A@res[0] : acc_solved represents the vector of the solved acceleration in spherical coordinates.
Then acc_solved = [acc_rad(0),acc_theta(0),acc_phi(0),...]. Then plot the result.
If you want to plot for example only the radial acceleration, execute this command :
- plt.plot([acc_solved[3*i] for i in range(len(acc_solved)//3)])
Here is the link to the files we use for this code : https://drive.google.com/drive/folders/1XgGn2QoFGJ-u_m4aoL2No-PmxIRraLg6?fbclid=IwAR04xPEqi1h-eGWR_inJfHa4dp8dzG7NPlgHcNKYfz0OT1v0uU7ADew9VR4
# =============================================================================
"""
import numpy as np
import matplotlib.pyplot as plt
from time import gmtime, strftime
import GH_import as imp
import GH_convert as conv
import GH_generate as gen
import GH_solve as solv
import GH_displayGeoid as dgeo
import GH_displaySat as dsat
import GH_export as exp
#import GH_displayTopo as dtopo
#import GH_terminal as term
#import GH_harmonics as harm
#import GH_geoMath as gmath
#import GH_earthMap as emap
from GH_import import data_path #= "../data"
file_name = "Polar_400km_EarthFixed_15jours_5sec.e"
lmax = 10
Pos,Vit, t = imp.Fetch_Pos_Vit(file_name, 5, spherical=False)
Pos_sphere = conv.cart2sphA(Pos)
acc = gen.Gen_Acc_2(Pos,Vit,t)
acc = conv.cart2sphA(acc)
acc = conv.Make_Line_acc(acc)
getMat = lambda lmax : solv.Get_PotGradMatrix2(lmax, Pos_sphere)
hc, hs = imp.Fetch_Coef()
hc = hc.flatten()
hc = np.sort(hc)
|
python
|
from django.conf.urls import url, include
#from django.contrib import admin
#from django.urls import path
from usuario.views import registar_usuario,editar_usuario,eliminar_usuario
app_name = 'usuario'
urlpatterns = [
url(r'^nuevo$',registar_usuario.as_view() , name="new"),
url(r'^edit_book/(?P<pk>\d+)/$',editar_usuario.as_view() , name="edit"),
url(r'^delete_book/(?P<pk>\d+)/$',eliminar_usuario.as_view() , name="delete"),
]
|
python
|
from hashlib import md5
from app import app, db
import sys
if sys.version_info >= (3, 0):
enable_search = False
else:
enable_search = True
import flask_whooshalchemy as whooshalchemy
# This is a direct translation of the association table.
# use the lower level APIs in flask-sqlalchemy to create the table without an associated model.
followers = db.Table(
'followers',
db.Column('follower_id', db.Integer, db.ForeignKey('user.id')),
db.Column('followed_id', db.Integer, db.ForeignKey('user.id'))
)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
nickname = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
posts = db.relationship('Post', backref='author', lazy='dynamic')
about_me = db.Column(db.String(140))
last_seen = db.Column(db.DateTime)
followed = db.relationship('User',
secondary=followers,
primaryjoin=(followers.c.follower_id == id),
secondaryjoin=(followers.c.followed_id == id),
backref=db.backref('followers', lazy='dynamic'),
lazy='dynamic')
@property
def is_authenticated(self):
return True
@property
def is_active(self):
return True
@property
def is_anonymous(self):
return False
def get_id(self):
try:
return unicode(self.id) # python 2
except NameError:
return str(self.id) # python 3
def avatar(self, size):
return 'http://www.gravatar.com/avatar/%s?d=mm&s=%d' % \
(md5(self.email.encode('utf-8')).hexdigest(), size)
def follow(self, user):
# When an object is returned, this object has to be added to
# the database session and committed.
if not self.is_following(user):
self.followed.append(user)
# return an object when they succeed or None when they fail.
return self
def unfollow(self, user):
if self.is_following(user):
self.followed.remove(user)
return self
'''
There are several methods in the query object that trigger the query execution.
We've seen that count() runs the query and returns the number of results
(throwing the actual results away).
We have also used first() to return the first result and throw away the rest, if any.
In this test we are using the all() method to get an array with all the results.
'''
def is_following(self, user):
return self.followed.filter(followers.c.followed_id == user.id).count() > 0
# This method returns a query object, not the results.
# This is similar to how relationships with lazy = 'dynamic' work.
def followed_posts(self):
return Post.query.join(followers, (followers.c.followed_id == Post.user_id))\
.filter(followers.c.follower_id == self.id)\
.order_by(Post.timestamp.desc())
# We can use without an instance of the Class.
@staticmethod
def make_unique_nickname(nickname):
if User.query.filter_by(nickname=nickname).first() is None:
return nickname
version = 2
while True:
new_nickname = nickname + str(version)
if User.query.filter_by(nickname=new_nickname).first() is None:
break
version += 1
return new_nickname
def __repr__(self):
return '<User %r>' % (self.nickname)
class Post(db.Model):
__searchable__ = ['body']
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.String(140))
timestamp = db.Column(db.DateTime)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
def __repr__(self):
return '<Post %r>' % (self.body)
if enable_search:
whooshalchemy.whoosh_index(app, Post)
|
python
|
import numpy as np
import pickle
from collections import defaultdict
import spacy
from spacy.symbols import nsubj, VERB
from models import load_models, generate
import argparse
import torch
nlp = spacy.load("en")
def get_subj_verb(sent):
"Given a parsed sentence, find subject, verb, and subject modifiers."
sub = set()
verbs = set()
mod = set()
for i, possible_subject in enumerate(sent):
if possible_subject.dep == nsubj and possible_subject.head.pos == VERB:
if possible_subject.head.head.pos == VERB:
verbs.add(str(possible_subject.head.head))
else:
verbs.add(str(possible_subject.head))
sub.add(str(possible_subject))
c = list(possible_subject.children)
for w in c:
mod.add(str(w))
if not c:
mod.add(str(sent[i-1]) if i != 0 else "NONE")
return verbs, sub, mod
def featurize(sent):
"Given a sentence construct a feature rep"
verb, sub, mod = get_subj_verb(sent)
d = {}
def add(d, pre, ls):
for l in ls:
d[pre + "_" + l] = 1
add(d, "VERB", list(verb)[:1])
add(d, "MOD", list(mod))
add(d, "NOUN", list(sub)[:1])
return d
def gen(vec):
"Generate argmax sentence from vector."
return generate(autoencoder, gan_gen, z=torch.FloatTensor(vec).view(1, -1),
vocab=idx2word, sample=False,
maxlen=model_args['maxlen'])
def gen_samples(vec):
"Generate sample sentences from vector."
sentences = []
sentences = generate(autoencoder, gan_gen, z=torch.FloatTensor(vec)
.view(1, -1).expand(20, vec.shape[0]),
vocab=idx2word, sample=True,
maxlen=model_args['maxlen'])[0]
return sentences
def switch(vec, mat, rev, f1, f2):
"Update vec away from feature1 and towards feature2."
means = []
m2 = np.mean(mat[list(rev[f2])], axis=0)
for f in f1:
if list(rev[f]):
means.append(np.mean(mat[list(rev[f])], axis=0))
m1 = np.mean(means) if f1 else np.zeros(m2.shape)
val = vec + (m2 - m1)
return val, vec - m1
def alter(args):
sents, features, rev, mat = pickle.load(open(args.dump, "br"))
mat = mat.numpy()
# Find examples to alter toward new feat.
new_feat = args.alter
pre = new_feat.split("_")[0]
word = new_feat.split("_")[1]
for i in range(args.nsent):
vec = mat[i]
for j in range(10):
sent = gen(vec)[0]
f = featurize(nlp(sent))
print("Sent ", j, ": \t ", sent, "\t")
if word in sent:
break
# Compute the feature distribution associated with this point.
samples = gen_samples(vec)
feats = [f] * 50
for s in samples:
feats.append(featurize(nlp(s)))
mod = []
for feat in feats:
for feature in feat:
if feature.startswith(pre):
mod.append(feature)
# Try to updated the vector towards new_feat
update, temp = switch(vec, mat, rev, mod, new_feat)
if j == 0:
orig = temp
# Interpolate with original.
vec = 0.2 * orig + 0.8 * update
print()
print()
def dump_samples(args):
"Construct a large number of samples with features and dump to file."
all_features = []
all_sents = []
batches = args.nbatches
batch = args.batch_size
samples = 1
total = batches * batch * samples
all_zs = torch.FloatTensor(total, model_args['z_size'])
rev = defaultdict(set)
for j in range(batches):
print("%d / %d batches " % (j, batches))
noise = torch.ones(batch, model_args['z_size'])
noise.normal_()
noise = noise.view(batch, 1, model_args['z_size'])\
.expand(batch, samples,
model_args['z_size']).contiguous()\
.view(batch*samples,
model_args['z_size'])
sentences = generate(autoencoder, gan_gen, z=noise,
vocab=idx2word, sample=True,
maxlen=model_args['maxlen'])
for i in range(batch * samples):
k = len(all_features)
nlp_sent = nlp(sentences[i])
feats = featurize(nlp_sent)
all_sents.append(sentences[i])
all_features.append(feats)
for f in feats:
rev[f].add(k)
all_zs[k] = noise[i]
pickle.dump((all_sents, all_features, rev, all_zs), open(args.dump, "bw"))
def main(args):
if args.mode == 'gen':
dump_samples(args)
elif args.mode == 'alter':
alter(args)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='PyTorch experiment')
parser.add_argument('mode', default='gen',
help='choices [gen, alter]')
parser.add_argument('--load_path', type=str, default='',
help='directory to load models from')
parser.add_argument('--dump', type=str, default="features.pkl",
help='path to sample dump')
parser.add_argument('--nbatches', type=int, default=1000)
parser.add_argument('--batch_size', type=int, default=1000)
parser.add_argument('--alter', type=str, default="")
parser.add_argument('--nsent', type=int, default=100)
args = parser.parse_args()
model_args, idx2word, autoencoder, gan_gen, gan_disc \
= load_models(args.load_path)
main(args)
|
python
|
# HTTP Error Code
# imported necessary library
import tkinter
from tkinter import *
import tkinter as tk
import tkinter.messagebox as mbox
import json
# created main window
window = Tk()
window.geometry("1000x700")
window.title("HTTP Error Code")
# ------------------ this is for adding gif image in the main window of application ---------------------------------------
frameCnt = 3
frames = [PhotoImage(file='Images/front.gif',format = 'gif -index %i' %(i)) for i in range(frameCnt)]
cnt = 0.0
def update(ind):
global cnt
frame = frames[ind]
if(cnt == 1.0):
cnt = 0
cnt = cnt + 0.2
ind += int(cnt)
if ind == frameCnt:
ind = 0
label.configure(image=frame)
window.after(100, update, ind)
label = Label(window)
label.place(x = 170, y = 150)
window.after(0, update, 0)
# --------------------------------------------------------------------
#loaded json data
data1 = json.load(open("code_data.json"))
code = data1["code"]
category = data1["category"]
term = data1["term"]
meaning = data1["meaning"]
# print(len(code))
# print(len(category))
# print(len(term))
# print(len(meaning))
def start_fun():
def get_info():
selected_code = code_var.get()
for i in range(0,len(code)):
if(code[i] == selected_code):
mbox.showinfo(selected_code + " HTTP Code Info", "HTTP Code : " + str(selected_code) + "\n\n1.) Category : " + str(category[i]) + "\n\n2.) Terms : " + str(term[i]) + "\n\n3.) Meanings : " + str(meaning[i]))
f1 = Frame(window, width=1000, height=700)
f1.propagate(0)
f1.pack(side='top')
c1 = Canvas(f1, width=1000, height=700) # blue
c1.pack()
p1 = PhotoImage(file="Images/second.gif")
c1.create_image(50, 120, image=p1, anchor="nw")
w1 = Canvas(window)
w1.p1 = p1
# top label
start1 = tk.Label(f1, text="HTTP ERROR CODE", font=("Arial", 55), fg="magenta") # same way bg
start1.place(x=120, y=10)
# top label
lbl1 = tk.Label(f1, text="Select Error Code : ", font=("Arial", 35), fg="brown") # same way bg
lbl1.place(x=180, y=420)
# creating the drop down menu button for selectng hour
code_var = tk.StringVar()
# as icon size are really small, we defined the following 7 sizes
code_choices = code
code_menu = OptionMenu(window, code_var, *code_choices)
code_menu.config(font=("Arial", 30), bg = "light green", fg = "blue", borderwidth=3)
code_menu["menu"].config(font=("Arial", 15), bg = "light yellow", fg = "blue")
code_menu.place(x=630, y=415)
code_var.set("100") # size 1 is selected as by default, and we can
# created exit button
getb = Button(window, text="GET - INFO", command=get_info, font=("Arial", 25), bg="light green", fg="blue",borderwidth=3, relief="raised")
getb.place(x=120, y=550)
# function for reseting
def reset_fun():
code_var.set("100")
# created exit button
resetb = Button(window, text="RESET", command=reset_fun, font=("Arial", 25), bg="orange", fg="blue",borderwidth=3, relief="raised")
resetb.place(x=460, y=550)
# function for exiting
def exit_fun():
if mbox.askokcancel("Exit", "Do you want to exit?"):
window.destroy()
# created exit button
exitb = Button(window, text="EXIT", command=exit_fun, font=("Arial", 25), bg="red", fg="blue",borderwidth=3, relief="raised")
exitb.place(x=750, y=550)
# top label
start1 = tk.Label(text="HTTP ERROR CODE", font=("Arial", 55), fg="magenta") # same way bg
start1.place(x=120, y=10)
# created exit button
startb = Button(window, text="START", command=start_fun, font=("Arial", 25), bg="light green", fg="blue", borderwidth=3, relief="raised")
startb.place(x=120, y=580)
# function for exiting
def exit_win():
if mbox.askokcancel("Exit", "Do you want to exit?"):
window.destroy()
# created exit button
exitb = Button(window, text="EXIT", command=exit_win, font=("Arial", 25), bg="red", fg="blue", borderwidth=3, relief="raised")
exitb.place(x=750, y=580)
window.protocol("WM_DELETE_WINDOW", exit_win)
window.mainloop()
|
python
|
is_all_upper = lambda t: t.isupper()
|
python
|
from .drm_service import DRMService
from .fairplay_drm_service import FairPlayDRM
from .aes_drm_service import AESDRM
class TSDRMService(DRMService):
MUXING_TYPE_URL = 'ts'
def __init__(self, http_client):
super().__init__(http_client=http_client)
self.FairPlay = FairPlayDRM(http_client=http_client, muxing_type_url=self.MUXING_TYPE_URL)
self.AES = AESDRM(http_client=http_client, muxing_type_url=self.MUXING_TYPE_URL)
|
python
|
#!/usr/bin/python
import yaml
import json
#Reading from YAML file
print "\n***Printing from the YAML file***"
yamlfile = 'yamloutput.yml'
with open (yamlfile) as f:
yamllist = yaml.load(f)
print yamllist
print "\n"
#Reading from JSON file
print "\n***Printing from the JSON file***"
jsonfile = 'jsonoutput.json'
with open (jsonfile) as f:
jsonlist = json.load(f)
print jsonlist
print "\n"
|
python
|
# Copyright 2018 StreamSets Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import pytest
from streamsets.testframework.markers import sdc_min_version
from streamsets.testframework.sdc_models import CustomLib
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
PMML_IRIS_MODEL_PATH = '/resources/resources/pmml_iris_model/iris_rf.pmml'
@pytest.fixture(scope='module')
def sdc_common_hook(args):
def hook(data_collector):
if not args.custom_stage_lib:
pytest.skip('Tensorflow processor tests only run if --custom-stage-lib is passed')
stage_lib_version = [lib.split(',')[1] for lib in args.custom_stage_lib if 'pmml' in lib]
if len(stage_lib_version) == 0:
pytest.skip('Tensorflow processor tests only run if --custom-stage-lib contains pmml')
data_collector.add_stage_lib(CustomLib('streamsets-datacollector-pmml-lib', stage_lib_version[0]))
return hook
@sdc_min_version('3.5.0')
def test_tensorflow_evaluator(sdc_builder, sdc_executor):
"""Test PMML Evaluator processor. The pipeline would look like:
dev_raw_data_source >> pmml_evaluator >> trash
With given raw_data below, PMML Evaluator processor evaluates each record using the
sample Iris classification model.
"""
raw_data = """
{
"petalLength": 6.4,
"petalWidth": 2.8,
"sepalLength": 5.6,
"sepalWidth": 2.2
}
{
"petalLength": 5.0,
"petalWidth": 2.3,
"sepalLength": 3.3,
"sepalWidth": 1.0
}
{
"petalLength": 4.9,
"petalWidth": 2.5,
"sepalLength": 4.5,
"sepalWidth": 1.7
}
{
"petalLength": 4.9,
"petalWidth": 3.1,
"sepalLength": 1.5,
"sepalWidth": 0.1
}
"""
pipeline_builder = sdc_builder.get_pipeline_builder()
dev_raw_data_source = pipeline_builder.add_stage('Dev Raw Data Source')
dev_raw_data_source.set_attributes(data_format='JSON', raw_data=raw_data)
pmml_evaluator = pipeline_builder.add_stage('PMML Evaluator')
pmml_input_configs = [{"pmmlFieldName": "Petal.Length", "fieldName": "/petalLength"},
{"pmmlFieldName": "Petal.Width", "fieldName": "/petalWidth"},
{"pmmlFieldName": "Sepal.Length", "fieldName": "/sepalLength"},
{"pmmlFieldName": "Sepal.Width", "fieldName": "/sepalWidth"}]
pmml_evaluator.set_attributes(input_configs=pmml_input_configs,
model_output_fields=['Predicted_Species',
'Probability_setosa',
'Probability_versicolor',
'Probability_virginica'],
output_field='/output',
saved_model_file_path=PMML_IRIS_MODEL_PATH)
trash = pipeline_builder.add_stage('Trash')
dev_raw_data_source >> pmml_evaluator >> trash
pipeline = pipeline_builder.build('PMML evaluator for IRIS Model')
sdc_executor.add_pipeline(pipeline)
sdc_executor.validate_pipeline(pipeline)
snapshot = sdc_executor.capture_snapshot(pipeline, start_pipeline=True).snapshot
sdc_executor.stop_pipeline(pipeline)
# Assert PMML Model evaluation Output
pmml_output = snapshot[pmml_evaluator.instance_name].output
output_field = pmml_output[0].field['output']
predicted_species_item = output_field['Predicted_Species']
assert predicted_species_item.type == 'STRING'
assert predicted_species_item == 'virginica'
|
python
|
import json
import cv2
import matplotlib.pyplot as plt
import numpy as np
import os
from labelme import utils
from skimage import img_as_ubyte
import PIL.Image
import random
JSON_DIR = 'json'
LABELCOLOR = { # 设定label染色情况
'product': 1,
'product': 2,
'product': 3,
'product': 4,
}
VOCVersion = 'VOC2012'
Path_VOCDevkit = 'VOCDevkit'
Path_VOC = os.path.join(Path_VOCDevkit, VOCVersion)
Path_Annotations = os.path.join(Path_VOCDevkit, 'Annotations')
Path_ImageSets = os.path.join(Path_VOCDevkit, 'ImageSets')
Path_ImageSets_Action = os.path.join(Path_ImageSets, 'Action')
Path_ImageSets_Layout = os.path.join(Path_ImageSets, 'Layout')
Path_ImageSets_Main = os.path.join(Path_ImageSets, 'Main')
Path_ImageSets_Segmentation = os.path.join(Path_ImageSets, 'Segmentation')
Path_ImageSets_Segmentation_train = os.path.join(Path_ImageSets_Segmentation, 'train.txt')
Path_ImageSets_Segmentation_val = os.path.join(Path_ImageSets_Segmentation, 'val.txt')
Path_JPEGImages = os.path.join(Path_VOCDevkit, 'JPEGImages')
Path_SegmentationClass = os.path.join(Path_VOCDevkit, 'SegmentationClass')
Path_SegmentationObject = os.path.join(Path_VOCDevkit, 'SegmentationObject')
def checkdir():
createdir(Path_VOCDevkit)
createdir(Path_VOC)
createdir(Path_Annotations)
createdir(Path_ImageSets)
createdir(Path_ImageSets_Action)
createdir(Path_ImageSets_Layout)
createdir(Path_ImageSets_Main)
createdir(Path_ImageSets_Segmentation)
createdir(Path_JPEGImages)
createdir(Path_SegmentationClass)
createdir(Path_SegmentationObject)
def createdir(path):
if not os.path.exists(path):
os.makedirs(path)
else:
pass
def cvt_one(json_path, save_path_image, save_path_mask, label_color):
# load img and json
data = json.load(open(json_path))
fileName = data['imagePath'][:-4]
img = utils.image.img_b64_to_arr(data['imageData'])
PIL.Image.fromarray(img).save(save_path_image)
lbl, lbl_names = utils.labelme_shapes_to_label(img.shape, data['shapes'])
# get background data
img = np.zeros([img.shape[0], img.shape[1]])
# draw roi
for i in range(len(data['shapes'])):
name = str(data['shapes'][i]['label'])
points = data['shapes'][i]['points']
color = label_color[name]
img = cv2.fillPoly(img, [np.array(points, dtype=int)], color)
plt.imshow(img)
plt.show()
cv2.imwrite(save_path_mask, img)
def devideDataset(ratio):
for folderroot, folderlist, filelist in os.walk(Path_SegmentationClass):
seglist = []
i = 0
while i < len(filelist):
if '.png' in filelist[i]:
seglist.append(filelist[i][:-4])
i += 1
random.shuffle(seglist)
offset = int(ratio * len(seglist))
train_list = seglist[offset:]
val_list = seglist[:offset]
writeTxt(Path_ImageSets_Segmentation_train, train_list)
writeTxt(Path_ImageSets_Segmentation_val, val_list)
def writeTxt(filePath, namelist):
file = open(filePath, 'w+')
file.seek(0)
for name in namelist:
file.write(name + '\n')
file.flush()
file.close()
if __name__ == '__main__':
checkdir()
for folderroot, folderlist, filelist in os.walk(JSON_DIR):
jsonfilelist = []
i = 0
while i < len(filelist):
if '.json' in filelist[i]:
jsonfilelist.append(filelist[i])
i += 1
for i in range(len(jsonfilelist)):
json_path = os.path.join(JSON_DIR, jsonfilelist[i])
save_path_image = os.path.join(Path_JPEGImages, jsonfilelist[i].replace('.json', '.jpg'))
save_path_mask = os.path.join(Path_SegmentationClass, jsonfilelist[i].replace('.json', '.png'))
print('Processing {}'.format(json_path))
cvt_one(json_path, save_path_image, save_path_mask, LABELCOLOR)
devideDataset(0.3)
|
python
|
from setuptools import setup
with open('README.md') as f:
long_description = f.read()
setup(
name='nicebytes',
author='Philipp Ploder',
url='https://github.com/Fylipp/nicebytes',
description='human-readable data quantities',
long_description=long_description,
long_description_content_type='text/markdown',
license='MIT',
py_modules=['nicebytes'],
scripts=['nicebytes', 'nicebytes.py'],
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: MIT License",
"Environment :: Console",
"Intended Audience :: End Users/Desktop",
"Topic :: Utilities",
"Topic :: System"
]
)
|
python
|
# -*- coding: utf-8 -*-
"""
profiling.tracing
~~~~~~~~~~~~~~~~~
Profiles deterministically by :func:`sys.setprofile`.
"""
from __future__ import absolute_import
import sys
import threading
from .. import sortkeys
from ..profiler import Profiler
from ..stats import RecordingStatistics, VoidRecordingStatistics as void
from ..utils import deferral
from ..viewer import StatisticsTable, fmt
from .timers import Timer
__all__ = ['TracingProfiler', 'TracingStatisticsTable']
TIMER_CLASS = Timer
class TracingStatisticsTable(StatisticsTable):
columns = [
('FUNCTION', 'left', ('weight', 1), sortkeys.by_function),
('CALLS', 'right', (6,), sortkeys.by_own_hits),
('OWN', 'right', (6,), sortkeys.by_own_time),
('/CALL', 'right', (6,), sortkeys.by_own_time_per_call),
('%', 'left', (4,), None),
('DEEP', 'right', (6,), sortkeys.by_deep_time),
('/CALL', 'right', (6,), sortkeys.by_deep_time_per_call),
('%', 'left', (4,), None),
]
order = sortkeys.by_deep_time
def make_cells(self, node, stats):
yield fmt.make_stat_text(stats)
yield fmt.make_int_or_na_text(stats.own_hits)
yield fmt.make_time_text(stats.own_time)
yield fmt.make_time_text(stats.own_time_per_call)
yield fmt.make_percent_text(stats.own_time, self.cpu_time)
yield fmt.make_time_text(stats.deep_time)
yield fmt.make_time_text(stats.deep_time_per_call)
yield fmt.make_percent_text(stats.deep_time, self.cpu_time)
class TracingProfiler(Profiler):
"""The tracing profiler."""
table_class = TracingStatisticsTable
#: The CPU timer. Usually it is an instance of :class:`profiling.tracing.
#: timers.Timer`.
timer = None
#: The CPU time of profiling overhead. It's the time spent in
#: :meth:`_profile`.
overhead = 0.0
def __init__(self, top_frames=(), top_codes=(),
upper_frames=(), upper_codes=(), timer=None):
timer = timer or TIMER_CLASS()
if not isinstance(timer, Timer):
raise TypeError('Not a timer instance')
base = super(TracingProfiler, self)
base.__init__(top_frames, top_codes, upper_frames, upper_codes)
self.timer = timer
self._times_entered = {}
def _profile(self, frame, event, arg):
"""The callback function to register by :func:`sys.setprofile`."""
# c = event.startswith('c_')
if event.startswith('c_'):
return
time1 = self.timer()
frames = self.frame_stack(frame)
if frames:
frames.pop()
parent_stats = self.stats
for f in frames:
parent_stats = parent_stats.ensure_child(f.f_code, void)
code = frame.f_code
frame_key = id(frame)
# if c:
# event = event[2:]
# code = mock_code(arg.__name__)
# frame_key = id(arg)
# record
time2 = self.timer()
self.overhead += time2 - time1
if event == 'call':
time = time2 - self.overhead
self.record_entering(time, code, frame_key, parent_stats)
elif event == 'return':
time = time1 - self.overhead
self.record_leaving(time, code, frame_key, parent_stats)
time3 = self.timer()
self.overhead += time3 - time2
def record_entering(self, time, code, frame_key, parent_stats):
"""Entered to a function call."""
stats = parent_stats.ensure_child(code, RecordingStatistics)
self._times_entered[(code, frame_key)] = time
stats.own_hits += 1
def record_leaving(self, time, code, frame_key, parent_stats):
"""Left from a function call."""
try:
stats = parent_stats.get_child(code)
time_entered = self._times_entered.pop((code, frame_key))
except KeyError:
return
time_elapsed = time - time_entered
stats.deep_time += max(0, time_elapsed)
def result(self):
base = super(TracingProfiler, self)
frozen_stats, cpu_time, wall_time = base.result()
return (frozen_stats, cpu_time - self.overhead, wall_time)
def run(self):
if sys.getprofile() is not None:
# NOTE: There's no threading.getprofile().
# The profiling function will be stored at threading._profile_hook
# but it's not documented.
raise RuntimeError('Another profiler already registered')
with deferral() as defer:
self._times_entered.clear()
self.overhead = 0.0
sys.setprofile(self._profile)
defer(sys.setprofile, None)
threading.setprofile(self._profile)
defer(threading.setprofile, None)
self.timer.start(self)
defer(self.timer.stop)
yield
|
python
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Project: Appraise evaluation system
Author: Matt Post <[email protected]>
This script takes a set of parallel files and writes out the XML file used to
setup the corresponding Appraise tasks.
usage:
$ build_xml.py [-h] [-id ID] [-source SOURCELANG] [-target TARGETLANG] \
source system [system ...]
where
-id is a system ID (e.g., "wmt-2012")
-source is a source language identifier (e.g., "es")
-target is a source language identifier (e.g., "en")
-diff-documents will mark each sentence as from a different document
(as opposed to sequential sentences in the same document)
source is the source language file
system[1..N] are system outputs parallel to the source file
"""
import argparse
PARSER = argparse.ArgumentParser(description="Build evaluation task input " \
"file.")
PARSER.add_argument("source", type=file, help="source language file")
PARSER.add_argument("reference", type=file, nargs="?", help="reference language file")
PARSER.add_argument("system", metavar="system", nargs="+", type=file,
help="parallel files to compare")
PARSER.add_argument("-id", type=str, default="none", help="ID name to use " \
"for the system name")
PARSER.add_argument("-source", type=str, default="spa", dest="sourceLang",
help="the source language")
PARSER.add_argument("-target", type=str, default="eng", dest="targetLang",
help="the target language")
PARSER.add_argument("-diff-documents", action="store_false", default=True,
dest="sameDocument", help="sentences are from different documents")
if __name__ == "__main__":
args = PARSER.parse_args()
source = []
for line in args.source:
source.append(line.strip())
reference = []
for line in args.reference:
reference.append(line.strip())
systems = []
for i, system in enumerate(args.system):
systems.append([])
for line in system:
systems[i].append(line.strip())
print '<set id="%s" source-language="%s" target-language="%s">' \
% (args.id, args.sourceLang, args.targetLang)
# TODO: change to use of .format() calls. Check that it works with UTF-8 data.
for i, sentence in enumerate(systems[0]):
# If the sentences are from different documents, we give each of them a
# different document name so that they will not be presented with context.
docid = args.source.name if args.sameDocument else '{}-{}'.format(
args.source.name, i+1)
print ' <seg id="%d" doc-id="%s">' % (i+1, docid)
print ' <source>%s</source>' % (source[i])
if len(reference) >= i+1:
print ' <reference>%s</reference>' % (reference[i])
for j, system in enumerate(systems):
print ' <translation system="%s">%s</translation>' \
% (args.system[j].name, system[i])
print ' </seg>'
print '</set>'
|
python
|
import datetime
import discord
from dotenv import dotenv_values
TOKEN = dotenv_values(".env")["TOKEN"]
class Client(discord.Client):
async def on_ready(self):
members = getlist(self.guilds[0])
votes = {}
for member in members:
votes[member] = 0
for member in members:
try:
dm = await member.create_dm()
messages = await dm.history(limit=5, oldest_first=False,
after=datetime.datetime.now() - datetime.timedelta(
days=2)).flatten()
for message in messages:
message = message.content.split()
if message[0] == "!vote" and not members[int(message[1]) - 1] == member:
votes[members[int(message[1]) - 1]] += 1
break
except Exception as e:
print(repr(e))
sortedvotes = sorted(votes, key=votes.get, reverse=True)
msg = "@everyone The election has ended and the results are are:\n"
for i, member in enumerate(sortedvotes):
if i == 0:
msg += f"{member.mention}: {votes[member]} votes\n"
elif votes[member] > 1:
msg += f"{member.name}: {votes[member]} votes\n"
elif votes[member] == 1:
msg += f"{member.name}: {votes[member]} vote\n"
else:
break
await self.guilds[0].text_channels[0].send(msg)
await sortedvotes[0].add_roles(self.guilds[0].get_role(810326558727602258))
await self.close()
def getlist(guild):
ids = open("./members.txt").readlines()
return [guild.get_member(int(uid)) for uid in ids]
intents = discord.Intents.default()
intents.members = True
Client(intents=intents).run(TOKEN)
|
python
|
from django.template.loader import get_template
from django_better_admin_arrayfield.forms.widgets import DynamicArrayWidget
def test_template_exists():
get_template(DynamicArrayWidget.template_name)
def test_format_value():
widget = DynamicArrayWidget()
assert widget.format_value("") == []
assert widget.format_value([1, 2, 3]) == [1, 2, 3]
def test_value_from_datadict(mocker):
widget = DynamicArrayWidget()
test_name = "name"
class MockData:
@staticmethod
def getlist(name):
return [name]
mocker.spy(MockData, "getlist")
assert widget.value_from_datadict(MockData, None, test_name) == [test_name]
assert MockData.getlist.call_count == 1
def test_value_from_datadict_get(mocker):
widget = DynamicArrayWidget()
test_name = "name"
class MockData:
@staticmethod
def get(name):
return name
mocker.spy(MockData, "get")
assert widget.value_from_datadict(MockData, None, test_name) == test_name
assert MockData.get.call_count == 1
def test_get_context():
widget = DynamicArrayWidget()
value = ["1", "2", "3"]
context = widget.get_context("name", value, [])
assert len(context["widget"]["subwidgets"]) == len(value)
|
python
|
import collections
class contributor:
def __init__(self, name, index):
self.name = name
self.index = index
self.ratings = collections.defaultdict(list)
def __str__(self) -> str:
return self.name
def __repr__(self) -> str:
return self.name
def __sort_ratings(self):
self.ratings = { r: self.ratings[r] for r in sorted(self.ratings, reverse=True) }
def personal_ranking(self) -> list:
self.__sort_ratings()
return self.ratings.values()
# Hardcoded contributors and column indexes.
CONTRIBUTORS = [
contributor('Quentin', 'ntQ'), contributor('Gary', 'ntG'), contributor('Vincent', 'ntV'),
contributor('Romain', 'ntR'), contributor('Samuel', 'ntS'), contributor('Galtier', 'ntGl'),
contributor('Roxane', 'ntRx'), contributor('Clémence', 'ntC'), contributor('Lucas', 'ntL')
]
if __name__ == "__main__":
print("Ach! Musik contributors are: {}".format(CONTRIBUTORS))
|
python
|
import json
import hashlib
from dojo.models import Finding
class TruffleHogJSONParser(object):
def __init__(self, filename, test):
data = filename.read()
self.dupes = dict()
self.items = ()
for line in data.splitlines():
json_data = self.parse_json(line)
file = json_data["path"]
reason = json_data["reason"]
titleText = "Hard Coded " + reason + " in: " + file
commit = json_data["commit"]
description = "**Commit:** " + commit.rstrip("\n") + "\n"
description += "**Commit Hash:** " + json_data["commitHash"] + "\n"
description += "**Commit Date:** " + json_data["date"] + "\n"
description += "**Branch:** " + json_data["branch"] + "\n"
description += "**Reason:** " + json_data["reason"] + "\n"
description += "**Path:** " + file + "\n"
severity = "High"
if reason == "High Entropy":
severity = "Info"
elif "Oauth" in reason or "AWS" in reason or "Heroku" in reason:
severity = "Critical"
elif reason == "Generic Secret":
severity = "Medium"
strings_found = ""
for string in json_data["stringsFound"]:
strings_found += string + "\n"
dupe_key = hashlib.md5(file + reason).hexdigest()
description += "\n**Strings Found:**\n" + strings_found + "\n"
if dupe_key in self.dupes:
finding = self.dupes[dupe_key]
finding.description = finding.description + description
self.dupes[dupe_key] = finding
else:
self.dupes[dupe_key] = True
finding = Finding(title=titleText,
test=test,
cwe=798,
active=False,
verified=False,
description=description,
severity=severity,
numerical_severity=Finding.get_numerical_severity(severity),
mitigation="Secrets and passwords should be stored in a secure vault and/or secure storage.",
impact="This weakness can lead to the exposure of resources or functionality to unintended actors, possibly providing attackers with sensitive information or even execute arbitrary code.",
references="N/A",
file_path=file,
url='N/A',
dynamic_finding=False,
static_finding=True)
self.dupes[dupe_key] = finding
self.items = self.dupes.values()
def parse_json(self, json_output):
try:
json_data = json.loads(json_output)
except ValueError:
raise Exception("Invalid format")
return json_data
|
python
|
import requests
import csv
key=input('Masukan produk yang akan dicari:')
limit=input('Masukan limit produk:')
hal = input('Masukan berapa halaman ke berapa:')
write = csv.writer(open('eCommerce/hasil/{}.csv'.format(key), 'w', newline=''))
header = ['nama produk','harga','terjual','rating produk','nama toko','lokasi toko']
write.writerow(header)
header = {
'authority': 'gql.tokopedia.com',
'method': 'POST',
'path': '/',
'scheme': 'https',
'accept': '*/*',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-US,en;q=0.9,id;q=0.8',
'content-length': '3091',
'content-type': 'application/json',
'origin': 'https://www.tokopedia.com',
'referer': 'https://www.tokopedia.com/search?st=product&q={}&navsource=home'.format(key),
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-site',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
data = {
"operationName": "SearchProductQueryV4",
"variables": {
"params": "device=desktop&navsource=home&ob=23&page={}&q={}&related=true&rows={}&safe_search=false&scheme=https&shipping=&source=search&st=product&start=0&topads_bucket=true&unique_id=bcff84691771dfbce6b4a85ee24ff652&user_addressId=&user_cityId=176&user_districtId=2274&user_id=&user_lat=&user_long=&user_postCode=&variants=".format(hal,key,limit)
},
"query": "query SearchProductQueryV4($params: String!) {\n ace_search_product_v4(params: $params) {\n header {\n totalData\n totalDataText\n processTime\n responseCode\n errorMessage\n additionalParams\n keywordProcess\n __typename\n }\n data {\n isQuerySafe\n ticker {\n text\n query\n typeId\n __typename\n }\n redirection {\n redirectUrl\n departmentId\n __typename\n }\n related {\n relatedKeyword\n otherRelated {\n keyword\n url\n product {\n id\n name\n price\n imageUrl\n rating\n countReview\n url\n priceStr\n wishlist\n shop {\n city\n isOfficial\n isPowerBadge\n __typename\n }\n ads {\n adsId: id\n productClickUrl\n productWishlistUrl\n shopClickUrl\n productViewUrl\n __typename\n }\n badges {\n title\n imageUrl\n show\n __typename\n }\n ratingAverage\n labelGroups {\n position\n type\n title\n __typename\n }\n __typename\n }\n __typename\n }\n __typename\n }\n suggestion {\n currentKeyword\n suggestion\n suggestionCount\n instead\n insteadCount\n query\n text\n __typename\n }\n products {\n id\n name\n ads {\n adsId: id\n productClickUrl\n productWishlistUrl\n productViewUrl\n __typename\n }\n badges {\n title\n imageUrl\n show\n __typename\n }\n category: departmentId\n categoryBreadcrumb\n categoryId\n categoryName\n countReview\n discountPercentage\n gaKey\n imageUrl\n labelGroups {\n position\n title\n type\n __typename\n }\n originalPrice\n price\n priceRange\n rating\n ratingAverage\n shop {\n id\n name\n url\n city\n isOfficial\n isPowerBadge\n __typename\n }\n url\n wishlist\n sourceEngine: source_engine\n __typename\n }\n __typename\n }\n __typename\n }\n}\n"
}
url = "https://gql.tokopedia.com/"
response = requests.post(url, headers=header, json=data)
res_json = response.json()
produk = res_json['data']['ace_search_product_v4']['data']['products']
for p in produk:
nama = p['name']
harga = p['price']
terjual = p['labelGroups'][0]['title']
rating = p['ratingAverage']
nama_toko = p['shop']['name']
lokasi_toko = p['shop']['city']
print('nama produk:',nama,'harga:',harga,'terjual:',terjual,'rating produk:',rating,'nama toko:',nama_toko,'lokasi toko:',lokasi_toko)
write = csv.writer(open('eCommerce/hasil/{}.csv'.format(key),'a',newline=''))
data = [nama,harga,terjual,rating,nama_toko,lokasi_toko]
write.writerow(data)
|
python
|
from pytube import YouTube
from tqdm import tqdm
import ffmpeg
import html
# insert test link here!
yt = YouTube('https://www.youtube.com/watch?v=2A3iZGQd0G4')
audio = yt.streams.filter().first()
pbar = tqdm(total=audio.filesize)
def progress_fn(self, chunk, *_):
pbar.update(len(chunk))
yt.register_on_progress_callback(progress_fn)
audio = yt.streams.filter().first()
audio.download(output_path="./tmp", filename="tmp")
(
ffmpeg
.input("./tmp/tmp.mp4")
.audio
.output('./out/' + html.unescape(audio.title) + ".mp3")
.run_async()
.wait()
)
|
python
|
import argparse
import json
import multiprocessing
import os
import pickle
import random
from multiprocessing import Pool, cpu_count
import nltk
import numpy as np
import torch
from tqdm import tqdm
from src.data_preprocessors.transformations import (
NoTransformation, SemanticPreservingTransformation,
BlockSwap, ConfusionRemover, DeadCodeInserter,
ForWhileTransformer, OperandSwap, VarRenamer
)
def set_seeds(seed):
torch.manual_seed(seed)
torch.random.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
torch.cuda.manual_seed(seed)
def create_transformers_from_conf_file(processing_conf):
classes = [BlockSwap, ConfusionRemover, DeadCodeInserter, ForWhileTransformer, OperandSwap, VarRenamer]
transformers = {
c: processing_conf[c.__name__] for c in classes
}
return transformers
class ExampleProcessor:
def __init__(
self,
language,
parser_path,
transformation_config,
bidirection_transformation=False,
max_function_length=400
):
self.language = language
self.parser_path = parser_path
self.transformation_config = transformation_config
self.max_function_length = max_function_length
self.bidirection_transformation = bidirection_transformation
def initialize(self):
global example_tokenizer
global example_transformer
transformers = create_transformers_from_conf_file(self.transformation_config)
if self.language == "nl":
example_tokenizer = nltk.word_tokenize
else:
example_tokenizer = NoTransformation(self.parser_path, self.language)
example_transformer = SemanticPreservingTransformation(
parser_path=self.parser_path, language=self.language, transform_functions=transformers
)
def process_example(self, code):
global example_tokenizer
global example_transformer
try:
if self.language == "nl":
original_code = " ".join(example_tokenizer(code))
else:
original_code, _ = example_tokenizer.transform_code(code)
if len(original_code.split()) > self.max_function_length:
return -1
transformed_code, used_transformer = example_transformer.transform_code(code)
if used_transformer:
if used_transformer == "ConfusionRemover": # Change the direction in case of the ConfusionRemover
temp = original_code
original_code = transformed_code
transformed_code = temp
if isinstance(self.bidirection_transformation, str) and self.bidirection_transformation == 'adaptive':
bidirection = (used_transformer in ["BlockSwap", "ForWhileTransformer", "OperandSwap"])
else:
assert isinstance(self.bidirection_transformation, bool)
bidirection = self.bidirection_transformation
if bidirection and np.random.uniform() < 0.5 \
and used_transformer != "SyntacticNoisingTransformation":
return {
'source': original_code,
'target': transformed_code,
'transformer': used_transformer
}
else:
return {
'source': transformed_code,
'target': original_code,
'transformer': used_transformer
}
else:
return -1
except KeyboardInterrupt:
print("Stopping parsing for ", code)
return -1
except:
return -1
def process_functions(
pool, example_processor, functions,
train_file_path=None, valid_file_path=None, valid_percentage=0.002
):
used_transformers = {}
success = 0
tf = open(train_file_path, "wt") if train_file_path is not None else None
vf = open(valid_file_path, "wt") if train_file_path is not None else None
with tqdm(total=len(functions)) as pbar:
processed_example_iterator = pool.imap(
func=example_processor.process_example,
iterable=functions,
chunksize=1000,
)
count = 0
while True:
pbar.update()
count += 1
try:
out = next(processed_example_iterator)
if isinstance(out, int) and out == -1:
continue
if out["transformer"] not in used_transformers.keys():
used_transformers[out["transformer"]] = 0
used_transformers[out["transformer"]] += 1
if np.random.uniform() < valid_percentage:
if vf is not None:
vf.write(json.dumps(out) + "\n")
vf.flush()
else:
if tf is not None:
tf.write(json.dumps(out) + "\n")
tf.flush()
success += 1
except multiprocessing.TimeoutError:
print(f"{count} encountered timeout")
except StopIteration:
print(f"{count} stop iteration")
break
if tf is not None:
tf.close()
if vf is not None:
vf.close()
print(
f"""
Total : {len(functions)},
Success : {success},
Failure : {len(functions) - success}
Stats : {json.dumps(used_transformers, indent=4)}
"""
)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--langs', default=["java"], nargs='+',
help="Languages to be processed"
)
parser.add_argument(
'--input_dir', help="Directory of the language pickle files"
)
parser.add_argument(
'--output_dir', help="Directory for saving processed code"
)
parser.add_argument(
'--processing_config_file', default="configs/data_processing_config.json",
help="Configuration file for data processing."
)
parser.add_argument(
'--parser_path', help="Tree-Sitter Parser Path",
)
parser.add_argument(
"--workers", help="Number of worker CPU", type=int, default=20
)
parser.add_argument(
"--timeout", type=int, help="Maximum number of seconds for a function to process.", default=10
)
parser.add_argument(
"--valid_percentage", type=float, help="Percentage of validation examples", default=0.001
)
parser.add_argument("--seed", type=int, default=5000)
args = parser.parse_args()
set_seeds(args.seed)
out_dir = args.output_dir
os.makedirs(out_dir, exist_ok=True)
configuration = json.load(open(args.processing_config_file))
print(configuration)
for lang in args.langs:
print(f"Now processing : {lang}")
pkl_file = os.path.join(args.input_dir, lang + ".pkl")
data = pickle.load(open(pkl_file, "rb"))
functions = [ex['function'] for ex in data]
# for f in functions[:5]:
# print(f)
# print("=" * 100)
if lang == "php":
functions = ["<?php\n" + f + "\n?>" for f in functions]
example_processor = ExampleProcessor(
language=lang,
parser_path=args.parser_path,
transformation_config=configuration["transformers"],
max_function_length=(
configuration["max_function_length"] if "max_function_length" in configuration else 400
),
bidirection_transformation=(
configuration["bidirection_transformation"] if "bidirection_transformation" in configuration else False
)
)
pool = Pool(
processes=min(cpu_count(), args.workers),
initializer=example_processor.initialize
)
process_functions(
pool=pool,
example_processor=example_processor,
functions=functions,
train_file_path=os.path.join(out_dir, f"{lang}_train.jsonl"),
valid_file_path=os.path.join(out_dir, f"{lang}_valid.jsonl"),
valid_percentage=args.valid_percentage
)
del pool
del example_processor
|
python
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from math import exp
import os
import re
import sys
# This code implements the non-linear regression method described in:
# Jean Jacquelin 2009,
# Régressions et équations intégrales,
# sec. REGRESSIONS NON LINEAIRES des genres : PUISSANCE, EXPONENTIELLE, LOGARITHME, WEIBULL,
# pp. 16-18.
# http://www.scribd.com/doc/14674814/Regressions-et-equations-integrales
# Given n data points (x[1], y[1]), ... (x[n], y[n])
# it computes coefficients a, b, and c that minimize error in the fit equation:
# y = a + b exp(c*x)
# TODO: This regression is not very robust, and currently fails with division by
# zero if the regression matrix is singular.
def exponential_non_linear_regression(x, y, n):
S = [0] * (n+1)
S[1] = 0
sum_xx = 0
sum_xS = 0
sum_SS = 0
sum_yx = 0
sum_yS = 0
for k in range(2, n+1):
S[k] = S[k-1] + 0.5 * (y[k] + y[k-1]) * (x[k] - x[k-1])
sum_xx += (x[k] - x[1]) * (x[k] - x[1])
sum_xS += (x[k] - x[1]) * S[k]
sum_SS += S[k] * S[k]
sum_yx += (y[k] - y[1]) * (x[k] - x[1])
sum_yS += (y[k] - y[1]) * S[k]
# ( A1 ) = ( sum_xx sum_xS ) -1 ( sum_yx )
# ( B1 ) ( sum_xS sum_SS ) ( sum_yS )
det_inv = sum_xx*sum_SS - sum_xS*sum_xS
if (det_inv == 0.0):
return None
det = 1 / det_inv
A1 = det * ( sum_SS*sum_yx - sum_xS*sum_yS)
B1 = det * (-sum_xS*sum_yx + sum_xx*sum_yS)
if (B1 == 0.0):
a1 = 0.0
else:
a1 = - A1 / B1
c1 = B1
c2 = c1
sum_theta = 0
sum_thetatheta = 0
sum_y = 0
sum_ytheta = 0
theta = [0] * (n+1)
for k in range(1, n+1):
theta[k] = exp(c2 * x[k])
sum_theta += theta[k]
sum_thetatheta += theta[k] * theta[k]
sum_y += y[k]
sum_ytheta += y[k] * theta[k]
# ( a2 ) = ( n sum_theta ) -1 ( sum_y )
# ( b2 ) ( sum_theta sum_thetatheta ) ( sum_ytheta )
inv_det = n*sum_thetatheta - sum_theta*sum_theta
if (inv_det == 0.0):
det = 0.0
else:
det = 1 / inv_det
a2 = det * ( sum_thetatheta*sum_y - sum_theta*sum_ytheta)
b2 = det * (-sum_theta*sum_y + n*sum_ytheta)
if (det != 0):
return "%g + %g * exp(%g*x)" % (a2, b2, c2)
else:
return None
# Output a datafile to output_file in the following form:
# # Load Value
# 0 0
# 40 15.7
# 90 31.9
# Returns a string representing the "curve of best fit"
def calculate_data(grinder_files, accumulate_callback, output_file, include_origin=True):
Load = []
Value = []
stages = 0
for file in grinder_files:
threads = 0
stage = int(os.path.basename(os.path.dirname(file))[6:]) # strip initial 'stage-'
if (stages < stage + 1):
stages = stage + 1
while len(Value) <= stage:
Load.append(0)
Value.append(0)
with open(file, 'r') as f:
for line in f:
# Count the threads in this Grinder logfile by looking at all the unique log messages.
# This is to determine the load level empirically.
# TODO: There is probably a more efficient way to communicate this from experiment execution.
m = re.match(r'....-..-.. ..:..:..,... INFO .*-0 thread-([0-9]*)', line)
if m:
thread = int(m.group(1))
if (threads < thread + 1):
threads = thread + 1
m = re.match(r'Test ', line)
if m:
# grinder-0.log file format:
# $1 = "Test"
# $2 = "0"...
# $3 = Tests
# $4 = Errors
# $5 = Mean Test Time (ms)
# $6 = Test Time Standard Deviation (ms)
# $7 = TPS
# $8 = Mean response length
# $9 = Response bytes per second
# $10 = Response errors
# $11 = Mean time to resolve host
# $12 = Mean time to establish connection
# $13 = Mean time to first byte
# $14 = Description
# Tests Errors Mean Test Test Time TPS Mean Response Response Mean time to Mean time to Mean time to
# Time (ms) Standard response bytes per errors resolve host establish first byte
# Deviation length second connection
# (ms)
#
#Test 0 1060 0 10224.49 7229.27 0.58 19.77 11.51 5 0.04 0.28 10221.48 "Status"
#Test 1 2408 0 10490.14 7157.16 1.32 16665.09 22049.02 8 0.04 0.30 10485.22 "Projects"
fields = re.split("[ \t]+", line)
agent_data = {
'tests': float(fields[2]),
'mean_test_time': float(fields[4]),
'tps': float(fields[6]),
'desc': line.split('"')[1]
}
accumulate_callback(Value, stage, agent_data)
Load[stage] += threads
Load = [0] + Load
Value = [0.0] + Value
if include_origin:
# Inject a "fake" (0,0) stage in the Load,Value lists.
Load = [0] + Load
Value = [0.0] + Value
fake_stages=1
else:
fake_stages=0
with open(output_file, 'w') as f:
f.write("Load Value\n")
for stage in range(1+fake_stages, stages+1+fake_stages):
f.write("%d %g\n" % (Load[stage], Value[stage]))
return exponential_non_linear_regression(Load, Value, stages+fake_stages)
|
python
|
from setuptools import setup
setup(name='pkgtest',
version='1.0.0',
description='A print test for PyPI',
author='winycg',
author_email='[email protected]',
url='https://www.python.org/',
license='MIT',
keywords='ga nn',
packages=['pkgtest'],
install_requires=['numpy>=1.14', 'tensorflow>=1.7'],
python_requires='>=3'
)
|
python
|
import boto3
import botocore
import sys
import os
class S3Client:
def __init__(self, bucket, key):
self.client = boto3.client('s3')
self.bucket = bucket
self.key = key
def get_content_length(self):
try:
return int(self.client.get_object(Bucket=self.bucket, Key=self.key)['ResponseMetadata']['HTTPHeaders']['content-length'])
except botocore.exceptions.NoCredentialsError:
print("""\nAWS credentials not found, please ensure that the credentials are available at "%s" file
content should look something like
[default]
aws_access_key_id=<put your aws access key>
aws_secret_access_key=<put your aws secret key>\n""" % (os.path.join(os.getenv("HOME"), ".aws", "credentials")))
sys.exit(1)
except botocore.exceptions.ParamValidationError:
print("\nCurrently only S3 file is supported and not directory. Please provide complete path of the intended file.\n")
sys.exit(1)
except botocore.exceptions.ClientError:
print("""\nGiven file does not exists or not a file.
Currently only S3 file is supported and not directory. Please provide complete path of the intended file.\n""")
sys.exit(1)
def get_data_with_byte_range(self, start, end):
return self.client.get_object(Bucket=self.bucket, Key=self.key, Range='bytes={}-{}'.format(start, end))['Body'].read()
def close_s3_client(self):
pass
|
python
|
import io
import os
import time
import zipfile
import h5py
import numpy as np
import pandas as pd
from PIL import Image
from django.http import HttpResponse
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.views import APIView
from tensorflow.python.keras.engine.saving import load_model
from deepleasy.control.options import OPTIMIZERS, LOSSES, DATASETS, LAYERS, ACTIVATIONS
from deepleasy.control.validation import model_builder_ok, clustering_checker
from deepleasy.models import Progress, History
from deepleasy.training.clustering import ClusteringLayer
from deepleasy.training.train import build_model_supervised, build_model_unsupervised
from webtfg.celery import app
model_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'models')
# Create your views here.
class ModelBuilderUnsupervised(APIView):
permission_classes = (IsAuthenticated, )
def post(self, request: Request):
if not model_builder_ok(request.data) and clustering_checker(request.data):
print(request.data)
return Response({
"success": False,
"message": "The model had some problems whilst data verification, refresh the page and try again"
})
try:
Progress(user=request.user, epochs=0, max_epochs=request.data["epochs"], running=False).save()
except:
return Response({
"success": False,
"message": "There is another model building, please wait until it's finished"
})
build_model_unsupervised.delay(request.data, request.user.username, model_path)
print(request.user)
return Response({
"success": True,
"message": "The model is built! Have a cup of tea while waiting :)"
})
class ModelBuilderSupervised(APIView):
permission_classes = (IsAuthenticated, )
def post(self, request: Request):
if not model_builder_ok(request.data):
print(request.data)
return Response({
"success": False,
"message": "The model had some problems whilst data verification, refresh the page and try again"
})
try:
Progress(user=request.user, epochs=0, max_epochs=request.data["epochs"], running=False).save()
except:
return Response({
"success": False,
"message": "There is another model building, please wait until it's finished"
})
build_model_supervised.delay(request.data, request.user.username, model_path)
print(request.user)
return Response({
"success": True,
"message": "The model is built! Have a cup of tea while waiting :)"
})
class ModelProgress(APIView):
permission_classes = (IsAuthenticated,)
def get(self, request: Request):
try:
progress = Progress.objects.get(user=request.user)
return Response({
"epochs": progress.epochs,
"max_epochs": progress.max_epochs,
"running": progress.running,
"task_id": progress.task_id
})
except Progress.DoesNotExist:
return Response({"message": "There is no active task right now"}, 404)
def post(self, request: Request):
try:
app.control.revoke(task_id=request.data["task_id"], terminate=True, timeout=1, wait=False)
except:
return Response("problem removing", 502)
Progress.objects.get(task_id=request.data["task_id"]).delete()
History(user=request.user, timestamp=int(int(time.time())), path="", accuracy=0.0, loss=0.0,
steps_info={"message": "Cancelled by user"}).save()
return Response("removed", 200)
class ModelHistory(APIView):
permission_classes = (IsAuthenticated, )
def get(self, request: Request):
history = History.objects.filter(user=request.user)
if len(history) == 0:
return Response({"message": "There is no history registers for you :("}, 404)
registers = {
"history": []
}
for h in reversed(history):
registers["history"].append({
"id": h.id,
"timestamp": h.timestamp,
"status": os.path.exists(h.path),
"accuracy": h.accuracy,
"loss": h.loss,
"dataset": h.dataset,
"steps_info": h.steps_info
})
return Response(registers)
def post(self, request: Request):
try:
history = History.objects.get(id=request.data["id"])
if history.path != "" and os.path.exists(history.path):
os.remove(history.path)
history.delete()
return Response("OK", 200)
except:
return Response("Error, data not found", 404)
class ModelOptions(APIView):
permission_classes = (IsAuthenticated, )
def get(self, request: Request):
return Response({
"layers": LAYERS,
"losses": LOSSES,
"datasets": [i.toJSON() for i in DATASETS],
"optimizers": OPTIMIZERS,
"activations": ACTIVATIONS
})
class ModelGetter(APIView):
permission_classes = (IsAuthenticated, )
def post(self, request: Request):
try:
h = History.objects.get(id=request.data["id"])
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, "a", zipfile.ZIP_DEFLATED, False) as zip_file:
# ModelGetter.zipdir(h.path, zip_file)
arc, _ = os.path.split(h.path)
zip_file.write(h.path, h.path[len(arc):])
r = HttpResponse(zip_buffer.getvalue(), content_type='application/zip')
r['Content-Disposition'] = 'attachment; filename="Model.zip"'
return r
except:
return Response("Error", 404)
@staticmethod
def zipdir(path, ziph):
# ziph is zipfile handle
abs_src, _ = os.path.split(path)
for root, dirs, files in os.walk(path):
for file in files:
absname = os.path.abspath(os.path.join(root, file))
arcname = absname[len(abs_src) + 1:]
ziph.write(absname, arcname=arcname)
class UserStats(APIView):
permission_classes = (IsAuthenticated, )
def get(self, request: Request):
progress = None
try:
progress = Progress.objects.get(user=request.user)
except:
pass
history = None
try:
history = History.objects.filter(user=request.user).count()
except:
pass
response = {}
if progress is not None:
response["epochs"] = progress.epochs
response["max_epochs"] = progress.max_epochs
response["running"] = progress.running
else:
response["epochs"] = 0
response["max_epochs"] = 0
response["running"] = False
if history is not None:
response["history_entries"] = history
else:
response["history_entries"] = 0
return Response(response)
class ModelPredict(APIView):
permission_classes = (IsAuthenticated,)
def post(self, request: Request):
if "zippy" not in request.data.keys():
return Response("Where is my zip?", 400)
elif "dataset" not in request.data.keys():
return Response("Where is the dataset?", 400)
elif request.data["dataset"] not in [x.name for x in DATASETS]:
return Response("Dataset not valid", 400)
try:
input_zip = zipfile.ZipFile(request.data["zippy"])
except zipfile.BadZipFile:
return Response("What kind of zip is this", 400)
predictions = None
model = None
dataset = None
pnames = []
for i in DATASETS:
if i.name == request.data["dataset"]:
if i.name == "reuters" or i.name == "imdb":
return Response({
"predictions": [
{"feature": "We cannot predict for {} dataset".format(i.name),
"prediction": "The reason is: https://snyk.io/blog/numpy-arbitrary-code-execution-vulnerability/"}
]
})
dataset = i
break
if dataset is None:
return Response("This is not a valid dataset", 400)
for x in input_zip.namelist():
if x.endswith(".h5"):
file = h5py.File(io.BytesIO(input_zip.read(x)))
model = load_model(file, custom_objects={'ClusteringLayer': ClusteringLayer})
elif x.endswith(".csv"):
csv = pd.read_csv(io.StringIO(input_zip.read(x)), header=None)
predictions = csv.values
pnames = [x for x in range(predictions)]
else:
try:
image = Image.open(io.BytesIO(input_zip.read(x)))
image.load()
image = np.asarray(image, dtype="float32") / 255
try:
image = image.reshape(dataset.input_shape)
except ValueError:
return Response("image {} is not in good format".format(x), 400)
if predictions is None:
predictions = np.array([image])
else:
predictions = np.append(predictions, [image], axis=0)
pnames.append(x)
except IOError:
pass
if model is not None:
predictions = model.predict(predictions)
predictions = predictions.argmax(axis=1)
print("PREDICTIONS", predictions)
return Response({
"predictions": [
{"feature": n, "prediction": p} for n, p in zip(pnames, predictions)
]
})
else:
return Response("Where is the h5?", 400)
|
python
|
# Hello, I'm party bot, I will be called from wsgi.py once
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler
from Bot.models import TelegramUser, Action, Day, WeekDay, Event, Vote, BotMessage, Advertisement
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup, KeyboardButton, ParseMode
import time
# TODO: for Kirill decorator
debug = False
def debug_print(item):
if debug:
print(item)
def get_keyboard(_chat):
user = TelegramUser.get_user(_chat)
keyboard = [[]]
if user.free_mode:
keyboard = [
['Четверг', 'Пятница'],
['Суббота', 'Воскресенье'],
['Все', 'Популярное 💯'],
['Акции']
]
else:
keyboard = [
['Четверг', 'Пятница'],
['Суббота', 'Воскресенье'],
['Бесплатно 🆓', 'Популярное 💯'],
['Акции']
]
return ReplyKeyboardMarkup(keyboard, one_time_keyboard=False)
def start_command(bot, update):
try:
TelegramUser.add_telegram_user(update.message.chat)
markup = get_keyboard(update.message.chat)
update.message.reply_text('Привет:', reply_markup=markup)
except Exception as ex:
print(ex)
def help_command(bot, update):
bot.sendMessage(chat_id=update.message.chat_id, text='help text')
def send_message_to_all(bot, update, text):
message = update.callback_query.message
sender = TelegramUser.get_user(message.chat)
if sender.is_VIP:
receivers = TelegramUser.get_all_users()
for receiver in receivers:
bot.sendMessage(chat_id=receiver.user_telegram_id, text=text,disable_web_page_prewview=True)
else:
bot.sendMessage(chat_id=message.chat_id,
text="Вы не можете использовать данную функцию, обратитесь к администратору")
command_dict = {
"/start": start_command,
"/help": help_command
}
week_day_dict = {
0: 'Понедельник',
1: 'Вторник',
2: 'Среда',
3: 'Четверг',
4: 'Пятница',
5: 'Суббота',
6: 'Воскресенье'
}
week_day_reverse_dict = {
'Понедельник': 0,
'Вторник': 1,
'Среда': 2,
'Четверг': 3,
'Пятница': 4,
'Суббота': 5,
'Воскресенье': 6
}
def echo(bot, update):
try:
text = update.message.text
if text == 'Акции':
send_advetrisments(bot=bot, update=update)
elif text == 'Популярное 💯':
send_message_top(bot=bot, update=update)
elif text == 'Бесплатно 🆓' or text == 'Все':
switch_free_mode(bot=bot, update=update)
else:
send_message_by_week_day(bot=bot, update=update)
except Exception as ex:
print(ex)
def switch_free_mode(bot, update):
user = TelegramUser.get_user(update.message.chat)
user.free_mode = not user.free_mode
user.save()
markup = get_keyboard(update.message.chat)
if user.free_mode:
update.message.reply_text('Показывать только бесплатные события', reply_markup=markup)
else:
update.message.reply_text('Показывать все события', reply_markup=markup)
def send_message_by_week_day(bot, update):
try:
user = TelegramUser.get_user(update.message.chat)
Action.add_action(update.message)
text = update.message.text
week_day_id = WeekDay(week_day_reverse_dict[text])
week_day = WeekDay(week_day_id)
events = Day.get_day_and_events(week_day.value, user.free_mode)
event_col = len(events) # .count()
if event_col == 0:
message = 'На ' + week_day_dict[int(week_day.value)] + ' мероприятий не запланировано'
bot.sendMessage(chat_id=update.message.chat_id, text=message,disable_web_page_prewview=True)
else:
# BotMessage.delete_old_messages(bot=bot, update=update, events=events,message=update.message)
for i in range(0, event_col):
event = events[i]
message = make_message(event)
reply_markup = get_inline_keyboard(event=event, user=user)
# BotMessage.send_message(bot=bot, update=update, message=message, parse_mode=ParseMode.MARKDOWN,
# reply_markup=reply_markup, event=event)
if i != (event_col - 1):
BotMessage.send_message(bot=bot, update=update, message=message, parse_mode=ParseMode.MARKDOWN,
reply_markup=reply_markup, event=event, silent=True)
time.sleep(1)
else:
BotMessage.send_message(bot=bot, update=update, message=message, parse_mode=ParseMode.MARKDOWN,
reply_markup=reply_markup, event=event, silent=False)
except KeyError as k_e:
print(k_e)
bot.sendMessage(chat_id=update.message.chat_id, text='не понимаю запрос')
except Exception as ex:
print(ex)
def send_message_top(bot, update):
try:
user = TelegramUser.get_user(update.message.chat)
debug_print(update.message.text)
Action.add_action(update.message)
text = update.message.text
events = []
events_only = []
for i in range(3, 7):
event = Day.get_day_and_top_events(i, user.free_mode)
if event is not None:
events.append((i, event))
events_only.append(event)
event_col = len(events)
if event_col == 0:
message = 'Мероприятия не найдены'
bot.sendMessage(chat_id=update.message.chat_id, text=message)
else:
# BotMessage.delete_old_messages(bot=bot, update=update, events=events_only,message=update.message)
for i in range(0, event_col):
event = events[i][1]
week_day_id = events[i][0]
message = make_message(event)
message = '*' + week_day_dict[week_day_id] + '*' + '\n' + message
reply_markup = get_inline_keyboard(event=event, user=user)
# BotMessage.send_message(bot=bot, update=update, message=message, parse_mode=ParseMode.MARKDOWN,
# reply_markup=reply_markup, event=event)
if i != (event_col - 1):
BotMessage.send_message(bot=bot, update=update, message=message, parse_mode=ParseMode.MARKDOWN,
reply_markup=reply_markup, event=event, silent=True)
time.sleep(1)
else:
BotMessage.send_message(bot=bot, update=update, message=message, parse_mode=ParseMode.MARKDOWN,
reply_markup=reply_markup, event=event, silent=False)
except KeyError as k_e:
print(k_e)
bot.sendMessage(chat_id=update.message.chat_id, text='не понимаю запрос')
except Exception as ex:
print(ex)
def send_advetrisments(bot, update):
try:
debug_print(update.message.text)
Action.add_action(update.message)
advertisments = Advertisement.objects.filter()
advertisment_col = len(advertisments)
if advertisment_col == 0:
message = 'Акций нет'
bot.sendMessage(chat_id=update.message.chat_id, text=message, disable_notification=True)
else:
# bot.sendMessage(chat_id=update.message.chat_id, text='*Акции*\n\n', parse_mode=ParseMode.MARKDOWN)
for i in range(0, advertisment_col):
# bot.sendMessage(chat_id=update.message.chat_id, text=advertisments[i].text, parse_mode=ParseMode.MARKDOWN)
if i != (advertisment_col - 1):
bot.sendMessage(chat_id=update.message.chat_id, text=advertisments[i].text,
parse_mode=ParseMode.MARKDOWN, disable_notification=True,disable_web_page_prewview=True)
time.sleep(1)
else:
bot.sendMessage(chat_id=update.message.chat_id, text=advertisments[i].text,
parse_mode=ParseMode.MARKDOWN,disable_web_page_prewview=True)
except KeyError as k_e:
print(k_e)
bot.sendMessage(chat_id=update.message.chat_id, text='не понимаю запрос')
except Exception as ex:
print(ex)
def get_inline_keyboard(event, user):
if event.get_ability_to_vote(user):
return get_filled_inline_keyboard(event)
else:
return get_empty_inline_keyboard()
def make_message(event):
message = ''
message += '*' + event.header + '*' + '\n'
message += event.description + '\n'
rating = event.rating
message += '' + 'Рейтинг: ' + str(rating) + ''
return message
def get_filled_inline_keyboard(event):
keyboard = [[InlineKeyboardButton("👍", callback_data=str(str(event.id) + '#^*_1')),
InlineKeyboardButton("👎", callback_data=str(str(event.id) + '#^*_0'))]]
return InlineKeyboardMarkup(keyboard)
def get_empty_inline_keyboard():
keyboard = [[]]
return InlineKeyboardMarkup(keyboard)
def button(bot, update):
try:
query = update.callback_query
query_data_tuple = get_data_tuple(query.data)
user = TelegramUser.get_user(update.callback_query.message.chat)
print(query_data_tuple[1])
if query_data_tuple[1] == 2 or query_data_tuple[1] == 3:
text = query_data_tuple[0]
if query_data_tuple[1] == 2:
bot.editMessageText(text='Рассылка выполнена', chat_id=update.callback_query.message.chat_id,
message_id=update.callback_query.message.message_id,
parse_mode=ParseMode.MARKDOWN,disable_web_page_prewview=True)
send_message_to_all(bot=bot, update=update, text=text)
else:
bot.editMessageText(text='Рассылка отменена', chat_id=update.callback_query.message.chat_id,
message_id=update.callback_query.message.message_id,
parse_mode=ParseMode.MARKDOWN,disable_web_page_prewview=True)
else:
event = Event.get_event(query_data_tuple[0])
if query_data_tuple[1] == 1:
type = True
else:
type = False
if event.get_ability_to_vote(user=user):
Vote.add_vote(type_of_vote=type, event=event, user=user)
event = Event.get_event(int(query_data_tuple[0]))
message = make_message(event)
reply_markup = get_empty_inline_keyboard()
bot.editMessageText(text=message, chat_id=query.message.chat_id, message_id=query.message.message_id,
parse_mode=ParseMode.MARKDOWN, reply_markup=reply_markup)
BotMessage.delete_old_messages(bot=bot, events=event, message=update.callback_query.message)
except Exception as ex:
print(ex)
def get_data_tuple(query_data):
ind = query_data.index('#^*_')
data1 = query_data[:ind]
data2 = int(query_data[ind + 4:])
return data1, data2
def error(bot, update, error):
try:
print("Error: ")
print(error)
except Exception as ex:
print(ex)
def command(bot, update):
print("heroku")
try:
Action.add_action(update.message)
command_text = update.message.text
print(command_text[0:4])
if command_text[0:4] == '/all':
sender = TelegramUser.get_user(update.message.chat)
if sender.is_VIP:
text = command_text[5:]
keyboard = [[InlineKeyboardButton("Да", callback_data=text + '#^*_2'),
InlineKeyboardButton("Нет", callback_data=text + '#^*_3')]]
reply_markup = InlineKeyboardMarkup(keyboard)
bot.sendMessage(text='Отправить всем следующее сообщение?\n' + text, chat_id=update.message.chat_id,
parse_mode=ParseMode.MARKDOWN, reply_markup=reply_markup,disable_web_page_prewview=True)
else:
bot.sendMessage(chat_id=update.message.chat_id,
text="Вы не можете использовать данную функцию, обратитесь к администратору",disable_web_page_prewview=True)
else:
func = command_dict[update.message.text]
func(bot, update)
except KeyError as k_e:
print(k_e)
bot.sendMessage(chat_id=update.message.chat_id, text="Sorry, I didn't understand that command")
except Exception as ex:
print(ex)
bot.sendMessage(chat_id=update.message.chat_id, text="System error")
command_handler = MessageHandler(Filters.command, command)
echo_handler = MessageHandler(Filters.text, echo)
updater = Updater(token='361018005:AAHY53Qj5EKEQHwf-g7LwoMf0UbiMzvCgAE')
dispatcher = updater.dispatcher
dispatcher.add_handler(command_handler)
dispatcher.add_error_handler(error)
dispatcher.add_handler(echo_handler)
updater.dispatcher.add_handler(CallbackQueryHandler(button))
def work_cycle():
while True:
try:
updater.start_polling()
time.sleep(10)
except Exception as ex:
print('bot crashed:')
from multiprocessing import Process
t1 = Process(target=work_cycle)
t1.start()
|
python
|
from trex_stl_lib.api import *
class STLS1(object):
def get_streams (self, direction = 0, **kwargs):
s1 = STLStream(name = 's1',
packet = STLPktBuilder(pkt = Ether()/IP(src="16.0.0.1",dst="48.0.0.1")/UDP(dport=12,sport=1025)/(10*'x')),
mode = STLTXSingleBurst(pps = 100, total_pkts = 7),
next = 's2'
)
s2 = STLStream(name = 's2',
self_start = False,
packet = STLPktBuilder(pkt = Ether()/IP(src="16.0.0.1",dst="48.0.0.2")/UDP(dport=12,sport=1025)/(10*'x')),
mode = STLTXSingleBurst(pps = 317, total_pkts = 13),
next = 's3'
)
s3 = STLStream(name = 's3',
self_start = False,
packet = STLPktBuilder(pkt = Ether()/IP(src="16.0.0.1",dst="48.0.0.3")/UDP(dport=12,sport=1025)/(10*'x')),
mode = STLTXMultiBurst(pps = 57, pkts_per_burst = 3, count = 5, ibg = 12),
next = 's4'
)
s4 = STLStream(name = 's4',
self_start = False,
packet = STLPktBuilder(pkt = Ether()/IP(src="16.0.0.1",dst="48.0.0.3")/UDP(dport=12,sport=1025)/(10*'x')),
mode = STLTXSingleBurst(pps = 4, total_pkts = 22),
next = 's5'
)
s5 = STLStream(name = 's5',
self_start = False,
packet = STLPktBuilder(pkt = Ether()/IP(src="16.0.0.1",dst="48.0.0.3")/UDP(dport=12,sport=1025)/(10*'x')),
mode = STLTXSingleBurst(pps = 17, total_pkts = 27),
action_count = 17,
next = 's1'
)
return [ s1, s2, s3, s4, s5 ]
# dynamic load - used for trex console or simulator
def register():
return STLS1()
|
python
|
import collections
from .base import BaseItertool
from .iter_dispatch import iter_
from .tee import tee
_zip = zip
class product(BaseItertool):
"""product(*iterables, repeat=1) --> product object
Cartesian product of input iterables. Equivalent to nested for-loops.
For example, product(A, B) returns the same as: ((x,y) for x in A for y in
B). The leftmost iterators are in the outermost for-loop, so the output
tuples cycle in a manner similar to an odometer (with the rightmost element
changing on every iteration).
To compute the product of an iterable with itself, specify the number of
repetitions with the optional repeat keyword argument. For example,
product(A, repeat=4) means the same as product(A, A, A, A).
product('ab', range(3)) --> ('a',0) ('a',1) ('a',2) ('b',0) ('b',1) ('b',2)
product((0,1), (0,1), (0,1)) --> (0,0,0) (0,0,1) (0,1,0) (0,1,1) (1,0,0)
...
"""
def __init__(self, *args, **kwargs):
if 'repeat' in kwargs:
repeat = kwargs['repeat']
del kwargs['repeat']
else:
repeat = None
if len(kwargs) > 0:
raise ValueError("Unrecognized keyword arguments: {}".format(
", ".join(kwargs)))
if repeat is not None:
self._iterables = sum(_zip(*(tee(it, repeat) for it in args)), ())
else:
self._iterables = tuple(iter_(it) for it in args)
self._contents = tuple([] for it in self._iterables)
self._exhausted = [False for it in self._iterables]
self._position = [-1 for it in self._iterables]
self._initialized = False
def __next__(self):
# Welcome to the spaghetti factory.
def _next(i):
# Advance the i'th iterator, wrapping if necessary.
# Returns the next value as well as a "carry bit" that
# tells us we've wrapped, i.e. to advance iterator i - 1 as well.
flip = False
# Handle the case where iteratior i still has stuff in it.
if not self._exhausted[i]:
try:
value = next(self._iterables[i])
self._contents[i].append(value)
self._position[i] += 1
except StopIteration:
# If contents is empty, the iterator was empty.
if len(self._contents[i]) == 0:
raise StopIteration
self._exhausted[i] = True
self._position[i] = -1 # The recursive call increments.
return _next(i)
else:
self._position[i] += 1
self._position[i] %= len(self._contents[i])
value = self._contents[i][self._position[i]]
# If we've wrapped, return True for the carry bit.
if self._position[i] == 0:
flip = True
return value, flip
# deque is already imported, could append to a list and reverse it.
result = collections.deque()
i = len(self._iterables) - 1
if not self._initialized:
# On the very first draw we need to draw one from every iterator.
while i >= 0:
result.appendleft(_next(i)[0])
i -= 1
self._initialized = True
else:
# Always advance the least-significant position iterator.
flip = True
# Keep drawing from lower-index iterators until the carry bit
# is unset.
while flip and i >= 0:
value, flip = _next(i)
i -= 1
result.appendleft(value)
# If the carry bit is still set after breaking out of the loop
# above, it means the most-significant iterator has wrapped,
# and we're done.
if flip:
raise StopIteration
# Read off any other unchanged values from lower-index iterators.
while i >= 0:
result.appendleft(self._contents[i][self._position[i]])
i -= 1
return tuple(result)
|
python
|
r"""
Lattice posets
"""
#*****************************************************************************
# Copyright (C) 2011 Nicolas M. Thiery <nthiery at users.sf.net>
#
# Distributed under the terms of the GNU General Public License (GPL)
# http://www.gnu.org/licenses/
#******************************************************************************
from sage.misc.cachefunc import cached_method
from sage.misc.abstract_method import abstract_method
from sage.categories.category import Category
from sage.categories.posets import Posets
class LatticePosets(Category):
r"""
The category of lattices, i.e. partially ordered sets in which any
two elements have a unique supremum (the elements' least upper
bound; called their *join*) and a unique infimum (greatest lower bound;
called their *meet*).
EXAMPLES::
sage: LatticePosets()
Category of lattice posets
sage: LatticePosets().super_categories()
[Category of posets]
sage: LatticePosets().example()
NotImplemented
.. seealso:: :class:`~sage.categories.posets.Posets`, :class:`FiniteLatticePosets`, :func:`LatticePoset`
TESTS::
sage: C = LatticePosets()
sage: TestSuite(C).run()
"""
@cached_method
def super_categories(self):
r"""
Returns a list of the (immediate) super categories of
``self``, as per :meth:`Category.super_categories`.
EXAMPLES::
sage: LatticePosets().super_categories()
[Category of posets]
"""
return [Posets()]
class ParentMethods:
@abstract_method
def meet(self, x, y):
"""
Returns the meet of `x` and `y` in this lattice
INPUT:
- ``x``, ``y`` -- elements of ``self``
EXAMPLES::
sage: D = LatticePoset((divisors(30), attrcall("divides")))
sage: D.meet( D(6), D(15) )
3
"""
@abstract_method
def join(self, x, y):
"""
Returns the join of `x` and `y` in this lattice
INPUT:
- ``x``, ``y`` -- elements of ``self``
EXAMPLES::
sage: D = LatticePoset((divisors(60), attrcall("divides")))
sage: D.join( D(6), D(10) )
30
"""
|
python
|
# uncompyle6 version 3.2.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)]
# Embedded file name: ctypes.macholib.framework
import re
__all__ = [
'framework_info']
STRICT_FRAMEWORK_RE = re.compile('(?x)\n(?P<location>^.*)(?:^|/)\n(?P<name>\n (?P<shortname>\\w+).framework/\n (?:Versions/(?P<version>[^/]+)/)?\n (?P=shortname)\n (?:_(?P<suffix>[^_]+))?\n)$\n')
def framework_info(filename):
is_framework = STRICT_FRAMEWORK_RE.match(filename)
if not is_framework:
return None
return is_framework.groupdict()
def test_framework_info():
def d(location=None, name=None, shortname=None, version=None, suffix=None):
return dict(location=location, name=name, shortname=shortname, version=version, suffix=suffix)
return
if __name__ == '__main__':
test_framework_info()
|
python
|
# bc_action_rules_bc.py
from pyke import contexts, pattern, bc_rule
pyke_version = '1.1.1'
compiler_version = 1
def speed_up(rule, arg_patterns, arg_context):
engine = rule.rule_base.engine
patterns = rule.goal_arg_patterns()
if len(arg_patterns) == len(patterns):
context = contexts.bc_context(rule)
try:
if all(map(lambda pat, arg:
pat.match_pattern(context, context,
arg, arg_context),
patterns,
arg_patterns)):
rule.rule_base.num_bc_rules_matched += 1
with engine.prove('action_facts', 'speed', context,
(rule.pattern(0),)) \
as gen_1:
for x_1 in gen_1:
assert x_1 is None, \
"bc_action_rules.speed_up: got unexpected plan from when clause 1"
rule.rule_base.num_bc_rule_successes += 1
yield
rule.rule_base.num_bc_rule_failures += 1
finally:
context.done()
def keep_speed(rule, arg_patterns, arg_context):
engine = rule.rule_base.engine
patterns = rule.goal_arg_patterns()
if len(arg_patterns) == len(patterns):
context = contexts.bc_context(rule)
try:
if all(map(lambda pat, arg:
pat.match_pattern(context, context,
arg, arg_context),
patterns,
arg_patterns)):
rule.rule_base.num_bc_rules_matched += 1
with engine.prove('action_facts', 'speed', context,
(rule.pattern(0),)) \
as gen_1:
for x_1 in gen_1:
assert x_1 is None, \
"bc_action_rules.keep_speed: got unexpected plan from when clause 1"
rule.rule_base.num_bc_rule_successes += 1
yield
rule.rule_base.num_bc_rule_failures += 1
finally:
context.done()
def brake(rule, arg_patterns, arg_context):
engine = rule.rule_base.engine
patterns = rule.goal_arg_patterns()
if len(arg_patterns) == len(patterns):
context = contexts.bc_context(rule)
try:
if all(map(lambda pat, arg:
pat.match_pattern(context, context,
arg, arg_context),
patterns,
arg_patterns)):
rule.rule_base.num_bc_rules_matched += 1
with engine.prove('action_facts', 'speed', context,
(rule.pattern(0),)) \
as gen_1:
for x_1 in gen_1:
assert x_1 is None, \
"bc_action_rules.brake: got unexpected plan from when clause 1"
rule.rule_base.num_bc_rule_successes += 1
yield
rule.rule_base.num_bc_rule_failures += 1
finally:
context.done()
def turn(rule, arg_patterns, arg_context):
engine = rule.rule_base.engine
patterns = rule.goal_arg_patterns()
if len(arg_patterns) == len(patterns):
context = contexts.bc_context(rule)
try:
if all(map(lambda pat, arg:
pat.match_pattern(context, context,
arg, arg_context),
patterns,
arg_patterns)):
rule.rule_base.num_bc_rules_matched += 1
with engine.prove('action_facts', 'section', context,
(rule.pattern(0),)) \
as gen_1:
for x_1 in gen_1:
assert x_1 is None, \
"bc_action_rules.turn: got unexpected plan from when clause 1"
rule.rule_base.num_bc_rule_successes += 1
yield
rule.rule_base.num_bc_rule_failures += 1
finally:
context.done()
def pits_1(rule, arg_patterns, arg_context):
engine = rule.rule_base.engine
patterns = rule.goal_arg_patterns()
if len(arg_patterns) == len(patterns):
context = contexts.bc_context(rule)
try:
if all(map(lambda pat, arg:
pat.match_pattern(context, context,
arg, arg_context),
patterns,
arg_patterns)):
rule.rule_base.num_bc_rules_matched += 1
with engine.prove('action_facts', 'slick_tires', context,
(rule.pattern(0),)) \
as gen_1:
for x_1 in gen_1:
assert x_1 is None, \
"bc_action_rules.pits_1: got unexpected plan from when clause 1"
with engine.prove('action_facts', 'weather', context,
(rule.pattern(1),)) \
as gen_2:
for x_2 in gen_2:
assert x_2 is None, \
"bc_action_rules.pits_1: got unexpected plan from when clause 2"
rule.rule_base.num_bc_rule_successes += 1
yield
rule.rule_base.num_bc_rule_failures += 1
finally:
context.done()
def pits_2(rule, arg_patterns, arg_context):
engine = rule.rule_base.engine
patterns = rule.goal_arg_patterns()
if len(arg_patterns) == len(patterns):
context = contexts.bc_context(rule)
try:
if all(map(lambda pat, arg:
pat.match_pattern(context, context,
arg, arg_context),
patterns,
arg_patterns)):
rule.rule_base.num_bc_rules_matched += 1
with engine.prove('action_facts', 'slick_tires', context,
(rule.pattern(0),)) \
as gen_1:
for x_1 in gen_1:
assert x_1 is None, \
"bc_action_rules.pits_2: got unexpected plan from when clause 1"
with engine.prove('action_facts', 'weather', context,
(rule.pattern(1),)) \
as gen_2:
for x_2 in gen_2:
assert x_2 is None, \
"bc_action_rules.pits_2: got unexpected plan from when clause 2"
if context.lookup_data('ans_1') != "Rainy":
with engine.prove('action_facts', 'humidity', context,
(rule.pattern(2),)) \
as gen_4:
for x_4 in gen_4:
assert x_4 is None, \
"bc_action_rules.pits_2: got unexpected plan from when clause 4"
if context.lookup_data('ans_2') <= 6:
rule.rule_base.num_bc_rule_successes += 1
yield
rule.rule_base.num_bc_rule_failures += 1
finally:
context.done()
def attack_1(rule, arg_patterns, arg_context):
engine = rule.rule_base.engine
patterns = rule.goal_arg_patterns()
if len(arg_patterns) == len(patterns):
context = contexts.bc_context(rule)
try:
if all(map(lambda pat, arg:
pat.match_pattern(context, context,
arg, arg_context),
patterns,
arg_patterns)):
rule.rule_base.num_bc_rules_matched += 1
with engine.prove('action_facts', 'section', context,
(rule.pattern(0),)) \
as gen_1:
for x_1 in gen_1:
assert x_1 is None, \
"bc_action_rules.attack_1: got unexpected plan from when clause 1"
with engine.prove('action_facts', 'nearest_forward', context,
(rule.pattern(1),)) \
as gen_2:
for x_2 in gen_2:
assert x_2 is None, \
"bc_action_rules.attack_1: got unexpected plan from when clause 2"
if context.lookup_data('ans') <= 0.5:
rule.rule_base.num_bc_rule_successes += 1
yield
rule.rule_base.num_bc_rule_failures += 1
finally:
context.done()
def attack_2(rule, arg_patterns, arg_context):
engine = rule.rule_base.engine
patterns = rule.goal_arg_patterns()
if len(arg_patterns) == len(patterns):
context = contexts.bc_context(rule)
try:
if all(map(lambda pat, arg:
pat.match_pattern(context, context,
arg, arg_context),
patterns,
arg_patterns)):
rule.rule_base.num_bc_rules_matched += 1
with engine.prove('action_facts', 'section', context,
(rule.pattern(0),)) \
as gen_1:
for x_1 in gen_1:
assert x_1 is None, \
"bc_action_rules.attack_2: got unexpected plan from when clause 1"
with engine.prove('action_facts', 'nearest_forward', context,
(rule.pattern(1),)) \
as gen_2:
for x_2 in gen_2:
assert x_2 is None, \
"bc_action_rules.attack_2: got unexpected plan from when clause 2"
if context.lookup_data('ans') <= 1:
rule.rule_base.num_bc_rule_successes += 1
yield
rule.rule_base.num_bc_rule_failures += 1
finally:
context.done()
def defend_1(rule, arg_patterns, arg_context):
engine = rule.rule_base.engine
patterns = rule.goal_arg_patterns()
if len(arg_patterns) == len(patterns):
context = contexts.bc_context(rule)
try:
if all(map(lambda pat, arg:
pat.match_pattern(context, context,
arg, arg_context),
patterns,
arg_patterns)):
rule.rule_base.num_bc_rules_matched += 1
with engine.prove('action_facts', 'section', context,
(rule.pattern(0),)) \
as gen_1:
for x_1 in gen_1:
assert x_1 is None, \
"bc_action_rules.defend_1: got unexpected plan from when clause 1"
with engine.prove('action_facts', 'nearest_behind', context,
(rule.pattern(1),)) \
as gen_2:
for x_2 in gen_2:
assert x_2 is None, \
"bc_action_rules.defend_1: got unexpected plan from when clause 2"
if context.lookup_data('ans') >= -0.5:
rule.rule_base.num_bc_rule_successes += 1
yield
rule.rule_base.num_bc_rule_failures += 1
finally:
context.done()
def defend_2(rule, arg_patterns, arg_context):
engine = rule.rule_base.engine
patterns = rule.goal_arg_patterns()
if len(arg_patterns) == len(patterns):
context = contexts.bc_context(rule)
try:
if all(map(lambda pat, arg:
pat.match_pattern(context, context,
arg, arg_context),
patterns,
arg_patterns)):
rule.rule_base.num_bc_rules_matched += 1
with engine.prove('action_facts', 'section', context,
(rule.pattern(0),)) \
as gen_1:
for x_1 in gen_1:
assert x_1 is None, \
"bc_action_rules.defend_2: got unexpected plan from when clause 1"
with engine.prove('action_facts', 'nearest_behind', context,
(rule.pattern(1),)) \
as gen_2:
for x_2 in gen_2:
assert x_2 is None, \
"bc_action_rules.defend_2: got unexpected plan from when clause 2"
if context.lookup_data('ans') >= -1:
rule.rule_base.num_bc_rule_successes += 1
yield
rule.rule_base.num_bc_rule_failures += 1
finally:
context.done()
def populate(engine):
This_rule_base = engine.get_create('bc_action_rules')
bc_rule.bc_rule('speed_up', This_rule_base, 'select_action',
speed_up, None,
(pattern.pattern_literal('SpeedUp'),),
(),
(pattern.pattern_literal("Lower"),))
bc_rule.bc_rule('keep_speed', This_rule_base, 'select_action',
keep_speed, None,
(pattern.pattern_literal('KeepSpeed'),),
(),
(pattern.pattern_literal("Same"),))
bc_rule.bc_rule('brake', This_rule_base, 'select_action',
brake, None,
(pattern.pattern_literal('Brake'),),
(),
(pattern.pattern_literal("Higher"),))
bc_rule.bc_rule('turn', This_rule_base, 'select_action',
turn, None,
(pattern.pattern_literal('Turn'),),
(),
(pattern.pattern_literal("Curve"),))
bc_rule.bc_rule('pits_1', This_rule_base, 'select_action',
pits_1, None,
(pattern.pattern_literal('Pits'),),
(),
(pattern.pattern_literal(True),
pattern.pattern_literal("Rainy"),))
bc_rule.bc_rule('pits_2', This_rule_base, 'select_action',
pits_2, None,
(pattern.pattern_literal('Pits'),),
(),
(pattern.pattern_literal(False),
contexts.variable('ans_1'),
contexts.variable('ans_2'),))
bc_rule.bc_rule('attack_1', This_rule_base, 'select_action',
attack_1, None,
(pattern.pattern_literal('Attack'),),
(),
(pattern.pattern_literal("Curve"),
contexts.variable('ans'),))
bc_rule.bc_rule('attack_2', This_rule_base, 'select_action',
attack_2, None,
(pattern.pattern_literal('Attack'),),
(),
(pattern.pattern_literal("Straight"),
contexts.variable('ans'),))
bc_rule.bc_rule('defend_1', This_rule_base, 'select_action',
defend_1, None,
(pattern.pattern_literal('Defend'),),
(),
(pattern.pattern_literal("Curve"),
contexts.variable('ans'),))
bc_rule.bc_rule('defend_2', This_rule_base, 'select_action',
defend_2, None,
(pattern.pattern_literal('Defend'),),
(),
(pattern.pattern_literal("Straight"),
contexts.variable('ans'),))
Krb_filename = '..\\bc_action_rules.krb'
Krb_lineno_map = (
((14, 18), (5, 5)),
((20, 25), (7, 7)),
((38, 42), (11, 11)),
((44, 49), (13, 13)),
((62, 66), (17, 17)),
((68, 73), (19, 19)),
((86, 90), (23, 23)),
((92, 97), (25, 25)),
((110, 114), (29, 29)),
((116, 121), (31, 31)),
((122, 127), (32, 32)),
((140, 144), (36, 36)),
((146, 151), (38, 38)),
((152, 157), (39, 39)),
((158, 158), (40, 40)),
((159, 164), (41, 41)),
((165, 165), (42, 42)),
((178, 182), (46, 46)),
((184, 189), (48, 48)),
((190, 195), (49, 49)),
((196, 196), (50, 50)),
((209, 213), (54, 54)),
((215, 220), (56, 56)),
((221, 226), (57, 57)),
((227, 227), (58, 58)),
((240, 244), (62, 62)),
((246, 251), (64, 64)),
((252, 257), (65, 65)),
((258, 258), (66, 66)),
((271, 275), (70, 70)),
((277, 282), (72, 72)),
((283, 288), (73, 73)),
((289, 289), (74, 74)),
)
|
python
|
"""
Created_at: 06 Oct. 2019 10:20:50
Target: EPISODES: set nullable `episodes.published_at`
"""
from playhouse.migrate import *
from migrations.models import database
previous = "0002_23052019_migration"
def upgrade():
migrator = PostgresqlMigrator(database)
migrate(migrator.drop_not_null("episodes", "published_at"))
def downgrade():
migrator = PostgresqlMigrator(database)
migrate(migrator.add_not_null("episodes", "published_at"))
|
python
|
#!/usr/bin/python
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import os
import sys
hidapi_topdir = os.path.join(os.getcwd(), 'hidapi')
hidapi_include = os.path.join(hidapi_topdir, 'hidapi')
def hidapi_src(platform):
return os.path.join(hidapi_topdir, platform, 'hid.c')
if sys.platform.startswith('linux'):
modules = [
Extension('hid',
sources = ['hid.pyx', 'chid.pxd', hidapi_src('libusb')],
include_dirs = [hidapi_include, '/usr/include/libusb-1.0'],
libraries = ['usb-1.0', 'udev', 'rt'],
),
Extension('hidraw',
sources = ['hidraw.pyx', hidapi_src('linux')],
include_dirs = [hidapi_include],
libraries = ['udev', 'rt'],
)
]
if sys.platform.startswith('darwin'):
os.environ['CFLAGS'] = '-framework IOKit -framework CoreFoundation'
os.environ['LDFLAGS'] = ''
modules = [
Extension('hid',
sources = ['hid.pyx', 'chid.pxd', hidapi_src('mac')],
include_dirs = [hidapi_include],
libraries = [],
)
]
if sys.platform.startswith('win'):
modules = [
Extension('hid',
sources = ['hid.pyx', 'chid.pxd', hidapi_src('windows')],
include_dirs = [hidapi_include],
libraries = ['setupapi'],
)
]
setup(
name = 'hidapi',
version = '0.7.99-5',
description = 'A Cython interface to the hidapi from https://github.com/signal11/hidapi',
author = 'Gary Bishop',
author_email = '[email protected]',
maintainer = 'Pavol Rusnak',
maintainer_email = '[email protected]',
url = 'https://github.com/trezor/cython-hidapi',
package_dir = {'hid': 'hidapi/*'},
classifiers = [
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX',
],
cmdclass = {'build_ext': build_ext},
ext_modules = modules
)
|
python
|
#!/bin/python
import csv
import sys
import struct
filename_in = sys.argv[1]
filename_out = sys.argv[2]
with open(filename_in) as csv_file:
csv_reader = csv.reader(csv_file, delimiter = ',');
line_count = 0
fileout = open(filename_out, "wb")
fileout.write(struct.pack('b', 0))
fileout.write(struct.pack('i', 0))
for row in csv_reader:
fileout.write(struct.pack('f', float(row[0])))
fileout.write(struct.pack('f', float(row[1])))
line_count = line_count+1
fileout.seek(1)
fileout.write(struct.pack('i', line_count))
|
python
|
# Copyright 2015-2021 SWIM.AI inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from abc import ABC, abstractmethod
from typing import Optional, Union, Any
class _ReconUtils:
@staticmethod
def _is_ident_start_char(char: Union[str, int]) -> bool:
"""
Check if a character is a valid first character of an identifier.
Valid start characters for identifiers: [A-Za-z_]
:param char: - Character to check.
:return: - True if the character is valid, False otherwise.
"""
if char:
char = _ReconUtils._to_ord(char)
return ord('A') <= char <= ord('Z') or char == ord('_') or ord('a') <= char <= ord('z')
else:
return False
@staticmethod
def _is_ident_char(char: Union[str, int]) -> bool:
"""
Check if a character is a valid character of an identifier.
Valid characters for identifiers: [A-Za-z_-]
:param char: - Character to check.
:return: - True if the character is valid, False otherwise.
"""
if char:
char = _ReconUtils._to_ord(char)
return char == ord('-') or _ReconUtils._is_digit(char) or _ReconUtils._is_ident_start_char(char)
else:
return False
@staticmethod
def _is_ident(value: str) -> bool:
"""
Check if a string value is a valid identifier.
:param value: - Value to check.
:return: - True if the value is valid identifier, False otherwise.
"""
if len(value) == 0:
return False
if not _ReconUtils._is_ident_start_char(value[0]):
return False
for char in value:
if not _ReconUtils._is_ident_char(char):
return False
return True
@staticmethod
def _is_space(char: Union[str, int]) -> bool:
"""
Check if a character is a space character.
:param char: - Character to check.
:return: - True if the character is a space character, False otherwise.
"""
if char:
char = _ReconUtils._to_ord(char)
return char == ord(' ') or char == ord('\t')
else:
return False
@staticmethod
def _is_digit(char: Union[str, int]) -> bool:
"""
Check if a character is a digit.
:param char: - Character to check.
:return: - True if the character is a digit, False otherwise.
"""
if char:
char = _ReconUtils._to_ord(char)
return ord('0') <= char <= ord('9')
else:
return False
@staticmethod
def _to_ord(char: Any) -> Optional[int]:
"""
Convert a character to its integer representation.
:param char: - Character to convert.
:return: - Integer representation of the character.
"""
if isinstance(char, str):
return ord(char)
if isinstance(char, int):
return char
else:
return None
class _Message(ABC):
def __init__(self) -> None:
self._message = ''
@property
def _value(self) -> str:
return self._message
@property
def _size(self) -> int:
return len(self._message)
@staticmethod
@abstractmethod
def _create(chars: str) -> '_Message':
raise NotImplementedError
def _append(self, obj: Any) -> None:
"""
Append the string representation of an object to the current message.
:param obj: - Object to append to the message.
"""
if isinstance(obj, str):
self._message = self._message + obj
elif isinstance(obj, (float, int)):
self._message = self._message + str(obj)
elif isinstance(obj, (_OutputMessage, _InputMessage)):
self._message = self._message + obj._value
else:
raise TypeError(f'Item of type {type(obj).__name__} cannot be added to Message!')
class _OutputMessage(_Message):
def __init__(self) -> None:
super().__init__()
@property
def _last_char(self) -> str:
"""
Return the last character of the message.
:return: - Last character of the message.
"""
if self._size > 0:
return self._message[-1]
else:
return ''
@staticmethod
def _create(chars: str = None) -> '_OutputMessage':
"""
Create an OutputMessage instance and initialise its message.
:param chars: - Initial value of the message.
:return: - OutputMessage instance.
"""
instance = _OutputMessage()
if chars:
instance._append(chars)
return instance
class _InputMessage(_Message):
def __init__(self) -> None:
super().__init__()
self.index = 0
@property
def _head(self) -> str:
"""
Get the character at the front of the InputMessage pointed by the message index.
:return: - The current head character of the InputMessage.
"""
if self._is_cont:
return self._message[self.index]
else:
return ''
@property
def _is_cont(self) -> bool:
"""
Check if there are any characters left in front of the InputMessage index.
:return: - False if the index is pointing at the last character or beyond, True otherwise.
"""
if self.index >= len(self._message):
return False
else:
return True
@staticmethod
def _create(chars: str = None) -> '_InputMessage':
"""
Create an OutputMessage instance and initialise its message.
:param chars: - Initial value of the message.
:return: - OutputMessage instance.
"""
instance = _InputMessage()
if chars:
instance._append(chars)
return instance
@staticmethod
def _skip_spaces(message: '_InputMessage') -> None:
"""
Moves the head of the message to the next non-space character.
:param message: - InputMessage object.
"""
char = message._head
while _ReconUtils._is_space(char):
char = message._step()
def _step(self) -> str:
"""
Move the head index forward by one.
:return: - The new head character of the InputMessage.
"""
self.index = self.index + 1
return self._head
|
python
|
import torch
import random
from layers import SEAL
from tqdm import trange
from utils import hierarchical_graph_reader, GraphDatasetGenerator
class SEALCITrainer(object):
"""
Semi-Supervised Graph Classification: A Hierarchical Graph Perspective Cautious Iteration model.
"""
def __init__(self,args):
"""
Creating dataset, doing dataset split, creating target and node index vectors.
:param args: Arguments object.
"""
self.args = args
self.macro_graph = hierarchical_graph_reader(self.args.hierarchical_graph)
self.dataset_generator = GraphDatasetGenerator(self.args.graphs)
self._setup_macro_graph()
self._create_split()
self._create_labeled_target()
self._create_node_indices()
def _setup_model(self):
"""
Creating a SEAL model.
"""
self.model = SEAL(self.args, self.dataset_generator.number_of_features, self.dataset_generator.number_of_labels)
def _setup_macro_graph(self):
"""
Creating an edge list for the hierarchical graph.
"""
self.macro_graph_edges = [[edge[0],edge[1]] for edge in self.macro_graph.edges()] + [[edge[1],edge[0]] for edge in self.macro_graph.edges()]
self.macro_graph_edges = torch.t(torch.LongTensor(self.macro_graph_edges))
def _create_split(self):
"""
Creating a labeled-unlabeled split.
"""
graph_indices = [index for index in range(len(self.dataset_generator.graphs))]
random.shuffle(graph_indices)
self.labeled_indices = graph_indices[0:self.args.labeled_count]
self.unlabeled_indices = graph_indices[self.args.labeled_count:]
def _create_labeled_target(self):
"""
Creating a mask for labeled instances and a target for them.
"""
self.labeled_mask = torch.LongTensor([0 for node in self.macro_graph.nodes()])
self.labeled_target = torch.LongTensor([0 for node in self.macro_graph.nodes()])
self.labeled_mask[torch.LongTensor(self.labeled_indices)] = 1
self.labeled_target[torch.LongTensor(self.labeled_indices)] = self.dataset_generator.target[torch.LongTensor(self.labeled_indices)]
def _create_node_indices(self):
"""
Creating an index of nodes.
"""
self.node_indices = [index for index in range(self.macro_graph.number_of_nodes())]
self.node_indices = torch.LongTensor(self.node_indices)
def fit_a_single_model(self):
"""
Fitting a single SEAL model.
"""
self._setup_model()
optimizer = torch.optim.Adam(self.model.parameters(), lr=self.args.learning_rate, weight_decay=self.args.weight_decay)
for epoch in range(self.args.epochs):
optimizer.zero_grad()
predictions, penalty = self.model(self.dataset_generator.graphs, self.macro_graph_edges)
loss = torch.nn.functional.nll_loss(predictions[self.labeled_mask==1], self.labeled_target[self.labeled_mask==1]) + self.args.gamma*penalty
loss.backward()
optimizer.step()
def score_a_single_model(self):
"""
Scoring the SEAL model.
"""
self.model.eval()
predictions, penalty = self.model(self.dataset_generator.graphs, self.macro_graph_edges)
scores, prediction_indices = predictions.max(dim=1)
correct = prediction_indices[self.labeled_mask==0].eq(self.labeled_target[self.labeled_mask==0]).sum().item()
normalizer = prediction_indices[self.labeled_mask==0].shape[0]
accuracy = float(correct)/float(normalizer)
return scores, prediction_indices, accuracy
def _choose_best_candidate(self, predictions, indices):
"""
Choosing the best candidate based on predictions.
:param predictions: Scores.
:param indices: Vector of likely labels.
:return candidate: Node chosen.
:return label: Label of node.
"""
nodes = self.node_indices[self.labeled_mask==0]
sub_predictions = predictions[self.labeled_mask==0]
sub_predictions, candidate = sub_predictions.max(dim=0)
candidate = nodes[candidate]
label = indices[candidate]
return candidate, label
def _update_target(self, candidate, label):
"""
Adding the new node to the mask and the target is updated with the predicted label.
:param candidate: Candidate node identifier.
:param label: Label of candidate node.
"""
self.labeled_mask[candidate] = 1
self.labeled_target[candidate] = label
def fit(self):
"""
Training models sequentially.
"""
print("\nTraining started.\n")
budget_size = trange(self.args.budget, desc='Unlabeled Accuracy: ', leave=True)
for step in budget_size:
self.fit_a_single_model()
scores, prediction_indices, accuracy = self.score_a_single_model()
candidate, label = self._choose_best_candidate(scores, prediction_indices)
self._update_target(candidate, label)
budget_size.set_description("Unlabeled Accuracy:%g" % round(accuracy, 4))
def score(self):
"""
Scoring the model.
"""
print("\nModel scoring.\n")
scores, prediction_indices, accuracy = self.score_a_single_model()
print("Unlabeled Accuracy:%g" % round(accuracy, 4))
|
python
|
# Copyright (c) 2017 NVIDIA Corporation
import torch
import argparse
from reco_encoder.data import input_layer
from reco_encoder.model import model
import torch.optim as optim
from torch.optim.lr_scheduler import MultiStepLR
import torch.nn as nn
from torch.autograd import Variable
import copy
import time
from pathlib import Path
from logger import Logger
from math import sqrt
import numpy as np
parser = argparse.ArgumentParser(description='RecoEncoder')
parser.add_argument('--lr', type=float, default=0.00001, metavar='N',
help='learning rate')
parser.add_argument('--weight_decay', type=float, default=0.0, metavar='N',
help='L2 weight decay')
parser.add_argument('--drop_prob', type=float, default=0.0, metavar='N',
help='dropout drop probability')
parser.add_argument('--noise_prob', type=float, default=0.0, metavar='N',
help='noise probability')
parser.add_argument('--batch_size', type=int, default=64, metavar='N',
help='global batch size')
parser.add_argument('--summary_frequency', type=int, default=100, metavar='N',
help='how often to save summaries')
parser.add_argument('--aug_step', type=int, default=-1, metavar='N',
help='do data augmentation every X step')
parser.add_argument('--constrained', action='store_true',
help='constrained autoencoder')
parser.add_argument('--skip_last_layer_nl', action='store_true',
help='if present, decoder\'s last layer will not apply non-linearity function')
parser.add_argument('--num_epochs', type=int, default=50, metavar='N',
help='maximum number of epochs')
parser.add_argument('--optimizer', type=str, default="adam", metavar='N',
help='optimizer kind: adam, momentum, adagrad or rmsprop')
parser.add_argument('--hidden_layers', type=str, default="1024,512,512,128", metavar='N',
help='hidden layer sizes, comma-separated')
parser.add_argument('--gpu_ids', type=str, default="0", metavar='N',
help='comma-separated gpu ids to use for data parallel training')
parser.add_argument('--path_to_train_data', type=str, default="", metavar='N',
help='Path to training data')
parser.add_argument('--path_to_eval_data', type=str, default="", metavar='N',
help='Path to evaluation data')
parser.add_argument('--non_linearity_type', type=str, default="selu", metavar='N',
help='type of the non-linearity used in activations')
parser.add_argument('--logdir', type=str, default="logs", metavar='N',
help='where to save model and write logs')
args = parser.parse_args()
print(args)
def do_eval(encoder, evaluation_data_layer):
encoder.eval()
denom = 0.0
total_epoch_loss = 0.0
for i, (eval, src) in enumerate(evaluation_data_layer.iterate_one_epoch_eval()):
inputs = Variable(src.cpu().to_dense())
targets = Variable(eval.cpu().to_dense())
outputs = encoder(inputs)
loss, num_ratings = model.MSEloss(outputs, targets)
total_epoch_loss += loss.data[0]
denom += num_ratings.data[0]
return sqrt(total_epoch_loss / denom)
def log_var_and_grad_summaries(logger, layers, global_step, prefix, log_histograms=False):
"""
Logs variable and grad stats for layer. Transfers data from GPU to CPU automatically
:param logger: TB logger
:param layers: param list
:param global_step: global step for TB
:param prefix: name prefix
:param log_histograms: (default: False) whether or not log histograms
:return:
"""
for ind, w in enumerate(layers):
# Variables
w_var = w.data.cpu().numpy()
logger.scalar_summary("Variables/FrobNorm/{}_{}".format(prefix, ind), np.linalg.norm(w_var),
global_step)
if log_histograms:
logger.histo_summary(tag="Variables/{}_{}".format(prefix, ind), values=w.data.cpu().numpy(),
step=global_step)
# Gradients
w_grad = w.grad.data.cpu().numpy()
logger.scalar_summary("Gradients/FrobNorm/{}_{}".format(prefix, ind), np.linalg.norm(w_grad),
global_step)
if log_histograms:
logger.histo_summary(tag="Gradients/{}_{}".format(prefix, ind), values=w.grad.data.cpu().numpy(),
step=global_step)
def main():
logger = Logger(args.logdir)
params = dict()
params['batch_size'] = args.batch_size
params['data_dir'] = args.path_to_train_data
params['major'] = 'users'
params['itemIdInd'] = 1
params['userIdInd'] = 0
print("Loading training data")
data_layer = input_layer.UserItemRecDataProvider(params=params)
print("Data loaded")
print("Total items found: {}".format(len(data_layer.data.keys())))
print("Vector dim: {}".format(data_layer.vector_dim))
print("Loading eval data")
eval_params = copy.deepcopy(params)
# must set eval batch size to 1 to make sure no examples are missed
eval_params['data_dir'] = args.path_to_eval_data
eval_data_layer = input_layer.UserItemRecDataProvider(params=eval_params,
user_id_map=data_layer.userIdMap, # the mappings are provided
item_id_map=data_layer.itemIdMap)
eval_data_layer.src_data = data_layer.data
rencoder = model.AutoEncoder(layer_sizes=[data_layer.vector_dim] + [int(l) for l in args.hidden_layers.split(',')],
nl_type=args.non_linearity_type,
is_constrained=args.constrained,
dp_drop_prob=args.drop_prob,
last_layer_activations=not args.skip_last_layer_nl)
model_checkpoint = args.logdir + "/model"
path_to_model = Path(model_checkpoint)
if path_to_model.is_file():
print("Loading model from: {}".format(model_checkpoint))
rencoder.load_state_dict(torch.load(model_checkpoint))
print('######################################################')
print('######################################################')
print('############# AutoEncoder Model: #####################')
print(rencoder)
print('######################################################')
print('######################################################')
gpu_ids = [int(g) for g in args.gpu_ids.split(',')]
print('Using GPUs: {}'.format(gpu_ids))
if len(gpu_ids)>1:
rencoder = nn.DataParallel(rencoder,
device_ids=gpu_ids)
rencoder = rencoder.cpu()
if args.optimizer == "adam":
optimizer = optim.Adam(rencoder.parameters(),
lr=args.lr,
weight_decay=args.weight_decay)
elif args.optimizer == "adagrad":
optimizer = optim.Adagrad(rencoder.parameters(),
lr=args.lr,
weight_decay=args.weight_decay)
elif args.optimizer == "momentum":
optimizer = optim.SGD(rencoder.parameters(),
lr=args.lr, momentum=0.9,
weight_decay=args.weight_decay)
scheduler = MultiStepLR(optimizer, milestones=[24, 36, 48, 66, 72], gamma=0.5)
elif args.optimizer == "rmsprop":
optimizer = optim.RMSprop(rencoder.parameters(),
lr=args.lr, momentum=0.9,
weight_decay=args.weight_decay)
else:
raise ValueError('Unknown optimizer kind')
t_loss = 0.0
t_loss_denom = 0.0
global_step = 0
if args.noise_prob > 0.0:
dp = nn.Dropout(p=args.noise_prob)
for epoch in range(args.num_epochs):
print('Doing epoch {} of {}'.format(epoch, args.num_epochs))
e_start_time = time.time()
rencoder.train()
total_epoch_loss = 0.0
denom = 0.0
if args.optimizer == "momentum":
scheduler.step()
for i, mb in enumerate(data_layer.iterate_one_epoch()):
inputs = Variable(mb.cpu().to_dense())
optimizer.zero_grad()
outputs = rencoder(inputs)
loss, num_ratings = model.MSEloss(outputs, inputs)
loss = loss / num_ratings
loss.backward()
optimizer.step()
global_step += 1
t_loss += loss.data[0]
t_loss_denom += 1
if i % args.summary_frequency == 0:
print('[%d, %5d] RMSE: %.7f' % (epoch, i, sqrt(t_loss / t_loss_denom)))
logger.scalar_summary("Training_RMSE", sqrt(t_loss/t_loss_denom), global_step)
t_loss = 0
t_loss_denom = 0.0
log_var_and_grad_summaries(logger, rencoder.encode_w, global_step, "Encode_W")
log_var_and_grad_summaries(logger, rencoder.encode_b, global_step, "Encode_b")
if not rencoder.is_constrained:
log_var_and_grad_summaries(logger, rencoder.decode_w, global_step, "Decode_W")
log_var_and_grad_summaries(logger, rencoder.decode_b, global_step, "Decode_b")
total_epoch_loss += loss.data[0]
denom += 1
#if args.aug_step > 0 and i % args.aug_step == 0 and i > 0:
if args.aug_step > 0:
# Magic data augmentation trick happen here
for t in range(args.aug_step):
inputs = Variable(outputs.data)
if args.noise_prob > 0.0:
inputs = dp(inputs)
optimizer.zero_grad()
outputs = rencoder(inputs)
loss, num_ratings = model.MSEloss(outputs, inputs)
loss = loss / num_ratings
loss.backward()
optimizer.step()
e_end_time = time.time()
print('Total epoch {} finished in {} seconds with TRAINING RMSE loss: {}'
.format(epoch, e_end_time - e_start_time, sqrt(total_epoch_loss/denom)))
logger.scalar_summary("Training_RMSE_per_epoch", sqrt(total_epoch_loss/denom), epoch)
logger.scalar_summary("Epoch_time", e_end_time - e_start_time, epoch)
if epoch % 3 == 0 or epoch == args.num_epochs - 1:
eval_loss = do_eval(rencoder, eval_data_layer)
print('Epoch {} EVALUATION LOSS: {}'.format(epoch, eval_loss))
logger.scalar_summary("EVALUATION_RMSE", eval_loss, epoch)
print("Saving model to {}".format(model_checkpoint + ".epoch_"+str(epoch)))
torch.save(rencoder.state_dict(), model_checkpoint + ".epoch_"+str(epoch))
print("Saving model to {}".format(model_checkpoint + ".last"))
torch.save(rencoder.state_dict(), model_checkpoint + ".last")
if __name__ == '__main__':
main()
|
python
|
# Copyright 2017 Become Corp. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Example code for
Service : KeywordEstimatorService
Operation: get
API Reference: https://github.com/yahoojp-marketing/sponsored-search-api-documents/blob/201901/docs/en/api_reference/services/KeywordEstimatorService.md
Generated by 'api_reference_example_generator.py' using code template 'examples/sample_template.py.template'
"""
import logging
import json
from yahooads import promotionalads
logging.basicConfig(level=logging.INFO)
# logging.getLogger('suds.client').setLevel(logging.DEBUG)
# logging.getLogger('suds.transport').setLevel(logging.DEBUG)
SERVICE = 'KeywordEstimatorService'
OPERATION = 'get'
OPERAND = {
"accountId": "SAMPLE-ACCOUNT-ID",
"campaignEstimateRequest": {
"campaignId": "SAMPLE-CAMPAIN-ID",
"adGroupEstimateRequests": [
{
"adGroupId": "SAMPLE-ADGROUP-ID",
"keywordEstimateRequests": {
"keyword": {
"text": "\u53e4\u7740",
"matchType": "PHRASE"
},
"isNegative": "FALSE",
"maxCpc": "5000"
},
"maxCpc": "800"
},
{
"adGroupId": "SAMPLE-ADGROUP-ID",
"keywordEstimateRequests": {
"keyword": {
"text": "\u82b1\u706b\u3000\u590f",
"matchType": "EXACT"
},
"isNegative": "FALSE",
"maxCpc": "9000"
},
"maxCpc": "1000"
}
],
"provinces": "JP-13",
"dailyBudget": "1000"
}
}
"""
SAMPLE RESPONSE = {
"rval": {
"totalNumEntries": "2",
"Page.Type": "KeywordEstimatorPage",
"values": [
{
"operationSucceeded": "true",
"data": {
"campaignId": "SAMPLE-CAMPAIN-ID",
"adGroupId": "SAMPLE-ADGROUP-ID",
"keyword": "\u53e4\u7740",
"min": {
"clicks": "29.59",
"rank": "1.0",
"cpc": "32.11",
"cost": "1055.55",
"impressions": "3000.0",
"ctr": "0.0012"
},
"max": {
"clicks": "36.16",
"rank": "1.1",
"cpc": "39.24",
"cost": "1290.12",
"impressions": "3100.0",
"ctr": "0.0022"
}
}
},
{
"operationSucceeded": "true",
"data": {
"campaignId": "SAMPLE-CAMPAIN-ID",
"adGroupId": "SAMPLE-ADGROUP-ID",
"keyword": "\u82b1\u706b\u3000\u590f",
"min": {
"clicks": "11.59",
"rank": "1.0",
"cpc": "32.01",
"cost": "2055.55",
"impressions": "3000.0",
"ctr": "0.0012"
},
"max": {
"clicks": "9999.16",
"rank": "1.1",
"cpc": "39.24",
"cost": "3290.12",
"impressions": "3100.0",
"ctr": "0.0022"
}
}
}
]
}
}
"""
def main():
client = promotionalads.PromotionalAdsClient.LoadFromConfiguration()
service = client.GetService(SERVICE)
print("REQUEST : {}.{}\n{}".format(SERVICE, OPERATION, json.dumps(OPERAND, indent=2)))
try:
if OPERATION == "get":
response = service.get(OPERAND)
elif OPERATION.startswith("get"):
get_method = getattr(service, OPERATION)
response = get_method(OPERAND)
elif OPERATION.startswith("mutate"):
response = service.mutate(OPERAND)
else:
raise("Unknown Operation '{}'".format(OPERATION))
print("RESPONSE :\n{}".format(response))
except Exception as e:
print("Exception at '{}' operations \n{}".format(SERVICE, e))
raise e
if __name__ == '__main__':
main()
|
python
|
"""Module for all encryption"""
# standard imports
import hashlib
import binascii
from os import urandom, getenv
from uuid import uuid4
# third party imports
from authlib.specs.rfc7519 import jwt
# local imports
from api.utilities.constants import CHARSETS
from api.utilities.constants import MESSAGES
from api.utilities.validations.custom_validations_error import ValidationError
from api.utilities.helpers.date_time import date_time
from api.utilities.helpers.errors import raises
class Encryption:
"""Class for all encryption"""
@staticmethod
def hash(password):
"""Hash password.
Args:
password (Str): Password to hash.
Returns:
String: Hashed password.
"""
# generate random values to generate the salt for hashing
random_bytes = urandom(120) + str(uuid4()).encode(CHARSETS[1])
# generate salt for the password hashing
salt = hashlib.sha256(random_bytes).hexdigest().encode(CHARSETS[1])
# hash the password
pwd_hash = hashlib.pbkdf2_hmac('sha512', password.encode(CHARSETS[0]),
salt, 100000)
# convert the hash to a hexadecimal
pwd_hash = binascii.hexlify(pwd_hash)
# returns the hash + salt
return (salt + pwd_hash).decode(CHARSETS[1])
@staticmethod
def verify(stored_password, provided_password):
"""Verify a stored password against one provided by user.
Args:
stored_password (Str): The stored password.
provided_password (Str): The password provided by the user.
Returns:
Boolean:
"""
# get the first 64 characters from the stored
# password, this is the salt
salt = stored_password[:64]
# get the remaining characters from the 64th index,
# this is the stored password
stored_password = stored_password[64:]
# hash the provided password
pwdhash = hashlib.pbkdf2_hmac('sha512',
provided_password.encode(CHARSETS[0]),
salt.encode(CHARSETS[1]), 100000)
# convert the hash to a hexadecimal and decode to ascii
pwdhash = binascii.hexlify(pwdhash).decode(CHARSETS[1])
# compares the hashed password with the stored hash
return pwdhash == stored_password
@staticmethod
def tokenize(payload, subject=None, **kwargs):
"""Generates a token for the given payload.
Args:
payload (dict): Payload
subject (str): Subject of the encryption
Returns:
String: JWT token
"""
header = {'alg': 'RS256'}
data = {
'data':
payload,
'iat':
date_time.time(),
'exp':
date_time.time(manipulate=True, manipulation_type='ADD', **kwargs),
'aud':
'Yard-it.com.ng',
'iss':
'Yard-it-API',
'sub':
subject
}
private_key = getenv('JWT_PRIVATE_KEY')
token = jwt.encode(
header=header, payload=data, key=private_key).decode(CHARSETS[0])
return token
@staticmethod
def detokenize(token):
"""Decodes the passed JWT token.
Args:
token (str): JWT token
Returns:
Dict: A dictionary of the decoded data.
"""
public_key = getenv('JWT_PUBLIC_KEY')
decoded_token = jwt.decode(token, public_key) if token else None
dt = date_time.time().timestamp()
now = int(round(dt))
if not decoded_token:
raises('No token was provided', 400)
if decoded_token and decoded_token['exp'] < now:
raises(MESSAGES['EXPIRED_TOKEN'], 403)
return decoded_token
|
python
|
from common import *
## for debug
def dummy_transform(image):
print ('\tdummy_transform')
return image
# kaggle science bowl-2 : ################################################################
def resize_to_factor2(image, mask, factor=16):
H,W = image.shape[:2]
h = (H//factor)*factor
w = (W //factor)*factor
return fix_resize_transform2(image, mask, w, h)
def fix_resize_transform2(image, mask, w, h):
H,W = image.shape[:2]
if (H,W) != (h,w):
image = cv2.resize(image,(w,h))
mask = mask.astype(np.float32)
mask = cv2.resize(mask,(w,h),cv2.INTER_NEAREST)
mask = mask.astype(np.int32)
return image, mask
def fix_crop_transform2(image, mask, x,y,w,h):
H,W = image.shape[:2]
assert(H>=h)
assert(W >=w)
if (x==-1 & y==-1):
x=(W-w)//2
y=(H-h)//2
if (x,y,w,h) != (0,0,W,H):
image = image[y:y+h, x:x+w]
mask = mask[y:y+h, x:x+w]
return image, mask
def random_crop_transform2(image, mask, w,h, u=0.5):
x,y = -1,-1
if random.random() < u:
H,W = image.shape[:2]
if H!=h:
y = np.random.choice(H-h)
else:
y=0
if W!=w:
x = np.random.choice(W-w)
else:
x=0
return fix_crop_transform2(image, mask, x,y,w,h)
def random_horizontal_flip_transform2(image, mask, u=0.5):
if random.random() < u:
image = cv2.flip(image,1) #np.fliplr(img) ##left-right
mask = cv2.flip(mask,1)
return image, mask
def random_vertical_flip_transform2(image, mask, u=0.5):
if random.random() < u:
image = cv2.flip(image,0)
mask = cv2.flip(mask,0)
return image, mask
def random_rotate90_transform2(image, mask, u=0.5):
if random.random() < u:
angle=random.randint(1,3)*90
if angle == 90:
image = image.transpose(1,0,2) #cv2.transpose(img)
image = cv2.flip(image,1)
mask = mask.transpose(1,0)
mask = cv2.flip(mask,1)
elif angle == 180:
image = cv2.flip(image,-1)
mask = cv2.flip(mask,-1)
elif angle == 270:
image = image.transpose(1,0,2) #cv2.transpose(img)
image = cv2.flip(image,0)
mask = mask.transpose(1,0)
mask = cv2.flip(mask,0)
return image, mask
def relabel_multi_mask(multi_mask):
data = multi_mask
data = data[:,:,np.newaxis]
unique_color = set( tuple(v) for m in data for v in m )
#print(len(unique_color))
H,W = data.shape[:2]
multi_mask = np.zeros((H,W),np.int32)
for color in unique_color:
#print(color)
if color == (0,): continue
mask = (data==color).all(axis=2)
label = skimage.morphology.label(mask)
index = [label!=0]
multi_mask[index] = label[index]+multi_mask.max()
return multi_mask
def random_shift_scale_rotate_transform2( image, mask,
shift_limit=[-0.0625,0.0625], scale_limit=[1/1.2,1.2],
rotate_limit=[-15,15], borderMode=cv2.BORDER_REFLECT_101 , u=0.5):
#cv2.BORDER_REFLECT_101 cv2.BORDER_CONSTANT
if random.random() < u:
height, width, channel = image.shape
angle = random.uniform(rotate_limit[0],rotate_limit[1]) #degree
scale = random.uniform(scale_limit[0],scale_limit[1])
sx = scale
sy = scale
dx = round(random.uniform(shift_limit[0],shift_limit[1])*width )
dy = round(random.uniform(shift_limit[0],shift_limit[1])*height)
cc = math.cos(angle/180*math.pi)*(sx)
ss = math.sin(angle/180*math.pi)*(sy)
rotate_matrix = np.array([ [cc,-ss], [ss,cc] ])
box0 = np.array([ [0,0], [width,0], [width,height], [0,height], ])
box1 = box0 - np.array([width/2,height/2])
box1 = np.dot(box1,rotate_matrix.T) + np.array([width/2+dx,height/2+dy])
box0 = box0.astype(np.float32)
box1 = box1.astype(np.float32)
mat = cv2.getPerspectiveTransform(box0,box1)
image = cv2.warpPerspective(image, mat, (width,height),flags=cv2.INTER_LINEAR,
borderMode=borderMode,borderValue=(0,0,0,)) #cv2.BORDER_CONSTANT, borderValue = (0, 0, 0)) #cv2.BORDER_REFLECT_101
mask = mask.astype(np.float32)
mask = cv2.warpPerspective(mask, mat, (width,height),flags=cv2.INTER_NEAREST,#cv2.INTER_LINEAR
borderMode=borderMode,borderValue=(0,0,0,)) #cv2.BORDER_CONSTANT, borderValue = (0, 0, 0)) #cv2.BORDER_REFLECT_101
mask = mask.astype(np.int32)
mask = relabel_multi_mask(mask)
return image, mask
# single image ########################################################
#agumentation (photometric) ----------------------
def random_brightness_shift_transform(image, limit=[16,64], u=0.5):
if np.random.random() < u:
alpha = np.random.uniform(limit[0], limit[1])
image = image + alpha*255
image = np.clip(image, 0, 255).astype(np.uint8)
return image
def random_brightness_transform(image, limit=[0.5,1.5], u=0.5):
if np.random.random() < u:
alpha = np.random.uniform(limit[0], limit[1])
image = alpha*image
image = np.clip(image, 0, 255).astype(np.uint8)
return image
def random_contrast_transform(image, limit=[0.5,1.5], u=0.5):
if np.random.random() < u:
alpha = np.random.uniform(limit[0], limit[1])
coef = np.array([[[0.114, 0.587, 0.299]]]) #rgb to gray (YCbCr)
gray = image * coef
gray = (3.0 * (1.0 - alpha) / gray.size) * np.sum(gray)
image = alpha*image + gray
image = np.clip(image, 0, 255).astype(np.uint8)
return image
def random_saturation_transform(image, limit=[0.5,1.5], u=0.5):
if np.random.random() < u:
alpha = np.random.uniform(limit[0], limit[1])
coef = np.array([[[0.114, 0.587, 0.299]]])
gray = image * coef
gray = np.sum(gray,axis=2, keepdims=True)
image = alpha*image + (1.0 - alpha)*gray
image = np.clip(image, 0, 255).astype(np.uint8)
return image
# https://github.com/chainer/chainercv/blob/master/chainercv/links/model/ssd/transforms.py
# https://github.com/fchollet/keras/pull/4806/files
# https://zhuanlan.zhihu.com/p/24425116
# http://lamda.nju.edu.cn/weixs/project/CNNTricks/CNNTricks.html
def random_hue_transform(image, limit=[-0.1,0.1], u=0.5):
if random.random() < u:
h = int(np.random.uniform(limit[0], limit[1])*180)
#print(h)
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
hsv[:, :, 0] = (hsv[:, :, 0].astype(int) + h) % 180
image = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
return image
def random_noise_transform(image, limit=[0, 0.5], u=0.5):
if random.random() < u:
H,W = image.shape[:2]
noise = np.random.uniform(limit[0],limit[1],size=(H,W))*255
image = image + noise[:,:,np.newaxis]*np.array([1,1,1])
image = np.clip(image, 0, 255).astype(np.uint8)
return image
# geometric ---
def resize_to_factor(image, factor=16):
height,width = image.shape[:2]
h = (height//factor)*factor
w = (width //factor)*factor
return fix_resize_transform(image, w, h)
def fix_resize_transform(image, w, h):
height,width = image.shape[:2]
if (height,width) != (h,w):
image = cv2.resize(image,(w,h))
return image
def pad_to_factor(image, factor=16):
height,width = image.shape[:2]
h = math.ceil(height/factor)*factor
w = math.ceil(width/factor)*factor
image = cv2.copyMakeBorder(image, top=0, bottom=h-height, left=0, right=w-width,
borderType= cv2.BORDER_REFLECT101, value=[0,0,0] )
return image
# main #################################################################
if __name__ == '__main__':
print( '%s: calling main function ... ' % os.path.basename(__file__))
print('\nsucess!')
|
python
|
import wrapper as w
import json
outFile = open("data/tgt/linear/test.txt", "w")
with open("data/tgt/giant_news0tgt0.txt", "r") as inFile:
for line in inFile:
serialized = json.loads(line[line.index("\t"):])
ex = w.GrapheneExtract(serialized)
linear = ex.linearize()
if linear != "":
outFile.write(line[:line.index("\t")] + "\t" + linear + "\n")
outFile.close()
|
python
|
"""
Copyright(c) 2021 Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
"""
from botocore.session import Session
from .command import MFACommand
def awscli_initialize(cli):
""" Entry point called by awscli """
cli.register('building-command-table.main', register_mfa_command)
def register_mfa_command(command_table, session: Session, **kwargs):
""" Register mfa command """
command_table['mfa'] = MFACommand(session)
|
python
|
from clases.catastrofe import catastrofe
from clases.catastrofe import AlDiaSiguiente
from clases.yinyang import Yin
from clases.yinyang import Yang
from clases.herenciaMultiple import Pared
from clases.herenciaMultiple import Ventana
from clases.herenciaMultiple import Casa
from clases.herenciaMultiple import ParedCortina
if __name__=="__main__":
print(AlDiaSiguiente.ciudades("new_york " , "los_angeles"))
if __name__== "__main__":
yin = Yin()
yang = Yang()
yin.yang = yang
print(yang)
print(yang is yin.yang)
Yang.__del__(yang)
print("?")
if __name__== "__main__":
Pared
Ventana
Casa
pared_norte = Pared("NORTE")
pared_oeste = Pared("OESTEE")
pared_sur = Pared("SUR")
pared_este = Pared("ESTE")
ventana_norte = Ventana(pared_norte, 0.5, "persiana")
ventana_oeste = Ventana(pared_oeste, 1, "persiana")
ventana_sur = Ventana(pared_sur, 2, "store vénitien")
ventana_este = Ventana(pared_este, 1, "persiana")
casa = Casa([pared_norte, pared_oeste, pared_sur, pared_este])
print(casa.superficie_cristal())
ParedCortina
pared_cortina = ParedCortina("SUR", 10)
casa.paredes[2] = pared_cortina
print(casa.superficie_cristal())
|
python
|
# Exercise 2.12
from math import *
ballRadius = float(input("Please enter the radius: "))
ballVolume = 4 / 3 * pi * ballRadius ** 3
ballSpace = 4 * pi * ballRadius ** 2
print("The Volume of the ball is", ballVolume)
print("The Superficial Area of the ball is", ballSpace)
|
python
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# These imports are for python3 compatibility inside python2
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import threading
import time
import cachetools
from apex.aprs import util as aprs_util
from .util import echo_colorized_frame
from .util import echo_colorized_warning
class NonrepeatingBuffer(object):
def __init__(self, base_tnc, base_name, base_port=None, echo_packets=True, buffer_size=10000, buffer_time=30):
self.packet_cache = cachetools.TTLCache(buffer_size, buffer_time)
self.lock = threading.Lock()
self.base_tnc = base_tnc
self.base_port = base_port
self.base_name = base_name
self.echo_packets = echo_packets
@property
def port(self):
return self.base_port
@property
def name(self):
return self.base_name
def connect(self, *args, **kwargs):
self.base_tnc.connect(*args, **kwargs)
def close(self, *args, **kwargs):
self.base_tnc.close(*args, **kwargs)
def write(self, frame, *args, **kwargs):
with self.lock:
frame_hash = str(aprs_util.hash_frame(frame))
if frame_hash not in self.packet_cache:
self.packet_cache[frame_hash] = frame
if self.base_port:
self.base_tnc.write(frame, self.base_port)
else:
self.base_tnc.write(frame)
if self.echo_packets:
echo_colorized_frame(frame, self.base_name, False)
def read(self, *args, **kwargs):
with self.lock:
frame = self.base_tnc.read(*args, **kwargs)
if not frame:
return frame
frame_hash = str(aprs_util.hash_frame(frame))
if frame_hash not in self.packet_cache:
self.packet_cache[frame_hash] = frame
if self.echo_packets:
echo_colorized_frame(frame, self.base_name, True)
return frame
else:
return None
class ReconnectingPacketBuffer(object):
STARTING_WAIT_TIME = 2
MAX_WAIT_TIME = 300
WAIT_TIME_MULTIPLIER = 2
MAX_INDEX = 1000000
def __init__(self, packet_layer):
self.packet_layer = packet_layer
self.to_packet_layer = cachetools.TTLCache(10, 30)
self.current_index = 0
self.from_packet_layer = cachetools.TTLCache(10, 30)
self.connect_thread = None
self.lock = threading.Lock()
self.running = False
self.reconnect_wait_time = self.STARTING_WAIT_TIME
self.last_connect_attempt = None
self.connect_args = None
self.connect_kwargs = None
self.connected = False
def __increment_wait_time(self):
self.reconnect_wait_time *= self.WAIT_TIME_MULTIPLIER
if self.reconnect_wait_time > self.MAX_WAIT_TIME:
self.reconnect_wait_time = self.MAX_WAIT_TIME
def __reset_wait_time(self):
self.reconnect_wait_time = self.STARTING_WAIT_TIME
def __run(self):
while self.running:
if not self.connected:
if not self.last_connect_attempt or time.time() - self.last_connect_attempt > self.reconnect_wait_time:
try:
self.last_connect_attempt = time.time()
self.packet_layer.connect(*self.connect_args, **self.connect_kwargs)
self.connected = True
except IOError:
echo_colorized_warning('Could not connect, will reattempt.')
try:
self.packet_layer.close()
except IOError:
pass
self.__increment_wait_time()
else:
time.sleep(1)
else:
io_occured = False
# lets attempt to read in a packet
try:
read_packet = self.packet_layer.read()
self.__reset_wait_time()
if read_packet:
with self.lock:
self.from_packet_layer[str(aprs_util.hash_frame(read_packet))] = read_packet
io_occured = True
except IOError:
echo_colorized_warning('Read failed. Will disconnect and attempt to reconnect.')
try:
self.packet_layer.close()
except IOError:
pass
self.connected = False
continue
# lets try to write a packet, if any are waiting.
write_packet = None
with self.lock:
if self.to_packet_layer:
write_packet = self.to_packet_layer.popitem()[1]
if write_packet:
try:
self.packet_layer.write(write_packet)
io_occured = True
self.__reset_wait_time()
except IOError:
echo_colorized_warning('Write failed. Will disconnect and attempt to reconnect.')
self.to_packet_layer[str(aprs_util.hash_frame(read_packet))] = write_packet
try:
self.packet_layer.close()
except IOError:
pass
self.connected = False
continue
if not io_occured:
time.sleep(1)
try:
self.packet_layer.close()
except IOError:
pass
def connect(self, *args, **kwargs):
with self.lock:
if self.connect_thread:
raise RuntimeError('already connected')
self.running = True
self.connect_args = args
self.connect_kwargs = kwargs
self.connect_thread = threading.Thread(target=self.__run)
self.connect_thread.start()
def close(self):
with self.lock:
if not self.connect_thread:
raise RuntimeError('not connected')
self.running = False
self.connect_thread.join()
self.connect_thread = None
def read(self):
with self.lock:
if self.from_packet_layer:
return self.from_packet_layer.popitem()[1]
return None
def write(self, packet):
with self.lock:
self.to_packet_layer[str(aprs_util.hash_frame(packet))] = packet
|
python
|
# Copyright (C) 2013-2016 DNAnexus, Inc.
#
# This file is part of dx-toolkit (DNAnexus platform client libraries).
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
'''
Accessing App-Specific Containers
+++++++++++++++++++++++++++++++++
Apps have associated resource containers and project cache containers.
To easily access these, the following utility functions are provided.
These functions are meant to be called only by a job.
'''
from __future__ import print_function, unicode_literals, division, absolute_import
import os
import dxpy
from ..exceptions import DXError
from .search import find_one_data_object
def load_app_resource(**kwargs):
'''
:param kwargs: keyword args for :func:`~dxpy.bindings.search.find_one_data_object`, with the exception of "project"
:raises: :exc:`~dxpy.exceptions.DXError` if "project" is given, if this is called with dxpy.JOB_ID not set, or if "DX_RESOURCES_ID" or "DX_PROJECT_CONTEXT_ID" is not found in the environment variables
:returns: None if no matching object is found; otherwise returns a dxpy object handler for that class of object
Searches for a data object in the app resources container matching the given keyword arguments. If found, the
object will be cloned into the running job's workspace container, and the handler for it will be returned. If the
app resources container ID is not found in DX_RESOURCES_ID, falls back to looking in the current project.
Example::
@dxpy.entry_point('main')
def main(*args, **kwargs):
x = load_app_resource(name="Indexed genome", classname='file')
dxpy.download_dxfile(x)
'''
if 'project' in kwargs:
raise DXError('Unexpected kwarg: "project"')
if dxpy.JOB_ID is None:
raise DXError('Not called by a job')
if 'DX_RESOURCES_ID' not in os.environ and 'DX_PROJECT_CONTEXT_ID' not in os.environ:
raise DXError('App resources container ID could not be found')
kwargs['project'] = os.environ.get('DX_RESOURCES_ID', os.environ.get('DX_PROJECT_CONTEXT_ID'))
kwargs['return_handler'] = True
return find_one_data_object(**kwargs)
def load_from_cache(**kwargs):
'''
:param kwargs: keyword args for :func:`~dxpy.bindings.search.find_one_data_object`, with the exception of "project"
:raises: :exc:`~dxpy.exceptions.DXError` if "project" is given, if this is called with dxpy.JOB_ID not set, or if "DX_PROJECT_CACHE_ID" is not found in the environment variables
:returns: None if no matching object is found; otherwise returns a dxpy object handler for that class of object
Searches for a data object in the project cache container matching
the given keyword arguments. If found, the object will be cloned
into the running job's workspace container, and the handler for it
will be returned.
Example::
@dxpy.entry_point('main')
def main(*args, **kwargs):
x = load_from_cache(name="Indexed genome", classname='file')
if x is None:
x = compute_result(*args)
save_to_cache(x)
'''
if 'project' in kwargs:
raise DXError('Unexpected kwarg: "project"')
if dxpy.JOB_ID is None:
raise DXError('Not called by a job')
if 'DX_PROJECT_CACHE_ID' not in os.environ:
raise DXError('Project cache ID could not be found in the environment variable DX_PROJECT_CACHE_ID')
kwargs['project'] = os.environ.get('DX_PROJECT_CACHE_ID')
kwargs['return_handler'] = True
cached_object = find_one_data_object(**kwargs)
if cached_object is None:
return None
return cached_object.clone(dxpy.WORKSPACE_ID)
# Maybe this should be a member function of a data object?
def save_to_cache(dxobject):
'''
:param dxobject: a dxpy object handler for an object to save to the cache
:raises: :exc:`~dxpy.exceptions.DXError` if this is called with dxpy.JOB_ID not set, or if "DX_PROJECT_CACHE_ID" is not found in the environment variables
Clones the given object to the project cache.
Example::
@dxpy.entry_point('main')
def main(*args, **kwargs):
x = load_from_cache(name="Indexed genome", classname='file')
if x is None:
x = compute_result(*args)
save_to_cache(x)
'''
if dxpy.JOB_ID is None:
raise DXError('Not called by a job')
if 'DX_PROJECT_CACHE_ID' not in os.environ:
raise DXError('Project cache ID could not be found in the environment variable DX_PROJECT_CACHE_ID')
dxobject.clone(os.environ.get('DX_PROJECT_CACHE_ID'))
|
python
|
from structural.composite.logic.order_calculator import OrderCalculator
class Product(OrderCalculator):
def __init__(self, name: str, value: float) -> None:
self._name = name
self._value = value
@property
def name(self) -> str:
return self._name
@property
def value(self) -> float:
return self._value
@property
def is_composite(self) -> bool:
return False
def __iter__(self) -> float:
yield self.value
|
python
|
# Copyright (C) 2016-2021 Alibaba Group Holding Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import threading
from efl import exporter
local = threading.local()
@exporter.export("Stage")
class Stage(object):
def __init__(self):
pass
@property
def sess(self):
return local.sess
def __call__(self, *args, **kwargs):
def func(sess):
local.sess = sess
return self.run(*args, **kwargs)
return func
def run(self, *args, **kwargs):
raise NotImplementedError("Stage's run func should be implemented")
|
python
|
#!/usr/bin/env python3
# Copyright 2019 Kohei Morita
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import sys
import resource
import argparse
from os import getenv, getuid, environ
from pwd import getpwnam
from shutil import rmtree
from datetime import datetime
from pathlib import Path
from logging import basicConfig, getLogger
import subprocess
from subprocess import run
import tempfile
from psutil import Process
logger = getLogger(__name__)
def outside(args, cmd):
logger.info('outside')
tmp = tempfile.NamedTemporaryFile()
arg = ['unshare', '-fpnm', '--mount-proc']
arg += [sys.argv[0]]
arg += ['--inside']
arg += ['--insideresult', tmp.name]
arg += sys.argv[1:]
mycode = 0
returncode = -1
time = -1
memory = -1
try:
proc = subprocess.run(arg, timeout=args.tl + 5.0)
mycode = proc.returncode
result = json.load(tmp)
returncode = result.get('returncode', -1)
time = result.get('time', -1)
memory = result.get('memory', -1)
except subprocess.TimeoutExpired:
logger.warning('outside catch timeout, this is unexpected')
mycode = 124
time = args.tl
result = {
'returncode': returncode,
'time': time,
'memory': memory,
}
logger.info('outside result = {}'.format(result))
if args.result:
args.result.write(json.dumps(result))
return mycode
def inside(args, execcmd):
logger.info('inside execute: {}'.format(execcmd))
# expand stack
resource.setrlimit(resource.RLIMIT_STACK,
(resource.RLIM_INFINITY, resource.RLIM_INFINITY))
# TODO: use TemporaryDirectory
tmpdir = Path(tempfile.mkdtemp())
tmpdir.chmod(0o777)
prepare_mount(tmpdir, args.overlay)
prepare_cgroup()
cmd = ['cgexec', '-g', 'pids,cpuset,memory:lib-judge']
cmd += ['chroot',
'--userspec=library-checker-user:library-checker-user', str(tmpdir)]
cmd += ['sh', '-c', ' '.join(['cd', 'sand', '&&'] + execcmd)]
mycode = 0
returncode = -1
time = -1
memory = -1
start = datetime.now()
try:
proc = subprocess.run(cmd,
stdin=args.stdin,
stdout=args.stdout,
stderr=args.stderr,
timeout=args.tl)
returncode = proc.returncode
except subprocess.TimeoutExpired:
logger.info('timeout command')
mycode = 124 # error code of timeout command
time = args.tl
else:
end = datetime.now()
time = (end - start).seconds + (end - start).microseconds / 1000000
with open('/sys/fs/cgroup/memory/lib-judge/memory.max_usage_in_bytes', 'r') as f:
memory = int(f.read())
subprocess.run(['pkill', '-KILL', '-u', 'library-checker-user'])
for child in Process().children():
child.wait()
result = {
'returncode': returncode,
'time': time,
'memory': memory,
}
logger.info('inside result = {}'.format(result))
args.insideresult.write(json.dumps({
'returncode': returncode,
'time': time,
'memory': memory,
}))
return mycode
def prepare_mount(tmpdir: Path, overlay):
sanddir = tmpdir / 'sand'
sanddir.mkdir()
if overlay:
workdir = Path(tempfile.mkdtemp())
workdir.chmod(0o777)
upperdir = Path(tempfile.mkdtemp())
upperdir.chmod(0o777)
cmd = ['mount', '-t', 'overlay', 'overlay', '-o']
cmd += ['lowerdir={},upperdir={},workdir={}'.format(
'./', str(upperdir), str(workdir))]
cmd += [str(sanddir)]
subprocess.run(cmd, check=True)
else:
cmd = ['mount', '--bind', './', str(sanddir)]
subprocess.run(cmd, check=True)
(tmpdir / 'proc').mkdir()
subprocess.run(['mount', '-t', 'proc', 'none',
str(tmpdir / 'proc')], check=True)
(tmpdir / 'tmp').mkdir()
(tmpdir / 'tmp').chmod(0o777)
for dname in ['dev', 'sys', 'bin', 'lib', 'lib64', 'usr', 'etc', 'opt', 'var']:
(tmpdir / dname).mkdir()
subprocess.run(['mount', '--bind', '-o', 'ro', '/' + dname,
str(tmpdir / dname)], check=True)
def prepare_cgroup():
run(['cgdelete', 'pids,cpuset,memory:/lib-judge'])
run(['cgcreate', '-g', 'pids,cpuset,memory:/lib-judge'], check=True)
run(['cgset', '-r', 'pids.max=1000', 'lib-judge'], check=True)
run(['cgset', '-r', 'cpuset.cpus=0', 'lib-judge'], check=True)
run(['cgset', '-r', 'cpuset.mems=0', 'lib-judge'], check=True)
run(['cgset', '-r', 'memory.limit_in_bytes=1G', 'lib-judge'], check=True)
run(['cgset', '-r', 'memory.memsw.limit_in_bytes=1G', 'lib-judge'], check=True)
if __name__ == "__main__":
basicConfig(
level=getenv('LOG_LEVEL', 'WARN'),
format="%(asctime)s %(levelname)s %(name)s : %(message)s"
)
assert sys.argv.count("--") == 1
if sys.argv.count("--") == 0:
logger.error('args must have -- : {}'.format(sys.argv))
exit(1)
sep_index = sys.argv.index("--")
parser = argparse.ArgumentParser(
description='Testcase Generator', usage='%(prog)s [options] -- command')
parser.add_argument('--stdin', type=argparse.FileType('r'), help='stdin')
parser.add_argument('--stdout', type=argparse.FileType('w'), help='stdout')
parser.add_argument('--stderr', type=argparse.FileType('w'), help='stderr')
parser.add_argument('--overlay', action='store_true',
help='overlay current dir?')
parser.add_argument('--result', type=argparse.FileType('w'),
help='result file')
parser.add_argument('--inside', action='store_true',
help='inside flag(DONT USE THIS FLAG DIRECTLY)')
parser.add_argument('--insideresult', type=argparse.FileType('w'),
help='inside result file(DONT USE THIS FLAG DIRECTLY)')
parser.add_argument('--tl', type=float, help='Time Limit', default=3600.0)
args = parser.parse_args(sys.argv[1:sep_index])
cmd = sys.argv[sep_index + 1:]
if not (0 <= args.tl and args.tl <= 3600):
logger.error('invalid tl: {}'.format(args.tl))
exit(1)
if args.inside:
exit(inside(args, cmd))
else:
exit(outside(args, cmd))
|
python
|
__author__ = 'marcos'
|
python
|
import pytest
from kgx.config import get_biolink_model_schema
def test_valid_biolink_version():
try:
schema = get_biolink_model_schema("2.2.1")
except TypeError as te:
assert False, "test failure!"
assert (
schema
== "https://raw.githubusercontent.com/biolink/biolink-model/2.2.1/biolink-model.yaml"
)
def test_invalid_biolink_version():
try:
schema = get_biolink_model_schema()
except TypeError as te:
assert (
True
), "Type error expected: passed the invalid non-semver, type error: " + str(te)
|
python
|
import os
import tensorflow as tf
from tensorflow.python.client import device_lib
from tensorflow.python.training.distribute import DistributionStrategy
from tensorflow.contrib.distribute import MirroredStrategy, TPUStrategy
from time import time
from estimator import CustomEstimator
from dataset import dataset_fn, dataset_size
from model import model_fn
from metrics import metrics_fn, log_fn
from loss import loss_fn
from optimizer import optimizer_fn
import time_utils
def get_available_gpus():
"""
:return: The number of available GPUs in the current machine .
"""
local_device_protos = device_lib.list_local_devices()
return [x.name for x in local_device_protos if x.device_type == 'GPU']
def get_available_tpus():
"""
:return: The number of available TPUs in the current machine .
"""
local_device_protos = device_lib.list_local_devices()
return [x.name for x in local_device_protos if x.device_type == 'TPU']
def get_training_strategy():
"""
:return: A training strategy. It could be TPUStrategy if we are running the code in TPUs,
DistributionStrategy if the code is distributed or MirroredStrategy if the code is running
in one machine with more than one GPU. This code expects all the machines to have the same
number of GPUs/TUPs.
"""
is_tpu = len(get_available_tpus()) > 0
if is_tpu:
return TPUStrategy()
multi_gpu = len(get_available_gpus()) > 1
distributed = 'TF_CONFIG' in os.environ
if multi_gpu and distributed:
# TODO in TF 1.11 set it to tf.contrib.distribute.MultiWorkerMirroredStrategy()
# return MultiWorkerMirroredStrategy()
return DistributionStrategy
if distributed:
return DistributionStrategy()
if multi_gpu:
return MirroredStrategy()
return None
def calculate_steps_per_epoch(args, config):
size = dataset_size(args)
count_one_tower = int(float(size) / args.batch_size + 0.5)
gpus_per_node = len(get_available_gpus())
if gpus_per_node > 1 and config.train_distribute.__class__.__name__ is 'DistributionStrategy':
gpus_per_node = 1
if gpus_per_node == 0:
# if we don't have GPU we count 1 for the CPUs
gpus_per_node = 1
return count_one_tower / (gpus_per_node * config.num_worker_replicas)
def train(args):
outputs_dir = args.outputs_dir
if not tf.gfile.Exists(outputs_dir):
tf.gfile.MakeDirs(outputs_dir)
config = tf.estimator.RunConfig(
model_dir=args.outputs_dir,
tf_random_seed=args.random_seed,
train_distribute=get_training_strategy(),
log_step_count_steps=args.log_steps,
save_summary_steps=args.log_steps,
)
hooks = []
# add time hook to stop the training after some time
if args.max_time is not None:
hooks.append(StopAtTimeHook(args.max_time))
## add hook to show a log with different tensors
hooks.append(tf.train.LoggingTensorHook(log_fn(), every_n_iter=args.log_steps))
estimator = CustomEstimator(
model_dir=args.outputs_dir,
model_fn=model_fn,
optimizer_fn=optimizer_fn,
loss_fn=loss_fn,
metrics_fn=metrics_fn,
params=args,
config=config,
steps_per_epoch=calculate_steps_per_epoch(args, config)
)
estimator.train(input_fn=lambda: dataset_fn(args), hooks=hooks)
class StopAtTimeHook(tf.train.SessionRunHook):
"""Hook that requests stop after a specified time."""
def __init__(self, time_running):
"""
:param int time_running: Maximum time running
"""
time_running_secs = time_utils.tdelta(time_running).total_seconds()
self._end_time = time() + time_running_secs
def after_run(self, run_context, run_values):
if time() > self._end_time:
run_context.request_stop()
|
python
|
from .log import Code, warning, info, debug, debug_line, ModuleError
from . import Config, Export
from .stages import main
from .utils import get_temp_folder
from .checker import check, check_equality
from .dsp import channel_count, size
from .utils import random_file
import soundfile as sf
import numpy as np
import os
import subprocess
import pickle
import zlib
import numpy as np
from .dsp import size, strided_app_2d, batch_rms_2d, fade, clip
from datetime import timedelta
def time_str(length, sample_rate) -> str:
return str(timedelta(seconds=length // sample_rate))
def save(
file: str,
result: np.ndarray,
sample_rate: int,
subtype: str,
name: str = 'result'
) -> None:
name = name.upper()
debug(f'Saving the {name} {sample_rate} Hz Stereo {subtype} to: \'{file}\'...')
sf.write(file, result, sample_rate, subtype)
debug(f'\'{file}\' is saved')
def create_preview(
target: np.ndarray,
result: np.ndarray,
config: Config,
preview_target: Export,
preview_result: Export
) -> None:
debug_line()
info(Code.INFO_MAKING_PREVIEWS)
target = clip(target, config.threshold)
debug(f'The maximum duration of the preview is {config.preview_size / config.internal_sample_rate} seconds, '
f'with the analysis step of {config.preview_analysis_step / config.internal_sample_rate} seconds')
target_pieces = strided_app_2d(target, config.preview_size, config.preview_analysis_step)
result_pieces = strided_app_2d(result, config.preview_size, config.preview_analysis_step)
result_loudest_piece_idx = np.argmax(batch_rms_2d(result_pieces))
target_piece = target_pieces[result_loudest_piece_idx].copy()
result_piece = result_pieces[result_loudest_piece_idx].copy()
del target, target_pieces, result_pieces
debug_sample_begin = config.preview_analysis_step * int(result_loudest_piece_idx)
debug_sample_end = debug_sample_begin + size(result_piece)
debug(f'The best part to preview: '
f'{time_str(debug_sample_begin, config.internal_sample_rate)} '
f'- {time_str(debug_sample_end, config.internal_sample_rate)}')
if size(result) != size(result_piece):
fade_size = min(config.preview_fade_size, size(result_piece) // config.preview_fade_coefficient)
target_piece, result_piece = fade(target_piece, fade_size), fade(result_piece, fade_size)
if preview_target:
save(preview_target.file, target_piece, config.internal_sample_rate, preview_target.subtype, 'target preview')
if preview_result:
save(preview_result.file, result_piece, config.internal_sample_rate, preview_result.subtype, 'result preview')
def load(file: str, file_type: str, temp_folder: str) -> (np.ndarray, int):
file_type = file_type.upper()
sound, sample_rate = None, None
debug(f'Loading the {file_type} file: \'{file}\'...')
try:
sound, sample_rate = sf.read(file, always_2d=True)
except RuntimeError as e:
debug(e)
if 'unknown format' in str(e):
sound, sample_rate = __load_with_ffmpeg(file, file_type, temp_folder)
if sound is None or sample_rate is None:
if file_type == 'TARGET':
raise ModuleError(Code.ERROR_TARGET_LOADING)
else:
raise ModuleError(Code.ERROR_REFERENCE_LOADING)
debug(f'The {file_type} file is loaded')
return sound, sample_rate
def __load_with_ffmpeg(file: str, file_type: str, temp_folder: str) -> (np.ndarray, int):
sound, sample_rate = None, None
debug(f'Trying to load \'{file}\' with ffmpeg...')
temp_file = os.path.join(temp_folder, random_file(prefix='temp'))
with open(os.devnull, 'w') as devnull:
try:
subprocess.check_call(
[
'ffmpeg',
'-i',
file,
temp_file
],
stdout=devnull,
stderr=devnull
)
sound, sample_rate = sf.read(temp_file, always_2d=True)
if file_type == 'TARGET':
warning(Code.WARNING_TARGET_IS_LOSSY)
else:
info(Code.INFO_REFERENCE_IS_LOSSY)
os.remove(temp_file)
except FileNotFoundError:
debug('ffmpeg is not found in the system! '
'Download, install and add it to PATH: https://www.ffmpeg.org/download.html')
except subprocess.CalledProcessError:
debug(f'ffmpeg cannot convert \'{file}\' to .wav!')
return sound, sample_rate
DATABASE = 'database'
def process(
target: str,
characteristics: str,
style : str,
intensity : str,
results: list,
config: Config = Config(),
preview_target: Export = None,
preview_result: Export = None
):
# debug_line()
# info(Code.INFO_LOADING)
if not results:
raise RuntimeError(f'The result list is empty')
# Get a temporary folder for converting mp3's
temp_folder = config.temp_folder if config.temp_folder else get_temp_folder(results)
# Load the target
target, target_sample_rate = load(target, 'target', temp_folder)
# Analyze the target
target, target_sample_rate = check(target, target_sample_rate, config, 'target')
# Load the reference
# reference, reference_sample_rate = load(characteristics, 'reference', temp_folder)
# Analyze the reference
reference_sample_rate = 44100
database = f'{DATABASE}/{style}-{intensity}.txt'
f_reference = open(database, "rb")
zipped = f_reference.read()
f_reference.close()
serialized = zlib.decompress(zipped)
reference = pickle.loads(serialized)
# Analyze the target and the reference together
if not config.allow_equality:
check_equality(target, reference)
# Validation of the most important conditions
if not (target_sample_rate == reference_sample_rate == config.internal_sample_rate)\
or not (channel_count(target) == channel_count(reference) == 2)\
or not (size(target) > config.fft_size and size(reference) > config.fft_size):
raise ModuleError(Code.ERROR_VALIDATION)
# Process
result, result_no_limiter, result_no_limiter_normalized = main(
target,
reference,
config,
need_default=any(rr.use_limiter for rr in results),
need_no_limiter=any(not rr.use_limiter and not rr.normalize for rr in results),
need_no_limiter_normalized=any(not rr.use_limiter and rr.normalize for rr in results),
)
del reference
if not (preview_target or preview_result):
del target
# debug_line()
# info(Code.INFO_EXPORTING)
# Save
for required_result in results:
if required_result.use_limiter:
correct_result = result
else:
if required_result.normalize:
correct_result = result_no_limiter_normalized
else:
correct_result = result_no_limiter
save(required_result.file, correct_result, config.internal_sample_rate, required_result.subtype)
# Creating a preview (if needed)
if preview_target or preview_result:
result = next(item for item in [result, result_no_limiter, result_no_limiter_normalized] if item is not None)
create_preview(target, result, config, preview_target, preview_result)
# debug_line()
# info(Code.INFO_COMPLETED)
|
python
|
# generated by datamodel-codegen:
# filename: openapi.yaml
# timestamp: 2021-12-31T02:53:00+00:00
from __future__ import annotations
from datetime import datetime
from enum import Enum
from typing import Annotated, Any, List, Optional
from pydantic import BaseModel, Field
class ServiceUpdateNotFoundFault(BaseModel):
__root__: Any
class InvalidParameterValueException(ServiceUpdateNotFoundFault):
pass
class SnapshotAlreadyExistsFault(ServiceUpdateNotFoundFault):
pass
class SnapshotNotFoundFault(ServiceUpdateNotFoundFault):
pass
class SnapshotQuotaExceededFault(ServiceUpdateNotFoundFault):
pass
class InvalidSnapshotStateFault(ServiceUpdateNotFoundFault):
pass
class ServiceLinkedRoleNotFoundFault(ServiceUpdateNotFoundFault):
pass
class InvalidParameterCombinationException(ServiceUpdateNotFoundFault):
pass
class TagQuotaPerResourceExceeded(ServiceUpdateNotFoundFault):
pass
class UserNotFoundFault(ServiceUpdateNotFoundFault):
pass
class DuplicateUserNameFault(ServiceUpdateNotFoundFault):
pass
class ACLAlreadyExistsFault(ServiceUpdateNotFoundFault):
pass
class DefaultUserRequired(ServiceUpdateNotFoundFault):
pass
class ACLQuotaExceededFault(ServiceUpdateNotFoundFault):
pass
class ClusterAlreadyExistsFault(ServiceUpdateNotFoundFault):
pass
class SubnetGroupNotFoundFault(ServiceUpdateNotFoundFault):
pass
class ClusterQuotaForCustomerExceededFault(ServiceUpdateNotFoundFault):
pass
class NodeQuotaForClusterExceededFault(ServiceUpdateNotFoundFault):
pass
class NodeQuotaForCustomerExceededFault(ServiceUpdateNotFoundFault):
pass
class ParameterGroupNotFoundFault(ServiceUpdateNotFoundFault):
pass
class InsufficientClusterCapacityFault(ServiceUpdateNotFoundFault):
pass
class InvalidVPCNetworkStateFault(ServiceUpdateNotFoundFault):
pass
class ShardsPerClusterQuotaExceededFault(ServiceUpdateNotFoundFault):
pass
class InvalidCredentialsException(ServiceUpdateNotFoundFault):
pass
class ACLNotFoundFault(ServiceUpdateNotFoundFault):
pass
class InvalidACLStateFault(ServiceUpdateNotFoundFault):
pass
class ParameterGroupQuotaExceededFault(ServiceUpdateNotFoundFault):
pass
class ParameterGroupAlreadyExistsFault(ServiceUpdateNotFoundFault):
pass
class InvalidParameterGroupStateFault(ServiceUpdateNotFoundFault):
pass
class ClusterNotFoundFault(ServiceUpdateNotFoundFault):
pass
class InvalidClusterStateFault(ServiceUpdateNotFoundFault):
pass
class SubnetGroupAlreadyExistsFault(ServiceUpdateNotFoundFault):
pass
class SubnetGroupQuotaExceededFault(ServiceUpdateNotFoundFault):
pass
class SubnetQuotaExceededFault(ServiceUpdateNotFoundFault):
pass
class InvalidSubnet(ServiceUpdateNotFoundFault):
pass
class SubnetNotAllowedFault(ServiceUpdateNotFoundFault):
pass
class UserAlreadyExistsFault(ServiceUpdateNotFoundFault):
pass
class UserQuotaExceededFault(ServiceUpdateNotFoundFault):
pass
class SubnetGroupInUseFault(ServiceUpdateNotFoundFault):
pass
class InvalidUserStateFault(ServiceUpdateNotFoundFault):
pass
class APICallRateForCustomerExceededFault(ServiceUpdateNotFoundFault):
pass
class ShardNotFoundFault(ServiceUpdateNotFoundFault):
pass
class TestFailoverNotAvailableFault(ServiceUpdateNotFoundFault):
pass
class InvalidKMSKeyFault(ServiceUpdateNotFoundFault):
pass
class InvalidARNFault(ServiceUpdateNotFoundFault):
pass
class TagNotFoundFault(ServiceUpdateNotFoundFault):
pass
class InvalidNodeStateFault(ServiceUpdateNotFoundFault):
pass
class NoOperationFault(ServiceUpdateNotFoundFault):
pass
class SubnetInUse(ServiceUpdateNotFoundFault):
pass
class String(BaseModel):
__root__: str
class ACLClusterNameList(BaseModel):
__root__: List[String]
class ACLName(BaseModel):
__root__: Annotated[str, Field(min_length=1, regex='[a-zA-Z][a-zA-Z0-9\\-]*')]
class ACLNameList(BaseModel):
__root__: List[ACLName]
class ACLsUpdateStatus(BaseModel):
"""
The status of the ACL update
"""
ACLToApply: Optional[ACLName] = None
class AZStatus(Enum):
singleaz = 'singleaz'
multiaz = 'multiaz'
class AccessString(BaseModel):
__root__: Annotated[str, Field(regex='.*\\S.*')]
class AuthenticationType(Enum):
password = 'password'
no_password = 'no-password'
class IntegerOptional(BaseModel):
__root__: int
class Authentication(BaseModel):
"""
Denotes the user's authentication properties, such as whether it requires a password to authenticate. Used in output responses.
"""
Type: Optional[AuthenticationType] = None
PasswordCount: Optional[IntegerOptional] = None
class InputAuthenticationType(Enum):
password = 'password'
class PasswordListInput(BaseModel):
__root__: Annotated[List[String], Field(min_items=1)]
class AuthenticationMode(BaseModel):
"""
Denotes the user's authentication properties, such as whether it requires a password to authenticate. Used in output responses.
"""
Type: Optional[InputAuthenticationType] = None
Passwords: Optional[PasswordListInput] = None
class AvailabilityZone(BaseModel):
"""
Indicates if the cluster has a Multi-AZ configuration (multiaz) or not (singleaz).
"""
Name: Optional[String] = None
class ClusterNameList(BaseModel):
__root__: Annotated[List[String], Field(max_items=20)]
class ServiceUpdateRequest(BaseModel):
"""
A request to apply a service update
"""
ServiceUpdateNameToApply: Optional[String] = None
class Boolean(BaseModel):
__root__: bool
class BooleanOptional(Boolean):
pass
class TargetBucket(BaseModel):
__root__: Annotated[str, Field(max_length=255, regex='^[A-Za-z0-9._-]+$')]
class KmsKeyId(BaseModel):
__root__: Annotated[str, Field(max_length=2048)]
class SecurityGroupIdsList(ACLClusterNameList):
pass
class SnapshotArnsList(ACLClusterNameList):
pass
class ParameterGroup(BaseModel):
"""
Represents the output of a CreateParameterGroup operation. A parameter group represents a combination of specific values for the parameters that are passed to the engine software during startup.
"""
Name: Optional[String] = None
Family: Optional[String] = None
Description: Optional[String] = None
ARN: Optional[String] = None
class SubnetIdentifierList(ACLClusterNameList):
pass
class UserName(ACLName):
pass
class User(BaseModel):
"""
You create users and assign them specific permissions by using an access string. You assign the users to Access Control Lists aligned with a specific role (administrators, human resources) that are then deployed to one or more MemoryDB clusters.
"""
Name: Optional[String] = None
Status: Optional[String] = None
AccessString: Optional[String] = None
ACLNames: Optional[ACLNameList] = None
MinimumEngineVersion: Optional[String] = None
Authentication: Optional[Authentication] = None
ARN: Optional[String] = None
class SourceType(Enum):
node = 'node'
parameter_group = 'parameter-group'
subnet_group = 'subnet-group'
cluster = 'cluster'
user = 'user'
acl = 'acl'
class TStamp(BaseModel):
__root__: datetime
class ParameterGroupList(BaseModel):
__root__: List[ParameterGroup]
class UserList(BaseModel):
__root__: List[User]
class Double(BaseModel):
__root__: float
class Integer(IntegerOptional):
pass
class EngineVersionInfo(BaseModel):
"""
Provides details of the Redis engine version
"""
EngineVersion: Optional[String] = None
EnginePatchVersion: Optional[String] = None
ParameterGroupFamily: Optional[String] = None
class Event(BaseModel):
"""
Represents a single occurrence of something interesting within the system. Some examples of events are creating a cluster or adding or removing a node.
"""
SourceName: Optional[String] = None
SourceType: Optional[SourceType] = None
Message: Optional[String] = None
Date: Optional[TStamp] = None
class FilterName(AccessString):
pass
class FilterValue(AccessString):
pass
class KeyList(ACLClusterNameList):
pass
class NodeTypeList(ACLClusterNameList):
pass
class Parameter(BaseModel):
"""
Describes an individual setting that controls some aspect of MemoryDB behavior.
"""
Name: Optional[String] = None
Value: Optional[String] = None
Description: Optional[String] = None
DataType: Optional[String] = None
AllowedValues: Optional[String] = None
MinimumEngineVersion: Optional[String] = None
class ParameterNameList(ACLClusterNameList):
pass
class ParameterNameValue(BaseModel):
"""
Describes a name-value pair that is used to update the value of a parameter.
"""
ParameterName: Optional[String] = None
ParameterValue: Optional[String] = None
class ParameterNameValueList(BaseModel):
__root__: List[ParameterNameValue]
class ServiceUpdateStatus(Enum):
available = 'available'
in_progress = 'in-progress'
complete = 'complete'
scheduled = 'scheduled'
class PendingModifiedServiceUpdate(BaseModel):
"""
Update action that has yet to be processed for the corresponding apply/stop request
"""
ServiceUpdateName: Optional[String] = None
Status: Optional[ServiceUpdateStatus] = None
class ReplicaConfigurationRequest(BaseModel):
"""
A request to configure the number of replicas in a shard
"""
ReplicaCount: Optional[Integer] = None
class SlotMigration(BaseModel):
"""
Represents the progress of an online resharding operation.
"""
ProgressPercentage: Optional[Double] = None
class SecurityGroupMembership(BaseModel):
"""
Represents a single security group and its status.
"""
SecurityGroupId: Optional[String] = None
Status: Optional[String] = None
class ServiceUpdateType(Enum):
security_update = 'security-update'
class ServiceUpdate(BaseModel):
"""
An update that you can apply to your MemoryDB clusters.
"""
ClusterName: Optional[String] = None
ServiceUpdateName: Optional[String] = None
ReleaseDate: Optional[TStamp] = None
Description: Optional[String] = None
Status: Optional[ServiceUpdateStatus] = None
Type: Optional[ServiceUpdateType] = None
NodesUpdated: Optional[String] = None
AutoUpdateStartDate: Optional[TStamp] = None
class ShardConfiguration1(BaseModel):
"""
Shard configuration options. Each shard configuration has the following: Slots and ReplicaCount.
"""
Slots: Optional[String] = None
ReplicaCount: Optional[IntegerOptional] = None
class ShardConfigurationRequest(BaseModel):
"""
A request to configure the sharding properties of a cluster
"""
ShardCount: Optional[Integer] = None
class ShardDetail(BaseModel):
"""
Provides details of a shard in a snapshot
"""
Name: Optional[String] = None
Configuration: Optional[ShardConfiguration1] = None
Size: Optional[String] = None
SnapshotCreationTime: Optional[TStamp] = None
class Subnet(BaseModel):
"""
Represents the subnet associated with a cluster. This parameter refers to subnets defined in Amazon Virtual Private Cloud (Amazon VPC) and used with MemoryDB.
"""
Identifier: Optional[String] = None
AvailabilityZone: Optional[AvailabilityZone] = None
class SubnetList(BaseModel):
__root__: List[Subnet]
class Tag(BaseModel):
"""
A tag that can be added to an MemoryDB resource. Tags are composed of a Key/Value pair. You can use tags to categorize and track all your MemoryDB resources. When you add or remove tags on clusters, those actions will be replicated to all nodes in the cluster. A tag with a null Value is permitted. For more information, see <a href="https://docs.aws.amazon.com/MemoryDB/latest/devguide/tagging-resources.html">Tagging your MemoryDB resources</a>
"""
Key: Optional[String] = None
Value: Optional[String] = None
class UnprocessedCluster(BaseModel):
"""
A cluster whose updates have failed
"""
ClusterName: Optional[String] = None
ErrorType: Optional[String] = None
ErrorMessage: Optional[String] = None
class BatchUpdateClusterRequest(BaseModel):
ClusterNames: ClusterNameList
ServiceUpdate: Optional[ServiceUpdateRequest] = None
class CreateParameterGroupResponse(BaseModel):
ParameterGroup: Optional[ParameterGroup] = None
class CreateUserResponse(BaseModel):
User: Optional[User] = None
class DeleteACLRequest(BaseModel):
ACLName: String
class DeleteClusterRequest(BaseModel):
ClusterName: String
FinalSnapshotName: Optional[String] = None
class DeleteParameterGroupResponse(CreateParameterGroupResponse):
pass
class DeleteParameterGroupRequest(BaseModel):
ParameterGroupName: String
class DeleteSnapshotRequest(BaseModel):
SnapshotName: String
class DeleteSubnetGroupRequest(BaseModel):
SubnetGroupName: String
class DeleteUserResponse(CreateUserResponse):
pass
class DeleteUserRequest(BaseModel):
UserName: UserName
class DescribeACLsRequest(BaseModel):
ACLName: Optional[String] = None
MaxResults: Optional[IntegerOptional] = None
NextToken: Optional[String] = None
class DescribeClustersRequest(BaseModel):
ClusterName: Optional[String] = None
MaxResults: Optional[IntegerOptional] = None
NextToken: Optional[String] = None
ShowShardDetails: Optional[BooleanOptional] = None
class DescribeEngineVersionsRequest(BaseModel):
EngineVersion: Optional[String] = None
ParameterGroupFamily: Optional[String] = None
MaxResults: Optional[IntegerOptional] = None
NextToken: Optional[String] = None
DefaultOnly: Optional[Boolean] = None
class DescribeEventsRequest(BaseModel):
SourceName: Optional[String] = None
SourceType: Optional[SourceType] = None
StartTime: Optional[TStamp] = None
EndTime: Optional[TStamp] = None
Duration: Optional[IntegerOptional] = None
MaxResults: Optional[IntegerOptional] = None
NextToken: Optional[String] = None
class DescribeParameterGroupsResponse(BaseModel):
NextToken: Optional[String] = None
ParameterGroups: Optional[ParameterGroupList] = None
class DescribeParameterGroupsRequest(BaseModel):
ParameterGroupName: Optional[String] = None
MaxResults: Optional[IntegerOptional] = None
NextToken: Optional[String] = None
class DescribeParametersRequest(BaseModel):
ParameterGroupName: String
MaxResults: Optional[IntegerOptional] = None
NextToken: Optional[String] = None
class DescribeSnapshotsRequest(BaseModel):
ClusterName: Optional[String] = None
SnapshotName: Optional[String] = None
Source: Optional[String] = None
NextToken: Optional[String] = None
MaxResults: Optional[IntegerOptional] = None
ShowDetail: Optional[BooleanOptional] = None
class DescribeSubnetGroupsRequest(BaseModel):
SubnetGroupName: Optional[String] = None
MaxResults: Optional[IntegerOptional] = None
NextToken: Optional[String] = None
class DescribeUsersResponse(BaseModel):
Users: Optional[UserList] = None
NextToken: Optional[String] = None
class FailoverShardRequest(BaseModel):
ClusterName: String
ShardName: String
class ListAllowedNodeTypeUpdatesResponse(BaseModel):
ScaleUpNodeTypes: Optional[NodeTypeList] = None
ScaleDownNodeTypes: Optional[NodeTypeList] = None
class ListAllowedNodeTypeUpdatesRequest(BaseModel):
ClusterName: String
class ListTagsRequest(BaseModel):
ResourceArn: String
class ResetParameterGroupResponse(CreateParameterGroupResponse):
pass
class ResetParameterGroupRequest(BaseModel):
ParameterGroupName: String
AllParameters: Optional[Boolean] = None
ParameterNames: Optional[ParameterNameList] = None
class UntagResourceRequest(BaseModel):
ResourceArn: String
TagKeys: KeyList
class UpdateClusterRequest(BaseModel):
ClusterName: String
Description: Optional[String] = None
SecurityGroupIds: Optional[SecurityGroupIdsList] = None
MaintenanceWindow: Optional[String] = None
SnsTopicArn: Optional[String] = None
SnsTopicStatus: Optional[String] = None
ParameterGroupName: Optional[String] = None
SnapshotWindow: Optional[String] = None
SnapshotRetentionLimit: Optional[IntegerOptional] = None
NodeType: Optional[String] = None
EngineVersion: Optional[String] = None
ReplicaConfiguration: Optional[ReplicaConfigurationRequest] = None
ShardConfiguration: Optional[ShardConfigurationRequest] = None
ACLName: Optional[ACLName] = None
class UpdateParameterGroupResponse(CreateParameterGroupResponse):
pass
class UpdateParameterGroupRequest(BaseModel):
ParameterGroupName: String
ParameterNameValues: ParameterNameValueList
class UpdateSubnetGroupRequest(BaseModel):
SubnetGroupName: String
Description: Optional[String] = None
SubnetIds: Optional[SubnetIdentifierList] = None
class UpdateUserResponse(CreateUserResponse):
pass
class UpdateUserRequest(BaseModel):
UserName: UserName
AuthenticationMode: Optional[AuthenticationMode] = None
AccessString: Optional[AccessString] = None
class UserNameList(BaseModel):
__root__: List[UserName]
class ACLPendingChanges(BaseModel):
"""
Returns the updates being applied to the ACL.
"""
UserNamesToRemove: Optional[UserNameList] = None
UserNamesToAdd: Optional[UserNameList] = None
class ACL(BaseModel):
"""
An Access Control List. You can authenticate users with Access Contol Lists. ACLs enable you to control cluster access by grouping users. These Access control lists are designed as a way to organize access to clusters.
"""
Name: Optional[String] = None
Status: Optional[String] = None
UserNames: Optional[UserNameList] = None
MinimumEngineVersion: Optional[String] = None
PendingChanges: Optional[ACLPendingChanges] = None
Clusters: Optional[ACLClusterNameList] = None
ARN: Optional[String] = None
class ACLList(BaseModel):
__root__: List[ACL]
class UnprocessedClusterList(BaseModel):
__root__: List[UnprocessedCluster]
class Endpoint(BaseModel):
"""
Represents the information required for client programs to connect to the cluster and its nodes.
"""
Address: Optional[String] = None
Port: Optional[Integer] = None
class SecurityGroupMembershipList(BaseModel):
__root__: List[SecurityGroupMembership]
class ShardDetails(BaseModel):
__root__: List[ShardDetail]
class ClusterConfiguration(BaseModel):
"""
A list of cluster configuration options.
"""
Name: Optional[String] = None
Description: Optional[String] = None
NodeType: Optional[String] = None
EngineVersion: Optional[String] = None
MaintenanceWindow: Optional[String] = None
TopicArn: Optional[String] = None
Port: Optional[IntegerOptional] = None
ParameterGroupName: Optional[String] = None
SubnetGroupName: Optional[String] = None
VpcId: Optional[String] = None
SnapshotRetentionLimit: Optional[IntegerOptional] = None
SnapshotWindow: Optional[String] = None
NumShards: Optional[IntegerOptional] = None
Shards: Optional[ShardDetails] = None
class ReshardingStatus(BaseModel):
"""
The status of the online resharding
"""
SlotMigration: Optional[SlotMigration] = None
class PendingModifiedServiceUpdateList(BaseModel):
__root__: List[PendingModifiedServiceUpdate]
class TagList(BaseModel):
__root__: Annotated[List[Tag], Field(max_items=200)]
class Snapshot(BaseModel):
"""
Represents a copy of an entire cluster as of the time when the snapshot was taken.
"""
Name: Optional[String] = None
Status: Optional[String] = None
Source: Optional[String] = None
KmsKeyId: Optional[String] = None
ARN: Optional[String] = None
ClusterConfiguration: Optional[ClusterConfiguration] = None
class UserNameListInput(BaseModel):
__root__: Annotated[List[UserName], Field(min_items=1)]
class SubnetGroup(BaseModel):
"""
<p>Represents the output of one of the following operations:</p> <ul> <li> <p>CreateSubnetGroup</p> </li> <li> <p>UpdateSubnetGroup</p> </li> </ul> <p>A subnet group is a collection of subnets (typically private) that you can designate for your clusters running in an Amazon Virtual Private Cloud (VPC) environment.</p>
"""
Name: Optional[String] = None
Description: Optional[String] = None
VpcId: Optional[String] = None
Subnets: Optional[SubnetList] = None
ARN: Optional[String] = None
class EngineVersionInfoList(BaseModel):
__root__: List[EngineVersionInfo]
class EventList(BaseModel):
__root__: List[Event]
class ParametersList(BaseModel):
__root__: List[Parameter]
class ServiceUpdateStatusList(BaseModel):
__root__: Annotated[List[ServiceUpdateStatus], Field(max_items=4)]
class ServiceUpdateList(BaseModel):
__root__: List[ServiceUpdate]
class SnapshotList(BaseModel):
__root__: List[Snapshot]
class SubnetGroupList(BaseModel):
__root__: List[SubnetGroup]
class FilterValueList(BaseModel):
__root__: Annotated[List[FilterValue], Field(min_items=1)]
class Filter(BaseModel):
"""
Used to streamline results of a search based on the property being filtered.
"""
Name: FilterName
Values: FilterValueList
class Node(BaseModel):
"""
Represents an individual node within a cluster. Each node runs its own instance of the cluster's protocol-compliant caching software.
"""
Name: Optional[String] = None
Status: Optional[String] = None
AvailabilityZone: Optional[String] = None
CreateTime: Optional[TStamp] = None
Endpoint: Optional[Endpoint] = None
class NodeList(BaseModel):
__root__: List[Node]
class Shard(BaseModel):
"""
Represents a collection of nodes in a cluster. One node in the node group is the read/write primary node. All the other nodes are read-only Replica nodes.
"""
Name: Optional[String] = None
Status: Optional[String] = None
Slots: Optional[String] = None
Nodes: Optional[NodeList] = None
NumberOfNodes: Optional[IntegerOptional] = None
class CopySnapshotResponse(BaseModel):
Snapshot: Optional[Snapshot] = None
class CopySnapshotRequest(BaseModel):
SourceSnapshotName: String
TargetSnapshotName: String
TargetBucket: Optional[TargetBucket] = None
KmsKeyId: Optional[KmsKeyId] = None
Tags: Optional[TagList] = None
class CreateACLResponse(BaseModel):
ACL: Optional[ACL] = None
class CreateACLRequest(BaseModel):
ACLName: String
UserNames: Optional[UserNameListInput] = None
Tags: Optional[TagList] = None
class CreateClusterRequest(BaseModel):
ClusterName: String
NodeType: String
ParameterGroupName: Optional[String] = None
Description: Optional[String] = None
NumShards: Optional[IntegerOptional] = None
NumReplicasPerShard: Optional[IntegerOptional] = None
SubnetGroupName: Optional[String] = None
SecurityGroupIds: Optional[SecurityGroupIdsList] = None
MaintenanceWindow: Optional[String] = None
Port: Optional[IntegerOptional] = None
SnsTopicArn: Optional[String] = None
TLSEnabled: Optional[BooleanOptional] = None
KmsKeyId: Optional[String] = None
SnapshotArns: Optional[SnapshotArnsList] = None
SnapshotName: Optional[String] = None
SnapshotRetentionLimit: Optional[IntegerOptional] = None
Tags: Optional[TagList] = None
SnapshotWindow: Optional[String] = None
ACLName: ACLName
EngineVersion: Optional[String] = None
AutoMinorVersionUpgrade: Optional[BooleanOptional] = None
class CreateParameterGroupRequest(BaseModel):
ParameterGroupName: String
Family: String
Description: Optional[String] = None
Tags: Optional[TagList] = None
class CreateSnapshotResponse(CopySnapshotResponse):
pass
class CreateSnapshotRequest(BaseModel):
ClusterName: String
SnapshotName: String
KmsKeyId: Optional[String] = None
Tags: Optional[TagList] = None
class CreateSubnetGroupResponse(BaseModel):
SubnetGroup: Optional[SubnetGroup] = None
class CreateSubnetGroupRequest(BaseModel):
SubnetGroupName: String
Description: Optional[String] = None
SubnetIds: SubnetIdentifierList
Tags: Optional[TagList] = None
class CreateUserRequest(BaseModel):
UserName: UserName
AuthenticationMode: AuthenticationMode
AccessString: AccessString
Tags: Optional[TagList] = None
class DeleteACLResponse(CreateACLResponse):
pass
class DeleteSnapshotResponse(CopySnapshotResponse):
pass
class DeleteSubnetGroupResponse(CreateSubnetGroupResponse):
pass
class DescribeACLsResponse(BaseModel):
ACLs: Optional[ACLList] = None
NextToken: Optional[String] = None
class DescribeEngineVersionsResponse(BaseModel):
NextToken: Optional[String] = None
EngineVersions: Optional[EngineVersionInfoList] = None
class DescribeEventsResponse(BaseModel):
NextToken: Optional[String] = None
Events: Optional[EventList] = None
class DescribeParametersResponse(BaseModel):
NextToken: Optional[String] = None
Parameters: Optional[ParametersList] = None
class DescribeServiceUpdatesResponse(BaseModel):
NextToken: Optional[String] = None
ServiceUpdates: Optional[ServiceUpdateList] = None
class DescribeServiceUpdatesRequest(BaseModel):
ServiceUpdateName: Optional[String] = None
ClusterNames: Optional[ClusterNameList] = None
Status: Optional[ServiceUpdateStatusList] = None
MaxResults: Optional[IntegerOptional] = None
NextToken: Optional[String] = None
class DescribeSnapshotsResponse(BaseModel):
NextToken: Optional[String] = None
Snapshots: Optional[SnapshotList] = None
class DescribeSubnetGroupsResponse(BaseModel):
NextToken: Optional[String] = None
SubnetGroups: Optional[SubnetGroupList] = None
class ListTagsResponse(BaseModel):
TagList: Optional[TagList] = None
class TagResourceResponse(ListTagsResponse):
pass
class TagResourceRequest(BaseModel):
ResourceArn: String
Tags: TagList
class UntagResourceResponse(ListTagsResponse):
pass
class UpdateACLResponse(CreateACLResponse):
pass
class UpdateACLRequest(BaseModel):
ACLName: String
UserNamesToAdd: Optional[UserNameListInput] = None
UserNamesToRemove: Optional[UserNameListInput] = None
class UpdateSubnetGroupResponse(CreateSubnetGroupResponse):
pass
class ClusterPendingUpdates(BaseModel):
"""
A list of updates being applied to the cluster
"""
Resharding: Optional[ReshardingStatus] = None
ACLs: Optional[ACLsUpdateStatus] = None
ServiceUpdates: Optional[PendingModifiedServiceUpdateList] = None
class ShardList(BaseModel):
__root__: List[Shard]
class Cluster(BaseModel):
"""
Contains all of the attributes of a specific cluster.
"""
Name: Optional[String] = None
Description: Optional[String] = None
Status: Optional[String] = None
PendingUpdates: Optional[ClusterPendingUpdates] = None
NumberOfShards: Optional[IntegerOptional] = None
Shards: Optional[ShardList] = None
AvailabilityMode: Optional[AZStatus] = None
ClusterEndpoint: Optional[Endpoint] = None
NodeType: Optional[String] = None
EngineVersion: Optional[String] = None
EnginePatchVersion: Optional[String] = None
ParameterGroupName: Optional[String] = None
ParameterGroupStatus: Optional[String] = None
SecurityGroups: Optional[SecurityGroupMembershipList] = None
SubnetGroupName: Optional[String] = None
TLSEnabled: Optional[BooleanOptional] = None
KmsKeyId: Optional[String] = None
ARN: Optional[String] = None
SnsTopicArn: Optional[String] = None
SnsTopicStatus: Optional[String] = None
SnapshotRetentionLimit: Optional[IntegerOptional] = None
MaintenanceWindow: Optional[String] = None
SnapshotWindow: Optional[String] = None
ACLName: Optional[ACLName] = None
AutoMinorVersionUpgrade: Optional[BooleanOptional] = None
class FilterList(BaseModel):
__root__: List[Filter]
class CreateClusterResponse(BaseModel):
Cluster: Optional[Cluster] = None
class DeleteClusterResponse(CreateClusterResponse):
pass
class DescribeUsersRequest(BaseModel):
UserName: Optional[UserName] = None
Filters: Optional[FilterList] = None
MaxResults: Optional[IntegerOptional] = None
NextToken: Optional[String] = None
class FailoverShardResponse(CreateClusterResponse):
pass
class UpdateClusterResponse(CreateClusterResponse):
pass
class ClusterList(BaseModel):
__root__: List[Cluster]
class BatchUpdateClusterResponse(BaseModel):
ProcessedClusters: Optional[ClusterList] = None
UnprocessedClusters: Optional[UnprocessedClusterList] = None
class DescribeClustersResponse(BaseModel):
NextToken: Optional[String] = None
Clusters: Optional[ClusterList] = None
|
python
|
from typing import List, Union, Optional, Dict, MutableMapping, Any, Set
import itertools
import math
import numbers
import copy
import operator
import warnings
import attr
from .load_dump import dumps as demes_dumps
Number = Union[int, float]
Name = str
Time = Number
Size = Number
Rate = float
Proportion = float
_ISCLOSE_REL_TOL = 1e-9
_ISCLOSE_ABS_TOL = 1e-12
# Validator functions.
def int_or_float(self, attribute, value):
if (
not isinstance(value, numbers.Real) and not hasattr(value, "__float__")
) or value != value: # type-agnostic test for NaN
raise TypeError(f"{attribute.name} must be a number")
def positive(self, attribute, value):
if value <= 0:
raise ValueError(f"{attribute.name} must be greater than zero")
def non_negative(self, attribute, value):
if value < 0:
raise ValueError(f"{attribute.name} must be non-negative")
def finite(self, attribute, value):
if math.isinf(value):
raise ValueError(f"{attribute.name} must be finite")
def unit_interval(self, attribute, value):
if not (0 <= value <= 1):
raise ValueError(f"must have 0 <= {attribute.name} <= 1")
def nonzero_len(self, attribute, value):
if len(value) == 0:
if isinstance(value, str):
raise ValueError(f"{attribute.name} must be a non-empty string")
else:
raise ValueError(f"{attribute.name} must have non-zero length")
def valid_deme_name(self, attribute, value):
if not value.isidentifier():
raise ValueError(
"Invalid deme name `{self.name}`. Names must be valid python identifiers. "
"We recommend choosing a name that starts with a letter or "
"underscore, and is followed by one or more letters, numbers, "
"or underscores."
)
def isclose_deme_proportions(
a_names: List[Name],
a_proportions: List[Proportion],
b_names: List[Name],
b_proportions: List[Proportion],
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
) -> bool:
"""
Returns true if (a_names, a_proportions) and (b_names, b_proportions)
are semantically equivalent. The order of names is ignored, and proportions
are checked for numerical closeness.
"""
if len(a_names) != len(b_names) or len(a_proportions) != len(b_proportions):
return False
a = sorted(zip(a_names, a_proportions), key=operator.itemgetter(0))
b = sorted(zip(b_names, b_proportions), key=operator.itemgetter(0))
for (a_id, a_proportion), (b_id, b_proportion) in zip(a, b):
if a_id != b_id or not math.isclose(
a_proportion, b_proportion, rel_tol=rel_tol, abs_tol=abs_tol
):
return False
return True
def validate_item(name, value, required_type, scope):
if not isinstance(value, required_type):
raise TypeError(
f"{scope}: field '{name}' must be a {required_type}; "
f"current type is {type(value)}."
)
# We need to use this trick because None is a meaninful input value for these
# pop_x functions.
NO_DEFAULT = object()
def pop_item(data, name, *, required_type, default=NO_DEFAULT, scope=""):
if name in data:
value = data.pop(name)
validate_item(name, value, required_type, scope=scope)
else:
if default is NO_DEFAULT:
raise KeyError(f"{scope}: required field '{name}' not found")
value = default
return value
def pop_list(data, name, default=NO_DEFAULT, required_type=None, scope=""):
value = pop_item(data, name, default=default, required_type=list)
if required_type is not None and default is not None:
for item in value:
validate_item(name, item, required_type, scope)
return value
def pop_object(data, name, default=NO_DEFAULT, scope=""):
return pop_item(
data, name, default=default, required_type=MutableMapping, scope=scope
)
def check_allowed(data, allowed_fields, scope):
for key in data.keys():
if key not in allowed_fields:
raise KeyError(
f"{scope}: unexpected field: '{key}'. "
f"Allowed fields are: {allowed_fields}"
)
def insert_defaults(data, defaults):
for key, value in defaults.items():
if key not in data:
data[key] = value
@attr.s(auto_attribs=True, kw_only=True, slots=True)
class Epoch:
"""
Population size parameters for a deme in a specified time period.
Times follow the forwards-in-time convention (time values increase
from the present towards the past). The start time of the epoch is
the more ancient time, and the end time is more recent, so that the
start time must be greater than the end time
:ivar float start_time: The start time of the epoch.
:ivar float ~.end_time: The end time of the epoch (must be specified).
:ivar float start_size: Population size at ``start_time``.
:ivar float end_size: Population size at ``end_time``.
If ``start_size != end_size``, the population size changes
monotonically between the start and end times.
:ivar str size_function: The size change function. This is either
``constant``, ``exponential`` or ``linear``, though it is possible
that additional values will be added in the future.
* ``constant``: the deme's size does not change over the epoch.
* ``exponential``: the deme's size changes exponentially from
``start_size`` to ``end_size`` over the epoch.
If :math:`t` is a time within the span of the epoch,
the deme size :math:`N` at :math:`t` can be calculated as:
.. code::
dt = (epoch.start_time - t) / epoch.time_span
r = math.log(epoch.end_size / epoch.start_size)
N = epoch.start_size * math.exp(r * dt)
* ``linear``: the deme's size changes linearly from
``start_size`` to ``end_size`` over the epoch.
If :math:`t` is a time within the span of the epoch,
the deme size :math:`N` at :math:`t` can be calculated as:
.. code::
dt = (epoch.start_time - t) / epoch.time_span
N = epoch.start_size + (epoch.end_size - epoch.start_size) * dt
:ivar float selfing_rate: The selfing rate for this epoch.
:ivar float cloning_rate: The cloning rate for this epoch.
"""
start_time: Time = attr.ib(validator=[int_or_float, non_negative])
end_time: Time = attr.ib(validator=[int_or_float, non_negative, finite])
start_size: Size = attr.ib(validator=[int_or_float, positive, finite])
end_size: Size = attr.ib(validator=[int_or_float, positive, finite])
size_function: str = attr.ib(
validator=attr.validators.in_(["constant", "exponential", "linear"])
)
selfing_rate: Proportion = attr.ib(
default=0, validator=[int_or_float, unit_interval]
)
cloning_rate: Proportion = attr.ib(
default=0, validator=[int_or_float, unit_interval]
)
def __attrs_post_init__(self):
if self.start_time <= self.end_time:
raise ValueError("must have start_time > end_time")
if math.isinf(self.start_time) and self.start_size != self.end_size:
raise ValueError("if start time is inf, must be a constant size epoch")
if self.size_function == "constant" and self.start_size != self.end_size:
raise ValueError("start_size != end_size, but size_function is constant")
if self.selfing_rate + self.cloning_rate > 1:
raise ValueError("must have selfing_rate + cloning_rate <= 1")
@property
def time_span(self):
"""
The time span of the epoch.
"""
return self.start_time - self.end_time
def assert_close(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
):
"""
Raises AssertionError if the object is not equal to ``other``,
up to a numerical tolerance.
Compares values of the following attributes:
``start_time``, ``end_time``, ``start_size``, ``end_size``,
``size_function``, ``selfing_rate``, ``cloning_rate``.
:param other: The epoch to compare against.
:type other: :class:`.Epoch`
:param ret_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type ret_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
"""
assert (
self.__class__ is other.__class__
), f"Failed as other epoch is not instance of {self.__class__} type."
assert math.isclose(
self.start_time, other.start_time, rel_tol=rel_tol, abs_tol=abs_tol
), f"Failed for start_time {self.start_time} != {other.start_time} (other)."
assert math.isclose(
self.end_time, other.end_time, rel_tol=rel_tol, abs_tol=abs_tol
), f"Failed for end_time {self.end_time} != {other.end_time} (other)."
assert math.isclose(
self.start_size, other.start_size, rel_tol=rel_tol, abs_tol=abs_tol
), (
f"Failed for start_size "
f"{self.start_size} != {other.start_size} (other)."
)
assert math.isclose(
self.end_size, other.end_size, rel_tol=rel_tol, abs_tol=abs_tol
), f"Failed for end_size {self.end_size} != {other.end_size} (other)."
assert self.size_function == other.size_function
assert math.isclose(
self.selfing_rate, other.selfing_rate, rel_tol=rel_tol, abs_tol=abs_tol
), (
f"Failed for selfing_rate "
f"{self.selfing_rate} != {other.selfing_rate} (other)."
)
assert math.isclose(
self.cloning_rate, other.cloning_rate, rel_tol=rel_tol, abs_tol=abs_tol
), (
f"Failed for cloning_rate "
f"{self.cloning_rate} != {other.cloning_rate} (other)."
)
def isclose(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
) -> bool:
"""
Returns true if the epoch and ``other`` epoch implement essentially
the same epoch. For more information see :meth:`assert_close`.
:param other: The epoch to compare against.
:type other: :class:`.Epoch`
:param ret_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type ret_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
:return: True if the two epochs are equivalent, False otherwise.
:rtype: bool
"""
try:
self.assert_close(other, rel_tol=rel_tol, abs_tol=abs_tol)
return True
except AssertionError:
return False
@attr.s(auto_attribs=True, kw_only=True, slots=True)
class AsymmetricMigration:
"""
Parameters for continuous asymmetric migration.
The source and destination demes follow the forwards-in-time convention,
where migrants are born in the source deme and (potentially) have children
in the dest deme.
:ivar str source: The source deme for asymmetric migration.
:ivar str dest: The destination deme for asymmetric migration.
:ivar float start_time: The time at which the migration rate is activated.
:ivar float ~.end_time: The time at which the migration rate is deactivated.
:ivar float rate: The rate of migration per generation.
"""
source: Name = attr.ib(
validator=[attr.validators.instance_of(str), valid_deme_name]
)
dest: Name = attr.ib(validator=[attr.validators.instance_of(str), valid_deme_name])
start_time: Time = attr.ib(validator=[int_or_float, non_negative])
end_time: Time = attr.ib(validator=[int_or_float, non_negative, finite])
rate: Rate = attr.ib(validator=[int_or_float, unit_interval])
def __attrs_post_init__(self):
if self.source == self.dest:
raise ValueError("source and dest cannot be the same deme")
if not (self.start_time > self.end_time):
raise ValueError("must have start_time > end_time")
def assert_close(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
):
"""
Raises AssertionError if the object is not equal to ``other``,
up to a numerical tolerance.
Compares values of the following attributes:
``source``, ``dest``, ``start_time``, ``end_time``, ``rate``.
:param AsymmetricMigration other: The migration to compare against.
:param ret_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type ret_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
"""
assert (
self.__class__ is other.__class__
), f"Failed as other migration is not instance of {self.__class__} type."
assert self.source == other.source
assert self.dest == other.dest
assert math.isclose(
self.start_time, other.start_time, rel_tol=rel_tol, abs_tol=abs_tol
), f"Failed for start_time {self.start_time} != {other.start_time} (other)."
assert math.isclose(
self.end_time, other.end_time, rel_tol=rel_tol, abs_tol=abs_tol
), f"Failed for end_time {self.end_time} != {other.end_time} (other)."
assert math.isclose(
self.rate, other.rate, rel_tol=rel_tol, abs_tol=abs_tol
), f"Failed for rate {self.rate} != {other.rate} (other)."
def isclose(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
) -> bool:
"""
Returns true if the migration is equal to the ``other`` migration.
For more information see :meth:`assert_close`.
:param AsymmetricMigration other: The migration to compare against.
:param ret_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type ret_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
:return: True if the two epochs are equivalent, False otherwise.
:rtype: bool
"""
try:
self.assert_close(other, rel_tol=rel_tol, abs_tol=abs_tol)
return True
except AssertionError:
return False
@attr.s(auto_attribs=True, kw_only=True, slots=True)
class Pulse:
"""
Parameters for a pulse of migration from one deme to another.
Source and destination demes follow the forwards-in-time convention,
of migrations born in the source deme having children in the dest
deme.
:ivar str source: The source deme.
:ivar str dest: The destination deme.
:ivar float ~.time: The time of migration.
:ivar float proportion: At the instant after migration, this is the
proportion of individuals in the destination deme made up of
individuals from the source deme.
"""
source: Name = attr.ib(
validator=[attr.validators.instance_of(str), valid_deme_name]
)
dest: Name = attr.ib(validator=[attr.validators.instance_of(str), valid_deme_name])
time: Time = attr.ib(validator=[int_or_float, positive, finite])
proportion: Proportion = attr.ib(validator=[int_or_float, unit_interval])
def __attrs_post_init__(self):
if self.source == self.dest:
raise ValueError("source and dest cannot be the same deme")
def assert_close(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
):
"""
Raises AssertionError if the object is not equal to ``other``,
up to a numerical tolerance.
Compares values of the following attributes:
``source``, ``dest``, ``time``, ``proportion``.
:param other: The pulse to compare against.
:type other: :class:`.Pulse`
:param ret_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type ret_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
"""
assert (
self.__class__ is other.__class__
), f"Failed as other pulse is not instance of {self.__class__} type."
assert self.source == other.source
assert self.dest == other.dest
assert math.isclose(
self.time, other.time, rel_tol=rel_tol, abs_tol=abs_tol
), f"Failed for time {self.time} != {other.time} (other)."
assert math.isclose(
self.proportion, other.proportion, rel_tol=rel_tol, abs_tol=abs_tol
), f"Failed for proportion {self.proportion} != {other.proportion} (other)."
def isclose(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
) -> bool:
"""
Returns true if the pulse is equal to the ``other`` pulse.
For more information see :meth:`assert_close`.
:param other: The pulse to compare against.
:type other: :class:`.Pulse`
:param ret_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type ret_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
:return: True if the two pulses are equivalent, False otherwise.
:rtype: bool
"""
try:
self.assert_close(other, rel_tol=rel_tol, abs_tol=abs_tol)
return True
except AssertionError:
return False
@attr.s(auto_attribs=True, kw_only=True, slots=True)
class Split:
"""
Parameters for a split event, in which a deme ends at a given time and
contributes ancestry to an arbitrary number of descendant demes. Note
that there could be just a single descendant deme, in which case ``split``
is a bit of a misnomer...
:ivar str parent: The parental deme.
:ivar list[str] children: A list of descendant demes.
:ivar float ~.time: The split time.
"""
parent: Name = attr.ib(
validator=[attr.validators.instance_of(str), valid_deme_name]
)
children: List[Name] = attr.ib(
validator=attr.validators.and_(
attr.validators.deep_iterable(
member_validator=attr.validators.and_(
attr.validators.instance_of(str), valid_deme_name
),
iterable_validator=attr.validators.instance_of(list),
),
nonzero_len,
)
)
time: Time = attr.ib(validator=[int_or_float, non_negative, finite])
def __attrs_post_init__(self):
if self.parent in self.children:
raise ValueError("child and parent cannot be the same deme")
if len(set(self.children)) != len(self.children):
raise ValueError("cannot repeat children in split")
def assert_close(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
) -> bool:
"""
Raises AssertionError if the object is not equal to ``other``,
up to a numerical tolerance.
Compares values of the following attributes:
``parent``, ``children``, ``time``.
:param other: The split to compare against.
:type other: :class:`.Split`
:param ret_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type ret_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
"""
assert (
self.__class__ is other.__class__
), f"Failed as other split is not instance of {self.__class__} type."
assert self.parent == other.parent
assert sorted(self.children) == sorted(other.children)
assert math.isclose(
self.time, other.time, rel_tol=rel_tol, abs_tol=abs_tol
), f"Failed for time {self.time} != {other.time} (other)."
return True
def isclose(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
) -> bool:
"""
Returns true if the split is equal to the ``other`` split.
Compares values of the following attributes:
``parent``, ``children``, ``time``.
:param other: The split to compare against.
:type other: :class:`.Split`
:param ret_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type ret_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
:return: True if the two splits are equivalent, False otherwise.
:rtype: bool
"""
try:
self.assert_close(other, rel_tol=rel_tol, abs_tol=abs_tol)
return True
except AssertionError:
return False
@attr.s(auto_attribs=True, kw_only=True, slots=True)
class Branch:
"""
Parameters for a branch event, where a new deme branches off from a parental
deme. The parental deme need not end at that time.
:ivar str parent: The parental deme.
:ivar str child: The descendant deme.
:ivar float ~.time: The branch time.
"""
parent: Name = attr.ib(
validator=[attr.validators.instance_of(str), valid_deme_name]
)
child: Name = attr.ib(validator=[attr.validators.instance_of(str), valid_deme_name])
time: Time = attr.ib(validator=[int_or_float, non_negative, finite])
def __attrs_post_init__(self):
if self.child == self.parent:
raise ValueError("child and parent cannot be the same deme")
def assert_close(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
):
"""
Raises AssertionError if the object is not equal to ``other``,
up to a numerical tolerance.
Compares values of the following attributes:
``parent``, ``child``, ``time``.
:param other: The branch to compare against.
:type other: :class:`.Branch`
:param ret_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type ret_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
"""
assert (
self.__class__ is other.__class__
), f"failed as other branch is not instance of {self.__class__} type."
assert self.parent == other.parent
assert self.child == other.child
assert math.isclose(
self.time, other.time, rel_tol=rel_tol, abs_tol=abs_tol
), f"Failed for time {self.time} != {other.time} (other)."
def isclose(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
) -> bool:
"""
Returns true if the branch is equal to the ``other`` branch.
For more information see :meth:`assert_close`.
:param other: The branch to compare against.
:type other: :class:`.Branch`
:param ret_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type ret_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
:return: True if the two branches are equivalent, False otherwise.
:rtype: bool
"""
try:
self.assert_close(other, rel_tol=rel_tol, abs_tol=abs_tol)
return True
except AssertionError:
return False
@attr.s(auto_attribs=True, kw_only=True, slots=True)
class Merge:
"""
Parameters for a merge event, in which two or more demes end at some time and
contribute to a descendant deme.
:ivar list[str] parents: A list of parental demes.
:ivar list[float] proportions: A list of ancestry proportions,
in order of ``parents``.
:ivar str child: The descendant deme.
:ivar float ~.time: The merge time.
"""
parents: List[Name] = attr.ib(
validator=attr.validators.deep_iterable(
member_validator=attr.validators.and_(
attr.validators.instance_of(str), valid_deme_name
),
iterable_validator=attr.validators.instance_of(list),
)
)
proportions: List[Proportion] = attr.ib(
validator=attr.validators.deep_iterable(
member_validator=int_or_float,
iterable_validator=attr.validators.instance_of(list),
)
)
child: Name = attr.ib(validator=[attr.validators.instance_of(str), valid_deme_name])
time: Time = attr.ib(validator=[int_or_float, non_negative, finite])
@proportions.validator
def _check_proportions(self, attribute, _value):
if len(self.proportions) > 0 and not math.isclose(sum(self.proportions), 1.0):
raise ValueError("proportions must sum to 1.0")
for proportion in self.proportions:
unit_interval(self, attribute, proportion)
positive(self, attribute, proportion)
def __attrs_post_init__(self):
if len(self.parents) < 2:
raise ValueError("merge must involve at least two ancestors")
if len(self.parents) != len(self.proportions):
raise ValueError("parents and proportions must have same length")
if self.child in self.parents:
raise ValueError("merged deme cannot be its own ancestor")
if len(set(self.parents)) != len(self.parents):
raise ValueError("cannot repeat parents in merge")
def assert_close(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
):
"""
Raises AssertionError if the object is not equal to ``other``,
up to a numerical tolerance.
Compares values of the following attributes:
``parents``, ``proportions``, ``child``, ``time``.
:param other: The merge to compare against.
:type other: :class:`.Merge`
:param ret_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type ret_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
"""
assert (
self.__class__ is other.__class__
), f"Failed as other merge is not instance of {self.__class__} type."
assert isclose_deme_proportions(
self.parents,
self.proportions,
other.parents,
other.proportions,
rel_tol=rel_tol,
abs_tol=abs_tol,
), (
f"Parents or corresponding proportions are different: "
f"parents: {self.parents}, {other.parents} (other), "
f"proportions: {self.proportions}, {other.proportions} (other)."
)
assert self.child == other.child
assert math.isclose(
self.time, other.time, rel_tol=rel_tol, abs_tol=abs_tol
), f"Failed for time {self.time} != {other.time} (other)."
def isclose(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
) -> bool:
"""
Returns true if the merge is equal to the ``other`` merge.
For more information see :meth:`assert_close`.
:param other: The merge to compare against.
:type other: :class:`.Merge`
:param ret_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type ret_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
:return: True if the two merges are equivalent, False otherwise.
:rtype: bool
"""
try:
self.assert_close(other, rel_tol=rel_tol, abs_tol=abs_tol)
return True
except AssertionError:
return False
@attr.s(auto_attribs=True, kw_only=True, slots=True)
class Admix:
"""
Parameters for an admixture event, where two or more demes contribute ancestry
to a new deme.
:ivar list[str] parents: A list of source demes.
:ivar list[float] proportions: A list of ancestry proportions,
in order of ``parents``.
:ivar str child: The admixed deme.
:ivar float ~.time: The admixture time.
"""
parents: List[Name] = attr.ib(
validator=attr.validators.deep_iterable(
member_validator=attr.validators.and_(
attr.validators.instance_of(str), valid_deme_name
),
iterable_validator=attr.validators.instance_of(list),
)
)
proportions: List[Proportion] = attr.ib(
validator=attr.validators.deep_iterable(
member_validator=int_or_float,
iterable_validator=attr.validators.instance_of(list),
)
)
child: Name = attr.ib(validator=[attr.validators.instance_of(str), valid_deme_name])
time: Time = attr.ib(validator=[int_or_float, non_negative, finite])
@proportions.validator
def _check_proportions(self, attribute, _value):
if len(self.proportions) > 0 and not math.isclose(sum(self.proportions), 1.0):
raise ValueError("proportions must sum to 1.0")
for proportion in self.proportions:
unit_interval(self, attribute, proportion)
positive(self, attribute, proportion)
def __attrs_post_init__(self):
if len(self.parents) < 2:
raise ValueError("admixture must involve at least two ancestors")
if len(self.parents) != len(self.proportions):
raise ValueError("parents and proportions must have same length")
if self.child in self.parents:
raise ValueError("admixed deme cannot be its own ancestor")
if len(set(self.parents)) != len(self.parents):
raise ValueError("cannot repeat parents in admixure")
def assert_close(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
):
"""
Raises AssertionError if the object is not equal to ``other``,
up to a numerical tolerance.
Compares values of the following attributes:
``parents``, ``proportions``, ``child``, ``time``.
:param other: The admixture to compare against.
:type other: :class:`.Admix`
:param ret_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type ret_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
"""
assert (
self.__class__ is other.__class__
), f"Failed as other admixture is not instance of {self.__class__} type."
assert isclose_deme_proportions(
self.parents,
self.proportions,
other.parents,
other.proportions,
rel_tol=rel_tol,
abs_tol=abs_tol,
), (
f"Parents or corresponding proportions are different: "
f"parents: {self.parents}, {other.parents} (other), "
f"proportions: {self.proportions}, {other.proportions} (other)."
)
assert self.child == other.child
assert math.isclose(
self.time,
other.time,
rel_tol=rel_tol,
abs_tol=abs_tol,
), f"Failed for time {self.time} != {other.time} (other)."
def isclose(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
) -> bool:
"""
Returns true if the admixture is equal to the ``other`` admixture.
For more information see :meth:`assert_close`.
:param other: The admixture to compare against.
:type other: :class:`.Admix`
:param ret_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type ret_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
:return: True if the two admixtures are equivalent, False otherwise.
:rtype: bool
"""
try:
self.assert_close(other, rel_tol=rel_tol, abs_tol=abs_tol)
return True
except AssertionError:
return False
@attr.s(auto_attribs=True, kw_only=True, slots=True)
class Deme:
"""
A collection of individuals that have a common set of population parameters.
:ivar str name: A conscise string that identifies the deme.
:ivar str description: A description of the deme. May be ``None``.
:ivar float start_time: The time at which the deme begins to exist.
:ivar list[str] ancestors: List of deme names for the deme's ancestors.
This may be ``None``, indicating the deme has no ancestors.
:ivar list[float] proportions: If ``ancestors`` is not ``None``,
this indicates the proportions of ancestry from each ancestor.
This list has the same length as ``ancestors``, and must sum to 1.
:ivar list[Epoch] epochs: A list of epochs, which define the population
size(s) of the deme. The deme must be created with all epochs listed.
"""
name: Name = attr.ib(validator=[attr.validators.instance_of(str), valid_deme_name])
description: Optional[str] = attr.ib(
validator=attr.validators.optional(
[attr.validators.instance_of(str), nonzero_len]
)
)
start_time: Time = attr.ib(validator=[int_or_float, positive])
ancestors: List[Name] = attr.ib(
validator=attr.validators.deep_iterable(
member_validator=attr.validators.and_(
attr.validators.instance_of(str), valid_deme_name
),
iterable_validator=attr.validators.instance_of(list),
)
)
proportions: List[Proportion] = attr.ib(
validator=attr.validators.deep_iterable(
member_validator=int_or_float,
iterable_validator=attr.validators.instance_of(list),
)
)
epochs: List[Epoch] = attr.ib(
validator=attr.validators.deep_iterable(
member_validator=attr.validators.instance_of(Epoch),
iterable_validator=attr.validators.instance_of(list),
)
)
@ancestors.validator
def _check_ancestors(self, _attribute, _value):
if len(set(self.ancestors)) != len(self.ancestors):
raise ValueError(
f"deme {self.name}: duplicate ancestors in {self.ancestors}"
)
if self.name in self.ancestors:
raise ValueError(f"deme {self.name}: deme cannot be its own ancestor")
@proportions.validator
def _check_proportions(self, attribute, _value):
if len(self.proportions) > 0 and not math.isclose(sum(self.proportions), 1.0):
raise ValueError(f"deme {self.name}: ancestry proportions must sum to 1.0")
for proportion in self.proportions:
unit_interval(self, attribute, proportion)
positive(self, attribute, proportion)
@epochs.validator
def _check_epochs(self, _attribute, _value):
# check epoch times align
for i, epoch in enumerate(self.epochs):
if i > 0:
if self.epochs[i - 1].end_time != epoch.start_time:
raise ValueError(
f"deme {self.name}: "
f"epoch[{i}].start_time != epoch[{i}-1].end_time"
)
def __attrs_post_init__(self):
# We check the lengths of ancestors and proportions match
# after the validators have confirmed that these are indeed lists.
if len(self.ancestors) != len(self.proportions):
raise ValueError(
f"deme {self.name}: ancestors and proportions have different lengths"
)
def _add_epoch(
self,
*,
end_time,
start_size=None,
end_size=None,
size_function=None,
selfing_rate=0,
cloning_rate=0,
):
if len(self.epochs) == 0:
start_time = self.start_time
# The first epoch is special.
if start_size is None and end_size is None:
raise KeyError(
f"deme {self.name}: first epoch must have start_size or end_size"
)
if start_size is None:
start_size = end_size
if end_size is None:
end_size = start_size
else:
start_time = self.epochs[-1].end_time
# Set size based on previous epoch.
if start_size is None:
start_size = self.epochs[-1].end_size
if end_size is None:
end_size = start_size
if size_function is None:
if start_size == end_size:
size_function = "constant"
else:
size_function = "exponential"
try:
epoch = Epoch(
start_time=start_time,
end_time=end_time,
start_size=start_size,
end_size=end_size,
size_function=size_function,
selfing_rate=selfing_rate,
cloning_rate=cloning_rate,
)
except (TypeError, ValueError) as e:
raise e.__class__(
f"deme {self.name}: epoch[{len(self.epochs)}]: invalid epoch"
) from e
self.epochs.append(epoch)
def assert_close(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
):
"""
Raises AssertionError if the object is not equal to ``other``,
up to a numerical tolerance.
Compares values of the following objects:
``name``, ``ancestors``, ``proportions``, epochs.
:param other: The deme to compare against.
:type other: :class:`.Deme`
:param ret_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type ret_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
"""
assert (
self.__class__ is other.__class__
), f"Failed as other deme is not instance of {self.__class__} type."
assert self.name == other.name
assert math.isclose(
self.start_time, other.start_time, rel_tol=rel_tol, abs_tol=abs_tol
), f"Failed for start_time {self.start_time} != {other.start_time} (other)."
assert isclose_deme_proportions(
self.ancestors,
self.proportions,
other.ancestors,
other.proportions,
rel_tol=rel_tol,
abs_tol=abs_tol,
), (
f"Ancestors or corresponding proportions are different: "
f"ancestors: {self.ancestors}, {other.ancestors} (other), "
f"proportions: {self.proportions}, {other.proportions} (other)."
)
for i, (e1, e2) in enumerate(zip(self.epochs, other.epochs)):
try:
e1.assert_close(e2, rel_tol=rel_tol, abs_tol=abs_tol)
except AssertionError as e:
raise AssertionError(f"Failed for epochs (number {i})") from e
def isclose(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
) -> bool:
"""
Returns true if the deme is equal to the ``other`` deme.
For more information see :meth:`assert_close`.
:param other: The deme to compare against.
:type other: :class:`.Deme`
:param ret_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type ret_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
:return: True if the two demes are equivalent, False otherwise.
:rtype: bool
"""
try:
self.assert_close(other, rel_tol=rel_tol, abs_tol=abs_tol)
return True
except AssertionError:
return False
@property
def end_time(self):
"""
The end time of the deme's existence.
"""
return self.epochs[-1].end_time
@property
def time_span(self):
"""
The time span over which the deme exists.
"""
return self.start_time - self.end_time
@attr.s(auto_attribs=True, kw_only=True, slots=True)
class Graph:
"""
The Graph class provides a high-level API for working with a demographic
model. A Graph object matches Demes' data model, with a small number of
additional redundant attributes that make the Graph a more convenient
object to use when inspecting a model's properties.
:ivar str description: A human readable description of the demography.
May be ``None``.
:ivar str time_units: The units of time used for the demography. This is
commonly ``years`` or ``generations``, but can be any string.
This field is intended to be useful for documenting a demography,
but the actual value provided here should not be relied upon.
:ivar float generation_time: The generation time of demes, in units given
by the ``time_units`` parameter. Concretely, dividing all times
by ``generation_time`` will convert the graph to have time
units in generations. If ``generation_time`` is ``None``, the units
are assumed to be in generations already.
See also: :meth:`.in_generations`.
:ivar list[str] doi: If the graph describes a published demography,
the DOI(s) should be be given here as a list.
:ivar list[Deme] demes: The demes in the demography.
:ivar list[AsymmetricMigration] migrations: The continuous migrations for
the demographic model.
:ivar list[Pulse] pulses: The migration pulses for the demography.
"""
description: Optional[str] = attr.ib(
default=None,
validator=attr.validators.optional(
[attr.validators.instance_of(str), nonzero_len]
),
)
time_units: str = attr.ib(validator=[attr.validators.instance_of(str), nonzero_len])
generation_time: Optional[Time] = attr.ib(
default=None,
validator=attr.validators.optional([int_or_float, positive, finite]),
)
doi: List[str] = attr.ib(
factory=list,
validator=attr.validators.deep_iterable(
member_validator=attr.validators.and_(
attr.validators.instance_of(str), nonzero_len
),
iterable_validator=attr.validators.instance_of(list),
),
)
demes: List[Deme] = attr.ib(factory=list, init=False)
migrations: List[AsymmetricMigration] = attr.ib(factory=list, init=False)
pulses: List[Pulse] = attr.ib(factory=list, init=False)
# This attribute is for internal use only. It's a (hidden) attribute
# because we're using slotted classes and can't add attributes after
# object creation (e.g. in __attrs_post_init__()).
_deme_map: Dict[Name, Deme] = attr.ib(
factory=dict, init=False, repr=False, cmp=False
)
def __attrs_post_init__(self):
if self.time_units != "generations" and self.generation_time is None:
raise ValueError(
'if time_units!="generations", generation_time must be specified'
)
def __getitem__(self, deme_name):
"""
Return the :class:`.Deme` with the specified name.
"""
return self._deme_map[deme_name]
def __contains__(self, deme_name):
"""
Check if the graph contains a deme with the specified name.
"""
return deme_name in self._deme_map
# Use the simplified YAML output as the string representation.
__str__ = demes_dumps
def assert_close(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
):
"""
Raises AssertionError if the object is not equal to ``other``,
up to a numerical tolerance.
Furthermore, the following implementation details are ignored during
the comparison:
- The graphs' ``description`` and ``doi`` attributes.
- The order in which ``migrations`` were specified.
- The order in which admixture ``pulses`` were specified.
- The order in which ``demes`` were specified.
- The order in which a deme's ``ancestors`` were specified.
:param other: The graph to compare against.
:type other: :class:`.Graph`
:param float rel_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:param float abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
"""
def assert_sorted_eq(aa, bb, *, rel_tol, abs_tol, name):
# Order-agnostic equality check.
assert len(aa) == len(bb)
for (a, b) in zip(sorted(aa), sorted(bb)):
try:
a.assert_close(b, rel_tol=rel_tol, abs_tol=abs_tol)
except AssertionError as e:
if isinstance(a, Deme) and isinstance(b, Deme):
raise AssertionError(
f"Failed for {name} {a.name} and {b.name}"
) from e
raise AssertionError(f"Failed for {name}") from e
assert (
self.__class__ is other.__class__
), f"Failed as other graph is not instance of {self.__class__} type."
assert self.time_units == other.time_units
assert self.generation_time == other.generation_time
assert_sorted_eq(
self.demes, other.demes, rel_tol=rel_tol, abs_tol=abs_tol, name="demes"
)
assert_sorted_eq(
self.migrations,
other.migrations,
rel_tol=rel_tol,
abs_tol=abs_tol,
name="migrations",
)
assert_sorted_eq(
self.pulses,
other.pulses,
rel_tol=rel_tol,
abs_tol=abs_tol,
name="pulses",
)
def isclose(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
) -> bool:
"""
Returns true if the graph and ``other`` implement essentially
the same demographic model. Numerical values are compared using the
:func:`math.isclose` function, from which this method takes its name.
Furthermore, the following implementation details are ignored during
the comparison:
- The graphs' ``description`` and ``doi`` attributes.
- The order in which ``migrations`` were specified.
- The order in which admixture ``pulses`` were specified.
- The order in which ``demes`` were specified.
- The order in which a deme's ``ancestors`` were specified.
:param other: The graph to compare against.
:type other: :class:`.Graph`
:param float rel_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:param float abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:return: True if the two graphs implement the same model, False otherwise.
:rtype: bool
"""
try:
self.assert_close(other, rel_tol=rel_tol, abs_tol=abs_tol)
return True
except AssertionError:
return False
def _add_deme(
self,
*,
name,
description=None,
ancestors=None,
proportions=None,
start_time=None,
) -> Deme:
"""
Add a deme to the graph.
:param str name: A string identifier for the deme.
:param list[str] ancestors: List of deme names for the deme's ancestors.
This may be ``None``, indicating the deme has no ancestors.
If the deme has multiple ancestors, the ``proportions`` parameter
must also be provided.
:param list[float] proportions: The ancestry proportions for ``ancestors``.
This list has the same length as ``ancestors``, and must sum to ``1.0``.
May be omitted if the deme has only one, or zero, ancestors.
:param float start_time: The time at which this deme begins existing,
in units of ``time_units`` before the present.
- If the deme has zero ancestors, and ``start_time`` is not specified,
the start time will be set to ``inf``.
- If the deme has one ancestor, and ``start_time`` is not specified,
the ``start_time`` will be set to the ancestor's ``end_time``.
- If the deme has multiple ancestors, the ``start_time`` must be
provided.
:return: Newly created deme.
:rtype: :class:`.Deme`
"""
# some basic deme property checks
if name in self:
raise ValueError(
f"deme[{len(self.demes)}] {name}: field 'name' must be unique"
)
if ancestors is None:
ancestors = []
if not isinstance(ancestors, list):
raise TypeError(
f"deme[{len(self.demes)}] {name}: field 'ancestors' must be "
"a list of deme names"
)
for ancestor in ancestors:
if ancestor not in self:
raise ValueError(
f"deme[{len(self.demes)}] {name}: ancestor deme '{ancestor}' "
"not found. Note: ancestor demes must be specified before "
"their children."
)
if proportions is None:
if len(ancestors) == 1:
proportions = [1.0]
else:
proportions = []
# set the start time to inf or to the ancestor's end time
if start_time is None:
if len(ancestors) > 0:
if len(ancestors) > 1:
raise ValueError(
f"deme[{len(self.demes)}] {name}: "
"field 'start_time' not found, "
"but is required for demes with multiple ancestors"
)
start_time = self[ancestors[0]].end_time
else:
start_time = math.inf
if len(ancestors) == 0 and not math.isinf(start_time):
raise ValueError(
f"deme[{len(self.demes)}] {name}: field 'ancestors' not found, "
"but is required for demes with a finite 'start_time'"
)
# check start time is valid wrt ancestor time intervals
for ancestor in ancestors:
anc = self[ancestor]
if not (anc.start_time > start_time >= anc.end_time):
raise ValueError(
f"deme[{len(self.demes)}] {name}: start_time={start_time} is "
"outside the interval of existence for ancestor "
f"'{ancestor}' ({anc.start_time}, {anc.end_time}]"
)
deme = Deme(
name=name,
description=description,
ancestors=ancestors,
proportions=proportions,
start_time=start_time,
epochs=[],
)
self._deme_map[deme.name] = deme
self.demes.append(deme)
return deme
def _check_time_intersection(self, deme1, deme2, time):
deme1 = self[deme1]
deme2 = self[deme2]
time_lo = max(deme1.end_time, deme2.end_time)
time_hi = min(deme1.start_time, deme2.start_time)
if time is not None:
if not (time_lo <= time <= time_hi):
raise ValueError(
f"time {time} not in interval [{time_lo}, {time_hi}], "
f"as defined by the time-intersection of {deme1.name} "
f"(start_time={deme1.start_time}, end_time={deme1.end_time}) "
f"and {deme2.name} (start_time={deme2.start_time}, "
f"end_time={deme2.end_time})."
)
return time_lo, time_hi
def _add_symmetric_migration(
self, *, demes, rate, start_time=None, end_time=None
) -> List[AsymmetricMigration]:
"""
Add continuous symmetric migrations between all pairs of demes in a list.
:param list[str] demes: Deme names. Migration is symmetric between all
pairs of demes in this list.
:param float rate: The rate of migration per generation.
:param float start_time: The time at which the migration rate is enabled.
:param float end_time: The time at which the migration rate is disabled.
:return: List of newly created migrations.
:rtype: list[AsymmetricMigration]
"""
if not isinstance(demes, list) or len(demes) < 2:
raise ValueError("must specify a list of two or more deme names")
migrations = []
for source, dest in itertools.permutations(demes, 2):
migration = self._add_asymmetric_migration(
source=source,
dest=dest,
rate=rate,
start_time=start_time,
end_time=end_time,
)
migrations.append(migration)
return migrations
def _add_asymmetric_migration(
self, *, source, dest, rate, start_time=None, end_time=None
) -> AsymmetricMigration:
"""
Add continuous migration from one deme to another.
Source and destination demes follow the forwards-in-time convention,
so that the migration rate refers to the movement of individuals from
the ``source`` deme to the ``dest`` deme.
:param str source: The name of the source deme.
:param str dest: The name of the destination deme.
:param float rate: The rate of migration per generation.
:param float start_time: The time at which the migration rate is enabled.
If ``None``, the start time is defined by the earliest time at
which the demes coexist.
:param float end_time: The time at which the migration rate is disabled.
If ``None``, the end time is defined by the latest time at which
the demes coexist.
:return: Newly created migration.
:rtype: :class:`.AsymmetricMigration`
"""
for deme_name in (source, dest):
if deme_name not in self:
raise ValueError(f"{deme_name} not in graph")
time_lo, time_hi = self._check_time_intersection(source, dest, start_time)
if start_time is None:
start_time = time_hi
else:
self._check_time_intersection(source, dest, start_time)
if end_time is None:
end_time = time_lo
else:
self._check_time_intersection(source, dest, end_time)
migration = AsymmetricMigration(
source=source,
dest=dest,
start_time=start_time,
end_time=end_time,
rate=rate,
)
self.migrations.append(migration)
return migration
def _add_pulse(self, *, source, dest, proportion, time) -> Pulse:
"""
Add a pulse of migration at a fixed time.
Source and destination demes follow the forwards-in-time convention.
:param str source: The name of the source deme.
:param str dest: The name of the destination deme.
:param float proportion: At the instant after migration, this is the expected
proportion of individuals in the destination deme made up of individuals
from the source deme.
:param float time: The time at which migrations occur.
:return: Newly created pulse.
:rtype: :class:`.Pulse`
"""
for deme_name in (source, dest):
if deme_name not in self:
raise ValueError(f"{deme_name} not in graph")
self._check_time_intersection(source, dest, time)
if time == self[dest].end_time:
raise ValueError(
f"invalid pulse at time={time}, which is dest={dest}'s end_time"
)
if time == self[source].start_time:
raise ValueError(
f"invalid pulse at time={time}, which is source={source}'s start_time"
)
# We create the new pulse object (which checks for common errors)
# before checking for edge cases below.
new_pulse = Pulse(
source=source,
dest=dest,
time=time,
proportion=proportion,
)
# Check for models that have multiple pulses defined at the same time.
# E.g. chains of pulses like: deme0 -> deme1; deme1 -> deme2,
# where reversing the order of the pulse definitions changes the
# interpretation of the model. Such models are valid, but the behaviour
# may not be what the user expects.
# See https://github.com/popsim-consortium/demes-python/issues/46
sources = set()
dests = set()
for pulse in self.pulses:
if pulse.time == time:
sources.add(pulse.source)
dests.add(pulse.dest)
if source in dests or dest in (sources | dests):
warnings.warn(
"Multiple pulses are defined for the same deme(s) at time "
f"{time}. The ancestry proportions after this time will thus "
"depend on the order in which the pulses have been specified. "
"To avoid unexpected behaviour, the graph can instead "
"be structured to introduce a new deme at this time with "
"the desired ancestry proportions."
)
# Check for multiple pulses into dest at the same time that
# give a sum of proportions > 1.
proportion_sum = proportion
for pulse in self.pulses:
if dest == pulse.dest and pulse.time == time:
proportion_sum += pulse.proportion
if proportion_sum > 1:
raise ValueError(
f"sum of pulse proportions > 1 for dest={dest} at time={time}"
)
self.pulses.append(new_pulse)
return new_pulse
def _migration_matrices(self):
"""
Return a list of migration matrices, and a list of end times that
partition them. The start time for the first matrix is inf.
"""
uniq_times = set(migration.start_time for migration in self.migrations)
uniq_times.update(migration.end_time for migration in self.migrations)
end_times = sorted(uniq_times, reverse=True)[1:]
n = len(self.demes)
mm_list = [[[0] * n for _ in range(n)] for _ in range(len(end_times))]
deme_id = {deme.name: j for j, deme in enumerate(self.demes)}
for migration in self.migrations:
start_time = math.inf
for k, end_time in enumerate(end_times):
if start_time <= migration.end_time:
break
if end_time < migration.start_time:
source_id = deme_id[migration.source]
dest_id = deme_id[migration.dest]
if mm_list[k][dest_id][source_id] > 0:
raise ValueError(
"multiple migrations defined for "
f"source={migration.source}, dest={migration.dest} "
f"between start_time={start_time}, end_time={end_time}"
)
mm_list[k][dest_id][source_id] = migration.rate
start_time = end_time
return mm_list, end_times
def _check_migration_rates(self):
"""
Check that the sum of migration ingress rates doesn't exceed 1 for any
deme in any interval of time.
"""
start_time = math.inf
mm_list, end_times = self._migration_matrices()
for migration_matrix, end_time in zip(mm_list, end_times):
for j, row in enumerate(migration_matrix):
row_sum = sum(row)
if row_sum > 1 and not math.isclose(row_sum, 1):
name = self.demes[j].name
raise ValueError(
f"sum of migration rates into deme {name} is greater "
f"than 1 during interval ({start_time}, {end_time}]"
)
start_time = end_time
def successors(self) -> Dict[Name, List[Name]]:
"""
Returns the successors (child demes) for all demes in the graph.
If ``graph`` is a :class:`Graph`, a `NetworkX <https://networkx.org/>`_
digraph of successors can be obtained as follows.
.. code::
import networkx as nx
succ = nx.from_dict_of_lists(graph.successors(), create_using=nx.DiGraph)
.. warning::
The successors do not include information about migrations or pulses.
:return: A NetworkX compatible dict-of-lists graph of the demes' successors.
:rtype: dict[str, list[str]]
"""
succ: Dict[Name, List[Name]] = {}
for deme_info in self.demes:
succ.setdefault(deme_info.name, [])
if deme_info.ancestors is not None:
for a in deme_info.ancestors:
succ.setdefault(a, [])
succ[a].append(deme_info.name)
return succ
def predecessors(self) -> Dict[Name, List[Name]]:
"""
Returns the predecessors (ancestors) for all demes in the graph.
If ``graph`` is a :class:`Graph`, a `NetworkX <https://networkx.org/>`_
digraph of predecessors can be obtained as follows.
.. code::
import networkx as nx
pred = nx.from_dict_of_lists(graph.predecessors(), create_using=nx.DiGraph)
.. warning::
The predecessors do not include information about migrations or pulses.
:return: A NetworkX compatible dict-of-lists graph of the demes' predecessors.
:rtype: dict[str, list[str]]
"""
pred: Dict[Name, List[Name]] = {}
for deme_info in self.demes:
pred.setdefault(deme_info.name, [])
if deme_info.ancestors is not None:
for a in deme_info.ancestors:
pred[deme_info.name].append(a)
return pred
def discrete_demographic_events(self) -> Dict[str, List[Any]]:
"""
Classify each discrete demographic event as one of the following:
:class:`Pulse`, :class:`Split`, :class:`Branch`, :class:`Merge`,
or :class:`Admix`.
If a deme has more than one ancestor, then that deme is created by a
merger or an admixture event, which are differentiated by end and
start times of those demes. If a deme has a single predecessor, we check
whether it is created by a branch (start time != predecessor's end time),
or split.
.. note::
By definition, the discrete demographic events do not include
migrations, as they are continuous events.
:return: A dictionary of lists of discrete demographic events.
The following keys are defined: "pulses", "splits", "branches",
"mergers", "admixtures", and their values are the corresponding
lists of :class:`Pulse`, :class:`Split`, :class:`Branch`,
:class:`Merge`, and :class:`Admix` objects.
:rtype: dict[str, list]
"""
demo_events: Dict[str, List[Any]] = {
"pulses": self.pulses,
"splits": [],
"branches": [],
"mergers": [],
"admixtures": [],
}
splits_to_add: Dict[Name, Set[Name]] = {}
for c, p in self.predecessors().items():
if len(p) == 0:
continue
elif len(p) == 1:
if self[c].start_time == self[p[0]].end_time:
splits_to_add.setdefault(p[0], set())
splits_to_add[p[0]].add(c)
else:
demo_events["branches"].append(
Branch(parent=p[0], child=c, time=self[c].start_time)
)
else:
time_aligned = True
for deme_from in p:
if self[c].start_time != self[deme_from].end_time:
time_aligned = False
if time_aligned is True:
demo_events["mergers"].append(
Merge(
parents=self[c].ancestors,
proportions=self[c].proportions,
child=c,
time=self[c].start_time,
)
)
else:
demo_events["admixtures"].append(
Admix(
parents=self[c].ancestors,
proportions=self[c].proportions,
child=c,
time=self[c].start_time,
)
)
for deme_from, demes_to in splits_to_add.items():
demo_events["splits"].append(
Split(
parent=deme_from,
children=list(demes_to),
time=self[deme_from].end_time,
)
)
return demo_events
def in_generations(self) -> "Graph":
"""
Return a copy of the graph with times in units of generations.
"""
graph = copy.deepcopy(self)
generation_time = self.generation_time
graph.generation_time = None
if graph.time_units != "generations" and generation_time is not None:
graph.time_units = "generations"
for deme in graph.demes:
deme.start_time /= generation_time
for epoch in deme.epochs:
epoch.start_time /= generation_time
epoch.end_time /= generation_time
for migration in graph.migrations:
migration.start_time /= generation_time
migration.end_time /= generation_time
for pulse in graph.pulses:
pulse.time /= generation_time
return graph
@classmethod
def fromdict(cls, data: MutableMapping[str, Any]) -> "Graph":
"""
Return a graph from a dict representation. The inverse of asdict().
"""
if not isinstance(data, MutableMapping):
raise TypeError("data is not a dictionary")
# Don't modify the input data dict.
data = copy.deepcopy(data)
check_allowed(
data,
[
"description",
"time_units",
"generation_time",
"defaults",
"doi",
"demes",
"migrations",
"pulses",
],
"toplevel",
)
defaults = pop_object(data, "defaults", {}, scope="toplevel")
check_allowed(
defaults,
["deme", "migration", "pulse", "epoch"],
"defaults",
)
deme_defaults = pop_object(defaults, "deme", {}, scope="defaults")
allowed_fields_deme = [
"description",
"start_time",
"ancestors",
"proportions",
]
allowed_fields_deme_inner = allowed_fields_deme + ["name", "defaults", "epochs"]
check_allowed(deme_defaults, allowed_fields_deme, "defaults: deme")
migration_defaults = pop_object(defaults, "migration", {}, scope="defaults")
allowed_fields_migration = [
"demes",
"source",
"dest",
"start_time",
"end_time",
"rate",
]
check_allowed(
migration_defaults, allowed_fields_migration, "defaults: migration"
)
pulse_defaults = pop_object(defaults, "pulse", {}, scope="defaults")
allowed_fields_pulse = ["source", "dest", "time", "proportion"]
check_allowed(pulse_defaults, allowed_fields_pulse, "defaults.pulse")
# epoch defaults may also be specified within a Deme definition.
global_epoch_defaults = pop_object(defaults, "epoch", {}, scope="defaults")
allowed_fields_epoch = [
"end_time",
"start_size",
"end_size",
"size_function",
"cloning_rate",
"selfing_rate",
]
check_allowed(global_epoch_defaults, allowed_fields_epoch, "defaults: epoch")
if "time_units" not in data:
raise KeyError("toplevel: required field 'time_units' not found")
graph = cls(
description=data.pop("description", None),
time_units=data.pop("time_units"),
doi=data.pop("doi", []),
generation_time=data.pop("generation_time", None),
)
for i, deme_data in enumerate(
pop_list(data, "demes", required_type=MutableMapping, scope="toplevel")
):
if "name" not in deme_data:
raise KeyError("demes[{i}]: required field 'name' not found")
deme_name = deme_data.pop("name")
check_allowed(
deme_data, allowed_fields_deme_inner, f"demes[{i}] {deme_name}"
)
insert_defaults(deme_data, deme_defaults)
deme = graph._add_deme(
name=deme_name,
description=deme_data.pop("description", None),
start_time=deme_data.pop("start_time", None),
ancestors=deme_data.pop("ancestors", None),
proportions=deme_data.pop("proportions", None),
)
local_defaults = pop_object(
deme_data, "defaults", {}, scope=f"demes[{i}] {deme.name}"
)
check_allowed(
local_defaults, ["epoch"], f"demes[{i}] {deme.name}: defaults"
)
local_epoch_defaults = pop_object(
local_defaults, "epoch", {}, scope=f"demes[{i}] {deme.name}: defaults"
)
epoch_defaults = global_epoch_defaults.copy()
epoch_defaults.update(local_epoch_defaults)
check_allowed(
epoch_defaults,
allowed_fields_epoch,
f"demes[{i}] {deme.name}: defaults: epoch",
)
if len(epoch_defaults) == 0 and "epochs" not in deme_data:
# This condition would be caught downstream, because start_size
# or end_size are required for the first epoch. But we check
# here to provide a more informative error message.
raise KeyError(
f"demes[{i}] {deme.name}: required field 'epochs' not found"
)
# There is always at least one epoch defined with the default values.
epochs = pop_list(
deme_data,
"epochs",
[{}],
required_type=MutableMapping,
scope=f"demes[{i}] {deme.name}",
)
for j, epoch_data in enumerate(epochs):
check_allowed(
epoch_data,
allowed_fields_epoch,
f"demes[{i}] {deme.name}: epochs[{j}]",
)
insert_defaults(epoch_data, epoch_defaults)
if "end_time" not in epoch_data:
if j == len(epochs) - 1:
epoch_data["end_time"] = 0
else:
raise KeyError(
f"demes[{i}] {deme.name}: epochs[{j}]: "
"required field 'end_time' not found"
)
deme._add_epoch(
end_time=epoch_data.pop("end_time"),
start_size=epoch_data.pop("start_size", None),
end_size=epoch_data.pop("end_size", None),
size_function=epoch_data.pop("size_function", None),
selfing_rate=epoch_data.pop("selfing_rate", 0),
cloning_rate=epoch_data.pop("cloning_rate", 0),
)
for i, migration_data in enumerate(
pop_list(
data, "migrations", [], required_type=MutableMapping, scope="toplevel"
)
):
check_allowed(migration_data, allowed_fields_migration, f"migration[{i}]")
insert_defaults(migration_data, migration_defaults)
if "rate" not in migration_data:
raise KeyError(f"migration[{i}]: required field 'rate' not found")
demes = migration_data.pop("demes", None)
source = migration_data.pop("source", None)
dest = migration_data.pop("dest", None)
if not (
# symmetric
(demes is not None and source is None and dest is None)
# asymmetric
or (demes is None and source is not None and dest is not None)
):
raise KeyError(
f"migration[{i}]: must be symmetric (specify 'demes' list) "
"*or* asymmetric (specify both 'source' and 'dest')."
)
try:
if demes is not None:
graph._add_symmetric_migration(
demes=demes,
rate=migration_data.pop("rate"),
start_time=migration_data.pop("start_time", None),
end_time=migration_data.pop("end_time", None),
)
else:
graph._add_asymmetric_migration(
source=source,
dest=dest,
rate=migration_data.pop("rate"),
start_time=migration_data.pop("start_time", None),
end_time=migration_data.pop("end_time", None),
)
except (TypeError, ValueError) as e:
raise e.__class__(f"migration[{i}]: invalid migration") from e
graph._check_migration_rates()
for i, pulse_data in enumerate(
pop_list(data, "pulses", [], required_type=MutableMapping, scope="toplevel")
):
check_allowed(pulse_data, allowed_fields_pulse, f"pulse[{i}]")
insert_defaults(pulse_data, pulse_defaults)
for field in ("source", "dest", "time", "proportion"):
if field not in pulse_data:
raise KeyError(f"pulse[{i}]: required field '{field}' not found")
try:
graph._add_pulse(
source=pulse_data.pop("source"),
dest=pulse_data.pop("dest"),
time=pulse_data.pop("time"),
proportion=pulse_data.pop("proportion"),
)
except (TypeError, ValueError) as e:
raise e.__class__(f"pulse[{i}]: invalid pulse") from e
return graph
def asdict(self) -> MutableMapping[str, Any]:
"""
Return a fully-resolved dict representation of the graph.
"""
def filt(attrib, value):
return (
value is not None
and not (hasattr(value, "__len__") and len(value) == 0)
and attrib.name != "_deme_map"
)
def coerce_numbers(inst, attribute, value):
# Explicitly convert numeric types to int or float, so that they
# don't cause problems for the YAML and JSON serialisers.
# E.g. numpy int32/int64 are part of Python's numeric tower as
# subclasses of numbers.Integral, similarly numpy's float32/float64
# are subclasses of numbers.Real. There are yet other numeric types,
# such as the standard library's decimal.Decimal, which are not part
# of the numeric tower, but provide a __float__() method.
if isinstance(value, numbers.Integral):
value = int(value)
elif isinstance(value, numbers.Real) or hasattr(value, "__float__"):
value = float(value)
return value
data = attr.asdict(self, filter=filt, value_serializer=coerce_numbers)
# translate to spec data model
for deme in data["demes"]:
for epoch in deme["epochs"]:
del epoch["start_time"]
return data
def asdict_simplified(self) -> MutableMapping[str, Any]:
"""
Return a simplified dict representation of the graph.
"""
def simplify_epochs(data):
"""
Remove epoch start times. Also remove deme start time
if implied by the deme ancestor(s)'s end time(s).
"""
for deme in data["demes"]:
for j, epoch in enumerate(deme["epochs"]):
if epoch["size_function"] in ("constant", "exponential"):
del epoch["size_function"]
if epoch["start_size"] == epoch["end_size"]:
del epoch["end_size"]
if epoch["selfing_rate"] == 0:
del epoch["selfing_rate"]
if epoch["cloning_rate"] == 0:
del epoch["cloning_rate"]
for deme in data["demes"]:
# remove implied start times
if math.isinf(deme["start_time"]):
del deme["start_time"]
if "ancestors" in deme and len(deme["ancestors"]) == 1:
del deme["proportions"]
# start time needed for more than 1 ancestor
if self[deme["ancestors"][0]].end_time == deme["start_time"]:
del deme["start_time"]
def simplify_migration_rates(data):
"""
Collapse symmetric migration rates, and remove redundant information
about start and end times if they are implied by the time overlap
interval of the demes involved.
To collapse symmetric migrations, we collect all source/dest migration
pairs for each set of migration attributes (rate, start_time, end_time),
and then iteratively check for all-way symmetric migration between all
demes that are involved in migrations for the given set of migration
attributes.
"""
def collapse_demes(pairs):
all_demes = []
for pair in pairs:
if pair[0] not in all_demes:
all_demes.append(pair[0])
if pair[1] not in all_demes:
all_demes.append(pair[1])
return all_demes
symmetric = []
asymmetric = data["migrations"].copy()
# first remove start/end times if equal time intersections
rate_sets = {}
# keys of rate_types are (rate, start_time, end_time)
for migration in data["migrations"]:
source = migration["source"]
dest = migration["dest"]
time_hi = min(self[source].start_time, self[dest].start_time)
time_lo = max(self[dest].end_time, self[dest].end_time)
if migration["end_time"] == time_lo:
del migration["end_time"]
if migration["start_time"] == time_hi:
del migration["start_time"]
k = tuple(
migration.get(key) for key in ("rate", "start_time", "end_time")
)
rate_sets.setdefault(k, [])
rate_sets[k].append((source, dest))
for k, pairs in rate_sets.items():
if len(pairs) == 1:
continue
# list of all demes that are source or dest in this rate set
all_demes = collapse_demes(pairs)
# we check all possible sets of n-way symmetric migration
i = len(all_demes)
while len(all_demes) >= 2 and i >= 2:
# loop through each possible set for a given set size i
compress_demes = False
for deme_set in itertools.combinations(all_demes, i):
# check if all (source, dest) pairs exist in pairs of migration
all_present = True
for deme_pair in itertools.permutations(deme_set, 2):
if deme_pair not in pairs:
all_present = False
break
# if they do all exist
if all_present:
compress_demes = True
# remove from asymmetric list
for deme_pair in itertools.permutations(deme_set, 2):
mig = {
"source": deme_pair[0],
"dest": deme_pair[1],
"rate": k[0],
}
if k[1] is not None:
mig["start_time"] = k[1]
if k[2] is not None:
mig["end_time"] = k[2]
asymmetric.remove(mig)
pairs.remove(deme_pair)
# add to symmetric list
sym_mig = dict(demes=[d for d in deme_set], rate=k[0])
if k[1] is not None:
sym_mig["start_time"] = k[1]
if k[2] is not None:
sym_mig["end_time"] = k[2]
symmetric.append(sym_mig)
# if we found a set of symmetric migrations, compress all_demes
if compress_demes:
all_demes = collapse_demes(pairs)
i = min(i, len(all_demes))
# otherwise, check one set size smaller
else:
i -= 1
data["migrations"] = symmetric + asymmetric
data = self.asdict()
if "migrations" in data:
simplify_migration_rates(data)
simplify_epochs(data)
return data
class Builder:
"""
The Builder provides a set of convenient methods for incrementally
constructing a deme graph. The state of the graph is stored internally as a
dictionary of objects following Demes' data model, and may be converted
into a fully-resolved :class:`Graph` object using the :meth:`.resolve()` method.
:ivar dict data: The data dictionary of the graph's current state.
The objects nested within this dictionary follow Demes' data model,
as described in the :ref:`spec:sec_ref`.
.. note::
Users may freely modify the data dictionary, as long as the data
model is not violated.
"""
def __init__(
self,
*,
description: str = None,
time_units: str = "generations",
generation_time: float = None,
doi: list = None,
defaults: dict = None,
):
"""
:param str description: A human readable description of the demography.
May be ``None``.
:param str time_units: The units of time used for the demography. This is
commonly ``years`` or ``generations``, but can be any string.
:param float generation_time: The generation time of demes, in units given
by the ``time_units`` parameter. Concretely, dividing all times
by ``generation_time`` will convert the graph to have time
units in generations. If ``generation_time`` is ``None``, the units
are assumed to be in generations already.
:param doi: If the graph describes a published demography, the DOI(s)
should be be given here as a list.
:type doi: list[str]
"""
self.data: MutableMapping[str, Any] = dict(time_units=time_units)
if description is not None:
self.data["description"] = description
if generation_time is not None:
self.data["generation_time"] = generation_time
if doi is not None:
self.data["doi"] = doi
if defaults is not None:
self.data["defaults"] = defaults
def add_deme(
self,
name: str,
*,
description: str = None,
ancestors: list = None,
proportions: list = None,
start_time: float = None,
epochs: list = None,
defaults: dict = None,
):
"""
Add a deme. Ancestor demes must be added before their children.
:param str name: A string identifier for the deme.
:param str description: A description of the deme. May be ``None``.
:param list[str] ancestors: List of deme names for the deme's ancestors.
This may be ``None``, indicating the deme has no ancestors.
:param list[float] proportions: If ``ancestors`` is not ``None``,
this indicates the proportions of ancestry from each ancestor.
This list has the same length as ``ancestors``, and must sum to 1.
:param float start_time: The deme's start time.
:param list[dict] epochs: List of epoch dictionaries. Each dictionary
follows the data model for an epoch.
"""
deme: MutableMapping[str, Any] = dict(name=name)
if description is not None:
deme["description"] = description
if ancestors is not None:
deme["ancestors"] = ancestors
if proportions is not None:
deme["proportions"] = proportions
if start_time is not None:
deme["start_time"] = start_time
if epochs is not None:
deme["epochs"] = epochs
if defaults is not None:
deme["defaults"] = defaults
if "demes" not in self.data:
self.data["demes"] = []
self.data["demes"].append(deme)
def add_migration(
self,
*,
rate: float = None,
# We use a special NO_DEFAULT value here, to distinguish between the user
# not specifying anything, and specifying the value None (which may be
# necessary to override a 'defaults' value set in the data dictionary).
demes: list = NO_DEFAULT, # type: ignore
source: str = NO_DEFAULT, # type: ignore
dest: str = NO_DEFAULT, # type: ignore
start_time: float = None,
end_time: float = None,
):
"""
Add continuous symmetric migrations between all pairs of demes in a list,
or alternately, add asymmetric migration from one deme to another.
Source and destination demes follow the forwards-in-time convention,
so that the migration rate refers to the movement of individuals from
the ``source`` deme to the ``dest`` deme.
:param list[str] demes: list of deme names. Migration is symmetric
between all pairs of demes in this list. If not specified,
migration will be asymmetric (and ``source`` and ``dest`` must
be given).
:param str source: The name of the source deme.
:param str dest: The name of the destination deme.
:param float rate: The rate of migration per generation.
:param float start_time: The time at which the migration rate is enabled.
If ``None``, the start time is defined by the earliest time at
which the demes coexist.
:param float end_time: The time at which the migration rate is disabled.
If ``None``, the end time is defined by the latest time at which
the demes coexist.
"""
migration: MutableMapping[str, Any] = dict()
if rate is not None:
migration["rate"] = rate
if demes is not NO_DEFAULT:
migration["demes"] = demes
if source is not NO_DEFAULT:
migration["source"] = source
if dest is not NO_DEFAULT:
migration["dest"] = dest
if start_time is not None:
migration["start_time"] = start_time
if end_time is not None:
migration["end_time"] = end_time
if "migrations" not in self.data:
self.data["migrations"] = []
self.data["migrations"].append(migration)
def add_pulse(
self,
*,
source: str = None,
dest: str = None,
proportion: float = None,
time: float = None,
):
"""
Add a pulse of migration at a fixed time.
Source and destination demes follow the forwards-in-time convention.
:param str source: The name of the source deme.
:param str dest: The name of the destination deme.
:param float proportion: At the instant after migration, this is the
expected proportion of individuals in the destination deme made up
of individuals from the source deme.
:param float time: The time at which migrations occur.
"""
pulse: MutableMapping[str, Any] = dict()
if source is not None:
pulse["source"] = source
if dest is not None:
pulse["dest"] = dest
if proportion is not None:
pulse["proportion"] = proportion
if time is not None:
pulse["time"] = time
if "pulses" not in self.data:
self.data["pulses"] = []
self.data["pulses"].append(pulse)
def resolve(self):
"""
Resolve the data dictionary into a Graph.
:return: The fully-resolved Graph.
:rtype: Graph
"""
return Graph.fromdict(self.data)
@classmethod
def fromdict(cls, data: MutableMapping[str, Any]) -> "Builder":
"""
Make a Builder object from an existing data dictionary.
:param MutableMapping data: The data dictionary to initialise the
graph's state. The objects nested within this dictionary must
follow Demes' data model, as described in the :ref:`spec:sec_ref`.
:return: The new Builder object.
:rtype: Builder
"""
builder = cls()
builder.data = data
return builder
|
python
|
import json
import urllib3
http = urllib3.PoolManager()
request = http.request('GET','https://booksbyptyadana.herokuapp.com/books')
data = request.data
print(request.status)
if len(data) > 0:
book_dict = dict()
books = json.loads(data.decode('utf-8'))
for book in books:
book_dict[book['book_name']]= book['author_name']
print(book_dict)
else:
print('no data received.')
|
python
|
from abc import ABC
from distutils.version import LooseVersion
from typing import Union
class Capabilities(ABC):
"""Represents capabilities of a connection / back end."""
def __init__(self, data):
pass
def version(self):
""" Get openEO version. DEPRECATED: use api_version instead"""
# Field: version
# TODO: raise deprecation warning here?
return self.api_version()
def api_version(self) -> str:
"""Get OpenEO API version."""
raise NotImplementedError
@property
def api_version_check(self) -> 'ComparableVersion':
"""Helper to easily check if the API version is at least or below some threshold version."""
api_version = self.api_version()
if not api_version:
raise ApiVersionException("No API version found")
return ComparableVersion(api_version)
def list_features(self):
""" List all supported features / endpoints."""
# Field: endpoints
pass
def has_features(self, method_name):
""" Check whether a feature / endpoint is supported."""
# Field: endpoints > ...
pass
def currency(self):
""" Get default billing currency."""
# Field: billing > currency
pass
def list_plans(self):
""" List all billing plans."""
# Field: billing > plans
pass
class ComparableVersion:
"""
Helper to compare a version (e.g. API version) against another (threshold) version
>>> v = ComparableVersion('1.2.3')
>>> v.at_least('1.2.1')
True
>>> v.at_least('1.10.2')
False
>>> v > "2.0"
False
To express a threshold condition you sometimes want the reference or threshold value on
the left hand side or right hand side of the logical expression.
There are two groups of methods to handle each case:
- right hand side referencing methods. These read more intuitively. For example:
`a.at_least(b)`: a is equal or higher than b
`a.below(b)`: a is lower than b
- left hand side referencing methods. These allow "currying" a threshold value
in a reusable condition callable. For example:
`a.or_higher(b)`: b is equal or higher than a
`a.accept_lower(b)`: b is lower than a
"""
def __init__(self, version: Union[str, 'ComparableVersion']):
if isinstance(version, ComparableVersion):
self._version = version._version
else:
self._version = LooseVersion(version)
def __repr__(self):
return '{c}({v!r})'.format(c=type(self).__name__, v=self._version)
def __str__(self):
return str(self._version)
def to_string(self):
return str(self)
def __ge__(self, other: Union[str, 'ComparableVersion']):
return self._version >= ComparableVersion(other)._version
def __gt__(self, other: Union[str, 'ComparableVersion']):
return self._version > ComparableVersion(other)._version
def __le__(self, other: Union[str, 'ComparableVersion']):
return self._version <= ComparableVersion(other)._version
def __lt__(self, other: Union[str, 'ComparableVersion']):
return self._version < ComparableVersion(other)._version
# Right hand side referencing expressions.
def at_least(self, other: Union[str, 'ComparableVersion']):
"""Self is at equal or higher than other."""
return self >= other
def above(self, other: Union[str, 'ComparableVersion']):
"""Self is higher than other."""
return self > other
def at_most(self, other: Union[str, 'ComparableVersion']):
"""Self is equal or lower than other."""
return self <= other
def below(self, other: Union[str, 'ComparableVersion']):
"""Self is lower than other."""
return self < other
# Left hand side referencing expressions.
def or_higher(self, other: Union[str, 'ComparableVersion']):
"""Other is equal or higher than self."""
return ComparableVersion(other) >= self
def or_lower(self, other: Union[str, 'ComparableVersion']):
"""Other is equal or lower than self"""
return ComparableVersion(other) <= self
def accept_lower(self, other: Union[str, 'ComparableVersion']):
"""Other is lower than self."""
return ComparableVersion(other) < self
def accept_higher(self, other: Union[str, 'ComparableVersion']):
"""Other is higher than self."""
return ComparableVersion(other) > self
class ApiVersionException(RuntimeError):
pass
|
python
|
#!../../../.env/bin/python
import os
import numpy as np
import time
a = np.array([
[1,0,3],
[0,2,1],
[0.1,0,0],
])
print a
row = 1
col = 2
print a[row][col]
assert a[row][col] == 1
expected_max_rows = [0, 1, 0]
expected_max_values = [1, 2, 3]
print 'expected_max_rows:', expected_max_rows
print 'expected_max_values:', expected_max_values
t0 = time.time()
actual_max_rows = list(np.argmax(a, axis=0))
td = time.time() - t0
actual_max_values = list(np.amax(a, axis=0))
print 'td:', round(td, 4)
print 'actual_max_rows:', actual_max_rows
print 'actual_max_values:', actual_max_values
assert actual_max_rows == expected_max_rows
assert actual_max_values == expected_max_values
|
python
|
from utils import overloadmethod, ApeInternalError
from astpass import DeepAstPass
import cstnodes as E
class Sentinel:
def __init__(self, value):
self.value = value
def __repr__(self):
return f'Sentinel({self.value!r})'
def is_sentinel(x):
return isinstance(x, Sentinel)
def is_iterable(x):
try:
iter(x)
return True
except TypeError:
return False
class IsGenPass(DeepAstPass):
"""A compiler pass to test for the presence of generators"""
def true_args(self, args):
return any(self.true_arg(a) for a in args if a is not args and (is_iterable(a) or is_sentinel(a)))
def true_arg(self, arg):
if is_iterable(arg):
return self.true_args(arg)
if is_sentinel(arg):
return arg.value
raise ApeInternalError('We should\'t ever get here')
def override_do_visit_wrapper(self, ast, new):
if isinstance(new, Sentinel):
return new
if isinstance(new, bool):
return Sentinel(new)
# no atomic expressions can yield
if ast is new:
return Sentinel(False)
cls, args = new
try:
return Sentinel(self.true_args(args))
except TypeError:
raise
def visit(self, ast):
return self.my_visit(ast)
@overloadmethod(use_as_default=True)
def my_visit(self, ast):
return super().visit(ast)
@my_visit.on((E.YieldFromExpression, E.YieldExpression))
def my_visit_Yield_Or_YieldFrom_Expression(self, ast):
return Sentinel(True)
@my_visit.on((E.FunctionExpression, E.FunctionDefinition))
def my_visit_FunctionDefinition_Or_FunctionExpression(self, ast):
return Sentinel(any(self.is_gen(p.default) for p in ast.params if p.default is not None))
@my_visit.wrapper()
def my_visit_wrapper(self, ast, new):
return self.override_do_visit_wrapper(ast, new)
def is_gen(self, ast):
return self.visit(ast).value
def is_gen(ast):
return IsGenPass().is_gen(ast)
|
python
|
import unittest
import numpy as np
from laika.raw_gnss import get_DOP, get_PDOP, get_HDOP, get_VDOP, get_TDOP
from laika.lib.coordinates import geodetic2ecef
class TestDOP(unittest.TestCase):
def setUp(self):
self.receiver = geodetic2ecef((0, 0, 0))
self.satellites = np.array([
[18935913, -3082759, -18366964],
[7469795, 22355916, -12240619],
[11083784, -18179141, 15877221],
[22862911, 13420911, 1607501]
])
def test_GDOP(self):
dop = get_DOP(self.receiver, self.satellites)
self.assertAlmostEqual(dop, 2.352329857908973)
def test_HDOP(self):
dop = get_HDOP(self.receiver, self.satellites)
self.assertAlmostEqual(dop, 1.3418910470124197)
def test_VDOP(self):
dop = get_VDOP(self.receiver, self.satellites)
self.assertAlmostEqual(dop, 1.7378390525714509)
def test_PDOP(self):
dop = get_PDOP(self.receiver, self.satellites)
self.assertAlmostEqual(dop, 2.195622042769321)
def test_TDOP(self):
dop = get_TDOP(self.receiver, self.satellites)
self.assertAlmostEqual(dop, 0.8442153787485294)
if __name__ == "__main__":
unittest.main()
|
python
|
# This utility should only be invoked via the itimUtil.sh wrapper script.
# Support utility to submit ITIM object changes via the ITIM API. Changes are specified
# through a text file.
# Changes are submitted asynchronously and status is reported later in the output.
# See usage information in the wrapper script.
# 2013-10-23 Paul T Sparks
# Added personCreate command. Added argStyle configuration to allow multiple "eval" options
# for commands with the same number of args.
# 2013-07-12 Paul T Sparks
# TODO Enhancements
# During *AttrAdd prevent adding duplicate values (?)
# ITIM API imports
from com.ibm.itim.apps import InitialPlatformContext, PlatformContext, Request
from com.ibm.itim.apps.identity import OrganizationalContainerMO, PersonManager, PersonMO
from com.ibm.itim.apps.jaas.callback import PlatformCallbackHandler
from com.ibm.itim.apps.policy import Entitlement, ProvisioningPolicy, ProvisioningPolicyManager, ProvisioningPolicyMO
from com.ibm.itim.apps.provisioning import AccountManager, AccountMO, ServiceMO
from com.ibm.itim.apps.search import SearchMO
from com.ibm.itim.apps.system import SystemUserMO
from com.ibm.itim.common import AttributeValue, EntitlementAttributeValue
from com.ibm.itim.dataservices.model import CompoundDN, DistinguishedName, ObjectProfileCategory, SearchParameters
from com.ibm.itim.dataservices.model.domain import Person,Service,OrganizationalContainerSearch,OrganizationSearch
from com.ibm.itim.dataservices.model.system import SystemUser
from com.ibm.websphere.security.auth.callback import WSCallbackHandlerImpl
from java.lang import Exception, System, Thread
from java.util import ArrayList, Collections, HashMap, Hashtable, Locale
from javax.security.auth.login import LoginContext
import os
import sys
import time
# Default WebSphere username for platform authentication
PLATFORM_ID='wasadmin'
# Interval for request status polling.
DEFAULT_POLLING_INTERVAL= 3 * 1000 # milliseconds
# Time to wait for all requests to complete before exiting.
FINAL_WAIT_TIME= 30 # seconds
# Turn debug info ON/OFF here
debugFlag= 0
# Conditionally output debug messages
def debug(*args):
if debugFlag:
print >> sys.stderr, ' '.join(map(str,args))
outfile= sys.stderr
# Output log messages
def log(*args):
print >> outfile, ' '.join(map(str,args))
# Abstract the ITIM API interface
class Itimapi:
# organization types
ORG='org'
ORGUNIT='orgunit'
BPUNIT='bpunit'
LOC='loc'
# List of pending ITIM request objects
requests= []
pollingInterval= DEFAULT_POLLING_INTERVAL
""" Polling interval in seconds for checking request status"""
# Set up and connect to ITIM
def __init__(self, platformID, platformPW, itimID, itimPW):
self.setupIbmCorbaProperties(platformID, platformPW)
# Get some configuration parameters that were loaded from enRole.properties
contextFactory= java.lang.System.getProperty("enrole.platform.contextFactory")
platformURL= java.lang.System.getProperty("enrole.appServer.url")
platformRealm= java.lang.System.getProperty("enrole.appServer.realm")
debug('platformURL=', platformURL)
self.tenant= java.lang.System.getProperty("enrole.defaulttenant.id")
self.tenantDN = "ou=%s,dc=itim" % self.tenant
env= Hashtable()
env.put(InitialPlatformContext.CONTEXT_FACTORY, contextFactory)
env.put(PlatformContext.PLATFORM_URL, platformURL)
env.put(PlatformContext.PLATFORM_PRINCIPAL, platformID)
env.put(PlatformContext.PLATFORM_CREDENTIALS, platformPW)
env.put(PlatformContext.PLATFORM_REALM, platformRealm)
debug(env.toString())
debug(java.lang.System.getProperty("com.ibm.CORBA.loginSource"))
debug(java.lang.System.getProperty("com.ibm.CORBA.loginUserid"))
debug(java.lang.System.getProperty("com.ibm.CORBA.loginPassword"))
self.platform= InitialPlatformContext(env)
callbackHandler= WSCallbackHandlerImpl(itimID, platformRealm, itimPW)
loginContext= LoginContext("WSLogin", callbackHandler)
loginContext.login()
self.subject= loginContext.getSubject()
# Some additional properties to allow access to ITIM platform
def setupIbmCorbaProperties(self, platformID, platformPW):
java.lang.System.setProperty("com.ibm.CORBA.loginSource", "properties")
java.lang.System.setProperty("com.ibm.CORBA.loginUserid", platformID)
java.lang.System.setProperty("com.ibm.CORBA.loginPassword", platformPW)
def getPlatformContext(self):
return self.platform
def getSubject(self):
return self.subject
# Get ITIM AccountManager object
def getAccountManager(self):
return AccountManager(self.platform, self.subject)
# Get ITIM PersonManager object
def getPersonManager(self):
return PersonManager(self.platform, self.subject)
def accountsForPerson(self, personMO):
"""Get list of Account objects for a person."""
acctMgr= AccountManager(self.platform, self.subject)
return acctMgr.getAccounts(personMO, Locale.US)
def findObjects(self, ldapFilter, objectType, constructor):
"""Returns a list of managed objects"""
searchMO= SearchMO(self.platform, self.subject)
searchMO.setContext(CompoundDN(DistinguishedName(self.tenant)))
searchMO.setCategory(objectType)
searchMO.setFilter(ldapFilter)
searchMO.setPaging(0)
searchResults= searchMO.execute()
objectList= searchResults.getResults()
searchResults.close()
moList= []
for mObject in objectList:
moList.append(constructor(self.platform, self.subject, mObject.getDistinguishedName()))
return moList
def findPersons(self, ldapFilter):
"""Find persons based on LDAP filter. Returns list of PersonMO objects"""
return self.findObjects(ldapFilter, ObjectProfileCategory.PERSON, PersonMO)
def findServices(self, ldapFilter):
"""Find services based on LDAP filter. Returns list of ServiceMO objects"""
return self.findObjects(ldapFilter, ObjectProfileCategory.SERVICE, ServiceMO)
def findAccounts(self, ldapFilter):
"""Find services based on LDAP filter. Returns list of ServiceMO objects"""
return self.findObjects(ldapFilter, ObjectProfileCategory.ACCOUNT, AccountMO)
def findSystemUsers(self, ldapFilter):
"""Returns list of ITIM accounts (systemuser objects) based on LDAP filter."""
return self.findObjects(ldapFilter, ObjectProfileCategory.SYSTEM_USER, SystemUserMO)
def findProvisioningPolices(self, ldapFilter):
"""Returns list of ProvisioningPolicyMO objects based on LDAP filter."""
return self.findObjects(ldapFilter, ObjectProfileCategory.PROVISIONING_POLICY, ProvisioningPolicyMO)
def findOrgsByName(self, ldapFilter):
"""Returns list of OrganizationalContainerMO objects based on LDAP filter."""
return self.findObjects(ldapFilter, ObjectProfileCategory.CONTAINER, OrganizationalContainerMO)
# TODO Finish this
def findOrgsByName(self, name):
ldapFilter='(|(ou=%s)(o=%s)(l=%s))' % (name, name, name)
# ldapFilter='(ou=%s)' % name
print 'ldapfilter=', ldapFilter
return self.findObjects(ldapFilter, ObjectProfileCategory.CONTAINER, OrganizationalContainerMO)
def close(self):
"""Close the ITIM API connection."""
self.platform.close()
# Map status values to user text.
COMPLETE_STATUS= {Request.SUCCEEDED:'succ', Request.FAILED:'fail', Request.WARNING:'warn'}
def __checkRequests(self):
toRemove= []
for i in self.requests:
request, description = i
status= request.status
if status in self.COMPLETE_STATUS.keys():
log('Result:',self.COMPLETE_STATUS[status],description)
toRemove.append(i)
for i in toRemove:
self.requests.remove(i)
return (0 == len(self.requests))
def requestsComplete(self, waitSeconds=0):
""" Check remaining outstanding ITIM requests to see if they are complete. Returns True if all requests
are complete. Will wait up to waitSeconds (+ pollingInterval) for all requests to complete.
"""
status= self.__checkRequests()
if waitSeconds == 0:
return status
endTime = System.currentTimeMillis() + 1000 * waitSeconds
while not status and (System.currentTimeMillis() < endTime):
Thread.sleep(self.pollingInterval)
status= self.__checkRequests()
return status
def submitRequest(self, description, operation, *args):
""" Add a submitted request to be monitored until completion."""
try:
request = operation(*args)
if request == None:
raise Exception('ITIM request returned null')
self.requests.append((request, time.strftime('%H:%M:%S') +' '+ description))
except java.lang.Exception, e:
log('Error submitting request:',description,'exception=', e)
except Exception, e:
log('Error submitting request:',description,'errno=', e.errno, 'strerror=', e.strerror)
def submitOperation(self, description, operation, *args):
""" Submit a synchronous ITIM operation."""
try:
operation(*args)
except java.lang.Exception, e:
log('Error submitting operation:',description,'exception=', e)
except Exception, e:
log('Error submitting operation:',description,'errno=', e.errno, 'strerror=', e.strerror)
# We get options from the environment rather than directly from the command line since the wsadmin jython is
# so old and limited that it can't do non-echoed input of passwords. Program option and argument validation is done
# using a wrapper script.
def getOptions():
options= {}
envKeys= os.environ.keys()
options['userid']= os.environ['USER_ID']
options['userpw']= os.environ['USER_PW']
options['platformpw']= os.environ['PLATFORM_PW']
if 'COMMAND_FILE' in envKeys:
options['cmdfile']= os.environ['COMMAND_FILE']
if 'OUTPUT_FILE' in envKeys:
options['outfile']= os.environ['OUTPUT_FILE']
options['dryrun']= ('DRY_RUN' in envKeys) and (os.environ['DRY_RUN'] == 'Y')
return options
# ITIM API handle
api= None
# output file handle
outfile= sys.stdout
# Wrap the itimapi function to allow skipping for dry runs.
def submitRequest(itimapi, description, operation, *args):
debug('submitting request')
if options['dryrun']:
log('Not submitting request:', description)
else:
itimapi.submitRequest(description, operation, *args)
# Wrap the itimapi function to allow skipping for dry runs.
def submitOperation(itimapi, description, operation, *args):
debug('submitting request')
if options['dryrun']:
log('Not submitting request:', description)
else:
itimapi.submitOperation(description, operation, *args)
# Replace attribute values for a DirectoryObject
def dirObjectAttrRep(obj, attrDict):
debug('dirObectAttrRep: Enter')
for attrname in attrDict.keys():
attrtype= type(attrDict[attrname])
if attrtype == type([]) or attrtype == type(()):
vals= ArrayList()
for v in attrDict[attrname]:
vals.add(v)
obj.setAttribute(AttributeValue(attrname, vals))
else:
obj.setAttribute(AttributeValue(attrname, str(attrDict[attrname])))
# Add attribute values to a DirectoryObject without overwriting existing attribute values.
def dirObjectAttrAdd(obj, attrDict):
debug('dirObectAttrAdd: Enter')
for attrname in attrDict.keys():
vals= ArrayList()
attrtype= type(attrDict[attrname])
if attrtype == type([]) or attrtype == type(()):
for v in attrDict[attrname]:
vals.add(v)
else:
vals.add(str(attrDict[attrname]))
av= obj.getAttribute(attrname)
if not av:
av= AttributeValue()
av.setName(attrname)
debug('AttrAdd- '+ attrname +' Before: '+ str(av.getValues()))
av.addValues(vals)
obj.setAttribute(av)
debug('AttrAdd- '+ attrname +' After: '+ str(av.getValues()))
# Delete attribute values from a DirectoryObject
def dirObjectAttrDel(obj, attrs):
debug('dirObjectAttrDel: Enter')
if type({}) != type(attrs): # remove all values
for attrname in attrs:
obj.removeAttribute(attrname)
else: # removed selected values
for attrname in attrs.keys():
attrtype= type(attrs[attrname])
if attrtype == type([]) or attrtype == type(()):
toBeRemoved= attrs[attrname]
else:
toBeRemoved= [str(attrs[attrname])]
newVals= ArrayList()
av= obj.getAttribute(attrname)
if not av: # no values in object
return
existingValues=av.getValues()
for attrVal in existingValues:
if not attrVal in toBeRemoved:
newVals.add(attrVal)
obj.setAttribute(AttributeValue(attrname, newVals))
# Attribute operation name to function mapping
attrOp= {
'Add': dirObjectAttrAdd,
'Del': dirObjectAttrDel,
'Rep': dirObjectAttrRep,
'add': dirObjectAttrAdd,
'del': dirObjectAttrDel,
'rep': dirObjectAttrRep,
}
# Extract specified attribute values for selected identities in the same format used for input.
def cmdPersonExtract(ldapfilter, attrlist):
log('cmdPersonExtract("'+ ldapfilter +'",'+ str(attrlist) +')')
for personMO in api.findPersons(ldapfilter):
person= personMO.getData()
uid= person.getAttribute('uid').getString()
outfile.write('personAttrRep~(uid='+ uid +')~{')
for attrname in attrlist:
attrval= person.getAttribute(attrname)
if not attrval:
continue
outfile.write("'"+ attrname +"':(")
for val in attrval.getValues():
outfile.write("'"+ val +"',")
outfile.write('),')
outfile.write('}\n')
# Perform requested operation on the specified attributes for the specified accounts
def cmdAccountAttr(ldapfilter, attrs):
log('cmd: accountAttr("%s",%s)' % (ldapfilter, str(attrs)))
for accountMO in api.findAccounts(ldapfilter):
account= accountMO.getData()
for op in attrs.keys():
attrOp[op](account, attrs[op])
name = account.getAttribute('erglobalid').getString()
submitRequest(api,'accountAttr globalid='+ name +' '+ str(attrs),
accountMO.update, account, None)
# Perform a restore operation on the specified accounts
def cmdAccountRestore(ldapfilter):
log('cmd: accountRestore("%s")' % (ldapfilter))
for accountMO in api.findAccounts(ldapfilter):
account= accountMO.getData()
name = account.getAttribute('erglobalid').getString()
password = "WFbR_OdzY=p98X=ZCM7r" # This should be ignored due to PW sync
submitRequest(api,'accountRestore globalid='+ name,
accountMO.restore, password, None)
# Perform requested operation on the specified attributes for the specified persons
def cmdPersonAttr(ldapfilter, attrs):
log('cmd: personAttr("%s",%s)' % (ldapfilter, str(attrs)))
for personMO in api.findPersons(ldapfilter):
person= personMO.getData()
for op in attrs.keys():
attrOp[op](person, attrs[op])
name= person.getAttribute('uid').getString()
name += '-'+ person.getAttribute('erglobalid').getString()
submitRequest(api,'personAttr name-globalid='+ name +' '+ str(attrs),
personMO.update, person, None)
# Perform requested operation on the specified attributes for the specified services
def cmdServiceAttr(ldapfilter, attrs):
log('cmd: serviceAttr("%s",%s)' % (ldapfilter, str(attrs)))
svcs= api.findServices(ldapfilter)
if len(svcs) == 0:
log('No services found for filter ',ldapfilter)
for serviceMO in svcs:
service= serviceMO.getData()
for op in attrs.keys():
attrOp[op](service, attrs[op])
name= service.getAttribute('erservicename').getString()
name += '-'+service.getAttribute('erglobalid').getString()
submitOperation(api,'serviceAttr name-globalid='+ name +' '+ str(attrs),
serviceMO.update, service)
# Perform requested operation on the specified attributes for the specified system user
# TODO There is no update method for SystemUserMO. Figure out how to best handle updates
# to SystemUser objects.
def cmdSystemUserAttr(ldapfilter, attrs):
log('cmd: systemuserAttr("%s",%s)' % (ldapfilter, str(attrs)))
for systemuserMO in api.findSystemUsers(ldapfilter):
systemuser= systemuserMO.getData()
for op in attrs.keys():
attrOp[op](systemuser, attrs[op])
name= systemuser.getAttribute('eruid').getString()
name += '-'+ systemuser.getAttribute('erglobalid').getString()
submitRequest(api,'systemuserAttr name-globalid='+ name +' '+ str(attrs),
systemuserMO.update, systemuser, None)
# Perform requested operation on the specified attributes for the specified persons
# DEPRECATED Use cmdPersonAttr
def cmdPersonAttrOp(op, ldapfilter, attrs):
log('cmd: personAttr%s("%s",%s)' % (op, ldapfilter, str(attrs)))
for personMO in api.findPersons(ldapfilter):
person= personMO.getData()
attrOp[op](person, attrs)
name = person.getAttribute('erglobalid').getString()
submitRequest(api,'personAttr'+ op +' globalid='+ name +' '+ str(attrs),
personMO.update, person, None)
# Restore selected identities and all of their accounts
def cmdPersonRestore(ldapfilter):
log('cmd: personRestore("'+ ldapfilter +'")')
acctMgr= api.getAccountManager()
for personMO in api.findPersons(ldapfilter):
uid= personMO.getData().getAttribute('uid').getString()
submitRequest(api, 'personRestore uid='+ uid, personMO.restore, None)
acctMOs= api.accountsForPerson(personMO)
accts= ArrayList()
for i in acctMOs:
accts.add(i.getData())
submitRequest(api, 'personAccountsRestore uid='+ uid, acctMgr.restore, accts, None)
# Suspend selected identities.
def cmdPersonSuspend(ldapfilter):
log('cmd: personSuspend("'+ ldapfilter +'")')
for personMO in api.findPersons(ldapfilter):
uid= personMO.getData().getAttribute('uid').getString()
submitRequest(api,'personSuspend uid='+ uid, personMO.suspend, None)
# Create a new identity
def cmdPersonCreate(organizationName, profileName, attrDict):
log('cmd: personCreate("'+ organizationName +'","'+ profileName +'",'+ str(attrDict) +')')
person= Person(profileName)
for attrname in attrDict.keys():
vals= ArrayList()
attrtype= type(attrDict[attrname])
if attrtype == type([]) or attrtype == type(()): # multi-valued attribute
for v in attrDict[attrname]:
vals.add(v)
else:
vals.add(str(attrDict[attrname]))
av= AttributeValue()
av.setName(attrname)
av.addValues(vals)
person.setAttribute(av)
containerMO= api.findOrgsByName(organizationName)
pMgr= api.getPersonManager()
submitRequest(api, 'personCreate:'+ str(attrDict), pMgr.createPerson, containerMO[0], person, None)
# Test command for developer use only.
def cmdTest(orgName):
policies= api.findProvisioningPolices('(erpolicyitemname=TAM)')
print policies
print policies[0]
print policies[0].getData()
print policies[0].getData().getDescription()
print policies[0].getData().getEntitlements()
print policies[0].getData().getEntitlements()[0].getType()
print policies[0].getData().getEntitlements()[0].getTarget()
print policies[0].getData().getEntitlements()[0].getProvisioningParameters()
# Wait for requests to complete
def cmdWaitForRequests(timeout):
log('cmd: waitForRequests('+ timeout +')')
if options['dryrun']:
return
if api.requestsComplete(int(timeout)):
log('Result: waitForRequests: Request processing completed.')
else:
log('Result: waitForRequests: Some requests have not completed.')
# Wait a specified amount of time
def cmdWait(timeout):
log('cmd: wait('+ timeout +')')
if options['dryrun']:
return
time.sleep(int(timeout))
# Map command names to number of args and function. The argStyle option is to allow different
# styles of arg evaluation prior to calling the command function.
CMD={
#command Name: (argStyle, numArgs, functionName)
'accountAttr': (2,2,cmdAccountAttr),
'accountRestore': (1,1,cmdAccountRestore),
'personAttr': (2,2,cmdPersonAttr),
'serviceAttr': (2,2,cmdServiceAttr),
# 'systemuserAttr': (2,2,cmdSystemUserAttr),
'personExtract': (2,2,cmdPersonExtract),
'personRestore': (1,1,cmdPersonRestore),
'personSuspend': (1,1,cmdPersonSuspend),
'personCreate': (3,3,cmdPersonCreate),
'test': (1,1,cmdTest),
'wait': (1,1,cmdWait),
'waitForRequests': (1,1,cmdWaitForRequests),
}
# Map attribute command names to operation and function name.
# These are the "old" style attribute commands. They are being included
# since the syntax was included in the design brief.
#ATTRCMD={
# #command Name: (op, functionName)
# 'personAttrAdd': ('Add',cmdPersonAttrOp),
# 'personAttrDel': ('Del',cmdPersonAttrOp),
# 'personAttrRep': ('Rep',cmdPersonAttrOp),
#}
# Main command processing loop. Read commands from input file and process them.
# There is special handling for attribute commands.
def processCommands(cmdfile):
linenum= 0
for cmdline in cmdfile.readlines():
linenum += 1
cmdline= cmdline.strip()
if len(cmdline) == 0: # skip empty lines
continue
if cmdline[0] == '#': # skip comment lines
continue
fields= cmdline.split('~')
cmd= fields[0]
# special processing for attribute commands
# if cmd in ATTRCMD.keys():
# op, cmdFn= ATTRCMD[cmd]
# cmdFn(op, fields[1], eval(fields[2]))
# continue
if not cmd in CMD.keys():
raise NameError('Unknown command: '+ cmd +' at line '+ str(linenum))
argStyle, numArgs, cmdFn = CMD[cmd]
if numArgs < len(fields) - 1:
raise TypeError('Missing args for command: '+ cmd +' at line '+ linenum)
if argStyle == 0:
cmdFn()
elif argStyle == 1:
cmdFn(fields[1])
elif argStyle == 2:
cmdFn(fields[1],eval(fields[2]))
elif argStyle == 3:
cmdFn(fields[1], fields[2], eval(fields[3]))
elif argStyle == 4:
cmdFn(fields[1], eval(fields[2]), eval(fields[3]))
debug('Command processing completed:')
#### Main Program #####
options= getOptions()
infile= sys.stdin
if 'cmdfile' in options.keys():
infile= open(options['cmdfile'],'r')
outfile= sys.stderr
if 'outfile' in options.keys():
debug('Writing to '+ options['outfile'])
outfile= open(options['outfile'],'w')
api= Itimapi(PLATFORM_ID, options['platformpw'], options['userid'], options['userpw'])
try:
processCommands(infile)
if api.requestsComplete(FINAL_WAIT_TIME):
log('Request processing completed.')
else:
log('Some requests have not completed. View the request status in the ITIM console')
except KeyboardInterrupt: # Exit nicely on Ctrl-C
pass
api.close()
outfile.close()
|
python
|
import random
from careers.career_enums import GigResult
from careers.career_gig import Gig, TELEMETRY_GIG_PROGRESS_TIMEOUT, TELEMETRY_GIG_PROGRESS_COMPLETE
from sims4.localization import TunableLocalizedStringFactory
from sims4.tuning.instances import lock_instance_tunables
from sims4.tuning.tunable import TunableReference, OptionalTunable, TunablePercent, TunableTuple
from tunable_time import TunableTimeSpan
import services
import sims4
logger = sims4.log.Logger('HomeAssignmentGig', default_owner='rrodgers')
class HomeAssignmentGig(Gig):
INSTANCE_TUNABLES = {'gig_picker_localization_format': TunableLocalizedStringFactory(description='\n String used to format the description in the gig picker. Currently\n has tokens for name, payout, gig time, tip title, and tip text.\n '), 'gig_assignment_aspiration': TunableReference(description='\n An aspiration to use as the assignment for this gig. The objectives\n of this aspiration\n ', manager=services.get_instance_manager(sims4.resources.Types.ASPIRATION), class_restrictions='AspirationGig'), 'bonus_gig_aspiration_tuning': OptionalTunable(description='\n Tuning for the bonus gig aspiration. This is optional, but if the\n aspiration is completed, it results in a chance for a better\n outcome.\n ', tunable=TunableTuple(bonus_gig_aspiration=TunableReference(description="\n The bonus aspiration to use as part of this gig's \n assignments.\n ", manager=services.get_instance_manager(sims4.resources.Types.ASPIRATION), class_restrictions='Aspiration'), great_success_chance=TunablePercent(description='\n Chance of a SUCCESS outcome being upgraded to \n GREAT_SUCCESS.\n ', default=0.0))), 'great_success_remaining_time': OptionalTunable(description='\n If the aspiration for this gig is completed with more than this\n amount of time left, the gig will be considered a great success.\n ', tunable=TunableTimeSpan())}
@classmethod
def get_aspiration(cls):
return cls.gig_assignment_aspiration
def register_aspiration_callbacks(self):
super().register_aspiration_callbacks()
if self.bonus_gig_aspiration_tuning is None:
return
bonus_aspiration = self.bonus_gig_aspiration_tuning.bonus_gig_aspiration
if not bonus_aspiration:
return
bonus_aspiration.register_callbacks()
aspiration_tracker = self._owner.aspiration_tracker
if aspiration_tracker is not None:
aspiration_tracker.validate_and_return_completed_status(bonus_aspiration)
aspiration_tracker.process_test_events_for_aspiration(bonus_aspiration)
def set_up_gig(self):
super().set_up_gig()
aspiration_tracker = self._owner.aspiration_tracker
aspiration_tracker.reset_milestone(self.gig_assignment_aspiration)
self.gig_assignment_aspiration.register_callbacks()
aspiration_tracker.process_test_events_for_aspiration(self.gig_assignment_aspiration)
if self.bonus_gig_aspiration_tuning is not None and self.bonus_gig_aspiration_tuning.bonus_gig_aspiration is not None:
aspiration_tracker.reset_milestone(self.bonus_gig_aspiration_tuning.bonus_gig_aspiration)
self.bonus_gig_aspiration_tuning.bonus_gig_aspiration.register_callbacks()
aspiration_tracker.process_test_events_for_aspiration(self.bonus_gig_aspiration_tuning.bonus_gig_aspiration)
def _determine_gig_outcome(self):
completed_objectives = 0
aspiration_tracker = self._owner.aspiration_tracker
if aspiration_tracker is not None:
for objective in self.gig_assignment_aspiration.objectives:
if aspiration_tracker.objective_completed(objective):
completed_objectives += 1
completed_bonus_objectives = 0
if self.bonus_gig_aspiration_tuning is not None:
if self.bonus_gig_aspiration_tuning.bonus_gig_aspiration is not None:
for objective in self.bonus_gig_aspiration_tuning.bonus_gig_aspiration.objectives:
if aspiration_tracker.objective_completed(objective):
completed_bonus_objectives += 1
else:
completed_objectives = len(self.gig_assignment_aspiration.objectives)
completed_bonus_objectives = 0
remaining_time = self._upcoming_gig_time - services.time_service().sim_now
if completed_objectives < len(self.gig_assignment_aspiration.objectives):
if completed_objectives == 0:
self._gig_result = GigResult.CRITICAL_FAILURE
elif self.critical_failure_test is not None:
resolver = self.get_resolver_for_gig()
if self.critical_failure_test.run_tests(resolver=resolver):
self._gig_result = GigResult.CRITICAL_FAILURE
else:
self._gig_result = GigResult.FAILURE
else:
self._gig_result = GigResult.FAILURE
self._send_gig_telemetry(TELEMETRY_GIG_PROGRESS_TIMEOUT)
elif self.great_success_remaining_time and remaining_time > self.great_success_remaining_time():
self._gig_result = GigResult.GREAT_SUCCESS
self._send_gig_telemetry(TELEMETRY_GIG_PROGRESS_COMPLETE)
elif completed_bonus_objectives > 0:
self._send_gig_telemetry(TELEMETRY_GIG_PROGRESS_COMPLETE)
if self.bonus_gig_aspiration_tuning and self.bonus_gig_aspiration_tuning.great_success_chance and random.random() <= self.bonus_gig_aspiration_tuning.great_success_chance:
self._gig_result = GigResult.GREAT_SUCCESS
else:
self._gig_result = GigResult.SUCCESS
else:
self._gig_result = GigResult.SUCCESS
self._send_gig_telemetry(TELEMETRY_GIG_PROGRESS_COMPLETE)
def get_overmax_evaluation_result(self, reward_text, overmax_level, *args, **kwargs):
return super().get_overmax_evaluation_result(reward_text, overmax_level, *args, **kwargs)
def send_prep_task_update(self):
pass
@classmethod
def build_gig_msg(cls, msg, sim, **kwargs):
super().build_gig_msg(msg, sim, **kwargs)
msg.aspiration_id = cls.gig_assignment_aspiration.guid64
def treat_work_time_as_due_date(self):
return True
lock_instance_tunables(HomeAssignmentGig, gig_prep_tasks=None, audio_on_prep_task_completion=None, career_events=None, gig_cast_rel_bit_collection_id=None, gig_cast=None, end_of_gig_dialog=None, payout_stat_data=None)
|
python
|
"""Plugwise Switch component for HomeAssistant."""
from __future__ import annotations
from typing import Any
from plugwise.exceptions import PlugwiseException
from homeassistant.components.switch import SwitchEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .const import DOMAIN, LOGGER, SWITCH_ICON
from .coordinator import PlugwiseDataUpdateCoordinator
from .entity import PlugwiseEntity
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the Smile switches from a config entry."""
coordinator = hass.data[DOMAIN][config_entry.entry_id]
async_add_entities(
PlugwiseSwitchEntity(coordinator, device_id)
for device_id, device in coordinator.data.devices.items()
if "switches" in device and "relay" in device["switches"]
)
class PlugwiseSwitchEntity(PlugwiseEntity, SwitchEntity):
"""Representation of a Plugwise plug."""
_attr_icon = SWITCH_ICON
def __init__(
self,
coordinator: PlugwiseDataUpdateCoordinator,
device_id: str,
) -> None:
"""Set up the Plugwise API."""
super().__init__(coordinator, device_id)
self._attr_unique_id = f"{device_id}-plug"
self._members = coordinator.data.devices[device_id].get("members")
self._attr_is_on = False
self._attr_name = coordinator.data.devices[device_id].get("name")
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the device on."""
try:
state_on = await self.coordinator.api.set_switch_state(
self._dev_id, self._members, "relay", "on"
)
except PlugwiseException:
LOGGER.error("Error while communicating to device")
else:
if state_on:
self._attr_is_on = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the device off."""
try:
state_off = await self.coordinator.api.set_switch_state(
self._dev_id, self._members, "relay", "off"
)
except PlugwiseException:
LOGGER.error("Error while communicating to device")
else:
if state_off:
self._attr_is_on = False
self.async_write_ha_state()
@callback
def _handle_coordinator_update(self) -> None:
"""Handle updated data from the coordinator."""
if not (data := self.coordinator.data.devices.get(self._dev_id)):
LOGGER.error("Received no data for device %s", self._dev_id)
super()._handle_coordinator_update()
return
self._attr_is_on = data["switches"].get("relay")
super()._handle_coordinator_update()
|
python
|
# Copyright (c) 2020 Simons Observatory.
# Full license can be found in the top level "LICENSE" file.
import numpy as np
from toast.timing import function_timer, Timer
from toast.utils import Logger
from ..sim_hwpss import OpSimHWPSS
def add_sim_hwpss_args(parser):
parser.add_argument(
"--hwpss-file",
required=False,
help="Database of HWPSS by frequency and incident angle",
)
parser.add_argument(
"--simulate-hwpss",
required=False,
action="store_true",
help="Simulate HWPSS",
dest="simulate_hwpss",
)
parser.add_argument(
"--no-simulate-hwpss",
required=False,
action="store_false",
help="Do not simulate HWPSS",
dest="simulate_hwpss",
)
parser.set_defaults(simulate_hwpss=False)
return
def simulate_hwpss(args, comm, data, mc, name):
if not args.simulate_hwpss:
return
log = Logger.get()
timer = Timer()
timer.start()
hwpssop = OpSimHWPSS(name=name, fname_hwpss=args.hwpss_file, mc=mc)
hwpssop.exec(data)
timer.report_clear("Simulate HWPSS")
return
|
python
|
import pandas as pd
import numpy as np
from pyam import utils
def test_pattern_match_none():
data = pd.Series(['foo', 'bar'])
values = ['baz']
obs = utils.pattern_match(data, values)
exp = [False, False]
assert (obs == exp).all()
def test_pattern_match_nan():
data = pd.Series(['foo', np.nan])
values = ['baz']
obs = utils.pattern_match(data, values)
exp = [False, False]
assert (obs == exp).all()
def test_pattern_match_one():
data = pd.Series(['foo', 'bar'])
values = ['foo']
obs = utils.pattern_match(data, values)
exp = [True, False]
assert (obs == exp).all()
def test_pattern_match_str_regex():
data = pd.Series(['foo', 'foo2', 'bar'])
values = ['foo']
obs = utils.pattern_match(data, values)
exp = [True, False, False]
assert (obs == exp).all()
def test_pattern_match_ast_regex():
data = pd.Series(['foo', 'foo2', 'bar'])
values = ['foo*']
obs = utils.pattern_match(data, values)
exp = [True, True, False]
assert (obs == exp).all()
def test_pattern_match_plus():
data = pd.Series(['foo', 'foo+', '+bar', 'b+az'])
values = ['*+*']
obs = utils.pattern_match(data, values)
exp = [False, True, True, True]
assert (obs == exp).all()
def test_pattern_match_dot():
data = pd.Series(['foo', 'fo.'])
values = ['fo.']
obs = utils.pattern_match(data, values)
exp = [False, True]
assert (obs == exp).all()
def test_pattern_match_brackets():
data = pd.Series(['foo (bar)', 'foo bar'])
values = ['foo (bar)']
obs = utils.pattern_match(data, values)
exp = [True, False]
assert (obs == exp).all()
def test_pattern_match_dollar():
data = pd.Series(['foo$bar', 'foo'])
values = ['foo$bar']
obs = utils.pattern_match(data, values)
exp = [True, False]
assert (obs == exp).all()
def test_pattern_regexp():
data = pd.Series(['foo', 'foa', 'foo$'])
values = ['fo.$']
obs = utils.pattern_match(data, values, regexp=True)
exp = [True, True, False]
assert (obs == exp).all()
|
python
|
from __future__ import absolute_import, division, print_function
from appr.models.kv.channel_kv_base import ChannelKvBase
from appr.models.kv.etcd.models_index import ModelsIndexEtcd
class Channel(ChannelKvBase):
index_class = ModelsIndexEtcd
|
python
|
# coding: utf-8
"""
RLSData.py
The Clear BSD License
Copyright (c) – 2016, NetApp, Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of NetApp, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
from pprint import pformat
from six import iteritems
class RLSData(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
"""
RLSData - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'device': 'RLSDevice', # (required parameter)
'channel': 'int', # (required parameter)
'loop_map_index': 'int', # (required parameter)
'rls_count': 'RLSCount', # (required parameter)
'baseline_time': 'int', # (required parameter)
'valid': 'bool'
}
self.attribute_map = {
'device': 'device', # (required parameter)
'channel': 'channel', # (required parameter)
'loop_map_index': 'loopMapIndex', # (required parameter)
'rls_count': 'rlsCount', # (required parameter)
'baseline_time': 'baselineTime', # (required parameter)
'valid': 'valid'
}
self._device = None
self._channel = None
self._loop_map_index = None
self._rls_count = None
self._baseline_time = None
self._valid = None
@property
def device(self):
"""
Gets the device of this RLSData.
The SYMbol reference value that uniquely identifies this device.
:return: The device of this RLSData.
:rtype: RLSDevice
:required/optional: required
"""
return self._device
@device.setter
def device(self, device):
"""
Sets the device of this RLSData.
The SYMbol reference value that uniquely identifies this device.
:param device: The device of this RLSData.
:type: RLSDevice
"""
self._device = device
@property
def channel(self):
"""
Gets the channel of this RLSData.
The channel the device is on.
:return: The channel of this RLSData.
:rtype: int
:required/optional: required
"""
return self._channel
@channel.setter
def channel(self, channel):
"""
Sets the channel of this RLSData.
The channel the device is on.
:param channel: The channel of this RLSData.
:type: int
"""
self._channel = channel
@property
def loop_map_index(self):
"""
Gets the loop_map_index of this RLSData.
The position in the fibre loop map the device is located at.
:return: The loop_map_index of this RLSData.
:rtype: int
:required/optional: required
"""
return self._loop_map_index
@loop_map_index.setter
def loop_map_index(self, loop_map_index):
"""
Sets the loop_map_index of this RLSData.
The position in the fibre loop map the device is located at.
:param loop_map_index: The loop_map_index of this RLSData.
:type: int
"""
self._loop_map_index = loop_map_index
@property
def rls_count(self):
"""
Gets the rls_count of this RLSData.
The RLS count for this device.
:return: The rls_count of this RLSData.
:rtype: RLSCount
:required/optional: required
"""
return self._rls_count
@rls_count.setter
def rls_count(self, rls_count):
"""
Sets the rls_count of this RLSData.
The RLS count for this device.
:param rls_count: The rls_count of this RLSData.
:type: RLSCount
"""
self._rls_count = rls_count
@property
def baseline_time(self):
"""
Gets the baseline_time of this RLSData.
The baseline time for this device, expressed as seconds since midnight GMT on January 1, 1970.
:return: The baseline_time of this RLSData.
:rtype: int
:required/optional: required
"""
return self._baseline_time
@baseline_time.setter
def baseline_time(self, baseline_time):
"""
Sets the baseline_time of this RLSData.
The baseline time for this device, expressed as seconds since midnight GMT on January 1, 1970.
:param baseline_time: The baseline_time of this RLSData.
:type: int
"""
self._baseline_time = baseline_time
@property
def valid(self):
"""
Gets the valid of this RLSData.
Set to true if the RSL Data is valid for the device.
:return: The valid of this RLSData.
:rtype: bool
:required/optional: required
"""
return self._valid
@valid.setter
def valid(self, valid):
"""
Sets the valid of this RLSData.
Set to true if the RSL Data is valid for the device.
:param valid: The valid of this RLSData.
:type: bool
"""
self._valid = valid
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
if self is None:
return None
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if self is None or other is None:
return None
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
|
python
|
# Generated by Django 3.1.2 on 2020-10-30 15:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pages', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='page',
options={'ordering': ['order', 'title'], 'verbose_name': 'página', 'verbose_name_plural': 'páginas'},
),
migrations.AddField(
model_name='page',
name='order',
field=models.SmallIntegerField(default=0, verbose_name='order'),
),
]
|
python
|
import csv
import cv2
import pandas as pd
import numpy as np
import os
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
import sklearn
import tensorflow as tf
import pickle
import keras
from sklearn.externals import joblib
from keras.models import Sequential
from keras.layers import Flatten, Dense, Lambda, Dropout, Cropping2D
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.optimizers import Adam
batch_size = 32
def generator2(samples, batch_size=batch_size):
num_samples = len(samples)
correction=0.4
while 1: # Loop forever so the generator never terminates
shuffle(samples)
for offset in range(0, num_samples, batch_size):
batch_samples = samples[offset:offset+batch_size]
images = []
angles = []
for batch_sample in batch_samples:
name = os.path.join(data_folder, "/".join(batch_sample[0].strip().split('/')[-2:]))
center_image = cv2.imread(name)
center_angle = float(batch_sample[3])
images.append(center_image)
angles.append(center_angle)
angles.append(-1.*center_angle)
images.append(cv2.flip(center_image, 1))
name_left = os.path.join(data_folder, "/".join(batch_sample[1].strip().split('/')[-2:]))
left_img = cv2.imread(name_left)
left_angle = center_angle+correction
images.append(left_img)
angles.append(left_angle)
angles.append(-1*left_angle)
images.append(cv2.flip(left_img, 1))
name_right = os.path.join(data_folder, "/".join(batch_sample[2].strip().split('/')[-2:]))
right_img = cv2.imread(name_right)
right_angle = center_angle-correction
images.append(right_img)
angles.append(right_angle)
angles.append(-1*right_angle)
images.append(cv2.flip(right_img, 1))
X_train = np.array(images)
y_train = np.array(angles)
yield sklearn.utils.shuffle(X_train, y_train)
data_folder = "P4Data"
samples = []
with open(os.path.join(data_folder, 'driving_log.csv')) as csvfile:
reader = csv.reader(csvfile)
for i, line in enumerate(reader):
samples.append(line)
train_samples, validation_samples = train_test_split(samples, test_size=0.2)
# compile and train the model using the generator function
train_generator = generator2(train_samples, batch_size=batch_size)
validation_generator = generator2(validation_samples, batch_size=batch_size)
drop_prob = 0.25
n_epochs = 20
class mycb(keras.callbacks.Callback):
def on_epoch_begin(self, epoch, logs=None):
lr = self.model.optimizer.lr
decay = self.model.optimizer.decay
iterations = self.model.optimizer.iterations
lr_with_decay = lr / (1. + decay * keras.backend.cast(iterations, keras.backend.dtype(decay)))
print(keras.backend.eval(lr_with_decay))
cb = mycb()
optimizer = keras.optimizers.Adam(lr=1e-3)
model = Sequential()
model.add(Lambda(lambda x: (x / 255.0) - 0.5, input_shape=(160,320,3)))
model.add(Cropping2D(cropping=((50,20), (0,0))))
model.add(Convolution2D(24,5, strides=(2,2), activation='relu'))
model.add(Convolution2D(36,5, strides=(2,2), activation='relu'))
model.add(Convolution2D(48,5, strides=(2,2), activation='relu'))
model.add(Convolution2D(64,3, activation='relu'))
model.add(Convolution2D(64,3, activation='relu'))
model.add(Flatten())
model.add(Dense(100, activation='relu'))
model.add(Dropout(rate=drop_prob))
model.add(Dense(50, activation='relu'))
model.add(Dropout(rate=drop_prob))
#model.add(keras.layers.LeakyReLU()) #
model.add(Dense(10, activation='relu'))
#model.add(Dropout(rate=drop_prob))
#model.add(keras.layers.LeakyReLU())
model.add(Dense(1))
model.compile(loss='mse', optimizer=optimizer)
train_stps_epoch = 3*2*len(train_samples)//batch_size #approx
val_stps_epoch = 3*2*len(validation_samples)//batch_size #approx
history = model.fit_generator(train_generator,
validation_data=validation_generator, epochs=n_epochs,
steps_per_epoch=train_stps_epoch, validation_steps=val_stps_epoch,
shuffle=True,
callbacks=[cb])
with open('trainHistoryDict', 'wb') as file_pi:
pickle.dump(history.history, file_pi)
model.save("model.h5")
|
python
|
"""Auto-generated file, do not edit by hand. SA metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_SA = PhoneMetadata(id='SA', country_code=966, international_prefix='00',
general_desc=PhoneNumberDesc(national_number_pattern='(?:[1-467]|92)\\d{7}|5\\d{8}|8\\d{9}', possible_number_pattern='\\d{7,10}'),
fixed_line=PhoneNumberDesc(national_number_pattern='(?:[12][24-8]|3[35-8]|4[3-68]|6[2-5]|7[235-7])\\d{6}', possible_number_pattern='\\d{7,8}', example_number='12345678'),
mobile=PhoneNumberDesc(national_number_pattern='(?:5[013-689]\\d|8111)\\d{6}', possible_number_pattern='\\d{9,10}', example_number='512345678'),
toll_free=PhoneNumberDesc(national_number_pattern='800\\d{7}', possible_number_pattern='\\d{10}', example_number='8001234567'),
premium_rate=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
shared_cost=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
personal_number=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
voip=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
pager=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
uan=PhoneNumberDesc(national_number_pattern='9200\\d{5}', possible_number_pattern='\\d{9}', example_number='920012345'),
emergency=PhoneNumberDesc(national_number_pattern='99[7-9]', possible_number_pattern='\\d{3}', example_number='999'),
voicemail=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
no_international_dialling=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
national_prefix='0',
national_prefix_for_parsing='0',
number_format=[NumberFormat(pattern='([1-467])(\\d{3})(\\d{4})', format=u'\\1 \\2 \\3', leading_digits_pattern=['[1-467]'], national_prefix_formatting_rule=u'0\\1'),
NumberFormat(pattern='(5\\d)(\\d{3})(\\d{4})', format=u'\\1 \\2 \\3', leading_digits_pattern=['5'], national_prefix_formatting_rule=u'0\\1'),
NumberFormat(pattern='(9200)(\\d{5})', format=u'\\1 \\2', leading_digits_pattern=['9'], national_prefix_formatting_rule=u'\\1'),
NumberFormat(pattern='(800)(\\d{3})(\\d{4})', format=u'\\1 \\2 \\3', leading_digits_pattern=['80'], national_prefix_formatting_rule=u'\\1'),
NumberFormat(pattern='(8111)(\\d{3})(\\d{3})', format=u'\\1 \\2 \\3', leading_digits_pattern=['81'], national_prefix_formatting_rule=u'0\\1')])
|
python
|
from rest_framework.viewsets import ModelViewSet
from exam.models import TblExamRecord as Model
from exam.serializers import RecordSerializer as Serializer
class RecordViewset(ModelViewSet):
queryset = Model.objects.all().order_by('-id')
serializer_class = Serializer
|
python
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class MybankCreditSupplychainCreditpayAmountQueryResponse(AlipayResponse):
def __init__(self):
super(MybankCreditSupplychainCreditpayAmountQueryResponse, self).__init__()
self._admit = None
self._available_amt = None
self._buyer_scene_id = None
self._signed = None
self._total_amt = None
self._trace_id = None
@property
def admit(self):
return self._admit
@admit.setter
def admit(self, value):
self._admit = value
@property
def available_amt(self):
return self._available_amt
@available_amt.setter
def available_amt(self, value):
self._available_amt = value
@property
def buyer_scene_id(self):
return self._buyer_scene_id
@buyer_scene_id.setter
def buyer_scene_id(self, value):
self._buyer_scene_id = value
@property
def signed(self):
return self._signed
@signed.setter
def signed(self, value):
self._signed = value
@property
def total_amt(self):
return self._total_amt
@total_amt.setter
def total_amt(self, value):
self._total_amt = value
@property
def trace_id(self):
return self._trace_id
@trace_id.setter
def trace_id(self, value):
self._trace_id = value
def parse_response_content(self, response_content):
response = super(MybankCreditSupplychainCreditpayAmountQueryResponse, self).parse_response_content(response_content)
if 'admit' in response:
self.admit = response['admit']
if 'available_amt' in response:
self.available_amt = response['available_amt']
if 'buyer_scene_id' in response:
self.buyer_scene_id = response['buyer_scene_id']
if 'signed' in response:
self.signed = response['signed']
if 'total_amt' in response:
self.total_amt = response['total_amt']
if 'trace_id' in response:
self.trace_id = response['trace_id']
|
python
|
import string
import numpy
import copy
from domrl.engine.agent import Agent
"""
class Agent(object):
def choose(self, decision, state):
return decision.moves[0]
class StdinAgent(Agent):
def choose(self, decision, state):
# Autoplay
if len(decision.moves) == 1:
return [0]
player = decision.player
print(f" ==== Decision to be made by {player} ==== ")
print(f"Actions: {player.actions} | Buys: {player.buys} | Coins: {player.coins}")
print("Hand: ", list(map(str, player.hand)))
print(decision.prompt)
for idx, move in enumerate(decision.moves):
print(f"{idx}: {move}")
# Get user input and process it.
while True:
user_input = input()
if user_input == "?":
state.event_log.print(player)
print(state)
else:
try:
ans = list(map(lambda x: int(x.strip()), user_input.split(',')))
except:
print('Clearly invalid input. Please try again.')
continue
break
return ans
class APIAgent(Agent):
def choose(self, decision, state):
# Autoplay
# if len(decision.moves) == 1:
# return [0]
player = decision.player
actions = player.actions
buys = player.buys
coins = player.coins
moves = decision.moves
hand = player.hand
state
while True:
user_input = input()
if user_input == "?":
state.event_log.print(player)
print(state)
else:
ans = list(map(lambda x: int(x.strip()), user_input.split(',')))
break
return ans
"""
class RandomAgent(Agent):
def policy(self, decision, state):
if 'Trash up to 4' in decision.prompt: # for chapel
my_list = []
range_max = numpy.random.randint(0, min(len(decision.moves), 4) + 1, 1, int)
for idx in range(0, range_max[0]):
new_item = -1
while new_item == -1 or new_item in my_list:
new_item = numpy.random.randint(0, len(decision.moves), 1, int)[0]
my_list.append(new_item)
return my_list
if len(decision.moves) == 0:
return []
if 'Discard down to 3 cards' in decision.prompt: # for militia
my_list = []
range_max = max(len(decision.player.hand) - 3, 0)
for idx in range(0, range_max):
new_item = -1
while new_item == -1 or new_item in my_list:
new_item = numpy.random.randint(0, len(decision.moves), 1, int)[0]
my_list.append(new_item)
return my_list
value = list(numpy.random.randint(0, len(decision.moves), 1, int))
return value
class PassOnBuySemiAgent(Agent):
def policy(self, decision, state):
if 'Buy' in decision.prompt:
return [0]
class CleverAgentOld(Agent):
def __init__(self, agent):
self.agent = agent
def policy(self, decision, state):
initialDecision = copy.deepcopy(decision)
# Automove If One Move
if len(decision.moves) == 1:
return [0]
for idx in range(0, len(initialDecision.moves)):
move = initialDecision.moves[idx]
if "Buy: Curse" in move.__str__():
decision.moves.pop(idx)
if hasattr(move, "card") and (
move.card.add_actions > 0 or ("treasure" in decision.prompt.lower() and move.card.coins > 0)):
return self.restrictDecision(decision.moves, initialDecision.moves, idx)
restrictedChoice = self.agent.policy(decision, state)
return self.restrictDecision(decision.moves, initialDecision.moves, restrictedChoice[0])
def restrictDecision(self, moves, initialMoves, chosen):
for idx in range(0, len(initialMoves)):
if str(initialMoves[idx]) == str(moves[chosen]):
return list([idx])
return [chosen]
class RulesSemiAgent(Agent):
def policy(self, decision, state):
# Automove If One Move
if len(decision.moves) == 1:
return [0]
for idx in range(0, len(decision.moves)):
try:
move = decision.moves[idx]
except:
break
if "Bandit" in str(move): # currently does not work
decision.moves.pop(idx)
if "Remodel" in str(move): # currently does not work
decision.moves.pop(idx)
class CleverSemiAgent(Agent):
def policy(self, decision, state):
# Automove If One Move
if len(decision.moves) == 1:
return [0]
for idx in range(0, len(decision.moves)):
try:
move = decision.moves[idx]
except:
break
if "Buy: Curse" in move.__str__():
decision.moves.pop(idx)
if hasattr(move, "card") and (
move.card.add_actions > 0 or ("treasure" in decision.prompt.lower() and move.card.coins > 0)):
return [idx]
class ApplySemiAgent(Agent):
def __init__(self, semiAgents, agent):
self.semiAgents = semiAgents
self.agent = agent
def policy(self, decision, state):
for semiAgent in self.semiAgents:
value = semiAgent.policy(decision, state)
if value is not None:
return value
return self.agent.policy(decision, state)
class BigMoneySemiAgent(Agent):
def policy(self, decision, state):
for stringDesired in ["Buy: Province", "Buy: Gold", "Buy: Silver"]:
for idx in range(0, len(decision.moves)):
try:
move = decision.moves[idx]
except:
break
if stringDesired in move.__str__():
return [idx]
class SmithySemiAgent(Agent):
def policy(self, decision, state):
for stringDesired in ["Play: Smithy"]:
for idx in range(0, len(decision.moves)):
try:
move = decision.moves[idx]
except:
break
if stringDesired in move.__str__():
return [idx]
for idx in range(0, len(decision.moves)):
try:
move = decision.moves[idx]
except:
break
if "Buy: Smithy" in move.__str__() and (
sum(1 for c in decision.player.all_cards if 'Smithy' in str(c)) / len(
decision.player.all_cards) < 0.1):
return [idx]
class DontBuyCopperOrEstateSemiAgent(Agent):
def policy(self, decision, state):
for idx in range(0, len(decision.moves)):
try:
move = decision.moves[idx]
except:
break
if 'Buy: Copper' in str(move) or 'Buy: Estate' in str(move):
decision.moves.pop(idx)
class MyHeuristicSemiAgent(Agent):
def policy(self, decision, state):
for stringDesired in []:
for idx in range(0, len(decision.moves)):
try:
move = decision.moves[idx]
except:
break
if stringDesired in move.__str__():
return [idx]
if 'Action' in decision.prompt:
for idx in range(0, len(decision.moves)):
try:
move = decision.moves[idx]
except:
break
if 'Militia' in str(move) or 'Smithy' in str(move):
return [idx]
if 'Buy' not in decision.prompt and 'Choose a pile to gain card from.' not in decision.prompt:
return
desired_deck = {'Festival': 1, 'Market': 1, 'Militia': 1, 'Smithy': 0.1, 'Village': 0.2}
if numpy.random.randint(0, 2, 1, int) == 1:
desired_deck = {'Market': 1, 'Festival': 1, 'Smithy': 0.1, 'Militia': 1, 'Village': 0.2}
for wish in desired_deck:
for idx in range(0, len(decision.moves)):
try:
move = decision.moves[idx]
except:
break
if wish in str(move) and (
sum(1 for c in decision.player.all_cards if wish in str(c)) / len(
decision.player.all_cards) < desired_deck[wish]):
return [idx]
class MarketSemiAgent(Agent):
def policy(self, decision, state):
if 'Action' in decision.prompt:
for stringDesired in ['Empty']:
for idx in range(0, len(decision.moves)):
try:
move = decision.moves[idx]
except:
break
if 'Militia' in str(move):
return [idx]
if 'Smithy' in str(move) and decision.player.actions > 1:
return [idx]
if stringDesired in str(move):
return [idx]
if 'Buy' not in decision.prompt and 'Choose a pile to gain card from.' not in decision.prompt:
return
desired_deck = {'Market': 1, 'Militia': 0.001, 'Smithy': 0.001, 'Village': 0.2}
for wish in desired_deck:
for idx in range(0, len(decision.moves)):
try:
move = decision.moves[idx]
except:
break
if wish in str(move):
if sum(1 for c in decision.player.all_cards if wish in str(c)) / len(
decision.player.all_cards) < desired_deck[wish]:
return [idx]
class CustomHeuristicsSemiAgent(Agent):
def __init__(self, desired_decks):
self.desired_deck = desired_decks
def policy(self, decision, state):
if 'Action' in decision.prompt:
for stringDesired in ['Empty']:
for idx in range(0, len(decision.moves)):
try:
move = decision.moves[idx]
except:
break
if 'Militia' in str(move):
return [idx]
if 'Smithy' in str(move) and decision.player.actions > 1:
return [idx]
if stringDesired in str(move):
return [idx]
if 'Buy' not in decision.prompt and 'Choose a pile to gain card from.' not in decision.prompt:
return
for wish in self.desired_deck:
for idx in range(0, len(decision.moves)):
try:
move = decision.moves[idx]
except:
break
if wish in str(move):
if sum(1 for c in decision.player.all_cards if wish in str(c)) / len(
decision.player.all_cards) < self.desired_deck[wish]:
return [idx]
class MarketNoSmithySemiAgent(Agent):
def policy(self, decision, state):
if 'Action' in decision.prompt:
for stringDesired in ['Empty']:
for idx in range(0, len(decision.moves)):
try:
move = decision.moves[idx]
except:
break
if 'Militia' in str(move):
return [idx]
if 'Smithy' in str(move) and decision.player.actions > 1:
return [idx]
if stringDesired in str(move):
return [idx]
if 'Buy' not in decision.prompt and 'Choose a pile to gain card from.' not in decision.prompt:
return
desired_deck = {'Market': 1, 'Militia': 0.1, 'Village': 0.2}
for wish in desired_deck:
for idx in range(0, len(decision.moves)):
try:
move = decision.moves[idx]
except:
break
if wish in str(move):
if sum(1 for c in decision.player.all_cards if wish in str(c)) / len(
decision.player.all_cards) < desired_deck[wish]:
return [idx]
class MarketNoSmithySemiAgent2(Agent):
def policy(self, decision, state):
if 'Action' in decision.prompt:
for stringDesired in ['Empty']:
for idx in range(0, len(decision.moves)):
try:
move = decision.moves[idx]
except:
break
if 'Militia' in str(move):
return [idx]
if 'Smithy' in str(move) and decision.player.actions > 1:
return [idx]
if stringDesired in str(move):
return [idx]
if 'Buy' not in decision.prompt and 'Choose a pile to gain card from.' not in decision.prompt:
return
desired_deck = {'Market': 1, 'Militia': 0.2, 'Village': 0.2}
for wish in desired_deck:
for idx in range(0, len(decision.moves)):
try:
move = decision.moves[idx]
except:
break
if wish in str(move):
if sum(1 for c in decision.player.all_cards if wish in str(c)) / len(
decision.player.all_cards) < desired_deck[wish]:
return [idx]
class OnlyBuyCopperIfSemiAgent(Agent):
def policy(self, decision, state):
for idx in range(0, len(decision.moves)):
try:
move = decision.moves[idx]
except:
break
if "Buy: Copper" in str(move):
if sum(c.coins for c in decision.player.all_cards) < 5:
return [idx]
else:
decision.moves.pop(idx)
class ChapelSemiAgent(Agent):
def policy(self, decision, state):
if 'Action' in decision.prompt:
for c in decision.player.hand:
if 'Estate' in str(c):
for idx in range(0, len(decision.moves)):
if 'Play: Chapel' in str(decision.moves[idx]):
return [idx]
if 'Trash up to 4' in decision.prompt:
moves = []
for idx in range(0, len(decision.moves)):
if len(moves) >= 4:
break
try:
move = decision.moves[idx]
except:
break
if "Choose: Estate" in move.__str__():
moves.append(idx)
for idx in range(0, len(decision.moves)):
if len(moves) >= 4:
break
try:
move = decision.moves[idx]
except:
break
if "Choose: Copper" in move.__str__() and (
sum(c.coins for c in decision.player.all_cards) -
sum(1 for planned_move in moves if 'Copper' in str(planned_move)) > 5):
moves.append(idx)
return moves
if 'Buy' in decision.prompt:
for idx in range(0, len(decision.moves)):
try:
move = decision.moves[idx]
except:
break
if 'Buy: Chapel' in str(move) and decision.player.coins < 4 and (
sum(1 for c in decision.player.all_cards if 'Chapel' in str(c)) == 0):
return [idx]
class AggressiveChapelSemiAgent(ChapelSemiAgent):
def policy(self, decision, state):
if 'Action' in decision.prompt:
for c in decision.player.hand:
if 'Estate' in str(c) or ('Copper' in str(c) and sum(c.coins for c in decision.player.all_cards) > 5):
for idx in range(0, len(decision.moves)):
if 'Play: Chapel' in str(decision.moves[idx]):
return [idx]
if 'Trash' in decision.prompt:
moves = []
for idx in range(0, len(decision.moves)):
if len(moves) >= 4:
break
try:
move = decision.moves[idx]
except:
break
if "Choose: Estate" in str(move):
moves.append(idx)
for idx in range(0, len(decision.moves)):
if len(moves) >= 4:
break
try:
move = decision.moves[idx]
except:
break
if "Choose: Copper" in str(move) and (
sum(c.coins for c in decision.player.all_cards) -
sum(1 for planned_move in moves if 'Copper' in str(decision.moves[planned_move])) > 5):
moves.append(idx)
return moves
for idx in range(0, len(decision.moves)):
try:
move = decision.moves[idx]
except:
break
if "Buy: Chapel" in str(move) and (sum(1 for c in decision.player.all_cards if 'Chapel' in str(c)) > 0):
decision.moves.pop(idx)
if "Buy: Chapel" in str(move) and decision.player.coins < 4 and (
sum(1 for c in decision.player.all_cards if 'Chapel' in str(c)) == 0):
return [idx]
class ProvinceSemiAgent(Agent):
def policy(self, decision, state):
for stringDesired in ["Buy: Province"]:
for idx in range(0, len(decision.moves)):
try:
move = decision.moves[idx]
except:
break
if stringDesired in move.__str__():
return [idx]
class ProvinceNeverLoseSemiAgent(Agent):
def policy(self, decision, state):
desired_strings = ["Buy: Province"]
if (state.supply_piles['Province'].qty == 1 and
(6 + decision.player.total_vp() <
max(state.other_players, key=lambda pr: pr.total_vp()).total_vp())):
desired_strings = ["Buy: Duchy"]
for stringDesired in desired_strings:
for idx in range(0, len(decision.moves)):
try:
move = decision.moves[idx]
except:
break
if stringDesired in str(move):
return [idx]
|
python
|
"""Functional tests for pylint."""
|
python
|
import time
from wrf.cache import _get_cache
from wrf import getvar
from netCDF4 import Dataset as nc
#a = nc("/Users/ladwig/Documents/wrf_files/wrf_vortex_single/wrfout_d02_2005-08-28_00:00:00")
#b = nc("/Users/ladwig/Documents/wrf_files/wrf_vortex_single/wrfout_d02_2005-08-28_03:00:00")
a = nc("/Users/ladwig/Documents/wrf_files/wrf_vortex_multi/moving_nest/wrfout_d02_2005-08-28_00:00:00")
b = nc("/Users/ladwig/Documents/wrf_files/wrf_vortex_multi/moving_nest/wrfout_d02_2005-08-28_12:00:00")
q = {"outoutoutout" : {"outoutout" : {"outout" : {"out1" : {"blah" : [a,b], "blah2" : [a,b]}, "out2" : {"blah" : [a,b], "blah2" : [a,b]} } } } }
t1 = time.time()
c = getvar(q, "rh", method="cat", timeidx=None, squeeze=True)
t2 = time.time()
print (c)
print ("time taken: {}".format((t2-t1)*1000.))
t1 = time.time()
c = getvar(q, "rh", method="cat", timeidx=None, squeeze=False)
t2 = time.time()
print (c)
print ("time taken: {}".format((t2-t1)*1000.))
t1 = time.time()
c = getvar(q, "rh", method="cat", timeidx=1, squeeze=True)
t2 = time.time()
print (c)
print ("time taken: {}".format((t2-t1)*1000.))
t1 = time.time()
c = getvar(q, "rh", method="cat", timeidx=1, squeeze=False)
t2 = time.time()
print(c)
print ("time taken: {}".format((t2-t1)*1000.))
t1 = time.time()
c = getvar(q, "rh", method="join", timeidx=None, squeeze=True)
t2 = time.time()
print (c)
print ("time taken: {}".format((t2-t1)*1000.))
t1 = time.time()
c = getvar(q, "rh", method="join", timeidx=None, squeeze=False)
t2 = time.time()
print(c)
print ("time taken: {}".format((t2-t1)*1000.))
t1 = time.time()
c = getvar(q, "rh", method="join", timeidx=1, squeeze=True)
t2 = time.time()
print (c)
print ("time taken: {}".format((t2-t1)*1000.))
t1 = time.time()
c = getvar(q, "rh", method="join", timeidx=1, squeeze=False)
t2 = time.time()
print (c)
print ("time taken: {}".format((t2-t1)*1000.))
|
python
|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
from .. import _utilities
import typing
# Export this package's modules as members:
from ._enums import *
from .get_key import *
from .get_managed_hsm import *
from .get_mhsm_private_endpoint_connection import *
from .get_private_endpoint_connection import *
from .get_secret import *
from .get_vault import *
from .key import *
from .managed_hsm import *
from .mhsm_private_endpoint_connection import *
from .private_endpoint_connection import *
from .secret import *
from .vault import *
from ._inputs import *
from . import outputs
# Make subpackages available:
if typing.TYPE_CHECKING:
import pulumi_azure_native.keyvault.v20150601 as __v20150601
v20150601 = __v20150601
import pulumi_azure_native.keyvault.v20161001 as __v20161001
v20161001 = __v20161001
import pulumi_azure_native.keyvault.v20180214 as __v20180214
v20180214 = __v20180214
import pulumi_azure_native.keyvault.v20180214preview as __v20180214preview
v20180214preview = __v20180214preview
import pulumi_azure_native.keyvault.v20190901 as __v20190901
v20190901 = __v20190901
import pulumi_azure_native.keyvault.v20200401preview as __v20200401preview
v20200401preview = __v20200401preview
import pulumi_azure_native.keyvault.v20210401preview as __v20210401preview
v20210401preview = __v20210401preview
import pulumi_azure_native.keyvault.v20210601preview as __v20210601preview
v20210601preview = __v20210601preview
else:
v20150601 = _utilities.lazy_import('pulumi_azure_native.keyvault.v20150601')
v20161001 = _utilities.lazy_import('pulumi_azure_native.keyvault.v20161001')
v20180214 = _utilities.lazy_import('pulumi_azure_native.keyvault.v20180214')
v20180214preview = _utilities.lazy_import('pulumi_azure_native.keyvault.v20180214preview')
v20190901 = _utilities.lazy_import('pulumi_azure_native.keyvault.v20190901')
v20200401preview = _utilities.lazy_import('pulumi_azure_native.keyvault.v20200401preview')
v20210401preview = _utilities.lazy_import('pulumi_azure_native.keyvault.v20210401preview')
v20210601preview = _utilities.lazy_import('pulumi_azure_native.keyvault.v20210601preview')
|
python
|
import datetime
import json
from flask_testing import TestCase
from config import create_app
from db import db
from models import ParkModel
from models.pay_type import PayType
from tests.base import generate_token
from tests.factories import AdminUserFactory
from tests.helpers_for_tests import GenerateTarifeData
class TestPaymentResource(TestCase):
def create_app(self):
return create_app("config.TestingConfig")
def setUp(self):
self.app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.init_app(self.app)
db.create_all()
self.user = AdminUserFactory()
self.token = generate_token(self.user)
self.headers = {
"Authorization": f"Bearer {self.token}",
"Content-Type": "Application/json",
}
GenerateTarifeData.generate_all_needed_data()
p = PayType(name="cash")
db.session.add(p)
db.session.commit()
def tearDown(self):
db.session.remove()
db.drop_all()
def test_pay_in_cash_when_all_is_ok_should_write_to_db(self):
"""
Insertt new card, try to pay, should raise error, because card not leaving,
after that change status to leave, try again to pay, return success. Try again
to pay already payed card, should raise error.
:return:
"""
data = {"card": "A123"}
self.path = "/parking"
self.path_to_pay = "/parking/1/cash"
response = self.client.post(
headers=self.headers, path=self.path, data=json.dumps(data)
)
test_card_after_update = ParkModel.query.filter_by(id=1).first()
test_card_after_update.income = (
test_card_after_update.income - datetime.timedelta(hours=1)
)
# Test to pay card when card not leave yet from parking, should raise error
response = self.client.post(headers=self.headers, path=self.path_to_pay)
assert response.status_code == 400
assert response.json["message"] == "This card not have bill yet"
response = self.client.post(
headers=self.headers, path=self.path, data=json.dumps(data)
)
test_card_after_update = ParkModel.query.filter_by(id=1).first()
response = self.client.post(headers=self.headers, path=self.path_to_pay)
assert response.status_code == 200
assert (
response.json == f"Success pay id: 1, sum: {test_card_after_update.price}."
)
# Test pay already pay card, should raise error
response = self.client.post(headers=self.headers, path=self.path_to_pay)
assert response.status_code == 400
assert response.json["message"] == "This bill already is payed"
|
python
|
# -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect
from django.views.decorators.http import require_http_methods, require_GET
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.contrib.auth import authenticate, login, logout
from django.urls import reverse
from django.utils.http import is_safe_url
from django_tables2 import SingleTableView
from django import forms
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.conf import settings
from django.shortcuts import get_object_or_404, redirect, render, render_to_response
from django.utils.translation import ugettext_lazy as _
from django.views.generic import TemplateView
from django.views.generic.edit import UpdateView, DeleteView, CreateView, ProcessFormView
from django.views.generic import FormView
from django.views.generic.detail import SingleObjectMixin
from rest_framework.authtoken.models import Token
from rest_framework.decorators import action
from rest_framework import generics
from rest_framework import viewsets
from rest_framework import views, status
from braces import views as braces_view
from .serializers import UserSerializer, UserProfileSerializer, SSHKeySerializer, MessageSerializer
from .models import UserKey, Profile
from .forms import ProfileForm, UserForm, UserKeyForm
from .tables import UserKeyTables
### API ViewSets ###
class EchoView(views.APIView):
def post(self, request, *args, **kwargs):
serializer = MessageSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
return Response(
serializer.data,
status=status.HTTP_201_CREATED
)
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
def post(self, request, *args, **kwargs):
serializer = UserSerializer(queryset, context={'request': request})
serializer.is_valid(raise_exception=True)
return Response(
serializer.data,
status=status.HTTP_201_CREATED
)
def get(self, request, *args, **kwargs):
serializer = UserSerializer(queryset, context={'request': request})
serializer.is_valid(raise_exception=True)
return Response(
serializer.data,
status=status.HTTP_202_ACCEPTED
)
class UserProfileViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows Profiles to be viewed or edited.
"""
queryset = Profile.objects.all()
serializer_class = UserProfileSerializer
class SSHKeyViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users SSHKey to be viewed or edited.
"""
queryset = UserKey.objects.all().order_by('-name')
serializer_class = SSHKeySerializer
@action(methods=['post'], detail=True)
def add_key(self, request, pk=None):
pass
### Class Based Views ###
class HomeView(TemplateView):
template_name="homepage.html"
def get_context_data(self, **kwargs):
ctx = super(HomeView, self).get_context_data(**kwargs)
ctx.update({})
return ctx
class SearchView(TemplateView):
template_name = "search.html"
def get_context_data(self, **kwargs):
ctx = super(SearchView, self).get_context_data(**kwargs)
ctx.update({})
return ctx
class SignupView(account.views.SignupView):
form_class = SignupForm
def after_signup(self, form):
self.save_profile(form)
super(SignupView, self).after_signup(form)
def save_profile(self, form):
profile = self.created_user.profile # replace with your reverse one-to-one profile attribute
profile.location = form.cleaned_data["location"]
profile.company = form.cleaned_data["company"]
profile.birthdate = form.cleaned_data["birthdate"]
profile.save()
class ProfileView(FormView):
template_name = "account/profile.html"
form_class = ProfileForm
redirect_field_name = "next"
form_kwargs = {}
messages = { "profile_updated": {
"level": messages.SUCCESS,
"text": _("Profile Updated.")
},
}
def get(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
context = self.get_context_data(**kwargs)
context['form'] = form
return self.render_to_response(context)
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
if form.is_valid():
return self.form_valid(form, **kwargs)
else:
return self.form_invalid(form, **kwargs)
return self.render_to_response(context)
def form_invalid(self, form, **kwargs):
context = self.get_context_data(**kwargs)
context['form'] = form
# here you can add things like:
return self.render_to_response(context)
def form_valid(self, form, **kwargs):
context = self.get_context_data(**kwargs)
context['form'] = form
# here you can add things like:
return self.render_to_response(context)
class UserKeyAddView(FormView):
#model = UserKey
#fields = ['name', 'key']
template_name = "account/userkey_add.html"
success_url = "account_sshkeys"
form_class = UserKeyForm
messages = { "sshkey_added": {
"level": messages.SUCCESS,
"text": _("UserKey Added.")
},
}
def get(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
context = self.get_context_data(**kwargs)
context['form'] = form
return self.render_to_response(context)
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
if form.is_valid():
return self.form_valid(form, **kwargs)
else:
return self.form_invalid(form, **kwargs)
def form_invalid(self, form, **kwargs):
context = self.get_context_data(**kwargs)
context['form'] = form
# here you can add things like:
context[show_results] = False
return self.render_to_response(context)
def form_valid(self, form, **kwargs):
context = self.get_context_data(**kwargs)
context['form'] = form
# here you can add things like:
context[show_results] = True
return self.render_to_response(context)
class UserKeyListView(SingleTableView):
model = UserKey
template_name = "account/userkey_list.html"
table_class = UserKeyTables
#class UserKeyUpdateView(UpdateView):
# model = UserKey
# template_name = "account/userkey_detail.html"
# success_url = 'account/sshkey/'
# messages = { "sshkey_updated": {
# "level": messages.SUCCESS,
# "text": _("SSH Key Updated.") },
# }
#class UserKeyDeleteView(DeleteView):
# model = UserKey
# form_class = UserKeyForm
# template_name = "account/userkey_delete.html"
#
# def form_valid(self, form):
# self.form.save(form)
# if self.messages.get("sshkey_deleted"):
# messages.add_message(
# self.request,
# self.messages["sshkey_deleted"]["level"],
# self.messages["profile_deleted"]["text"]
# )
# return redirect(self.get_success_url())
#
# #def get_success_url(self):
# #return reverse("account_sshkeys")
#
##### Views ####
@login_required
@require_http_methods(['GET', 'POST'])
def userkey_add(request):
if request.method == 'POST':
userkey = UserKey(user=request.user)
userkey.request = request
form = UserKeyForm(request.POST, instance=userkey)
if form.is_valid():
form.save()
default_redirect = reverse('account_sshkeys')
url = request.GET.get('next', default_redirect)
if not is_safe_url(url=url, host=request.get_host()):
url = default_redirect
message = 'SSH public key %s was added.' % userkey.name
messages.success(request, message, fail_silently=True)
return HttpResponseRedirect(url)
else:
form = UserKeyForm()
return render(request, 'account/userkey_detail.html',
context={'form': form, 'action': 'add'})
@login_required
@require_http_methods(['GET', 'POST'])
def userkey_edit(request, pk):
if not settings.SSHKEY_ALLOW_EDIT:
raise PermissionDenied
userkey = get_object_or_404(UserKey, pk=pk)
if userkey.user != request.user:
raise PermissionDenied
if request.method == 'POST':
form = UserKeyForm(request.POST, instance=userkey)
if form.is_valid():
form.save()
default_redirect = reverse('account_sshkeys')
url = request.GET.get('next', default_redirect)
if not is_safe_url(url=url, host=request.get_host()):
url = default_redirect
message = 'SSH public key %s was saved.' % userkey.name
messages.success(request, message, fail_silently=True)
return HttpResponseRedirect(url)
else:
form = UserKeyForm(instance=userkey)
return render(request, 'account/userkey_detail.html',
context={'form': form, 'action': 'edit'})
@login_required
@require_GET
def userkey_delete(request, pk):
userkey = get_object_or_404(UserKey, pk=pk)
if userkey.user != request.user:
raise PermissionDenied
userkey.delete()
message = 'SSH public key %s was deleted.' % userkey.name
messages.success(request, message, fail_silently=True)
return HttpResponseRedirect(reverse('account_sshkeys'))
def get_auth_token(request):
'''
This view is used if you want to use the standard AUTH
Token instead of a JWT Token that expires. A Token will be
created when the User is created in the DB and is viewable
in the admin url. Just create a url view like so in urls.py
url(r"^api/get_auth_token/$", views.get_auth_token, name="authtoken"),
'''
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user is not None:
# the password verified for the user
if user.is_active:
token, created = Token.objects.get_or_create(user=user)
request.session['auth'] = token.key
return redirect('/polls/', request)
return redirect(settings.LOGIN_URL, request)
|
python
|
import re
from datetime import datetime
class HadoopSeriesParser:
def __init__(self):
self.attribute_count = 8
self.foundation_date_regex = r'^([^\t]*\t){1}"\d{4}"\^\^<http://www.w3.org/2001/XMLSchema#date>.*$'
def parse(self, result_data):
lines_attributes = []
### Structure
# <http://dbpedia.org/resource/Axel!>
# "2002-09-21"^^<http://www.w3.org/2001/XMLSchema#date>
# "Axel!"@de
# "35"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger>
# (Produzent) BSP: <http://dbpedia.org/resource/Tina_Fey>
# (???)
# (Bild) BSP: <http://commons.wikimedia.org/wiki/Special:FilePath/Ty_Pennington.jpg>
# "Axel! ist eine deutsche Comedy-Serie mit Axel Stein in der Titelrolle, in der witzige Episoden aus dem Leben der Figur Axel und seiner Freunde gezeigt werden. Die Serie wurde auf Sat.1 ausgestrahlt. Als Fortsetzung entstand eine weitere Serie mit dem Namen Axel! will\u2019s wissen."@de
for line in result_data:
if re.match(self.foundation_date_regex, line):
line_parts = line.split('\t', -1)
if len(line_parts) == self.attribute_count:
line_attributes = {}
if line_parts[0]:
line_attributes['url'] = line_parts[0].strip('<>')
if line_parts[1]:
line_attributes['foundation_date'] = line_parts[1].split('"', -1)
foundation_date_parts = line_attributes['foundation_date'].split('-', -1)
line_attributes['foundation_date_year'] = foundation_date_parts[0]
line_attributes['foundation_date_month'] = foundation_date_parts[1]
line_attributes['foundation_date_day'] = foundation_date_parts[2]
if line_parts[2]:
line_attributes['name'] = line_parts[2].split('"', -1)[1]
if line_parts[3]:
line_attributes['episode_count'] = line_parts[3].split('"', -1)[1]
if line_parts[4]:
line_attributes['producer_url'] = line_parts[4].split('<>', -1)[1]
if line_parts[5]:
line_attributes['image_url'] = line_parts[5].split('<>', -1)[1]
if line_parts[7]:
line_attributes['summary'] = line_parts[7].split('"', -1)[1]
lines_attributes.append(line_attributes)
else:
pass # ignore the incomplete lines
return lines_attributes
|
python
|
import sys
import os
import pytest
import pandas as pd
import arcus.ml.dataframes as adf
import logging
from unittest.mock import patch
from collections import Counter
logging.basicConfig(level=logging.DEBUG)
mylogger = logging.getLogger()
# initialize list of lists
categorical_data = [['BE', 10], ['FR', 15], ['BE', 14], ['UK', 14], ['SE', 14], ['SE', 14]]
def setup_module(module):
''' Setup for the entire module '''
# Do the actual setup stuff here
pass
def setup_function(func):
''' Setup for test functions '''
def test_shuffle():
# initialize list of lists
data = [['tom', 10], ['nick', 15], ['juli', 14]]
# Create the pandas DataFrame
test_df = pd.DataFrame(data, columns = ['Name', 'Age'])
# print dataframe.
shuffled_df = adf.shuffle(test_df)
assert len(shuffled_df)==len(test_df)
assert shuffled_df[shuffled_df.Name == 'nick'].iloc[0].Age == 15
def test_one_hot_encoding_default():
# Create the pandas DataFrame
test_df = pd.DataFrame(categorical_data, columns = ['Country', 'Infected'])
# One hot encode the Country column
encoded_df = adf.one_hot_encode(test_df, 'Country')
assert len(encoded_df.columns) == 5
assert 'Country_BE' in encoded_df.columns
assert len(encoded_df.loc[encoded_df['Country_BE'] == 1]) == 2
assert len(encoded_df.loc[encoded_df['Country_FR'] == 0]) == 5
def test_one_hot_encoding_keepcolumn():
# Create the pandas DataFrame
test_df = pd.DataFrame(categorical_data, columns = ['Country', 'Infected'])
# One hot encode the Country column
encoded_df = adf.one_hot_encode(test_df, 'Country', drop_column=False)
assert len(encoded_df.columns) == 6
assert 'Country_SE' in encoded_df.columns
assert len(encoded_df.loc[encoded_df['Country_UK'] == 1]) == 1
@patch("matplotlib.pyplot.show")
def test_one_hot_encoding_prefix(mock_show):
# Create the pandas DataFrame
test_df = pd.DataFrame(categorical_data, columns = ['Country', 'Infected'])
encoded_df = adf.one_hot_encode(test_df, 'Country', prefix='cnt')
# One hot encode the Country column
assert len(encoded_df.columns) == 5
assert 'cnt_BE' in encoded_df.columns
assert len(encoded_df.loc[encoded_df['cnt_UK'] == 1]) == 1
@patch("matplotlib.pyplot.show")
def test_plot_features_selectedcols(mock_show):
df = pd.read_csv('tests/resources/datasets/car-fuel.csv')
_, _axes = adf.plot_features(df, column_names=['speed', 'temp_outside'])
assert len(_axes.ravel()) == 2
_ax = _axes[0]
assert _ax.numCols == 2
assert _ax.numRows == 1
@patch("matplotlib.pyplot.show")
def test_plot_features_onerow(mock_show):
df = pd.read_csv('tests/resources/datasets/car-fuel.csv')
_, _axes = adf.plot_features(df, column_names=['speed', 'temp_outside'])
assert len(_axes.ravel()) == 2
_ax = _axes[0]
assert _ax.numCols == 2
assert _ax.numRows == 1
@patch("matplotlib.pyplot.show")
def test_plot_features_grid_size(mock_show):
df = pd.read_csv('tests/resources/datasets/car-fuel.csv')
_, _axes = adf.plot_features(df, grid_shape=(2,3))
assert len(_axes.ravel()) == 6
_ax = _axes[0][0]
assert _ax.numCols == 3
assert _ax.numRows == 2
@patch("matplotlib.pyplot.show")
def test_plot_features_default(mock_show):
df = pd.read_csv('tests/resources/datasets/car-fuel.csv')
_, _axes = adf.plot_features(df)
assert len(_axes.ravel()) == 5
assert _axes[0].numCols == 5
assert _axes[0].numRows == 1
def test_keep_numeric_features():
test_df = pd.DataFrame(categorical_data, columns = ['Country', 'Infected'])
num_df = adf.keep_numeric_features(test_df)
assert len(num_df.columns) == 1
def test_keep_numeric_features_onehotencoded():
test_df = pd.DataFrame(categorical_data, columns = ['Country', 'Infected'])
encoded_df = adf.one_hot_encode(test_df, 'Country', prefix='cnt')
num_df = adf.keep_numeric_features(encoded_df)
assert len(num_df.columns) == 5
def test_keep_numeric_features_csv():
df = pd.read_csv('tests/resources/datasets/car-fuel.csv')
num_df = adf.keep_numeric_features(df)
assert len(num_df.columns) == 5
def test_class_distribution_default():
df = pd.read_csv('tests/resources/datasets/car-fuel.csv')
cnt1 = Counter(df.gas_type)
df = adf.distribute_class(df, 'gas_type')
cnt2 = Counter(df.gas_type)
# Smallest class size from first should be same as largest from new
assert min(cnt1.values()) == max (cnt2.values())
# Sizes of new df should be the same
assert min(cnt2.values()) == max (cnt2.values())
assert len(df) == min(cnt1.values()) * 2
def test_class_distribution_class_size():
cs = 30
df = pd.read_csv('tests/resources/datasets/car-fuel.csv')
cnt1 = Counter(df.gas_type)
df = adf.distribute_class(df, 'gas_type', cs)
cnt2 = Counter(df.gas_type)
# Sizes of new df should be the same
assert min(cnt2.values()) == max (cnt2.values())
assert len(df) == cs * 2
def test_class_distribution_noshuffle():
cs = 30
df = pd.read_csv('tests/resources/datasets/car-fuel.csv')
cnt1 = Counter(df.gas_type)
df = adf.distribute_class(df, 'gas_type', cs, False)
cnt2 = Counter(df.iloc[0:cs].gas_type)
assert len(cnt2.keys()) == 1
|
python
|
#/usr/bin/python
# Copyright 2013 by Hartmut Goebel <[email protected]>
# Licence: GNU Public Licence v3 (GPLv3), but not for military use
import subprocess
import argparse
GRAPH_HEADER = '''
digraph "%s"
{
nodesep=0; sep=0; ranksep=0
ratio="compress"
packmode="node"; pack=1
pad=0
splines=true
rankdir=TB // top-bottom
concentrate=true;
//K=0
edge [arrowsize=0.7,fontsize="6",fontcolor=grey]
node [fontname="Helvetica",fontsize="10"]
//node [shape=plaintext,height=0,width=4]
node [shape=plaintext,height=0]
'''
ignore = set('coreutils python perl ruby bash desktop-file-utils initscripts shadowutils'.split())
MAX_DEPTH = 5 # see option --depth
seen = set(ignore)
nodenames = {}
def nodename(name):
if name not in nodenames:
nodenames[name] = (''.join(c for c in name if c.isalnum())
+ '_' + str(abs(hash(name))))
return nodenames[name]
def draw_req(pkg, depth):
if pkg in seen or depth >= MAX_DEPTH:
return
seen.add(pkg)
pn = nodename(pkg)
print ('%s[label="%s"]' % (pn, pkg))
try:
req = subprocess.check_output(['rpm', '--query', '--requires', pkg])
except:
return
if not req:
contine
for req in req.strip().splitlines():
req = req.split(None, 1)[0]
if '/' in req or '(' in req:
continue
rn = nodename(req)
print ('%s[label="%s"]' % (rn, req))
print ('%s -> %s [color=plum]' % (pn, rn))
draw_req(req, depth+1)
parser = argparse.ArgumentParser()
parser.add_argument('--depth', type=int, default=MAX_DEPTH,
help='walk the tree that deep, default: %(default)s')
parser.add_argument('pkgname', nargs='+')
args = parser.parse_args()
MAX_DEPTH = args.depth
print GRAPH_HEADER % "XXX"
for pkg in args.pkgname:
draw_req(pkg, 0)
print "}"
|
python
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.