hexsha stringlengths 40 40 | size int64 2 1.02M | ext stringclasses 10
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 245 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 245 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 2 1.02M | avg_line_length float64 1 417k | max_line_length int64 1 987k | alphanum_fraction float64 0 1 | content_no_comment stringlengths 0 1.01M | is_comment_constant_removed bool 1
class | is_sharp_comment_removed bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1c36b732a37d291cf4aa9d43a5a0c13843ce5496 | 2,581 | py | Python | 05_normal_distribution_simulator/studio/charting/histograms.py | Shiao-Computing-Volumes/project-based-learning-in-python | 52e0b02cf085de97c3b5d9aa44bf8786d8a9ad19 | [
"Apache-2.0"
] | 1 | 2021-08-17T23:53:46.000Z | 2021-08-17T23:53:46.000Z | 05_normal_distribution_simulator/studio/charting/histograms.py | Shiao-Computing-Volumes/project-based-learning-in-python | 52e0b02cf085de97c3b5d9aa44bf8786d8a9ad19 | [
"Apache-2.0"
] | null | null | null | 05_normal_distribution_simulator/studio/charting/histograms.py | Shiao-Computing-Volumes/project-based-learning-in-python | 52e0b02cf085de97c3b5d9aa44bf8786d8a9ad19 | [
"Apache-2.0"
] | null | null | null | import numpy as np
import scipy.stats
import matplotlib.pyplot as plt
from studio.settings.frames import STYLE, THEME_COLOR, AIDED_COLOR
from studio.settings.frames import FIGSIZE, DPI
from studio.frames.camera import Camera
from studio.charting.components.legends import captioning
plt.style.use(STYLE)
def hist_density(datasets, suptitle, title, captions1, caption2):
fig = plt.figure(figsize=FIGSIZE, dpi=DPI)
fig.suptitle(suptitle)
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
ax1.spines['right'].set_visible(False)
ax1.spines['top'].set_visible(False)
ax1.spines['left'].set_color(AIDED_COLOR)
ax1.spines['bottom'].set_color(AIDED_COLOR)
ax2.spines['right'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax2.spines['left'].set_color(AIDED_COLOR)
ax2.spines['bottom'].set_color(AIDED_COLOR)
camera = Camera(fig)
for index in range(len(datasets)):
n = len(datasets[index])
if n < 101: step = int(n/5)
else: step = int(n/10)
for i in range(0, len(datasets[index]), step):
single_histogram(ax1, datasets[index], i+step, title, captions1[index])
single_density(ax2, datasets[index], i+step, title, caption2)
camera.snap()
return camera.animate()
def single_histogram(ax, data, i, title, caption):
max_value = max(data)
min_value = min(data)
bin_width = (max_value - min_value) / float(len(data) - 1)
n_bins = np.arange(min_value, max_value + bin_width, bin_width)
ax.hist(data[:i], n_bins,
linewidth=1.2,
edgecolor=THEME_COLOR,
color=THEME_COLOR,
alpha=0.8)
# captioning
ax, legend = captioning(ax, caption)
ax.set_title(title.format("Histogram"), fontsize=10, loc="left")
# ax.set_xlabel("X")
ax.set_ylabel("Frequency")
ax.tick_params(axis='x', colors=AIDED_COLOR)
ax.tick_params(axis='y', colors=AIDED_COLOR)
return ax
def single_density(ax, data, i, title, caption):
density = scipy.stats.gaussian_kde(data[:i])
x = np.linspace(min(data), max(data), 500)
ax.plot(x, density(x), color=THEME_COLOR)
ax.fill_between(x, density(x), 0, facecolor=THEME_COLOR, alpha=0.5)
# captioning
ax, legend = captioning(ax, caption)
ax.set_title(title.format("Density"), fontsize=10, loc="left")
ax.set_xlabel("X")
ax.set_ylabel("Density")
ax.tick_params(axis='x', colors=AIDED_COLOR)
ax.tick_params(axis='y', colors=AIDED_COLOR)
return ax
| 32.2625 | 83 | 0.660597 | import numpy as np
import scipy.stats
import matplotlib.pyplot as plt
from studio.settings.frames import STYLE, THEME_COLOR, AIDED_COLOR
from studio.settings.frames import FIGSIZE, DPI
from studio.frames.camera import Camera
from studio.charting.components.legends import captioning
plt.style.use(STYLE)
def hist_density(datasets, suptitle, title, captions1, caption2):
fig = plt.figure(figsize=FIGSIZE, dpi=DPI)
fig.suptitle(suptitle)
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
ax1.spines['right'].set_visible(False)
ax1.spines['top'].set_visible(False)
ax1.spines['left'].set_color(AIDED_COLOR)
ax1.spines['bottom'].set_color(AIDED_COLOR)
ax2.spines['right'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax2.spines['left'].set_color(AIDED_COLOR)
ax2.spines['bottom'].set_color(AIDED_COLOR)
camera = Camera(fig)
for index in range(len(datasets)):
n = len(datasets[index])
if n < 101: step = int(n/5)
else: step = int(n/10)
for i in range(0, len(datasets[index]), step):
single_histogram(ax1, datasets[index], i+step, title, captions1[index])
single_density(ax2, datasets[index], i+step, title, caption2)
camera.snap()
return camera.animate()
def single_histogram(ax, data, i, title, caption):
max_value = max(data)
min_value = min(data)
bin_width = (max_value - min_value) / float(len(data) - 1)
n_bins = np.arange(min_value, max_value + bin_width, bin_width)
ax.hist(data[:i], n_bins,
linewidth=1.2,
edgecolor=THEME_COLOR,
color=THEME_COLOR,
alpha=0.8)
ax, legend = captioning(ax, caption)
ax.set_title(title.format("Histogram"), fontsize=10, loc="left")
ax.set_ylabel("Frequency")
ax.tick_params(axis='x', colors=AIDED_COLOR)
ax.tick_params(axis='y', colors=AIDED_COLOR)
return ax
def single_density(ax, data, i, title, caption):
density = scipy.stats.gaussian_kde(data[:i])
x = np.linspace(min(data), max(data), 500)
ax.plot(x, density(x), color=THEME_COLOR)
ax.fill_between(x, density(x), 0, facecolor=THEME_COLOR, alpha=0.5)
ax, legend = captioning(ax, caption)
ax.set_title(title.format("Density"), fontsize=10, loc="left")
ax.set_xlabel("X")
ax.set_ylabel("Density")
ax.tick_params(axis='x', colors=AIDED_COLOR)
ax.tick_params(axis='y', colors=AIDED_COLOR)
return ax
| true | true |
1c36b806de11d9f2cd755d855696a3e816702e8e | 4,361 | py | Python | docs/codeql/ql-training/conf.py | madhurimamandal/codeql | 76bf8878da4d951ed98238b7239c199a3dfddf16 | [
"MIT"
] | 4,036 | 2020-04-29T00:09:57.000Z | 2022-03-31T14:16:38.000Z | docs/codeql/ql-training/conf.py | madhurimamandal/codeql | 76bf8878da4d951ed98238b7239c199a3dfddf16 | [
"MIT"
] | 2,970 | 2020-04-28T17:24:18.000Z | 2022-03-31T22:40:46.000Z | docs/codeql/ql-training/conf.py | ScriptBox99/github-codeql | 2ecf0d3264db8fb4904b2056964da469372a235c | [
"MIT"
] | 794 | 2020-04-29T00:28:25.000Z | 2022-03-30T08:21:46.000Z | # -*- coding: utf-8 -*-
#
# CodeQL training slides build configuration file
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# For details of all possible config values,
# see https://www.sphinx-doc.org/en/master/usage/configuration.html
##################################################################################
# -- GLOBAL GENERAL CONFIG VALUES ------------------------------------------------
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.7.9'
# Beware that some of the extensions don't work in version 1.8
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.intersphinx',
'sphinx.ext.mathjax',
'hieroglyph',
'sphinx.ext.graphviz',
]
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# Import the QL Lexer to use for syntax highlighting
import sys
import os
def setup(sphinx):
sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.path.pardir))
from qllexer import QLLexer
sphinx.add_lexer("ql", QLLexer())
# Set QL as the default language for highlighting code. Set to none to disable
# syntax highlighting. If omitted or left blank, it defaults to Python 3.
highlight_language = 'ql'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'CodeQL training and variant analysis examples'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static-training']
# Add any paths that contain templates here, relative to this directory.
#templates_path = ['../rst-styles/_templates-training']
#slide_theme_options = {'custom_css':'custom.css'}
slide_theme = 'slides-semmle-2'
slide_theme_path = ["_static-training/"]
# -- Project-specifc options for HTML output ----------------------------------------------
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
html_title = 'CodeQL training and variant analysis examples'
# Output file base name for HTML help builder.
htmlhelp_basename = 'CodeQL training'
# The Semmle version info for the current release you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
# version = u'1.24'
# The full version, including alpha/beta/rc tags.
# release = u'1.24'
# copyright = u'2019 Semmle Ltd'
# author = u'Semmle Ltd'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
language = None
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# If true, links to the reST sources are added to the pages.
html_show_sourcelink = False
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
html_show_sphinx = False
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = {'font_size': '16px',
'body_text': '#333',
'link': '#2F1695',
'link_hover': '#2F1695',
'font_family': 'Lato, sans-serif',
'head_font_family': 'Moderat, sans-serif',
'show_powered_by': False,
'nosidebar':True,
}
# Exclude the slide snippets from the build
exclude_patterns = ['slide-snippets']
############################################################################## | 34.888 | 93 | 0.667966 | true | true | |
1c36b81bf56ec94a2a91b25eebf4a82ac94ac1e8 | 374 | py | Python | support/admin.py | shakyasaijal/businessAnalytics | 9312bae79709387c6eadd50f87f6be85bd52c396 | [
"BSD-3-Clause"
] | null | null | null | support/admin.py | shakyasaijal/businessAnalytics | 9312bae79709387c6eadd50f87f6be85bd52c396 | [
"BSD-3-Clause"
] | 8 | 2021-03-30T13:03:11.000Z | 2022-03-12T00:20:13.000Z | support/admin.py | shakyasaijal/businessAnalytics | 9312bae79709387c6eadd50f87f6be85bd52c396 | [
"BSD-3-Clause"
] | null | null | null | from django.contrib import admin
from . import models
class BranchAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('branch_name',)}
list_display = ('branch_name','location', 'contact', 'branch_head')
search_fields = ['branch_name', 'location', 'contact', 'branch_head']
list_filter = ("location",)
admin.site.register(models.Branches, BranchAdmin) | 34 | 73 | 0.719251 | from django.contrib import admin
from . import models
class BranchAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('branch_name',)}
list_display = ('branch_name','location', 'contact', 'branch_head')
search_fields = ['branch_name', 'location', 'contact', 'branch_head']
list_filter = ("location",)
admin.site.register(models.Branches, BranchAdmin) | true | true |
1c36b88b82c23e7d8eede2f80625c3ec21c19267 | 4,134 | py | Python | src/abcgan/transforms.py | brillouinzone/atmosense-abcgan | 30b77fd082a55869e58839a4cfbab61a7eab2b13 | [
"MIT"
] | 1 | 2022-02-06T09:54:40.000Z | 2022-02-06T09:54:40.000Z | src/abcgan/transforms.py | brillouinzone/atmosense-abcgan | 30b77fd082a55869e58839a4cfbab61a7eab2b13 | [
"MIT"
] | 1 | 2021-08-21T21:06:17.000Z | 2021-08-21T21:06:17.000Z | src/abcgan/transforms.py | brillouinzone/atmosense-abcgan | 30b77fd082a55869e58839a4cfbab61a7eab2b13 | [
"MIT"
] | 2 | 2021-08-14T06:41:20.000Z | 2021-12-14T19:32:48.000Z | """
Transforms to and from z-scaled variables.
Uses numpy only (no pytorch)
"""
import numpy as np # noqa
import abcgan.constants as const
def encode(data, name):
"""
Encode variables, or just add extra dimension
Parameters
----------
data : np.ndarray
array of variable values.
name : str
name of the variable.
Returns
-------
enc : np.ndarray
array of encoded variables (with an extra dimension in all cases)
"""
if name in const.cyclic_driver:
wrap_val = const.cyclic_driver[name]
enc = data % wrap_val
enc = (enc / wrap_val) * 2.0 * np.pi
enc = np.stack((np.cos(enc), np.sin(enc)), axis=-1)
else:
enc = data[..., None] # add trailing singleton dimension
return enc
def decode(data):
"""
Encode variables, or just add extra dimension
Parameters
----------
data : np.ndarray
array of feature values.
Returns
-------
enc : np.ndarray
array of encoded variables
"""
curr = 0
decs = []
for name in const.driver_names:
if name in const.cyclic_driver:
wrap_val = const.cyclic_driver[name]
cval = data[:, curr]
sval = data[:, curr + 1]
theta = np.arctan2(sval, cval)
dec = theta * wrap_val / 2.0 / np.pi
dec = dec % wrap_val
decs.append(dec)
curr += 2
else:
decs.append(data[:, curr])
curr += 1
return np.stack(decs, axis=-1)
def compute_valid(bvs):
# valid only if value within thresholds and if at least one non-zero value
valid_mask = np.zeros((bvs.shape[0], const.n_bv_feat))
for i in range(const.n_bv_feat):
valid_mask[:, i] = ~(((const.bv_thresholds[i][0] > bvs[:, :, i]) |
(bvs[:, :, i] > const.bv_thresholds[i][1])).any(-1) |
((bvs[:, :, i] == 0).all(-1)))
# valid only if every altitude is valid (skip first for now)
valid_mask = valid_mask.all(-1)
return valid_mask
def scale_driver(drivers):
"""
Return a scaled version of the drivers.
Parameters
--------------
drivers: np.ndarray
n_samples x n_driver
Returns
--------------
driver_feat: np.ndarray
n_samples x n_driver_feat
"""
drivers = np.hstack([
encode(drivers[:, i], n)
for i, n in enumerate(const.driver_names)
])
drivers = np.log(1 + drivers)
driver_feat = (drivers - const.driver_mu) / const.driver_sigma
return driver_feat
def scale_bv(bvs):
"""
Return a scaled version of the drivers.
Parameters
--------------
bvs: np.ndarray
n_samples x n_bv
Returns
--------------
bv_feat: np.ndarray
n_samples x n_bv_feat
"""
valid_mask = compute_valid(bvs)
bvs = np.log(1 + bvs)
bv_feat = (bvs - const.bv_mu) / const.bv_sigma
# pad bvs to max_alt if needed
if bv_feat.shape[1] < const.max_alt:
pad_alt = const.max_alt - bv_feat.shape[1]
bv_feat = np.pad(bv_feat,
((0, 0), (0, pad_alt), (0, 0)),
constant_values=np.nan)
elif bv_feat.shape[1] > const.max_alt:
bv_feat = bv_feat[:, :const.max_alt, :]
return bv_feat, valid_mask
def get_driver(driver_feat):
"""
Invert featurization to recover driving parameters.
Parameters
--------------
drivers: np.ndarray
n_samples x n_driver
Returns
--------------
scaled_feat: np.ndarray
n_samples x n_driver_feat
"""
drivers = const.driver_sigma * driver_feat + const.driver_mu
drivers = np.exp(drivers) - 1.0
drivers = decode(drivers)
return drivers
def get_bv(bv_feat):
"""
Invert featurization to recover bvs.
Parameters
--------------
bvs: np.ndarray
n_samples x n_bv
Returns
--------------
scaled_feat: np.ndarray
n_samples x n_bv_feat
"""
bvs = const.bv_sigma * bv_feat + const.bv_mu
bvs = np.exp(bvs) - 1.0
return bvs
| 24.461538 | 83 | 0.557571 | import numpy as np
import abcgan.constants as const
def encode(data, name):
if name in const.cyclic_driver:
wrap_val = const.cyclic_driver[name]
enc = data % wrap_val
enc = (enc / wrap_val) * 2.0 * np.pi
enc = np.stack((np.cos(enc), np.sin(enc)), axis=-1)
else:
enc = data[..., None]
return enc
def decode(data):
curr = 0
decs = []
for name in const.driver_names:
if name in const.cyclic_driver:
wrap_val = const.cyclic_driver[name]
cval = data[:, curr]
sval = data[:, curr + 1]
theta = np.arctan2(sval, cval)
dec = theta * wrap_val / 2.0 / np.pi
dec = dec % wrap_val
decs.append(dec)
curr += 2
else:
decs.append(data[:, curr])
curr += 1
return np.stack(decs, axis=-1)
def compute_valid(bvs):
valid_mask = np.zeros((bvs.shape[0], const.n_bv_feat))
for i in range(const.n_bv_feat):
valid_mask[:, i] = ~(((const.bv_thresholds[i][0] > bvs[:, :, i]) |
(bvs[:, :, i] > const.bv_thresholds[i][1])).any(-1) |
((bvs[:, :, i] == 0).all(-1)))
valid_mask = valid_mask.all(-1)
return valid_mask
def scale_driver(drivers):
drivers = np.hstack([
encode(drivers[:, i], n)
for i, n in enumerate(const.driver_names)
])
drivers = np.log(1 + drivers)
driver_feat = (drivers - const.driver_mu) / const.driver_sigma
return driver_feat
def scale_bv(bvs):
valid_mask = compute_valid(bvs)
bvs = np.log(1 + bvs)
bv_feat = (bvs - const.bv_mu) / const.bv_sigma
if bv_feat.shape[1] < const.max_alt:
pad_alt = const.max_alt - bv_feat.shape[1]
bv_feat = np.pad(bv_feat,
((0, 0), (0, pad_alt), (0, 0)),
constant_values=np.nan)
elif bv_feat.shape[1] > const.max_alt:
bv_feat = bv_feat[:, :const.max_alt, :]
return bv_feat, valid_mask
def get_driver(driver_feat):
drivers = const.driver_sigma * driver_feat + const.driver_mu
drivers = np.exp(drivers) - 1.0
drivers = decode(drivers)
return drivers
def get_bv(bv_feat):
bvs = const.bv_sigma * bv_feat + const.bv_mu
bvs = np.exp(bvs) - 1.0
return bvs
| true | true |
1c36b9540a1cfb59160976ae676a2d6a7a56812a | 220 | py | Python | tern/adapters/tests/test_init.py | luhn/tern | a206c4084ddb22ed903117819c3b7b572c854ea5 | [
"MIT"
] | 1 | 2020-09-06T19:10:50.000Z | 2020-09-06T19:10:50.000Z | tern/adapters/tests/test_init.py | luhn/tern | a206c4084ddb22ed903117819c3b7b572c854ea5 | [
"MIT"
] | null | null | null | tern/adapters/tests/test_init.py | luhn/tern | a206c4084ddb22ed903117819c3b7b572c854ea5 | [
"MIT"
] | null | null | null | from __future__ import absolute_import
from .. import extract_adapter
from ..postgresql import PostgreSQLAdapter
def test_extract_adapter():
assert extract_adapter('tern.adapters.postgresql') is PostgreSQLAdapter
| 24.444444 | 75 | 0.827273 | from __future__ import absolute_import
from .. import extract_adapter
from ..postgresql import PostgreSQLAdapter
def test_extract_adapter():
assert extract_adapter('tern.adapters.postgresql') is PostgreSQLAdapter
| true | true |
1c36baff65cd3c4db0b667ec08a4a525b362ee96 | 2,413 | py | Python | stancode_projects/breakout.py | she12306/stancode_prjects | 374cca15e5aead0864d30206fbf84b5a79b8d19b | [
"MIT"
] | null | null | null | stancode_projects/breakout.py | she12306/stancode_prjects | 374cca15e5aead0864d30206fbf84b5a79b8d19b | [
"MIT"
] | null | null | null | stancode_projects/breakout.py | she12306/stancode_prjects | 374cca15e5aead0864d30206fbf84b5a79b8d19b | [
"MIT"
] | null | null | null | """
stanCode Breakout Project
Adapted from Eric Roberts's Breakout by
Sonja Johnson-Yu, Kylie Jue, Nick Bowman,
and Jerry Liao.
The animation part works here.
"""
from campy.gui.events.timer import pause
from breakoutgraphics import BreakoutGraphics
FRAME_RATE = 1000 / 120 # 120 frames per second
NUM_LIVES = 3 # Number of attempts
TOTAL_SCORE = 100
def main():
graphics = BreakoutGraphics()
lives = NUM_LIVES
graphics.draw_hp(lives)
dx = graphics.get_dx()
dy = graphics.get_dy()
while True:
pause(FRAME_RATE)
if lives > 0:
if graphics.score < TOTAL_SCORE:
if graphics.is_game_start:
graphics.ball.move(dx, dy)
# Collision detection
if graphics.collision():
# Prevent the ball from rebounding twice in the area of the paddle
if graphics.ball.y + graphics.ball.height > graphics.paddle.y and dy < 0:
pass
else:
dy *= -1
# Hit a special brick, the speed will change.
if graphics.is_slow:
dy *= 0.8
graphics.is_slow = False
if graphics.is_fast:
dy *= 1.2
graphics.is_fast = False
# Border detection
if graphics.ball.x <= 0 or \
graphics.ball.x >= graphics.window.width - graphics.ball.width:
dx *= -1
if graphics.ball.y <= 0:
dy *= -1
if graphics.ball.y >= graphics.window.height:
lives -= 1
graphics.reduce_hp(lives)
graphics.is_game_start = False
graphics.initialize_ball_position()
dx = graphics.reset_dx()
dy = graphics.get_dy()
# Difficulty adjustment
if graphics.score >= 80:
graphics.harder()
else:
graphics.win()
break
else:
graphics.lose()
break
if __name__ == '__main__':
main()
| 32.608108 | 97 | 0.463324 |
from campy.gui.events.timer import pause
from breakoutgraphics import BreakoutGraphics
FRAME_RATE = 1000 / 120
NUM_LIVES = 3
TOTAL_SCORE = 100
def main():
graphics = BreakoutGraphics()
lives = NUM_LIVES
graphics.draw_hp(lives)
dx = graphics.get_dx()
dy = graphics.get_dy()
while True:
pause(FRAME_RATE)
if lives > 0:
if graphics.score < TOTAL_SCORE:
if graphics.is_game_start:
graphics.ball.move(dx, dy)
if graphics.collision():
if graphics.ball.y + graphics.ball.height > graphics.paddle.y and dy < 0:
pass
else:
dy *= -1
if graphics.is_slow:
dy *= 0.8
graphics.is_slow = False
if graphics.is_fast:
dy *= 1.2
graphics.is_fast = False
if graphics.ball.x <= 0 or \
graphics.ball.x >= graphics.window.width - graphics.ball.width:
dx *= -1
if graphics.ball.y <= 0:
dy *= -1
if graphics.ball.y >= graphics.window.height:
lives -= 1
graphics.reduce_hp(lives)
graphics.is_game_start = False
graphics.initialize_ball_position()
dx = graphics.reset_dx()
dy = graphics.get_dy()
if graphics.score >= 80:
graphics.harder()
else:
graphics.win()
break
else:
graphics.lose()
break
if __name__ == '__main__':
main()
| true | true |
1c36bb0d893f1bfdb757b53ebaabfb637f523d75 | 3,784 | py | Python | misc/scrape.py | hykilpikonna/CSC110 | 12a4f9361e0c79fe03cafa3c283eb96706359f46 | [
"MIT"
] | null | null | null | misc/scrape.py | hykilpikonna/CSC110 | 12a4f9361e0c79fe03cafa3c283eb96706359f46 | [
"MIT"
] | null | null | null | misc/scrape.py | hykilpikonna/CSC110 | 12a4f9361e0c79fe03cafa3c283eb96706359f46 | [
"MIT"
] | null | null | null | """
Since the final test is open-notes, I've made this script to combine all course notes into one html
file, so I can ctrl+F without needing to find which chapter some definition is from.
"""
import binascii
import os
import re
import secrets
from pathlib import Path
import requests
def write(file: str, text: str) -> None:
"""
Write text to a file
:param file: File path
:param text: Text
:return: None
"""
if '/' in file:
Path(file).parent.mkdir(parents=True, exist_ok=True)
with open(file, 'w', encoding='utf-8') as f:
f.write(text)
def read(file: str) -> str:
"""
Read file content
:param file: File path (will be converted to lowercase)
:return: None
"""
with open(file, 'r', encoding='utf-8') as f:
return f.read()
def get(url: str) -> str:
req = requests.get(url)
req.encoding = req.apparent_encoding
return req.text
if __name__ == '__main__':
host = 'https://www.teach.cs.toronto.edu'
baseurl = f'{host}/~csc110y/fall/notes/'
basedir = 'notes'
r = get(baseurl)
# Replace references
g: set[str] = set(re.findall('(?<=href=").*?(?=")', r))
for href in g:
url = href
filename = href.replace('~', '-')
if not (url.startswith('//') or url.startswith('http')):
if url.startswith('/'):
url = host + url
else:
url = baseurl + url
else:
filename = filename.split("//")[1]
if filename.endswith('/'):
filename += 'index.html'
r = r.replace(href, filename)
path = os.path.join(basedir, filename)
if os.path.isfile(path):
continue
content = get(url)
write(path, content)
write(os.path.join(basedir, 'index.html'), r)
# Create full file
r = re.sub('<[/]*(section|p).*?>', '', r)
r = r.replace('<a href="www.teach.cs.toronto.edu/-csc110y/fall/notes/index.html">CSC110 Course Notes Home</a>',
'{INJECT_HERE}')
links: list[str] = re.findall('<a.*?>.*?</a>', r)
for link in links:
uid = secrets.token_hex(5)
href: str = re.findall('(?<=href=").*?(?=")', link)[0]
anchor = '-'.join([i[:2] for i in href.split('/')])
html = read(os.path.join(basedir, href))
html = re.sub('<(!DOCTYPE|html|/html|body|/body).*?>', '', html)
html = re.sub('<(head|div style="display:none"|footer)>.*?</(head|div|footer)>', '', html,
flags=re.DOTALL)
# Replace IDs
ids = set(re.findall('(?<=id=").*?(?=")', html))
for id in ids:
html = html.replace(f'"{id}"', f'"{id}-{uid}"')
html = html.replace(f'"#{id}"', f'"#{id}-{uid}"')
if '<section>' in html and '</section>' not in html:
html += '</section>'
# Download images
g: set[str] = set(re.findall('(?<=src=").*?(?=")', html))
for src in g:
if src.startswith('//') or src.startswith('http'):
continue
path = os.path.join(basedir, src)
# if os.path.isfile(path):
# continue
if src.startswith('/'):
url = host + src
else:
url = baseurl + f'{href.split("/")[-2]}/' + src
print(url)
img_data = requests.get(url).content
Path(path).parent.mkdir(parents=True, exist_ok=True)
with open(path, 'wb') as f:
f.write(img_data)
r = r.replace(link, f'<a id="anchor-{anchor}"></a>' + html)
# print(link.replace(href, f'#anchor-{anchor}'))
r = r.replace('{INJECT_HERE}', read('scrape-addon.html'))
write(os.path.join(basedir, 'full.html'), r)
| 29.107692 | 115 | 0.524577 | import binascii
import os
import re
import secrets
from pathlib import Path
import requests
def write(file: str, text: str) -> None:
if '/' in file:
Path(file).parent.mkdir(parents=True, exist_ok=True)
with open(file, 'w', encoding='utf-8') as f:
f.write(text)
def read(file: str) -> str:
with open(file, 'r', encoding='utf-8') as f:
return f.read()
def get(url: str) -> str:
req = requests.get(url)
req.encoding = req.apparent_encoding
return req.text
if __name__ == '__main__':
host = 'https://www.teach.cs.toronto.edu'
baseurl = f'{host}/~csc110y/fall/notes/'
basedir = 'notes'
r = get(baseurl)
g: set[str] = set(re.findall('(?<=href=").*?(?=")', r))
for href in g:
url = href
filename = href.replace('~', '-')
if not (url.startswith('//') or url.startswith('http')):
if url.startswith('/'):
url = host + url
else:
url = baseurl + url
else:
filename = filename.split("//")[1]
if filename.endswith('/'):
filename += 'index.html'
r = r.replace(href, filename)
path = os.path.join(basedir, filename)
if os.path.isfile(path):
continue
content = get(url)
write(path, content)
write(os.path.join(basedir, 'index.html'), r)
r = re.sub('<[/]*(section|p).*?>', '', r)
r = r.replace('<a href="www.teach.cs.toronto.edu/-csc110y/fall/notes/index.html">CSC110 Course Notes Home</a>',
'{INJECT_HERE}')
links: list[str] = re.findall('<a.*?>.*?</a>', r)
for link in links:
uid = secrets.token_hex(5)
href: str = re.findall('(?<=href=").*?(?=")', link)[0]
anchor = '-'.join([i[:2] for i in href.split('/')])
html = read(os.path.join(basedir, href))
html = re.sub('<(!DOCTYPE|html|/html|body|/body).*?>', '', html)
html = re.sub('<(head|div style="display:none"|footer)>.*?</(head|div|footer)>', '', html,
flags=re.DOTALL)
ids = set(re.findall('(?<=id=").*?(?=")', html))
for id in ids:
html = html.replace(f'"{id}"', f'"{id}-{uid}"')
html = html.replace(f'"#{id}"', f'"#{id}-{uid}"')
if '<section>' in html and '</section>' not in html:
html += '</section>'
g: set[str] = set(re.findall('(?<=src=").*?(?=")', html))
for src in g:
if src.startswith('//') or src.startswith('http'):
continue
path = os.path.join(basedir, src)
if src.startswith('/'):
url = host + src
else:
url = baseurl + f'{href.split("/")[-2]}/' + src
print(url)
img_data = requests.get(url).content
Path(path).parent.mkdir(parents=True, exist_ok=True)
with open(path, 'wb') as f:
f.write(img_data)
r = r.replace(link, f'<a id="anchor-{anchor}"></a>' + html)
r = r.replace('{INJECT_HERE}', read('scrape-addon.html'))
write(os.path.join(basedir, 'full.html'), r)
| true | true |
1c36bde0449b4db12177a90b53aa97e67068eccf | 1,476 | py | Python | tests/test_main.py | flamusdiu/flask-mistune | 03ca85e652c40afc77017c9856488b3a9aff9611 | [
"MIT"
] | 2 | 2021-04-12T22:54:51.000Z | 2021-04-13T01:48:56.000Z | tests/test_main.py | flamusdiu/flask-mistune | 03ca85e652c40afc77017c9856488b3a9aff9611 | [
"MIT"
] | null | null | null | tests/test_main.py | flamusdiu/flask-mistune | 03ca85e652c40afc77017c9856488b3a9aff9611 | [
"MIT"
] | null | null | null | """Run all pytests for application."""
import pytest
from flask import Flask, Markup, render_template_string
from flask_mistune import Mistune, markdown
@pytest.fixture()
def client():
"""Configure Flask App.
Flask app is a dummy application to test filters for this module.
"""
app = Flask(__name__)
app.config['TESTING'] = True
Mistune(app)
@app.route('/test')
def markdown_template_filter():
text = '~~testing markdown filter~~ *test*'
return render_template_string('{{ text|markdown }}', text=text)
@app.route('/test2')
def markdown_template_block():
test = '*test*'
text = '{% filter markdown %}{{ test }}{% endfilter %}'
return render_template_string(text, test=test)
with app.test_client() as client:
yield client
def test_render_template_filter(client):
"""Test template filtering."""
resp = client.get('/test')
assert resp.data.decode('utf-8') == (
'<p><del>testing markdown filter</del> ' '<em>test</em></p>\n'
)
def test_render_template_block(client):
"""Test template block."""
resp = client.get('/test2')
print(resp.data)
assert resp.data.decode('utf-8') == u'<p><em>test</em></p>\n'
def test_markdown_function(client):
"""Test markdown rendering from a string."""
string = 'this is a *markdown* string'
assert markdown.render(string) == Markup(
'<p>this is a <em>markdown</em> string</p>\n'
)
| 27.333333 | 71 | 0.636179 | import pytest
from flask import Flask, Markup, render_template_string
from flask_mistune import Mistune, markdown
@pytest.fixture()
def client():
app = Flask(__name__)
app.config['TESTING'] = True
Mistune(app)
@app.route('/test')
def markdown_template_filter():
text = '~~testing markdown filter~~ *test*'
return render_template_string('{{ text|markdown }}', text=text)
@app.route('/test2')
def markdown_template_block():
test = '*test*'
text = '{% filter markdown %}{{ test }}{% endfilter %}'
return render_template_string(text, test=test)
with app.test_client() as client:
yield client
def test_render_template_filter(client):
resp = client.get('/test')
assert resp.data.decode('utf-8') == (
'<p><del>testing markdown filter</del> ' '<em>test</em></p>\n'
)
def test_render_template_block(client):
resp = client.get('/test2')
print(resp.data)
assert resp.data.decode('utf-8') == u'<p><em>test</em></p>\n'
def test_markdown_function(client):
string = 'this is a *markdown* string'
assert markdown.render(string) == Markup(
'<p>this is a <em>markdown</em> string</p>\n'
)
| true | true |
1c36be35e2dfbcbfdb318f1e3be0e093253ac663 | 456 | py | Python | Scripts/pip3-script.py | JYurgie/DeepLabV3Tuned | d8fb59e5d67f9b4d1d2cff37acb1d22ac9ab1b47 | [
"MIT"
] | null | null | null | Scripts/pip3-script.py | JYurgie/DeepLabV3Tuned | d8fb59e5d67f9b4d1d2cff37acb1d22ac9ab1b47 | [
"MIT"
] | null | null | null | Scripts/pip3-script.py | JYurgie/DeepLabV3Tuned | d8fb59e5d67f9b4d1d2cff37acb1d22ac9ab1b47 | [
"MIT"
] | null | null | null | #!"C:\Users\JYurgelon\OneDrive - Leland Stanford Junior University\CS230\DeepLabV3Tuned\Scripts\python.exe"
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==19.0.3','console_scripts','pip3'
__requires__ = 'pip==19.0.3'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('pip==19.0.3', 'console_scripts', 'pip3')()
)
| 35.076923 | 107 | 0.684211 |
__requires__ = 'pip==19.0.3'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('pip==19.0.3', 'console_scripts', 'pip3')()
)
| true | true |
1c36bf389af9854bc6ee9434ee5721ccf5bcf634 | 16,479 | py | Python | python/plugins/processing/gui/AlgorithmDialog.py | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | null | null | null | python/plugins/processing/gui/AlgorithmDialog.py | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | null | null | null | python/plugins/processing/gui/AlgorithmDialog.py | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | 1 | 2021-12-25T08:40:30.000Z | 2021-12-25T08:40:30.000Z | # -*- coding: utf-8 -*-
"""
***************************************************************************
AlgorithmDialog.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""
__author__ = 'Victor Olaya'
__date__ = 'August 2012'
__copyright__ = '(C) 2012, Victor Olaya'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '176c06ceefb5f555205e72b20c962740cc0ec183'
import os
from pprint import pformat
import time
from qgis.PyQt.QtCore import QCoreApplication, Qt
from qgis.PyQt.QtWidgets import QMessageBox, QPushButton, QSizePolicy, QDialogButtonBox
from qgis.PyQt.QtGui import QColor, QPalette
from qgis.core import (Qgis,
QgsProject,
QgsApplication,
QgsProcessingUtils,
QgsProcessingParameterDefinition,
QgsProcessingAlgRunnerTask,
QgsProcessingOutputHtml,
QgsProcessingParameterVectorDestination,
QgsProcessingOutputLayerDefinition,
QgsProcessingParameterFeatureSink,
QgsProcessingParameterRasterDestination,
QgsProcessingAlgorithm,
QgsProcessingParameters,
QgsProxyProgressTask,
QgsTaskManager)
from qgis.gui import (QgsGui,
QgsMessageBar,
QgsProcessingAlgorithmDialogBase)
from qgis.utils import iface
from processing.core.ProcessingLog import ProcessingLog
from processing.core.ProcessingConfig import ProcessingConfig
from processing.core.ProcessingResults import resultsList
from processing.gui.ParametersPanel import ParametersPanel
from processing.gui.BatchAlgorithmDialog import BatchAlgorithmDialog
from processing.gui.AlgorithmDialogBase import AlgorithmDialogBase
from processing.gui.AlgorithmExecutor import executeIterating, execute, execute_in_place
from processing.gui.Postprocessing import handleAlgorithmResults
from processing.gui.wrappers import WidgetWrapper
from processing.tools import dataobjects
class AlgorithmDialog(QgsProcessingAlgorithmDialogBase):
def __init__(self, alg, in_place=False, parent=None):
super().__init__(parent)
self.feedback_dialog = None
self.in_place = in_place
self.active_layer = None
self.context = None
self.feedback = None
self.setAlgorithm(alg)
self.setMainWidget(self.getParametersPanel(alg, self))
if not self.in_place:
self.runAsBatchButton = QPushButton(QCoreApplication.translate("AlgorithmDialog", "Run as Batch Process…"))
self.runAsBatchButton.clicked.connect(self.runAsBatch)
self.buttonBox().addButton(self.runAsBatchButton, QDialogButtonBox.ResetRole) # reset role to ensure left alignment
else:
self.active_layer = iface.activeLayer()
self.runAsBatchButton = None
has_selection = self.active_layer and (self.active_layer.selectedFeatureCount() > 0)
self.buttonBox().button(QDialogButtonBox.Ok).setText(QCoreApplication.translate("AlgorithmDialog", "Modify Selected Features")
if has_selection else QCoreApplication.translate("AlgorithmDialog", "Modify All Features"))
self.buttonBox().button(QDialogButtonBox.Close).setText(QCoreApplication.translate("AlgorithmDialog", "Cancel"))
self.setWindowTitle(self.windowTitle() + ' | ' + self.active_layer.name())
def getParametersPanel(self, alg, parent):
return ParametersPanel(parent, alg, self.in_place)
def runAsBatch(self):
self.close()
dlg = BatchAlgorithmDialog(self.algorithm().create(), parent=iface.mainWindow())
dlg.show()
dlg.exec_()
def setParameters(self, parameters):
self.mainWidget().setParameters(parameters)
def getParameterValues(self):
parameters = {}
if self.mainWidget() is None:
return parameters
for param in self.algorithm().parameterDefinitions():
if param.flags() & QgsProcessingParameterDefinition.FlagHidden:
continue
if not param.isDestination():
if self.in_place and param.name() == 'INPUT':
parameters[param.name()] = self.active_layer
continue
try:
wrapper = self.mainWidget().wrappers[param.name()]
except KeyError:
continue
# For compatibility with 3.x API, we need to check whether the wrapper is
# the deprecated WidgetWrapper class. If not, it's the newer
# QgsAbstractProcessingParameterWidgetWrapper class
# TODO QGIS 4.0 - remove
if issubclass(wrapper.__class__, WidgetWrapper):
widget = wrapper.widget
else:
widget = wrapper.wrappedWidget()
if widget is None:
continue
value = wrapper.parameterValue()
parameters[param.name()] = value
if not param.checkValueIsAcceptable(value):
raise AlgorithmDialogBase.InvalidParameterValue(param, widget)
else:
if self.in_place and param.name() == 'OUTPUT':
parameters[param.name()] = 'memory:'
continue
dest_project = None
if not param.flags() & QgsProcessingParameterDefinition.FlagHidden and \
isinstance(param, (QgsProcessingParameterRasterDestination,
QgsProcessingParameterFeatureSink,
QgsProcessingParameterVectorDestination)):
if self.mainWidget().checkBoxes[param.name()].isChecked():
dest_project = QgsProject.instance()
widget = self.mainWidget().outputWidgets[param.name()]
value = widget.getValue()
if value and isinstance(value, QgsProcessingOutputLayerDefinition):
value.destinationProject = dest_project
if value:
parameters[param.name()] = value
if param.isDestination():
context = dataobjects.createContext()
ok, error = self.algorithm().provider().isSupportedOutputValue(value, param, context)
if not ok:
raise AlgorithmDialogBase.InvalidOutputExtension(widget, error)
return self.algorithm().preprocessParameters(parameters)
def runAlgorithm(self):
self.feedback = self.createFeedback()
self.context = dataobjects.createContext(self.feedback)
checkCRS = ProcessingConfig.getSetting(ProcessingConfig.WARN_UNMATCHING_CRS)
try:
parameters = self.getParameterValues()
if checkCRS and not self.algorithm().validateInputCrs(parameters, self.context):
reply = QMessageBox.question(self, self.tr("Unmatching CRS's"),
self.tr('Parameters do not all use the same CRS. This can '
'cause unexpected results.\nDo you want to '
'continue?'),
QMessageBox.Yes | QMessageBox.No,
QMessageBox.No)
if reply == QMessageBox.No:
return
ok, msg = self.algorithm().checkParameterValues(parameters, self.context)
if not ok:
QMessageBox.warning(
self, self.tr('Unable to execute algorithm'), msg)
return
self.runButton().setEnabled(False)
self.cancelButton().setEnabled(False)
buttons = self.mainWidget().iterateButtons
self.iterateParam = None
for i in range(len(list(buttons.values()))):
button = list(buttons.values())[i]
if button.isChecked():
self.iterateParam = list(buttons.keys())[i]
break
self.clearProgress()
self.feedback.pushVersionInfo(self.algorithm().provider())
self.setProgressText(QCoreApplication.translate('AlgorithmDialog', 'Processing algorithm…'))
self.setInfo(
QCoreApplication.translate('AlgorithmDialog', '<b>Algorithm \'{0}\' starting…</b>').format(self.algorithm().displayName()), escapeHtml=False)
self.feedback.pushInfo(self.tr('Input parameters:'))
display_params = []
for k, v in parameters.items():
display_params.append("'" + k + "' : " + self.algorithm().parameterDefinition(k).valueAsPythonString(v, self.context))
self.feedback.pushCommandInfo('{ ' + ', '.join(display_params) + ' }')
self.feedback.pushInfo('')
start_time = time.time()
if self.iterateParam:
# Make sure the Log tab is visible before executing the algorithm
try:
self.showLog()
self.repaint()
except:
pass
self.cancelButton().setEnabled(self.algorithm().flags() & QgsProcessingAlgorithm.FlagCanCancel)
if executeIterating(self.algorithm(), parameters, self.iterateParam, self.context, self.feedback):
self.feedback.pushInfo(
self.tr('Execution completed in {0:0.2f} seconds').format(time.time() - start_time))
self.cancelButton().setEnabled(False)
self.finish(True, parameters, self.context, self.feedback)
else:
self.cancelButton().setEnabled(False)
self.resetGui()
else:
command = self.algorithm().asPythonCommand(parameters, self.context)
if command:
ProcessingLog.addToLog(command)
QgsGui.instance().processingRecentAlgorithmLog().push(self.algorithm().id())
self.cancelButton().setEnabled(self.algorithm().flags() & QgsProcessingAlgorithm.FlagCanCancel)
def on_complete(ok, results):
if ok:
self.feedback.pushInfo(self.tr('Execution completed in {0:0.2f} seconds').format(time.time() - start_time))
self.feedback.pushInfo(self.tr('Results:'))
self.feedback.pushCommandInfo(pformat(results))
else:
self.feedback.reportError(
self.tr('Execution failed after {0:0.2f} seconds').format(time.time() - start_time))
self.feedback.pushInfo('')
if self.feedback_dialog is not None:
self.feedback_dialog.close()
self.feedback_dialog.deleteLater()
self.feedback_dialog = None
self.cancelButton().setEnabled(False)
if not self.in_place:
self.finish(ok, results, self.context, self.feedback)
elif ok:
self.close()
self.feedback = None
self.context = None
if not self.in_place and not (self.algorithm().flags() & QgsProcessingAlgorithm.FlagNoThreading):
# Make sure the Log tab is visible before executing the algorithm
self.showLog()
task = QgsProcessingAlgRunnerTask(self.algorithm(), parameters, self.context, self.feedback)
if task.isCanceled():
on_complete(False, {})
else:
task.executed.connect(on_complete)
self.setCurrentTask(task)
else:
self.proxy_progress = QgsProxyProgressTask(QCoreApplication.translate("AlgorithmDialog", "Executing “{}”").format(self.algorithm().displayName()))
QgsApplication.taskManager().addTask(self.proxy_progress)
self.feedback.progressChanged.connect(self.proxy_progress.setProxyProgress)
self.feedback_dialog = self.createProgressDialog()
self.feedback_dialog.show()
if self.in_place:
ok, results = execute_in_place(self.algorithm(), parameters, self.context, self.feedback)
else:
ok, results = execute(self.algorithm(), parameters, self.context, self.feedback)
self.feedback.progressChanged.disconnect()
self.proxy_progress.finalize(ok)
on_complete(ok, results)
except AlgorithmDialogBase.InvalidParameterValue as e:
try:
self.buttonBox().accepted.connect(lambda e=e:
e.widget.setPalette(QPalette()))
palette = e.widget.palette()
palette.setColor(QPalette.Base, QColor(255, 255, 0))
e.widget.setPalette(palette)
except:
pass
self.messageBar().clearWidgets()
self.messageBar().pushMessage("", self.tr("Wrong or missing parameter value: {0}").format(e.parameter.description()),
level=Qgis.Warning, duration=5)
except AlgorithmDialogBase.InvalidOutputExtension as e:
try:
self.buttonBox().accepted.connect(lambda e=e:
e.widget.setPalette(QPalette()))
palette = e.widget.palette()
palette.setColor(QPalette.Base, QColor(255, 255, 0))
e.widget.setPalette(palette)
except:
pass
self.messageBar().clearWidgets()
self.messageBar().pushMessage("", e.message,
level=Qgis.Warning, duration=5)
def finish(self, successful, result, context, feedback):
keepOpen = not successful or ProcessingConfig.getSetting(ProcessingConfig.KEEP_DIALOG_OPEN)
if self.iterateParam is None:
# add html results to results dock
for out in self.algorithm().outputDefinitions():
if isinstance(out, QgsProcessingOutputHtml) and out.name() in result and result[out.name()]:
resultsList.addResult(icon=self.algorithm().icon(), name=out.description(), timestamp=time.localtime(),
result=result[out.name()])
if not handleAlgorithmResults(self.algorithm(), context, feedback, not keepOpen, result):
self.resetGui()
return
self.setExecuted(True)
self.setResults(result)
self.setInfo(self.tr('Algorithm \'{0}\' finished').format(self.algorithm().displayName()), escapeHtml=False)
if not keepOpen:
self.close()
else:
self.resetGui()
if self.algorithm().hasHtmlOutputs():
self.setInfo(
self.tr('HTML output has been generated by this algorithm.'
'\nOpen the results dialog to check it.'), escapeHtml=False)
| 47.627168 | 166 | 0.560228 |
__author__ = 'Victor Olaya'
__date__ = 'August 2012'
__copyright__ = '(C) 2012, Victor Olaya'
__revision__ = '176c06ceefb5f555205e72b20c962740cc0ec183'
import os
from pprint import pformat
import time
from qgis.PyQt.QtCore import QCoreApplication, Qt
from qgis.PyQt.QtWidgets import QMessageBox, QPushButton, QSizePolicy, QDialogButtonBox
from qgis.PyQt.QtGui import QColor, QPalette
from qgis.core import (Qgis,
QgsProject,
QgsApplication,
QgsProcessingUtils,
QgsProcessingParameterDefinition,
QgsProcessingAlgRunnerTask,
QgsProcessingOutputHtml,
QgsProcessingParameterVectorDestination,
QgsProcessingOutputLayerDefinition,
QgsProcessingParameterFeatureSink,
QgsProcessingParameterRasterDestination,
QgsProcessingAlgorithm,
QgsProcessingParameters,
QgsProxyProgressTask,
QgsTaskManager)
from qgis.gui import (QgsGui,
QgsMessageBar,
QgsProcessingAlgorithmDialogBase)
from qgis.utils import iface
from processing.core.ProcessingLog import ProcessingLog
from processing.core.ProcessingConfig import ProcessingConfig
from processing.core.ProcessingResults import resultsList
from processing.gui.ParametersPanel import ParametersPanel
from processing.gui.BatchAlgorithmDialog import BatchAlgorithmDialog
from processing.gui.AlgorithmDialogBase import AlgorithmDialogBase
from processing.gui.AlgorithmExecutor import executeIterating, execute, execute_in_place
from processing.gui.Postprocessing import handleAlgorithmResults
from processing.gui.wrappers import WidgetWrapper
from processing.tools import dataobjects
class AlgorithmDialog(QgsProcessingAlgorithmDialogBase):
def __init__(self, alg, in_place=False, parent=None):
super().__init__(parent)
self.feedback_dialog = None
self.in_place = in_place
self.active_layer = None
self.context = None
self.feedback = None
self.setAlgorithm(alg)
self.setMainWidget(self.getParametersPanel(alg, self))
if not self.in_place:
self.runAsBatchButton = QPushButton(QCoreApplication.translate("AlgorithmDialog", "Run as Batch Process…"))
self.runAsBatchButton.clicked.connect(self.runAsBatch)
self.buttonBox().addButton(self.runAsBatchButton, QDialogButtonBox.ResetRole)
else:
self.active_layer = iface.activeLayer()
self.runAsBatchButton = None
has_selection = self.active_layer and (self.active_layer.selectedFeatureCount() > 0)
self.buttonBox().button(QDialogButtonBox.Ok).setText(QCoreApplication.translate("AlgorithmDialog", "Modify Selected Features")
if has_selection else QCoreApplication.translate("AlgorithmDialog", "Modify All Features"))
self.buttonBox().button(QDialogButtonBox.Close).setText(QCoreApplication.translate("AlgorithmDialog", "Cancel"))
self.setWindowTitle(self.windowTitle() + ' | ' + self.active_layer.name())
def getParametersPanel(self, alg, parent):
return ParametersPanel(parent, alg, self.in_place)
def runAsBatch(self):
self.close()
dlg = BatchAlgorithmDialog(self.algorithm().create(), parent=iface.mainWindow())
dlg.show()
dlg.exec_()
def setParameters(self, parameters):
self.mainWidget().setParameters(parameters)
def getParameterValues(self):
parameters = {}
if self.mainWidget() is None:
return parameters
for param in self.algorithm().parameterDefinitions():
if param.flags() & QgsProcessingParameterDefinition.FlagHidden:
continue
if not param.isDestination():
if self.in_place and param.name() == 'INPUT':
parameters[param.name()] = self.active_layer
continue
try:
wrapper = self.mainWidget().wrappers[param.name()]
except KeyError:
continue
# QgsAbstractProcessingParameterWidgetWrapper class
# TODO QGIS 4.0 - remove
if issubclass(wrapper.__class__, WidgetWrapper):
widget = wrapper.widget
else:
widget = wrapper.wrappedWidget()
if widget is None:
continue
value = wrapper.parameterValue()
parameters[param.name()] = value
if not param.checkValueIsAcceptable(value):
raise AlgorithmDialogBase.InvalidParameterValue(param, widget)
else:
if self.in_place and param.name() == 'OUTPUT':
parameters[param.name()] = 'memory:'
continue
dest_project = None
if not param.flags() & QgsProcessingParameterDefinition.FlagHidden and \
isinstance(param, (QgsProcessingParameterRasterDestination,
QgsProcessingParameterFeatureSink,
QgsProcessingParameterVectorDestination)):
if self.mainWidget().checkBoxes[param.name()].isChecked():
dest_project = QgsProject.instance()
widget = self.mainWidget().outputWidgets[param.name()]
value = widget.getValue()
if value and isinstance(value, QgsProcessingOutputLayerDefinition):
value.destinationProject = dest_project
if value:
parameters[param.name()] = value
if param.isDestination():
context = dataobjects.createContext()
ok, error = self.algorithm().provider().isSupportedOutputValue(value, param, context)
if not ok:
raise AlgorithmDialogBase.InvalidOutputExtension(widget, error)
return self.algorithm().preprocessParameters(parameters)
def runAlgorithm(self):
self.feedback = self.createFeedback()
self.context = dataobjects.createContext(self.feedback)
checkCRS = ProcessingConfig.getSetting(ProcessingConfig.WARN_UNMATCHING_CRS)
try:
parameters = self.getParameterValues()
if checkCRS and not self.algorithm().validateInputCrs(parameters, self.context):
reply = QMessageBox.question(self, self.tr("Unmatching CRS's"),
self.tr('Parameters do not all use the same CRS. This can '
'cause unexpected results.\nDo you want to '
'continue?'),
QMessageBox.Yes | QMessageBox.No,
QMessageBox.No)
if reply == QMessageBox.No:
return
ok, msg = self.algorithm().checkParameterValues(parameters, self.context)
if not ok:
QMessageBox.warning(
self, self.tr('Unable to execute algorithm'), msg)
return
self.runButton().setEnabled(False)
self.cancelButton().setEnabled(False)
buttons = self.mainWidget().iterateButtons
self.iterateParam = None
for i in range(len(list(buttons.values()))):
button = list(buttons.values())[i]
if button.isChecked():
self.iterateParam = list(buttons.keys())[i]
break
self.clearProgress()
self.feedback.pushVersionInfo(self.algorithm().provider())
self.setProgressText(QCoreApplication.translate('AlgorithmDialog', 'Processing algorithm…'))
self.setInfo(
QCoreApplication.translate('AlgorithmDialog', '<b>Algorithm \'{0}\' starting…</b>').format(self.algorithm().displayName()), escapeHtml=False)
self.feedback.pushInfo(self.tr('Input parameters:'))
display_params = []
for k, v in parameters.items():
display_params.append("'" + k + "' : " + self.algorithm().parameterDefinition(k).valueAsPythonString(v, self.context))
self.feedback.pushCommandInfo('{ ' + ', '.join(display_params) + ' }')
self.feedback.pushInfo('')
start_time = time.time()
if self.iterateParam:
try:
self.showLog()
self.repaint()
except:
pass
self.cancelButton().setEnabled(self.algorithm().flags() & QgsProcessingAlgorithm.FlagCanCancel)
if executeIterating(self.algorithm(), parameters, self.iterateParam, self.context, self.feedback):
self.feedback.pushInfo(
self.tr('Execution completed in {0:0.2f} seconds').format(time.time() - start_time))
self.cancelButton().setEnabled(False)
self.finish(True, parameters, self.context, self.feedback)
else:
self.cancelButton().setEnabled(False)
self.resetGui()
else:
command = self.algorithm().asPythonCommand(parameters, self.context)
if command:
ProcessingLog.addToLog(command)
QgsGui.instance().processingRecentAlgorithmLog().push(self.algorithm().id())
self.cancelButton().setEnabled(self.algorithm().flags() & QgsProcessingAlgorithm.FlagCanCancel)
def on_complete(ok, results):
if ok:
self.feedback.pushInfo(self.tr('Execution completed in {0:0.2f} seconds').format(time.time() - start_time))
self.feedback.pushInfo(self.tr('Results:'))
self.feedback.pushCommandInfo(pformat(results))
else:
self.feedback.reportError(
self.tr('Execution failed after {0:0.2f} seconds').format(time.time() - start_time))
self.feedback.pushInfo('')
if self.feedback_dialog is not None:
self.feedback_dialog.close()
self.feedback_dialog.deleteLater()
self.feedback_dialog = None
self.cancelButton().setEnabled(False)
if not self.in_place:
self.finish(ok, results, self.context, self.feedback)
elif ok:
self.close()
self.feedback = None
self.context = None
if not self.in_place and not (self.algorithm().flags() & QgsProcessingAlgorithm.FlagNoThreading):
self.showLog()
task = QgsProcessingAlgRunnerTask(self.algorithm(), parameters, self.context, self.feedback)
if task.isCanceled():
on_complete(False, {})
else:
task.executed.connect(on_complete)
self.setCurrentTask(task)
else:
self.proxy_progress = QgsProxyProgressTask(QCoreApplication.translate("AlgorithmDialog", "Executing “{}”").format(self.algorithm().displayName()))
QgsApplication.taskManager().addTask(self.proxy_progress)
self.feedback.progressChanged.connect(self.proxy_progress.setProxyProgress)
self.feedback_dialog = self.createProgressDialog()
self.feedback_dialog.show()
if self.in_place:
ok, results = execute_in_place(self.algorithm(), parameters, self.context, self.feedback)
else:
ok, results = execute(self.algorithm(), parameters, self.context, self.feedback)
self.feedback.progressChanged.disconnect()
self.proxy_progress.finalize(ok)
on_complete(ok, results)
except AlgorithmDialogBase.InvalidParameterValue as e:
try:
self.buttonBox().accepted.connect(lambda e=e:
e.widget.setPalette(QPalette()))
palette = e.widget.palette()
palette.setColor(QPalette.Base, QColor(255, 255, 0))
e.widget.setPalette(palette)
except:
pass
self.messageBar().clearWidgets()
self.messageBar().pushMessage("", self.tr("Wrong or missing parameter value: {0}").format(e.parameter.description()),
level=Qgis.Warning, duration=5)
except AlgorithmDialogBase.InvalidOutputExtension as e:
try:
self.buttonBox().accepted.connect(lambda e=e:
e.widget.setPalette(QPalette()))
palette = e.widget.palette()
palette.setColor(QPalette.Base, QColor(255, 255, 0))
e.widget.setPalette(palette)
except:
pass
self.messageBar().clearWidgets()
self.messageBar().pushMessage("", e.message,
level=Qgis.Warning, duration=5)
def finish(self, successful, result, context, feedback):
keepOpen = not successful or ProcessingConfig.getSetting(ProcessingConfig.KEEP_DIALOG_OPEN)
if self.iterateParam is None:
for out in self.algorithm().outputDefinitions():
if isinstance(out, QgsProcessingOutputHtml) and out.name() in result and result[out.name()]:
resultsList.addResult(icon=self.algorithm().icon(), name=out.description(), timestamp=time.localtime(),
result=result[out.name()])
if not handleAlgorithmResults(self.algorithm(), context, feedback, not keepOpen, result):
self.resetGui()
return
self.setExecuted(True)
self.setResults(result)
self.setInfo(self.tr('Algorithm \'{0}\' finished').format(self.algorithm().displayName()), escapeHtml=False)
if not keepOpen:
self.close()
else:
self.resetGui()
if self.algorithm().hasHtmlOutputs():
self.setInfo(
self.tr('HTML output has been generated by this algorithm.'
'\nOpen the results dialog to check it.'), escapeHtml=False)
| true | true |
1c36bf7a60e081aeabe7db1765be81e2a21c2010 | 1,150 | py | Python | corehq/apps/reports/analytics/dbaccessors.py | rochakchauhan/commcare-hq | aa7ab3c2d0c51fe10f2b51b08101bb4b5a376236 | [
"BSD-3-Clause"
] | 1 | 2020-07-14T13:00:23.000Z | 2020-07-14T13:00:23.000Z | corehq/apps/reports/analytics/dbaccessors.py | rochakchauhan/commcare-hq | aa7ab3c2d0c51fe10f2b51b08101bb4b5a376236 | [
"BSD-3-Clause"
] | 1 | 2021-06-02T04:45:16.000Z | 2021-06-02T04:45:16.000Z | corehq/apps/reports/analytics/dbaccessors.py | rochakchauhan/commcare-hq | aa7ab3c2d0c51fe10f2b51b08101bb4b5a376236 | [
"BSD-3-Clause"
] | null | null | null | from __future__ import absolute_import, unicode_literals
from collections import defaultdict, namedtuple
from corehq.form_processor.interfaces.dbaccessors import LedgerAccessors
def get_wrapped_ledger_values(domain, case_ids, section_id, entry_ids=None):
if isinstance(case_ids, (list, tuple, set)):
case_ids_list = list(case_ids)
else:
case_ids_list = [case_ids]
return LedgerAccessors(domain).get_ledger_values_for_cases(case_ids_list, [section_id], entry_ids)
def products_with_ledgers(domain, case_ids, section_id, entry_ids=None):
return {
ledger.entry_id
for ledger in get_wrapped_ledger_values(domain, case_ids, section_id, entry_ids)
}
def get_aggregated_ledger_values(domain, case_ids, section_id, entry_ids=None):
ledgers = get_wrapped_ledger_values(domain, case_ids, section_id, entry_ids)
ret = defaultdict(lambda: 0)
for ledger in ledgers:
ret[ledger.entry_id] += ledger.balance
row_class = namedtuple('AggregateLedgerValue', ['entry_id', 'balance'])
return [
row_class(entry_id, balance)
for entry_id, balance in ret.items()
]
| 33.823529 | 102 | 0.744348 | from __future__ import absolute_import, unicode_literals
from collections import defaultdict, namedtuple
from corehq.form_processor.interfaces.dbaccessors import LedgerAccessors
def get_wrapped_ledger_values(domain, case_ids, section_id, entry_ids=None):
if isinstance(case_ids, (list, tuple, set)):
case_ids_list = list(case_ids)
else:
case_ids_list = [case_ids]
return LedgerAccessors(domain).get_ledger_values_for_cases(case_ids_list, [section_id], entry_ids)
def products_with_ledgers(domain, case_ids, section_id, entry_ids=None):
return {
ledger.entry_id
for ledger in get_wrapped_ledger_values(domain, case_ids, section_id, entry_ids)
}
def get_aggregated_ledger_values(domain, case_ids, section_id, entry_ids=None):
ledgers = get_wrapped_ledger_values(domain, case_ids, section_id, entry_ids)
ret = defaultdict(lambda: 0)
for ledger in ledgers:
ret[ledger.entry_id] += ledger.balance
row_class = namedtuple('AggregateLedgerValue', ['entry_id', 'balance'])
return [
row_class(entry_id, balance)
for entry_id, balance in ret.items()
]
| true | true |
1c36c04b4d50e33e5e4c27c3ff26f2975bfb9d8e | 2,159 | py | Python | sdks/python/apache_beam/examples/wordcount_test.py | cristicmf/beam | 317a8b50f46c37ce0af50a1b9cce2437253e42a7 | [
"Apache-2.0"
] | null | null | null | sdks/python/apache_beam/examples/wordcount_test.py | cristicmf/beam | 317a8b50f46c37ce0af50a1b9cce2437253e42a7 | [
"Apache-2.0"
] | 1 | 2022-02-10T06:28:03.000Z | 2022-02-10T06:28:03.000Z | sdks/python/apache_beam/examples/wordcount_test.py | cristicmf/beam | 317a8b50f46c37ce0af50a1b9cce2437253e42a7 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#
"""Test for the wordcount example."""
from __future__ import absolute_import
import collections
import logging
import re
import tempfile
import unittest
from apache_beam.examples import wordcount
from apache_beam.testing.util import open_shards
class WordCountTest(unittest.TestCase):
SAMPLE_TEXT = (
u'a b c a b a\nacento gráfico\nJuly 30, 2018\n\n aa bb cc aa bb aa')
def create_temp_file(self, contents):
with tempfile.NamedTemporaryFile(delete=False) as f:
f.write(contents.encode('utf-8'))
return f.name
def test_basics(self):
temp_path = self.create_temp_file(self.SAMPLE_TEXT)
expected_words = collections.defaultdict(int)
for word in re.findall(r'[\w\']+', self.SAMPLE_TEXT, re.UNICODE):
expected_words[word] += 1
wordcount.run([
'--input=%s*' % temp_path,
'--output=%s.result' % temp_path])
# Parse result file and compare.
results = []
with open_shards(temp_path + '.result-*-of-*') as result_file:
for line in result_file:
match = re.search(r'(\S+): ([0-9]+)', line.decode('utf-8'))
if match is not None:
results.append((match.group(1), int(match.group(2))))
self.assertEqual(sorted(results), sorted(expected_words.items()))
if __name__ == '__main__':
logging.getLogger().setLevel(logging.INFO)
unittest.main()
| 33.734375 | 74 | 0.71283 |
from __future__ import absolute_import
import collections
import logging
import re
import tempfile
import unittest
from apache_beam.examples import wordcount
from apache_beam.testing.util import open_shards
class WordCountTest(unittest.TestCase):
SAMPLE_TEXT = (
u'a b c a b a\nacento gráfico\nJuly 30, 2018\n\n aa bb cc aa bb aa')
def create_temp_file(self, contents):
with tempfile.NamedTemporaryFile(delete=False) as f:
f.write(contents.encode('utf-8'))
return f.name
def test_basics(self):
temp_path = self.create_temp_file(self.SAMPLE_TEXT)
expected_words = collections.defaultdict(int)
for word in re.findall(r'[\w\']+', self.SAMPLE_TEXT, re.UNICODE):
expected_words[word] += 1
wordcount.run([
'--input=%s*' % temp_path,
'--output=%s.result' % temp_path])
# Parse result file and compare.
results = []
with open_shards(temp_path + '.result-*-of-*') as result_file:
for line in result_file:
match = re.search(r'(\S+): ([0-9]+)', line.decode('utf-8'))
if match is not None:
results.append((match.group(1), int(match.group(2))))
self.assertEqual(sorted(results), sorted(expected_words.items()))
if __name__ == '__main__':
logging.getLogger().setLevel(logging.INFO)
unittest.main()
| true | true |
1c36c236bd0459f159c30bfecfd65ab15db40812 | 903 | py | Python | Desafio3/Cliente.py | bmortella/DesafioRedes | 20d6c23c8cd5171c0a8cffe6a4967d7dd2edd30d | [
"MIT"
] | null | null | null | Desafio3/Cliente.py | bmortella/DesafioRedes | 20d6c23c8cd5171c0a8cffe6a4967d7dd2edd30d | [
"MIT"
] | null | null | null | Desafio3/Cliente.py | bmortella/DesafioRedes | 20d6c23c8cd5171c0a8cffe6a4967d7dd2edd30d | [
"MIT"
] | null | null | null | import socket, threading #importa modulo socket
TCP_IP = '127.0.0.1' # endereço IP do servidor
TCP_PORTA = 24000 # porta disponibilizada pelo servidor
TAMANHO_BUFFER = 1024
NOME = input("Digite seu nome: ")
# Criação de socket TCP do cliente
cliente = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Conecta ao servidor em IP e porta especifica
cliente.connect((TCP_IP, TCP_PORTA))
print("Conectado! Digite quit para sair.")
class Receiver(threading.Thread):
def __init__(self, conn):
threading.Thread.__init__(self)
self.conn = conn
def run(self):
while True:
data, addr = self.conn.recvfrom(1024)
print(data.decode("UTF-8"))
Receiver(cliente).start()
while True:
msg = input(":> ")
cliente.send("{}: {}".format(NOME, msg).encode("UTF-8"))
if msg == "quit":
break
cliente.close()
print("Desconectado.")
| 23.763158 | 60 | 0.662237 | import socket, threading
TCP_IP = '127.0.0.1'
TCP_PORTA = 24000
TAMANHO_BUFFER = 1024
NOME = input("Digite seu nome: ")
cliente = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
cliente.connect((TCP_IP, TCP_PORTA))
print("Conectado! Digite quit para sair.")
class Receiver(threading.Thread):
def __init__(self, conn):
threading.Thread.__init__(self)
self.conn = conn
def run(self):
while True:
data, addr = self.conn.recvfrom(1024)
print(data.decode("UTF-8"))
Receiver(cliente).start()
while True:
msg = input(":> ")
cliente.send("{}: {}".format(NOME, msg).encode("UTF-8"))
if msg == "quit":
break
cliente.close()
print("Desconectado.")
| true | true |
1c36c2466bfa504402e3e68ef24b4c2c9b38218b | 13,125 | py | Python | fedn/fedn/clients/reducer/statestore/mongoreducerstatestore.py | eriks-aidotse/fedn | ab784e6ac45fd02be4532c9bbc8d5b8c75b62d51 | [
"Apache-2.0"
] | null | null | null | fedn/fedn/clients/reducer/statestore/mongoreducerstatestore.py | eriks-aidotse/fedn | ab784e6ac45fd02be4532c9bbc8d5b8c75b62d51 | [
"Apache-2.0"
] | null | null | null | fedn/fedn/clients/reducer/statestore/mongoreducerstatestore.py | eriks-aidotse/fedn | ab784e6ac45fd02be4532c9bbc8d5b8c75b62d51 | [
"Apache-2.0"
] | null | null | null | from fedn.clients.reducer.state import ReducerStateToString, StringToReducerState
from fedn.common.storage.db.mongo import connect_to_mongodb
from .reducerstatestore import ReducerStateStore
class MongoReducerStateStore(ReducerStateStore):
"""
"""
def __init__(self, network_id, config, defaults=None):
self.__inited = False
try:
self.config = config
self.network_id = network_id
self.mdb = connect_to_mongodb(self.config, self.network_id)
# FEDn network
self.network = self.mdb['network']
self.reducer = self.network['reducer']
self.combiners = self.network['combiners']
self.clients = self.network['clients']
self.storage = self.network['storage']
self.certificates = self.network['certificates']
# Control
self.control = self.mdb['control']
self.control_config = self.control['config']
self.state = self.control['state']
self.model = self.control['model']
self.round = self.control["round"]
# Logging and dashboards
self.status = self.control["status"]
self.round_time = self.control["round_time"]
self.psutil_monitoring = self.control["psutil_monitoring"]
self.combiner_round_time = self.control['combiner_round_time']
self.__inited = True
except Exception as e:
print("FAILED TO CONNECT TO MONGO, {}".format(e), flush=True)
self.state = None
self.model = None
self.control = None
self.network = None
self.combiners = None
self.clients = None
raise
import yaml
if defaults:
with open(defaults, 'r') as file:
try:
settings = dict(yaml.safe_load(file))
print(settings, flush=True)
# Control settings
if "control" in settings and settings["control"]:
control = settings['control']
try:
self.transition(str(control['state']))
except KeyError:
self.transition("idle")
if "model" in control:
if not self.get_latest():
self.set_latest(str(control['model']))
else:
print(
"Model trail already initialized - refusing to overwrite from config. Purge model trail if you want to reseed the system.",
flush=True)
if "context" in control:
print("Setting filepath to {}".format(control['context']), flush=True)
# TODO Fix the ugly latering of indirection due to a bug in secure_filename returning an object with filename as attribute
# TODO fix with unboxing of value before storing and where consuming.
self.control.config.update_one({'key': 'package'},
{'$set': {'filename': control['context']}}, True)
if "helper" in control:
# self.set_framework(control['helper'])
pass
round_config = {'timeout': 180, 'validate': True}
try:
round_config['timeout'] = control['timeout']
except:
pass
try:
round_config['validate'] = control['validate']
except:
pass
# Storage settings
self.set_storage_backend(settings['storage'])
self.__inited = True
except yaml.YAMLError as e:
print(e)
def is_inited(self):
"""
:return:
"""
return self.__inited
def get_config(self):
"""
:return:
"""
data = {
'type': 'MongoDB',
'mongo_config': self.config,
'network_id': self.network_id
}
return data
def state(self):
"""
:return:
"""
return StringToReducerState(self.state.find_one()['current_state'])
def transition(self, state):
"""
:param state:
:return:
"""
old_state = self.state.find_one({'state': 'current_state'})
if old_state != state:
return self.state.update_one({'state': 'current_state'}, {'$set': {'state': ReducerStateToString(state)}}, True)
else:
print("Not updating state, already in {}".format(ReducerStateToString(state)))
def set_latest(self, model_id):
"""
:param model_id:
"""
from datetime import datetime
x = self.model.update_one({'key': 'current_model'}, {'$set': {'model': model_id}}, True)
self.model.update_one({'key': 'model_trail'}, {'$push': {'model': model_id, 'committed_at': str(datetime.now())}},
True)
def get_first(self):
""" Return model_id for the latest model in the model_trail """
import pymongo
ret = self.model.find_one({'key': 'model_trail'}, sort=[("committed_at", pymongo.ASCENDING)])
if ret == None:
return None
try:
model_id = ret['model']
if model_id == '' or model_id == ' ': # ugly check for empty string
return None
return model_id
except (KeyError, IndexError):
return None
def get_latest(self):
""" Return model_id for the latest model in the model_trail """
ret = self.model.find_one({'key': 'current_model'})
if ret == None:
return None
try:
model_id = ret['model']
if model_id == '' or model_id == ' ': # ugly check for empty string
return None
return model_id
except (KeyError, IndexError):
return None
def set_round_config(self, config):
"""
:param config:
"""
from datetime import datetime
x = self.control.config.update_one({'key': 'round_config'}, {'$set': config}, True)
def get_round_config(self):
"""
:return:
"""
ret = self.control.config.find({'key': 'round_config'})
try:
retcheck = ret[0]
if retcheck == None or retcheck == '' or retcheck == ' ': # ugly check for empty string
return None
return retcheck
except (KeyError, IndexError):
return None
def set_compute_context(self, filename):
"""
:param filename:
"""
from datetime import datetime
x = self.control.config.update_one({'key': 'package'}, {'$set': {'filename': filename}}, True)
self.control.config.update_one({'key': 'package_trail'},
{'$push': {'filename': filename, 'committed_at': str(datetime.now())}}, True)
def get_compute_context(self):
"""
:return:
"""
ret = self.control.config.find({'key': 'package'})
try:
retcheck = ret[0]
if retcheck == None or retcheck == '' or retcheck == ' ': # ugly check for empty string
return None
return retcheck
except (KeyError, IndexError):
return None
def set_framework(self, helper):
"""
:param helper:
"""
self.control.config.update_one({'key': 'package'},
{'$set': {'helper': helper}}, True)
def get_framework(self):
"""
:return:
"""
ret = self.control.config.find_one({'key': 'package'})
#if local compute package used, then 'package' is None
if not ret:
#get framework from round_config instead
ret = self.control.config.find_one({'key': 'round_config'})
print('FRAMEWORK:', ret)
try:
retcheck = ret['helper']
if retcheck == '' or retcheck == ' ': # ugly check for empty string
return None
return retcheck
except (KeyError, IndexError):
return None
def get_model_info(self):
"""
:return:
"""
ret = self.model.find_one({'key': 'model_trail'})
try:
if ret:
committed_at = ret['committed_at']
model = ret['model']
model_dictionary = dict(zip(model, committed_at))
return model_dictionary
else:
return None
except (KeyError, IndexError):
return None
def get_events(self):
"""
:return:
"""
ret = self.control.status.find({})
return ret
def get_storage_backend(self):
""" """
try:
ret = self.storage.find({'status': 'enabled'}, projection={'_id': False})
return ret[0]
except (KeyError, IndexError):
return None
def set_storage_backend(self, config):
""" """
from datetime import datetime
import copy
config = copy.deepcopy(config)
config['updated_at'] = str(datetime.now())
config['status'] = 'enabled'
ret = self.storage.update_one({'storage_type': config['storage_type']}, {'$set': config}, True)
def set_reducer(self, reducer_data):
""" """
from datetime import datetime
reducer_data['updated_at'] = str(datetime.now())
ret = self.reducer.update_one({'name': reducer_data['name']}, {'$set': reducer_data}, True)
def get_reducer(self):
""" """
try:
ret = self.reducer.find_one()
return ret
except:
return None
def list_combiners(self):
""" """
try:
ret = self.combiners.find()
return list(ret)
except:
return None
def get_combiner(self, name):
""" """
try:
ret = self.combiners.find_one({'name': name})
return ret
except:
return None
def get_combiners(self):
""" """
try:
ret = self.combiners.find()
return list(ret)
except:
return None
def set_combiner(self, combiner_data):
"""
Set or update combiner record.
combiner_data: dictionary, output of combiner.to_dict())
"""
from datetime import datetime
combiner_data['updated_at'] = str(datetime.now())
ret = self.combiners.update_one({'name': combiner_data['name']}, {'$set': combiner_data}, True)
def delete_combiner(self, combiner):
""" """
try:
self.combiners.delete_one({'name': combiner})
except:
print("WARNING, failed to delete combiner: {}".format(combiner), flush=True)
def set_client(self, client_data):
"""
Set or update client record.
client_data: dictionarys
"""
from datetime import datetime
client_data['updated_at'] = str(datetime.now())
ret = self.clients.update_one({'name': client_data['name']}, {'$set': client_data}, True)
def get_client(self, name):
""" """
try:
ret = self.clients.find({'key': name})
if list(ret) == []:
return None
else:
return ret
except:
return None
def list_clients(self):
""" """
try:
ret = self.clients.find()
return list(ret)
except:
return None
def drop_control(self):
""" """
# Control
self.state.drop()
self.control_config.drop()
self.control.drop()
self.drop_models()
def drop_models(self):
""" """
self.model.drop()
self.combiner_round_time.drop()
self.status.drop()
self.psutil_monitoring.drop()
self.round_time.drop()
self.round.drop()
def update_client_status(self, client_data, status, role):
"""
Set or update client status.
assign roles to the active clients (trainer, validator, trainer-validator)
"""
self.clients.update_one({"name": client_data['name']},
{"$set":
{
"status": status,
"role": role
}
})
| 32.487624 | 159 | 0.500648 | from fedn.clients.reducer.state import ReducerStateToString, StringToReducerState
from fedn.common.storage.db.mongo import connect_to_mongodb
from .reducerstatestore import ReducerStateStore
class MongoReducerStateStore(ReducerStateStore):
def __init__(self, network_id, config, defaults=None):
self.__inited = False
try:
self.config = config
self.network_id = network_id
self.mdb = connect_to_mongodb(self.config, self.network_id)
self.network = self.mdb['network']
self.reducer = self.network['reducer']
self.combiners = self.network['combiners']
self.clients = self.network['clients']
self.storage = self.network['storage']
self.certificates = self.network['certificates']
self.control = self.mdb['control']
self.control_config = self.control['config']
self.state = self.control['state']
self.model = self.control['model']
self.round = self.control["round"]
self.status = self.control["status"]
self.round_time = self.control["round_time"]
self.psutil_monitoring = self.control["psutil_monitoring"]
self.combiner_round_time = self.control['combiner_round_time']
self.__inited = True
except Exception as e:
print("FAILED TO CONNECT TO MONGO, {}".format(e), flush=True)
self.state = None
self.model = None
self.control = None
self.network = None
self.combiners = None
self.clients = None
raise
import yaml
if defaults:
with open(defaults, 'r') as file:
try:
settings = dict(yaml.safe_load(file))
print(settings, flush=True)
if "control" in settings and settings["control"]:
control = settings['control']
try:
self.transition(str(control['state']))
except KeyError:
self.transition("idle")
if "model" in control:
if not self.get_latest():
self.set_latest(str(control['model']))
else:
print(
"Model trail already initialized - refusing to overwrite from config. Purge model trail if you want to reseed the system.",
flush=True)
if "context" in control:
print("Setting filepath to {}".format(control['context']), flush=True)
self.control.config.update_one({'key': 'package'},
{'$set': {'filename': control['context']}}, True)
if "helper" in control:
pass
round_config = {'timeout': 180, 'validate': True}
try:
round_config['timeout'] = control['timeout']
except:
pass
try:
round_config['validate'] = control['validate']
except:
pass
self.set_storage_backend(settings['storage'])
self.__inited = True
except yaml.YAMLError as e:
print(e)
def is_inited(self):
return self.__inited
def get_config(self):
data = {
'type': 'MongoDB',
'mongo_config': self.config,
'network_id': self.network_id
}
return data
def state(self):
return StringToReducerState(self.state.find_one()['current_state'])
def transition(self, state):
old_state = self.state.find_one({'state': 'current_state'})
if old_state != state:
return self.state.update_one({'state': 'current_state'}, {'$set': {'state': ReducerStateToString(state)}}, True)
else:
print("Not updating state, already in {}".format(ReducerStateToString(state)))
def set_latest(self, model_id):
from datetime import datetime
x = self.model.update_one({'key': 'current_model'}, {'$set': {'model': model_id}}, True)
self.model.update_one({'key': 'model_trail'}, {'$push': {'model': model_id, 'committed_at': str(datetime.now())}},
True)
def get_first(self):
import pymongo
ret = self.model.find_one({'key': 'model_trail'}, sort=[("committed_at", pymongo.ASCENDING)])
if ret == None:
return None
try:
model_id = ret['model']
if model_id == '' or model_id == ' ':
return None
return model_id
except (KeyError, IndexError):
return None
def get_latest(self):
ret = self.model.find_one({'key': 'current_model'})
if ret == None:
return None
try:
model_id = ret['model']
if model_id == '' or model_id == ' ':
return None
return model_id
except (KeyError, IndexError):
return None
def set_round_config(self, config):
from datetime import datetime
x = self.control.config.update_one({'key': 'round_config'}, {'$set': config}, True)
def get_round_config(self):
ret = self.control.config.find({'key': 'round_config'})
try:
retcheck = ret[0]
if retcheck == None or retcheck == '' or retcheck == ' ':
return None
return retcheck
except (KeyError, IndexError):
return None
def set_compute_context(self, filename):
from datetime import datetime
x = self.control.config.update_one({'key': 'package'}, {'$set': {'filename': filename}}, True)
self.control.config.update_one({'key': 'package_trail'},
{'$push': {'filename': filename, 'committed_at': str(datetime.now())}}, True)
def get_compute_context(self):
ret = self.control.config.find({'key': 'package'})
try:
retcheck = ret[0]
if retcheck == None or retcheck == '' or retcheck == ' ':
return None
return retcheck
except (KeyError, IndexError):
return None
def set_framework(self, helper):
self.control.config.update_one({'key': 'package'},
{'$set': {'helper': helper}}, True)
def get_framework(self):
ret = self.control.config.find_one({'key': 'package'})
if not ret:
ret = self.control.config.find_one({'key': 'round_config'})
print('FRAMEWORK:', ret)
try:
retcheck = ret['helper']
if retcheck == '' or retcheck == ' ':
return None
return retcheck
except (KeyError, IndexError):
return None
def get_model_info(self):
ret = self.model.find_one({'key': 'model_trail'})
try:
if ret:
committed_at = ret['committed_at']
model = ret['model']
model_dictionary = dict(zip(model, committed_at))
return model_dictionary
else:
return None
except (KeyError, IndexError):
return None
def get_events(self):
ret = self.control.status.find({})
return ret
def get_storage_backend(self):
try:
ret = self.storage.find({'status': 'enabled'}, projection={'_id': False})
return ret[0]
except (KeyError, IndexError):
return None
def set_storage_backend(self, config):
from datetime import datetime
import copy
config = copy.deepcopy(config)
config['updated_at'] = str(datetime.now())
config['status'] = 'enabled'
ret = self.storage.update_one({'storage_type': config['storage_type']}, {'$set': config}, True)
def set_reducer(self, reducer_data):
from datetime import datetime
reducer_data['updated_at'] = str(datetime.now())
ret = self.reducer.update_one({'name': reducer_data['name']}, {'$set': reducer_data}, True)
def get_reducer(self):
try:
ret = self.reducer.find_one()
return ret
except:
return None
def list_combiners(self):
try:
ret = self.combiners.find()
return list(ret)
except:
return None
def get_combiner(self, name):
try:
ret = self.combiners.find_one({'name': name})
return ret
except:
return None
def get_combiners(self):
try:
ret = self.combiners.find()
return list(ret)
except:
return None
def set_combiner(self, combiner_data):
from datetime import datetime
combiner_data['updated_at'] = str(datetime.now())
ret = self.combiners.update_one({'name': combiner_data['name']}, {'$set': combiner_data}, True)
def delete_combiner(self, combiner):
try:
self.combiners.delete_one({'name': combiner})
except:
print("WARNING, failed to delete combiner: {}".format(combiner), flush=True)
def set_client(self, client_data):
from datetime import datetime
client_data['updated_at'] = str(datetime.now())
ret = self.clients.update_one({'name': client_data['name']}, {'$set': client_data}, True)
def get_client(self, name):
try:
ret = self.clients.find({'key': name})
if list(ret) == []:
return None
else:
return ret
except:
return None
def list_clients(self):
try:
ret = self.clients.find()
return list(ret)
except:
return None
def drop_control(self):
self.state.drop()
self.control_config.drop()
self.control.drop()
self.drop_models()
def drop_models(self):
self.model.drop()
self.combiner_round_time.drop()
self.status.drop()
self.psutil_monitoring.drop()
self.round_time.drop()
self.round.drop()
def update_client_status(self, client_data, status, role):
self.clients.update_one({"name": client_data['name']},
{"$set":
{
"status": status,
"role": role
}
})
| true | true |
1c36c4a395c6a589601a4bb4837e93ec3c469347 | 7,105 | py | Python | pyzbar/wrapper.py | nmccann/pyzbar | dc2fcd0ba54bfcfff0eeea77080b1f225a6ca0e0 | [
"MIT"
] | null | null | null | pyzbar/wrapper.py | nmccann/pyzbar | dc2fcd0ba54bfcfff0eeea77080b1f225a6ca0e0 | [
"MIT"
] | null | null | null | pyzbar/wrapper.py | nmccann/pyzbar | dc2fcd0ba54bfcfff0eeea77080b1f225a6ca0e0 | [
"MIT"
] | null | null | null | """Low-level wrapper around zbar's interface
"""
from ctypes import (
c_ubyte, c_char_p, c_int, c_uint, c_ulong, c_void_p, Structure,
CFUNCTYPE, POINTER
)
from enum import IntEnum, unique
from . import zbar_library
__all__ = [
'EXTERNAL_DEPENDENCIES', 'LIBZBAR', 'ZBarConfig', 'ZBarSymbol',
'zbar_image_create', 'zbar_image_destroy', 'zbar_image_first_symbol',
'zbar_image_scanner_create', 'zbar_image_scanner_destroy',
'zbar_image_scanner_set_config', 'zbar_image_set_data',
'zbar_image_set_format', 'zbar_image_set_size', 'zbar_scan_image',
'zbar_symbol_get_data_length', 'zbar_symbol_get_data',
'zbar_symbol_get_loc_size', 'zbar_symbol_get_loc_x',
'zbar_symbol_get_loc_y', 'zbar_symbol_next'
]
# Globals populated in load_libzbar
LIBZBAR = None
"""ctypes.CDLL
"""
EXTERNAL_DEPENDENCIES = []
"""List of instances of ctypes.CDLL. Helpful when freezing.
"""
# Types
c_ubyte_p = POINTER(c_ubyte)
c_uint_p = POINTER(c_uint)
c_ulong_p = POINTER(c_ulong)
"""unsigned char* type
"""
# Defines and enums
@unique
class ZBarSymbol(IntEnum):
NONE = 0 # /**< no symbol decoded */
PARTIAL = 1 # /**< intermediate status */
EAN2 = 2 # /**< GS1 2-digit add-on */
EAN5 = 5 # /**< GS1 5-digit add-on */
EAN8 = 8 # /**< EAN-8 */
UPCE = 9 # /**< UPC-E */
ISBN10 = 10 # /**< ISBN-10 (from EAN-13). @since 0.4 */
UPCA = 12 # /**< UPC-A */
EAN13 = 13 # /**< EAN-13 */
ISBN13 = 14 # /**< ISBN-13 (from EAN-13). @since 0.4 */
COMPOSITE = 15 # /**< EAN/UPC composite */
I25 = 25 # /**< Interleaved 2 of 5. @since 0.4 */
DATABAR = 34 # /**< GS1 DataBar (RSS). @since 0.11 */
DATABAR_EXP = 35 # /**< GS1 DataBar Expanded. @since 0.11 */
CODABAR = 38 # /**< Codabar. @since 0.11 */
CODE39 = 39 # /**< Code 39. @since 0.4 */
PDF417 = 57 # /**< PDF417. @since 0.6 */
QRCODE = 64 # /**< QR Code. @since 0.10 */
CODE93 = 93 # /**< Code 93. @since 0.11 */
CODE128 = 128 # /**< Code 128 */
@unique
class ZBarConfig(IntEnum):
CFG_ENABLE = 0 # /**< enable symbology/feature */
CFG_ADD_CHECK = 1 # /**< enable check digit when optional */
CFG_EMIT_CHECK = 2 # /**< return check digit when present */
CFG_ASCII = 3 # /**< enable full ASCII character set */
CFG_BINARY = 4, # /**< don't convert binary data to text */
CFG_NUM = 5 # /**< number of boolean decoder configs */
CFG_MIN_LEN = 0x20 # /**< minimum data length for valid decode */
CFG_MAX_LEN = 0x21 # /**< maximum data length for valid decode */
CFG_UNCERTAINTY = 0x40 # /**< required video consistency frames */
CFG_POSITION = 0x80 # /**< enable scanner to collect position data */
CFG_TEST_INVERTED = 0x81 # /**< if fails to decode, test inverted * /
CFG_X_DENSITY = 0x100 # /**< image scanner vertical scan density */
CFG_Y_DENSITY = 0x101 # /**< image scanner horizontal scan density */
# Structs
class zbar_image_scanner(Structure):
"""Opaque C++ class with private implementation
"""
pass
class zbar_image(Structure):
"""Opaque C++ class with private implementation
"""
pass
class zbar_symbol(Structure):
"""Opaque C++ class with private implementation
The first item in the structure is an integeger value in the ZBarSymbol
enumeration.
"""
_fields_ = [
('type', c_int),
]
def load_libzbar():
"""Loads the zbar shared library and its dependencies.
Populates the globals LIBZBAR and EXTERNAL_DEPENDENCIES.
"""
global LIBZBAR
global EXTERNAL_DEPENDENCIES
if not LIBZBAR:
libzbar, dependencies = zbar_library.load()
LIBZBAR = libzbar
EXTERNAL_DEPENDENCIES = [LIBZBAR] + dependencies
return LIBZBAR
# Function signatures
def zbar_function(fname, restype, *args):
"""Returns a foreign function exported by `zbar`.
Args:
fname (:obj:`str`): Name of the exported function as string.
restype (:obj:): Return type - one of the `ctypes` primitive C data
types.
*args: Arguments - a sequence of `ctypes` primitive C data types.
Returns:
cddl.CFunctionType: A wrapper around the function.
"""
prototype = CFUNCTYPE(restype, *args)
return prototype((fname, load_libzbar()))
zbar_version = zbar_function(
'zbar_version',
c_int,
c_uint_p, # major,
c_uint_p, # minor
)
zbar_set_verbosity = zbar_function(
'zbar_set_verbosity',
None,
c_int
)
zbar_image_scanner_create = zbar_function(
'zbar_image_scanner_create',
POINTER(zbar_image_scanner)
)
zbar_image_scanner_destroy = zbar_function(
'zbar_image_scanner_destroy',
None,
POINTER(zbar_image_scanner)
)
zbar_parse_config = zbar_function(
'zbar_parse_config',
c_int,
c_char_p, # config_string,
POINTER(c_int), # symbology - values in ZBarSymbol
POINTER(c_int), # config - values in ZBarConfig
POINTER(c_int), # value
)
zbar_image_scanner_set_config = zbar_function(
'zbar_image_scanner_set_config',
c_int,
POINTER(zbar_image_scanner), # scanner
c_int, # symbology - values in ZBarSymbol
c_int, # config - values in ZBarConfig
c_int # value
)
zbar_image_create = zbar_function(
'zbar_image_create',
POINTER(zbar_image)
)
zbar_image_destroy = zbar_function(
'zbar_image_destroy',
None,
POINTER(zbar_image)
)
zbar_image_set_format = zbar_function(
'zbar_image_set_format',
None,
POINTER(zbar_image),
c_uint
)
zbar_image_set_size = zbar_function(
'zbar_image_set_size',
None,
POINTER(zbar_image),
c_uint, # width
c_uint # height
)
zbar_image_set_data = zbar_function(
'zbar_image_set_data',
None,
POINTER(zbar_image),
c_void_p, # data
c_ulong, # raw_image_data_length
c_void_p # A function pointer(!)
)
zbar_scan_image = zbar_function(
'zbar_scan_image',
c_int,
POINTER(zbar_image_scanner),
POINTER(zbar_image)
)
zbar_image_first_symbol = zbar_function(
'zbar_image_first_symbol',
POINTER(zbar_symbol),
POINTER(zbar_image)
)
zbar_symbol_get_data_length = zbar_function(
'zbar_symbol_get_data_length',
c_uint,
POINTER(zbar_symbol)
)
zbar_symbol_get_data = zbar_function(
'zbar_symbol_get_data',
c_ubyte_p,
POINTER(zbar_symbol)
)
zbar_symbol_get_loc_size = zbar_function(
'zbar_symbol_get_loc_size',
c_uint,
POINTER(zbar_symbol)
)
zbar_symbol_get_loc_x = zbar_function(
'zbar_symbol_get_loc_x',
c_int,
POINTER(zbar_symbol),
c_uint
)
zbar_symbol_get_loc_y = zbar_function(
'zbar_symbol_get_loc_y',
c_int,
POINTER(zbar_symbol),
c_uint
)
zbar_symbol_next = zbar_function(
'zbar_symbol_next',
POINTER(zbar_symbol),
POINTER(zbar_symbol)
)
| 26.412639 | 79 | 0.63772 | from ctypes import (
c_ubyte, c_char_p, c_int, c_uint, c_ulong, c_void_p, Structure,
CFUNCTYPE, POINTER
)
from enum import IntEnum, unique
from . import zbar_library
__all__ = [
'EXTERNAL_DEPENDENCIES', 'LIBZBAR', 'ZBarConfig', 'ZBarSymbol',
'zbar_image_create', 'zbar_image_destroy', 'zbar_image_first_symbol',
'zbar_image_scanner_create', 'zbar_image_scanner_destroy',
'zbar_image_scanner_set_config', 'zbar_image_set_data',
'zbar_image_set_format', 'zbar_image_set_size', 'zbar_scan_image',
'zbar_symbol_get_data_length', 'zbar_symbol_get_data',
'zbar_symbol_get_loc_size', 'zbar_symbol_get_loc_x',
'zbar_symbol_get_loc_y', 'zbar_symbol_next'
]
LIBZBAR = None
EXTERNAL_DEPENDENCIES = []
c_ubyte_p = POINTER(c_ubyte)
c_uint_p = POINTER(c_uint)
c_ulong_p = POINTER(c_ulong)
@unique
class ZBarSymbol(IntEnum):
NONE = 0
PARTIAL = 1
EAN2 = 2
EAN5 = 5
EAN8 = 8
UPCE = 9
ISBN10 = 10
UPCA = 12
EAN13 = 13
ISBN13 = 14
COMPOSITE = 15
I25 = 25
DATABAR = 34
DATABAR_EXP = 35
CODABAR = 38
CODE39 = 39
PDF417 = 57
QRCODE = 64
CODE93 = 93
CODE128 = 128
@unique
class ZBarConfig(IntEnum):
CFG_ENABLE = 0
CFG_ADD_CHECK = 1
CFG_EMIT_CHECK = 2
CFG_ASCII = 3
CFG_BINARY = 4,
CFG_NUM = 5 # /**< number of boolean decoder configs */
CFG_MIN_LEN = 0x20 # /**< minimum data length for valid decode */
CFG_MAX_LEN = 0x21 # /**< maximum data length for valid decode */
CFG_UNCERTAINTY = 0x40 # /**< required video consistency frames */
CFG_POSITION = 0x80 # /**< enable scanner to collect position data */
CFG_TEST_INVERTED = 0x81 # /**< if fails to decode, test inverted * /
CFG_X_DENSITY = 0x100 # /**< image scanner vertical scan density */
CFG_Y_DENSITY = 0x101 # /**< image scanner horizontal scan density */
# Structs
class zbar_image_scanner(Structure):
pass
class zbar_image(Structure):
pass
class zbar_symbol(Structure):
_fields_ = [
('type', c_int),
]
def load_libzbar():
global LIBZBAR
global EXTERNAL_DEPENDENCIES
if not LIBZBAR:
libzbar, dependencies = zbar_library.load()
LIBZBAR = libzbar
EXTERNAL_DEPENDENCIES = [LIBZBAR] + dependencies
return LIBZBAR
# Function signatures
def zbar_function(fname, restype, *args):
prototype = CFUNCTYPE(restype, *args)
return prototype((fname, load_libzbar()))
zbar_version = zbar_function(
'zbar_version',
c_int,
c_uint_p, # major,
c_uint_p, # minor
)
zbar_set_verbosity = zbar_function(
'zbar_set_verbosity',
None,
c_int
)
zbar_image_scanner_create = zbar_function(
'zbar_image_scanner_create',
POINTER(zbar_image_scanner)
)
zbar_image_scanner_destroy = zbar_function(
'zbar_image_scanner_destroy',
None,
POINTER(zbar_image_scanner)
)
zbar_parse_config = zbar_function(
'zbar_parse_config',
c_int,
c_char_p, # config_string,
POINTER(c_int), # symbology - values in ZBarSymbol
POINTER(c_int), # config - values in ZBarConfig
POINTER(c_int), # value
)
zbar_image_scanner_set_config = zbar_function(
'zbar_image_scanner_set_config',
c_int,
POINTER(zbar_image_scanner), # scanner
c_int, # symbology - values in ZBarSymbol
c_int, # config - values in ZBarConfig
c_int # value
)
zbar_image_create = zbar_function(
'zbar_image_create',
POINTER(zbar_image)
)
zbar_image_destroy = zbar_function(
'zbar_image_destroy',
None,
POINTER(zbar_image)
)
zbar_image_set_format = zbar_function(
'zbar_image_set_format',
None,
POINTER(zbar_image),
c_uint
)
zbar_image_set_size = zbar_function(
'zbar_image_set_size',
None,
POINTER(zbar_image),
c_uint, # width
c_uint # height
)
zbar_image_set_data = zbar_function(
'zbar_image_set_data',
None,
POINTER(zbar_image),
c_void_p, # data
c_ulong, # raw_image_data_length
c_void_p # A function pointer(!)
)
zbar_scan_image = zbar_function(
'zbar_scan_image',
c_int,
POINTER(zbar_image_scanner),
POINTER(zbar_image)
)
zbar_image_first_symbol = zbar_function(
'zbar_image_first_symbol',
POINTER(zbar_symbol),
POINTER(zbar_image)
)
zbar_symbol_get_data_length = zbar_function(
'zbar_symbol_get_data_length',
c_uint,
POINTER(zbar_symbol)
)
zbar_symbol_get_data = zbar_function(
'zbar_symbol_get_data',
c_ubyte_p,
POINTER(zbar_symbol)
)
zbar_symbol_get_loc_size = zbar_function(
'zbar_symbol_get_loc_size',
c_uint,
POINTER(zbar_symbol)
)
zbar_symbol_get_loc_x = zbar_function(
'zbar_symbol_get_loc_x',
c_int,
POINTER(zbar_symbol),
c_uint
)
zbar_symbol_get_loc_y = zbar_function(
'zbar_symbol_get_loc_y',
c_int,
POINTER(zbar_symbol),
c_uint
)
zbar_symbol_next = zbar_function(
'zbar_symbol_next',
POINTER(zbar_symbol),
POINTER(zbar_symbol)
)
| true | true |
1c36c6ed65220131f69f502c9a2b505085085e10 | 12,354 | py | Python | accounts/views.py | hpanwar08/greatkart | 834ff9fabdbb9493f54bcfd5d23505831b4a66d2 | [
"MIT"
] | null | null | null | accounts/views.py | hpanwar08/greatkart | 834ff9fabdbb9493f54bcfd5d23505831b4a66d2 | [
"MIT"
] | null | null | null | accounts/views.py | hpanwar08/greatkart | 834ff9fabdbb9493f54bcfd5d23505831b4a66d2 | [
"MIT"
] | null | null | null | import logging
from urllib.parse import urlencode, urlparse
from django.contrib import auth
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.shortcuts import get_current_site
from django.core.mail import EmailMessage
from django.http import HttpRequest
from django.shortcuts import render, redirect, get_object_or_404
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from accounts.forms import RegistrationForm
from accounts.models import Account, UserProfile
from accounts.services import register_service
from cart.models import Cart, CartItem
from cart.views import _get_session_id
from order.models import Order, OrderItem
from accounts.forms import UserForm, UserProfileForm
logger = logging.getLogger(__file__)
def register(request: HttpRequest):
form = RegistrationForm()
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
email = form.cleaned_data['email']
phone_number = form.cleaned_data['phone_number']
password = form.cleaned_data['password']
user = register_service.create_inactive_account(first_name, last_name, email, phone_number, password)
user.save()
# Create a user profile
profile = UserProfile()
profile.user_id = user.id
profile.profile_picture = 'default/default-user.png'
profile.save()
current_site = get_current_site(request)
email_subject = 'Activate your account'
email_body = render_to_string('accounts/account_verification_email.html',
{
'user': user,
'domain': current_site,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': default_token_generator.make_token(user)
})
email_message = EmailMessage(email_subject, email_body, to=[user.email])
email_message.send()
logger.info('Verification email sent.')
base_url = reverse('accounts:login')
query_string = urlencode({
'command': 'validation',
'email': user.email
})
url = f"{base_url}?{query_string}"
return redirect(url)
context = {
'form': form
}
return render(request, 'accounts/register.html', context)
def login(request: HttpRequest):
if request.user.is_authenticated:
return redirect('accounts:dashboard')
if request.method == 'POST':
email = request.POST.get('email')
password = request.POST.get('password')
user = auth.authenticate(email=email, password=password)
if user:
# assign anonymous cart to user
try:
# get cart items and their variation in current session cart
cart = Cart.objects.get(cart_id=_get_session_id(request))
new_cart_items = cart.cart_items.all().prefetch_related('variations')
new_cart_item_variations = []
new_cart_items_ids = []
for new_cart_item in new_cart_items:
new_cart_item_variations.append(list(new_cart_item.variations.all()))
new_cart_items_ids.append(new_cart_item)
# get all the items from user's already existing cart
user_cart_items = CartItem.objects.filter(buyer=user).prefetch_related('variations')
existing_items = []
existing_item_ids = []
for user_cart_item in user_cart_items:
existing_items.append(list(user_cart_item.variations.all()))
existing_item_ids.append(user_cart_item)
# find if current cart item is in user's cart, if yes increment else assign user
for idx, item in enumerate(new_cart_item_variations):
if item in existing_items:
existing_id = existing_items.index(item)
existing_item = existing_item_ids[existing_id]
item = new_cart_items_ids[idx]
existing_item.quantity += item.quantity
existing_item.save()
else:
item = new_cart_items_ids[idx]
item.buyer = user
item.save()
except Cart.DoesNotExist:
logger.exception('Cart does not exists')
auth.login(request, user)
referer_url = request.META.get('HTTP_REFERER')
query = urlparse(referer_url).query
logger.info(f"Query {query} {referer_url}")
query_params = dict(q.split('=') for q in query.split('&') if q)
if 'next' in query_params:
return redirect(query_params['next'])
messages.success(request, 'You are logged in.')
return redirect('accounts:dashboard')
else:
messages.error(request, "Incorrect username or password")
return redirect('accounts:login')
return render(request, 'accounts/login.html')
@login_required
def logout(request: HttpRequest):
auth.logout(request)
messages.success(request, 'You are logged out. Login again!')
return redirect('accounts:login')
def activate(request: HttpRequest, uidb64: str, token: str):
user = None
try:
userid = urlsafe_base64_decode(uidb64).decode()
user = Account._default_manager.get(pk=userid)
except (ValueError, TypeError, OverflowError, Account.DoesNotExist) as e:
logger.exception('Error')
user = None
if user and default_token_generator.check_token(user, token):
user.is_active = True
user.save()
messages.success(request, 'Your account is activated')
logger.info('Account activated')
return redirect('accounts:login')
else:
messages.error(request, 'Invalid verification url!')
return redirect('accounts:register')
@login_required
def dashboard(request: HttpRequest):
orders = Order.objects.filter(user=request.user, is_ordered=True).order_by('-created_at')
orders_count = orders.count()
context = {
'orders_count': orders_count
}
return render(request, 'accounts/dashboard.html', context)
def forgot_password(request: HttpRequest):
if request.method == 'POST':
email = request.POST.get('email')
try:
user = Account.objects.get(email__exact=email)
# send password reset email
current_site = get_current_site(request)
email_subject = 'Reset your password'
email_body = render_to_string('accounts/reset_password_email.html',
{
'user': user,
'domain': current_site,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': default_token_generator.make_token(user)
})
email_message = EmailMessage(email_subject, email_body, to=[user.email])
email_message.send()
messages.success(request, 'Password reset email sent to your email.')
return redirect('accounts:login')
except Account.DoesNotExist as e:
messages.error(request, 'Account does not exist. Please check and type again')
return render(request, 'accounts/forgot_password.html')
def reset_password_validate(request: HttpRequest, uidb64: str, token: str):
user = None
try:
userid = urlsafe_base64_decode(uidb64).decode()
user = Account._default_manager.get(pk=userid)
print(user)
# return retype password form
except (ValueError, TypeError, OverflowError, Account.DoesNotExist) as e:
logger.exception('Error')
user = None
if user and default_token_generator.check_token(user, token):
request.session['uid'] = user.id
return render(request, 'accounts/reset_password.html')
messages.error(request, 'Invalid password reset link.')
return redirect("accounts:login")
def reset_password(request: HttpRequest):
if request.method == 'POST':
password = request.POST.get('password')
password1 = request.POST.get('password1')
if password == password1:
uid = request.session.get('uid')
if uid:
user = Account.objects.get(pk=uid)
user.set_password(password)
user.save()
del request.session['uid']
messages.success(request, 'Password successfully changed')
return redirect('accounts:login')
else:
messages.error(request, 'Invalid password reset request')
return redirect('accounts:forgot_password')
messages.error(request, 'Passwords did not match!')
return render(request, 'accounts/reset_password.html')
def my_orders(request: HttpRequest):
orders = Order.objects.filter(user=request.user, is_ordered=True).order_by('-created_at')
context = {
'orders': orders
}
return render(request, 'accounts/my_orders.html', context)
@login_required
def edit_profile(request: HttpRequest):
userprofile = get_object_or_404(UserProfile, user=request.user)
if request.method == 'POST':
user_form = UserForm(request.POST, instance=request.user)
profile_form = UserProfileForm(request.POST, request.FILES, instance=userprofile)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
messages.success(request, 'Your profile has been updated.')
return redirect('edit_profile')
else:
user_form = UserForm(instance=request.user)
profile_form = UserProfileForm(instance=userprofile)
context = {
'user_form': user_form,
'profile_form': profile_form,
'userprofile': userprofile,
}
return render(request, 'accounts/edit_profile.html', context)
@login_required
def change_password(request):
if request.method == 'POST':
current_password = request.POST['current_password']
new_password = request.POST['new_password']
confirm_password = request.POST['confirm_password']
user = Account.objects.get(username__exact=request.user.username)
if new_password == confirm_password:
success = user.check_password(current_password)
if success:
user.set_password(new_password)
user.save()
# auth.logout(request)
messages.success(request, 'Password updated successfully.')
return redirect('accounts:change_password')
else:
messages.error(request, 'Please enter valid current password')
return redirect('accounts:change_password')
else:
messages.error(request, 'Password does not match!')
return redirect('accounts:change_password')
return render(request, 'accounts/change_password.html')
@login_required
def order_detail(request, order_id):
order_detail = OrderItem.objects.filter(order__order_number=order_id)
order = Order.objects.get(order_number=order_id)
subtotal = 0
for i in order_detail:
subtotal += i.product_price * i.quantity
context = {
'order_detail': order_detail,
'order': order,
'subtotal': subtotal,
}
return render(request, 'accounts/order_detail.html', context)
| 38.012308 | 113 | 0.620366 | import logging
from urllib.parse import urlencode, urlparse
from django.contrib import auth
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.shortcuts import get_current_site
from django.core.mail import EmailMessage
from django.http import HttpRequest
from django.shortcuts import render, redirect, get_object_or_404
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from accounts.forms import RegistrationForm
from accounts.models import Account, UserProfile
from accounts.services import register_service
from cart.models import Cart, CartItem
from cart.views import _get_session_id
from order.models import Order, OrderItem
from accounts.forms import UserForm, UserProfileForm
logger = logging.getLogger(__file__)
def register(request: HttpRequest):
form = RegistrationForm()
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
email = form.cleaned_data['email']
phone_number = form.cleaned_data['phone_number']
password = form.cleaned_data['password']
user = register_service.create_inactive_account(first_name, last_name, email, phone_number, password)
user.save()
profile = UserProfile()
profile.user_id = user.id
profile.profile_picture = 'default/default-user.png'
profile.save()
current_site = get_current_site(request)
email_subject = 'Activate your account'
email_body = render_to_string('accounts/account_verification_email.html',
{
'user': user,
'domain': current_site,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': default_token_generator.make_token(user)
})
email_message = EmailMessage(email_subject, email_body, to=[user.email])
email_message.send()
logger.info('Verification email sent.')
base_url = reverse('accounts:login')
query_string = urlencode({
'command': 'validation',
'email': user.email
})
url = f"{base_url}?{query_string}"
return redirect(url)
context = {
'form': form
}
return render(request, 'accounts/register.html', context)
def login(request: HttpRequest):
if request.user.is_authenticated:
return redirect('accounts:dashboard')
if request.method == 'POST':
email = request.POST.get('email')
password = request.POST.get('password')
user = auth.authenticate(email=email, password=password)
if user:
try:
cart = Cart.objects.get(cart_id=_get_session_id(request))
new_cart_items = cart.cart_items.all().prefetch_related('variations')
new_cart_item_variations = []
new_cart_items_ids = []
for new_cart_item in new_cart_items:
new_cart_item_variations.append(list(new_cart_item.variations.all()))
new_cart_items_ids.append(new_cart_item)
user_cart_items = CartItem.objects.filter(buyer=user).prefetch_related('variations')
existing_items = []
existing_item_ids = []
for user_cart_item in user_cart_items:
existing_items.append(list(user_cart_item.variations.all()))
existing_item_ids.append(user_cart_item)
# find if current cart item is in user's cart, if yes increment else assign user
for idx, item in enumerate(new_cart_item_variations):
if item in existing_items:
existing_id = existing_items.index(item)
existing_item = existing_item_ids[existing_id]
item = new_cart_items_ids[idx]
existing_item.quantity += item.quantity
existing_item.save()
else:
item = new_cart_items_ids[idx]
item.buyer = user
item.save()
except Cart.DoesNotExist:
logger.exception('Cart does not exists')
auth.login(request, user)
referer_url = request.META.get('HTTP_REFERER')
query = urlparse(referer_url).query
logger.info(f"Query {query} {referer_url}")
query_params = dict(q.split('=') for q in query.split('&') if q)
if 'next' in query_params:
return redirect(query_params['next'])
messages.success(request, 'You are logged in.')
return redirect('accounts:dashboard')
else:
messages.error(request, "Incorrect username or password")
return redirect('accounts:login')
return render(request, 'accounts/login.html')
@login_required
def logout(request: HttpRequest):
auth.logout(request)
messages.success(request, 'You are logged out. Login again!')
return redirect('accounts:login')
def activate(request: HttpRequest, uidb64: str, token: str):
user = None
try:
userid = urlsafe_base64_decode(uidb64).decode()
user = Account._default_manager.get(pk=userid)
except (ValueError, TypeError, OverflowError, Account.DoesNotExist) as e:
logger.exception('Error')
user = None
if user and default_token_generator.check_token(user, token):
user.is_active = True
user.save()
messages.success(request, 'Your account is activated')
logger.info('Account activated')
return redirect('accounts:login')
else:
messages.error(request, 'Invalid verification url!')
return redirect('accounts:register')
@login_required
def dashboard(request: HttpRequest):
orders = Order.objects.filter(user=request.user, is_ordered=True).order_by('-created_at')
orders_count = orders.count()
context = {
'orders_count': orders_count
}
return render(request, 'accounts/dashboard.html', context)
def forgot_password(request: HttpRequest):
if request.method == 'POST':
email = request.POST.get('email')
try:
user = Account.objects.get(email__exact=email)
current_site = get_current_site(request)
email_subject = 'Reset your password'
email_body = render_to_string('accounts/reset_password_email.html',
{
'user': user,
'domain': current_site,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': default_token_generator.make_token(user)
})
email_message = EmailMessage(email_subject, email_body, to=[user.email])
email_message.send()
messages.success(request, 'Password reset email sent to your email.')
return redirect('accounts:login')
except Account.DoesNotExist as e:
messages.error(request, 'Account does not exist. Please check and type again')
return render(request, 'accounts/forgot_password.html')
def reset_password_validate(request: HttpRequest, uidb64: str, token: str):
user = None
try:
userid = urlsafe_base64_decode(uidb64).decode()
user = Account._default_manager.get(pk=userid)
print(user)
except (ValueError, TypeError, OverflowError, Account.DoesNotExist) as e:
logger.exception('Error')
user = None
if user and default_token_generator.check_token(user, token):
request.session['uid'] = user.id
return render(request, 'accounts/reset_password.html')
messages.error(request, 'Invalid password reset link.')
return redirect("accounts:login")
def reset_password(request: HttpRequest):
if request.method == 'POST':
password = request.POST.get('password')
password1 = request.POST.get('password1')
if password == password1:
uid = request.session.get('uid')
if uid:
user = Account.objects.get(pk=uid)
user.set_password(password)
user.save()
del request.session['uid']
messages.success(request, 'Password successfully changed')
return redirect('accounts:login')
else:
messages.error(request, 'Invalid password reset request')
return redirect('accounts:forgot_password')
messages.error(request, 'Passwords did not match!')
return render(request, 'accounts/reset_password.html')
def my_orders(request: HttpRequest):
orders = Order.objects.filter(user=request.user, is_ordered=True).order_by('-created_at')
context = {
'orders': orders
}
return render(request, 'accounts/my_orders.html', context)
@login_required
def edit_profile(request: HttpRequest):
userprofile = get_object_or_404(UserProfile, user=request.user)
if request.method == 'POST':
user_form = UserForm(request.POST, instance=request.user)
profile_form = UserProfileForm(request.POST, request.FILES, instance=userprofile)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
messages.success(request, 'Your profile has been updated.')
return redirect('edit_profile')
else:
user_form = UserForm(instance=request.user)
profile_form = UserProfileForm(instance=userprofile)
context = {
'user_form': user_form,
'profile_form': profile_form,
'userprofile': userprofile,
}
return render(request, 'accounts/edit_profile.html', context)
@login_required
def change_password(request):
if request.method == 'POST':
current_password = request.POST['current_password']
new_password = request.POST['new_password']
confirm_password = request.POST['confirm_password']
user = Account.objects.get(username__exact=request.user.username)
if new_password == confirm_password:
success = user.check_password(current_password)
if success:
user.set_password(new_password)
user.save()
messages.success(request, 'Password updated successfully.')
return redirect('accounts:change_password')
else:
messages.error(request, 'Please enter valid current password')
return redirect('accounts:change_password')
else:
messages.error(request, 'Password does not match!')
return redirect('accounts:change_password')
return render(request, 'accounts/change_password.html')
@login_required
def order_detail(request, order_id):
order_detail = OrderItem.objects.filter(order__order_number=order_id)
order = Order.objects.get(order_number=order_id)
subtotal = 0
for i in order_detail:
subtotal += i.product_price * i.quantity
context = {
'order_detail': order_detail,
'order': order,
'subtotal': subtotal,
}
return render(request, 'accounts/order_detail.html', context)
| true | true |
1c36c7e48c0c3d9ff4a6ece15e342d3ce4a853eb | 39,762 | py | Python | gen/JavaLexer.py | SadraGoudarzdashti/CompilerProject | a1a03422715c8582507dd35dece44dcacff3ae15 | [
"MIT"
] | null | null | null | gen/JavaLexer.py | SadraGoudarzdashti/CompilerProject | a1a03422715c8582507dd35dece44dcacff3ae15 | [
"MIT"
] | null | null | null | gen/JavaLexer.py | SadraGoudarzdashti/CompilerProject | a1a03422715c8582507dd35dece44dcacff3ae15 | [
"MIT"
] | null | null | null | # Generated from C:/compiler_project/CompilerProject\JavaLexer.g4 by ANTLR 4.9.1
from antlr4 import *
from io import StringIO
from typing.io import TextIO
import sys
def serializedATN():
with StringIO() as buf:
buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2q")
buf.write("\u03b3\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7")
buf.write("\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r")
buf.write("\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22\4\23")
buf.write("\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30")
buf.write("\4\31\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t\35\4\36")
buf.write("\t\36\4\37\t\37\4 \t \4!\t!\4\"\t\"\4#\t#\4$\t$\4%\t%")
buf.write("\4&\t&\4\'\t\'\4(\t(\4)\t)\4*\t*\4+\t+\4,\t,\4-\t-\4.")
buf.write("\t.\4/\t/\4\60\t\60\4\61\t\61\4\62\t\62\4\63\t\63\4\64")
buf.write("\t\64\4\65\t\65\4\66\t\66\4\67\t\67\48\t8\49\t9\4:\t:")
buf.write("\4;\t;\4<\t<\4=\t=\4>\t>\4?\t?\4@\t@\4A\tA\4B\tB\4C\t")
buf.write("C\4D\tD\4E\tE\4F\tF\4G\tG\4H\tH\4I\tI\4J\tJ\4K\tK\4L\t")
buf.write("L\4M\tM\4N\tN\4O\tO\4P\tP\4Q\tQ\4R\tR\4S\tS\4T\tT\4U\t")
buf.write("U\4V\tV\4W\tW\4X\tX\4Y\tY\4Z\tZ\4[\t[\4\\\t\\\4]\t]\4")
buf.write("^\t^\4_\t_\4`\t`\4a\ta\4b\tb\4c\tc\4d\td\4e\te\4f\tf\4")
buf.write("g\tg\4h\th\4i\ti\4j\tj\4k\tk\4l\tl\4m\tm\4n\tn\4o\to\4")
buf.write("p\tp\4q\tq\4r\tr\4s\ts\4t\tt\4u\tu\4v\tv\4w\tw\3\2\3\2")
buf.write("\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\3\3\3\3\3\3\3\3\3\3\3\3")
buf.write("\3\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\5\3\5\3\5\3\5\3\5")
buf.write("\3\5\3\6\3\6\3\6\3\6\3\6\3\7\3\7\3\7\3\7\3\7\3\b\3\b\3")
buf.write("\b\3\b\3\b\3\b\3\t\3\t\3\t\3\t\3\t\3\n\3\n\3\n\3\n\3\n")
buf.write("\3\n\3\13\3\13\3\13\3\13\3\13\3\13\3\f\3\f\3\f\3\f\3\f")
buf.write("\3\f\3\f\3\f\3\f\3\r\3\r\3\r\3\r\3\r\3\r\3\r\3\r\3\16")
buf.write("\3\16\3\16\3\17\3\17\3\17\3\17\3\17\3\17\3\17\3\20\3\20")
buf.write("\3\20\3\20\3\20\3\21\3\21\3\21\3\21\3\21\3\22\3\22\3\22")
buf.write("\3\22\3\22\3\22\3\22\3\22\3\23\3\23\3\23\3\23\3\23\3\23")
buf.write("\3\24\3\24\3\24\3\24\3\24\3\24\3\24\3\24\3\25\3\25\3\25")
buf.write("\3\25\3\25\3\25\3\26\3\26\3\26\3\26\3\27\3\27\3\27\3\30")
buf.write("\3\30\3\30\3\30\3\30\3\31\3\31\3\31\3\31\3\31\3\31\3\31")
buf.write("\3\31\3\31\3\31\3\31\3\32\3\32\3\32\3\32\3\32\3\32\3\32")
buf.write("\3\33\3\33\3\33\3\33\3\33\3\33\3\33\3\33\3\33\3\33\3\33")
buf.write("\3\34\3\34\3\34\3\34\3\35\3\35\3\35\3\35\3\35\3\35\3\35")
buf.write("\3\35\3\35\3\35\3\36\3\36\3\36\3\36\3\36\3\37\3\37\3\37")
buf.write("\3\37\3\37\3\37\3\37\3 \3 \3 \3 \3!\3!\3!\3!\3!\3!\3!")
buf.write("\3!\3\"\3\"\3\"\3\"\3\"\3\"\3\"\3\"\3#\3#\3#\3#\3#\3#")
buf.write("\3#\3#\3#\3#\3$\3$\3$\3$\3$\3$\3$\3%\3%\3%\3%\3%\3%\3")
buf.write("%\3&\3&\3&\3&\3&\3&\3\'\3\'\3\'\3\'\3\'\3\'\3\'\3(\3(")
buf.write("\3(\3(\3(\3(\3(\3(\3(\3)\3)\3)\3)\3)\3)\3*\3*\3*\3*\3")
buf.write("*\3*\3*\3+\3+\3+\3+\3+\3+\3+\3+\3+\3+\3+\3+\3+\3,\3,\3")
buf.write(",\3,\3,\3-\3-\3-\3-\3-\3-\3.\3.\3.\3.\3.\3.\3.\3/\3/\3")
buf.write("/\3/\3/\3/\3/\3/\3/\3/\3\60\3\60\3\60\3\60\3\61\3\61\3")
buf.write("\61\3\61\3\61\3\62\3\62\3\62\3\62\3\62\3\62\3\62\3\62")
buf.write("\3\62\3\63\3\63\3\63\3\63\3\63\3\63\3\64\3\64\3\64\5\64")
buf.write("\u0246\n\64\3\64\6\64\u0249\n\64\r\64\16\64\u024a\3\64")
buf.write("\5\64\u024e\n\64\5\64\u0250\n\64\3\64\5\64\u0253\n\64")
buf.write("\3\65\3\65\3\65\3\65\7\65\u0259\n\65\f\65\16\65\u025c")
buf.write("\13\65\3\65\5\65\u025f\n\65\3\65\5\65\u0262\n\65\3\66")
buf.write("\3\66\7\66\u0266\n\66\f\66\16\66\u0269\13\66\3\66\3\66")
buf.write("\7\66\u026d\n\66\f\66\16\66\u0270\13\66\3\66\5\66\u0273")
buf.write("\n\66\3\66\5\66\u0276\n\66\3\67\3\67\3\67\3\67\7\67\u027c")
buf.write("\n\67\f\67\16\67\u027f\13\67\3\67\5\67\u0282\n\67\3\67")
buf.write("\5\67\u0285\n\67\38\38\38\58\u028a\n8\38\38\58\u028e\n")
buf.write("8\38\58\u0291\n8\38\58\u0294\n8\38\38\38\58\u0299\n8\3")
buf.write("8\58\u029c\n8\58\u029e\n8\39\39\39\39\59\u02a4\n9\39\5")
buf.write("9\u02a7\n9\39\39\59\u02ab\n9\39\39\59\u02af\n9\39\39\5")
buf.write("9\u02b3\n9\3:\3:\3:\3:\3:\3:\3:\3:\3:\5:\u02be\n:\3;\3")
buf.write(";\3;\5;\u02c3\n;\3;\3;\3<\3<\3<\7<\u02ca\n<\f<\16<\u02cd")
buf.write("\13<\3<\3<\3=\3=\3=\3=\3=\3>\3>\3?\3?\3@\3@\3A\3A\3B\3")
buf.write("B\3C\3C\3D\3D\3E\3E\3F\3F\3G\3G\3H\3H\3I\3I\3J\3J\3K\3")
buf.write("K\3L\3L\3M\3M\3N\3N\3N\3O\3O\3O\3P\3P\3P\3Q\3Q\3Q\3R\3")
buf.write("R\3R\3S\3S\3S\3T\3T\3T\3U\3U\3U\3V\3V\3W\3W\3X\3X\3Y\3")
buf.write("Y\3Z\3Z\3[\3[\3\\\3\\\3]\3]\3^\3^\3^\3_\3_\3_\3`\3`\3")
buf.write("`\3a\3a\3a\3b\3b\3b\3c\3c\3c\3d\3d\3d\3e\3e\3e\3f\3f\3")
buf.write("f\3f\3g\3g\3g\3g\3h\3h\3h\3h\3h\3i\3i\3i\3j\3j\3j\3k\3")
buf.write("k\3l\3l\3l\3l\3m\6m\u0350\nm\rm\16m\u0351\3m\3m\3n\3n")
buf.write("\3n\3n\7n\u035a\nn\fn\16n\u035d\13n\3n\3n\3n\3n\3n\3o")
buf.write("\3o\3o\3o\7o\u0368\no\fo\16o\u036b\13o\3o\3o\3p\3p\7p")
buf.write("\u0371\np\fp\16p\u0374\13p\3q\3q\5q\u0378\nq\3q\3q\3r")
buf.write("\3r\3r\3r\5r\u0380\nr\3r\5r\u0383\nr\3r\3r\3r\6r\u0388")
buf.write("\nr\rr\16r\u0389\3r\3r\3r\3r\3r\5r\u0391\nr\3s\3s\3s\7")
buf.write("s\u0396\ns\fs\16s\u0399\13s\3s\5s\u039c\ns\3t\3t\3u\3")
buf.write("u\7u\u03a2\nu\fu\16u\u03a5\13u\3u\5u\u03a8\nu\3v\3v\5")
buf.write("v\u03ac\nv\3w\3w\3w\3w\5w\u03b2\nw\3\u035b\2x\3\3\5\4")
buf.write("\7\5\t\6\13\7\r\b\17\t\21\n\23\13\25\f\27\r\31\16\33\17")
buf.write("\35\20\37\21!\22#\23%\24\'\25)\26+\27-\30/\31\61\32\63")
buf.write("\33\65\34\67\359\36;\37= ?!A\"C#E$G%I&K\'M(O)Q*S+U,W-")
buf.write("Y.[/]\60_\61a\62c\63e\64g\65i\66k\67m8o9q:s;u<w=y>{?}")
buf.write("@\177A\u0081B\u0083C\u0085D\u0087E\u0089F\u008bG\u008d")
buf.write("H\u008fI\u0091J\u0093K\u0095L\u0097M\u0099N\u009bO\u009d")
buf.write("P\u009fQ\u00a1R\u00a3S\u00a5T\u00a7U\u00a9V\u00abW\u00ad")
buf.write("X\u00afY\u00b1Z\u00b3[\u00b5\\\u00b7]\u00b9^\u00bb_\u00bd")
buf.write("`\u00bfa\u00c1b\u00c3c\u00c5d\u00c7e\u00c9f\u00cbg\u00cd")
buf.write("h\u00cfi\u00d1j\u00d3k\u00d5l\u00d7m\u00d9n\u00dbo\u00dd")
buf.write("p\u00dfq\u00e1\2\u00e3\2\u00e5\2\u00e7\2\u00e9\2\u00eb")
buf.write("\2\u00ed\2\3\2\34\3\2\63;\4\2NNnn\4\2ZZzz\5\2\62;CHch")
buf.write("\6\2\62;CHaach\3\2\629\4\2\629aa\4\2DDdd\3\2\62\63\4\2")
buf.write("\62\63aa\6\2FFHHffhh\4\2RRrr\4\2--//\6\2\f\f\17\17))^")
buf.write("^\6\2\f\f\17\17$$^^\5\2\13\f\16\17\"\"\4\2\f\f\17\17\4")
buf.write("\2GGgg\n\2$$))^^ddhhppttvv\3\2\62\65\3\2\62;\4\2\62;a")
buf.write("a\6\2&&C\\aac|\4\2\2\u0081\ud802\udc01\3\2\ud802\udc01")
buf.write("\3\2\udc02\ue001\2\u03dc\2\3\3\2\2\2\2\5\3\2\2\2\2\7\3")
buf.write("\2\2\2\2\t\3\2\2\2\2\13\3\2\2\2\2\r\3\2\2\2\2\17\3\2\2")
buf.write("\2\2\21\3\2\2\2\2\23\3\2\2\2\2\25\3\2\2\2\2\27\3\2\2\2")
buf.write("\2\31\3\2\2\2\2\33\3\2\2\2\2\35\3\2\2\2\2\37\3\2\2\2\2")
buf.write("!\3\2\2\2\2#\3\2\2\2\2%\3\2\2\2\2\'\3\2\2\2\2)\3\2\2\2")
buf.write("\2+\3\2\2\2\2-\3\2\2\2\2/\3\2\2\2\2\61\3\2\2\2\2\63\3")
buf.write("\2\2\2\2\65\3\2\2\2\2\67\3\2\2\2\29\3\2\2\2\2;\3\2\2\2")
buf.write("\2=\3\2\2\2\2?\3\2\2\2\2A\3\2\2\2\2C\3\2\2\2\2E\3\2\2")
buf.write("\2\2G\3\2\2\2\2I\3\2\2\2\2K\3\2\2\2\2M\3\2\2\2\2O\3\2")
buf.write("\2\2\2Q\3\2\2\2\2S\3\2\2\2\2U\3\2\2\2\2W\3\2\2\2\2Y\3")
buf.write("\2\2\2\2[\3\2\2\2\2]\3\2\2\2\2_\3\2\2\2\2a\3\2\2\2\2c")
buf.write("\3\2\2\2\2e\3\2\2\2\2g\3\2\2\2\2i\3\2\2\2\2k\3\2\2\2\2")
buf.write("m\3\2\2\2\2o\3\2\2\2\2q\3\2\2\2\2s\3\2\2\2\2u\3\2\2\2")
buf.write("\2w\3\2\2\2\2y\3\2\2\2\2{\3\2\2\2\2}\3\2\2\2\2\177\3\2")
buf.write("\2\2\2\u0081\3\2\2\2\2\u0083\3\2\2\2\2\u0085\3\2\2\2\2")
buf.write("\u0087\3\2\2\2\2\u0089\3\2\2\2\2\u008b\3\2\2\2\2\u008d")
buf.write("\3\2\2\2\2\u008f\3\2\2\2\2\u0091\3\2\2\2\2\u0093\3\2\2")
buf.write("\2\2\u0095\3\2\2\2\2\u0097\3\2\2\2\2\u0099\3\2\2\2\2\u009b")
buf.write("\3\2\2\2\2\u009d\3\2\2\2\2\u009f\3\2\2\2\2\u00a1\3\2\2")
buf.write("\2\2\u00a3\3\2\2\2\2\u00a5\3\2\2\2\2\u00a7\3\2\2\2\2\u00a9")
buf.write("\3\2\2\2\2\u00ab\3\2\2\2\2\u00ad\3\2\2\2\2\u00af\3\2\2")
buf.write("\2\2\u00b1\3\2\2\2\2\u00b3\3\2\2\2\2\u00b5\3\2\2\2\2\u00b7")
buf.write("\3\2\2\2\2\u00b9\3\2\2\2\2\u00bb\3\2\2\2\2\u00bd\3\2\2")
buf.write("\2\2\u00bf\3\2\2\2\2\u00c1\3\2\2\2\2\u00c3\3\2\2\2\2\u00c5")
buf.write("\3\2\2\2\2\u00c7\3\2\2\2\2\u00c9\3\2\2\2\2\u00cb\3\2\2")
buf.write("\2\2\u00cd\3\2\2\2\2\u00cf\3\2\2\2\2\u00d1\3\2\2\2\2\u00d3")
buf.write("\3\2\2\2\2\u00d5\3\2\2\2\2\u00d7\3\2\2\2\2\u00d9\3\2\2")
buf.write("\2\2\u00db\3\2\2\2\2\u00dd\3\2\2\2\2\u00df\3\2\2\2\3\u00ef")
buf.write("\3\2\2\2\5\u00f8\3\2\2\2\7\u00ff\3\2\2\2\t\u0107\3\2\2")
buf.write("\2\13\u010d\3\2\2\2\r\u0112\3\2\2\2\17\u0117\3\2\2\2\21")
buf.write("\u011d\3\2\2\2\23\u0122\3\2\2\2\25\u0128\3\2\2\2\27\u012e")
buf.write("\3\2\2\2\31\u0137\3\2\2\2\33\u013f\3\2\2\2\35\u0142\3")
buf.write("\2\2\2\37\u0149\3\2\2\2!\u014e\3\2\2\2#\u0153\3\2\2\2")
buf.write("%\u015b\3\2\2\2\'\u0161\3\2\2\2)\u0169\3\2\2\2+\u016f")
buf.write("\3\2\2\2-\u0173\3\2\2\2/\u0176\3\2\2\2\61\u017b\3\2\2")
buf.write("\2\63\u0186\3\2\2\2\65\u018d\3\2\2\2\67\u0198\3\2\2\2")
buf.write("9\u019c\3\2\2\2;\u01a6\3\2\2\2=\u01ab\3\2\2\2?\u01b2\3")
buf.write("\2\2\2A\u01b6\3\2\2\2C\u01be\3\2\2\2E\u01c6\3\2\2\2G\u01d0")
buf.write("\3\2\2\2I\u01d7\3\2\2\2K\u01de\3\2\2\2M\u01e4\3\2\2\2")
buf.write("O\u01eb\3\2\2\2Q\u01f4\3\2\2\2S\u01fa\3\2\2\2U\u0201\3")
buf.write("\2\2\2W\u020e\3\2\2\2Y\u0213\3\2\2\2[\u0219\3\2\2\2]\u0220")
buf.write("\3\2\2\2_\u022a\3\2\2\2a\u022e\3\2\2\2c\u0233\3\2\2\2")
buf.write("e\u023c\3\2\2\2g\u024f\3\2\2\2i\u0254\3\2\2\2k\u0263\3")
buf.write("\2\2\2m\u0277\3\2\2\2o\u029d\3\2\2\2q\u029f\3\2\2\2s\u02bd")
buf.write("\3\2\2\2u\u02bf\3\2\2\2w\u02c6\3\2\2\2y\u02d0\3\2\2\2")
buf.write("{\u02d5\3\2\2\2}\u02d7\3\2\2\2\177\u02d9\3\2\2\2\u0081")
buf.write("\u02db\3\2\2\2\u0083\u02dd\3\2\2\2\u0085\u02df\3\2\2\2")
buf.write("\u0087\u02e1\3\2\2\2\u0089\u02e3\3\2\2\2\u008b\u02e5\3")
buf.write("\2\2\2\u008d\u02e7\3\2\2\2\u008f\u02e9\3\2\2\2\u0091\u02eb")
buf.write("\3\2\2\2\u0093\u02ed\3\2\2\2\u0095\u02ef\3\2\2\2\u0097")
buf.write("\u02f1\3\2\2\2\u0099\u02f3\3\2\2\2\u009b\u02f5\3\2\2\2")
buf.write("\u009d\u02f8\3\2\2\2\u009f\u02fb\3\2\2\2\u00a1\u02fe\3")
buf.write("\2\2\2\u00a3\u0301\3\2\2\2\u00a5\u0304\3\2\2\2\u00a7\u0307")
buf.write("\3\2\2\2\u00a9\u030a\3\2\2\2\u00ab\u030d\3\2\2\2\u00ad")
buf.write("\u030f\3\2\2\2\u00af\u0311\3\2\2\2\u00b1\u0313\3\2\2\2")
buf.write("\u00b3\u0315\3\2\2\2\u00b5\u0317\3\2\2\2\u00b7\u0319\3")
buf.write("\2\2\2\u00b9\u031b\3\2\2\2\u00bb\u031d\3\2\2\2\u00bd\u0320")
buf.write("\3\2\2\2\u00bf\u0323\3\2\2\2\u00c1\u0326\3\2\2\2\u00c3")
buf.write("\u0329\3\2\2\2\u00c5\u032c\3\2\2\2\u00c7\u032f\3\2\2\2")
buf.write("\u00c9\u0332\3\2\2\2\u00cb\u0335\3\2\2\2\u00cd\u0339\3")
buf.write("\2\2\2\u00cf\u033d\3\2\2\2\u00d1\u0342\3\2\2\2\u00d3\u0345")
buf.write("\3\2\2\2\u00d5\u0348\3\2\2\2\u00d7\u034a\3\2\2\2\u00d9")
buf.write("\u034f\3\2\2\2\u00db\u0355\3\2\2\2\u00dd\u0363\3\2\2\2")
buf.write("\u00df\u036e\3\2\2\2\u00e1\u0375\3\2\2\2\u00e3\u0390\3")
buf.write("\2\2\2\u00e5\u0392\3\2\2\2\u00e7\u039d\3\2\2\2\u00e9\u039f")
buf.write("\3\2\2\2\u00eb\u03ab\3\2\2\2\u00ed\u03b1\3\2\2\2\u00ef")
buf.write("\u00f0\7c\2\2\u00f0\u00f1\7d\2\2\u00f1\u00f2\7u\2\2\u00f2")
buf.write("\u00f3\7v\2\2\u00f3\u00f4\7t\2\2\u00f4\u00f5\7c\2\2\u00f5")
buf.write("\u00f6\7e\2\2\u00f6\u00f7\7v\2\2\u00f7\4\3\2\2\2\u00f8")
buf.write("\u00f9\7c\2\2\u00f9\u00fa\7u\2\2\u00fa\u00fb\7u\2\2\u00fb")
buf.write("\u00fc\7g\2\2\u00fc\u00fd\7t\2\2\u00fd\u00fe\7v\2\2\u00fe")
buf.write("\6\3\2\2\2\u00ff\u0100\7d\2\2\u0100\u0101\7q\2\2\u0101")
buf.write("\u0102\7q\2\2\u0102\u0103\7n\2\2\u0103\u0104\7g\2\2\u0104")
buf.write("\u0105\7c\2\2\u0105\u0106\7p\2\2\u0106\b\3\2\2\2\u0107")
buf.write("\u0108\7d\2\2\u0108\u0109\7t\2\2\u0109\u010a\7g\2\2\u010a")
buf.write("\u010b\7c\2\2\u010b\u010c\7m\2\2\u010c\n\3\2\2\2\u010d")
buf.write("\u010e\7d\2\2\u010e\u010f\7{\2\2\u010f\u0110\7v\2\2\u0110")
buf.write("\u0111\7g\2\2\u0111\f\3\2\2\2\u0112\u0113\7e\2\2\u0113")
buf.write("\u0114\7c\2\2\u0114\u0115\7u\2\2\u0115\u0116\7g\2\2\u0116")
buf.write("\16\3\2\2\2\u0117\u0118\7e\2\2\u0118\u0119\7c\2\2\u0119")
buf.write("\u011a\7v\2\2\u011a\u011b\7e\2\2\u011b\u011c\7j\2\2\u011c")
buf.write("\20\3\2\2\2\u011d\u011e\7e\2\2\u011e\u011f\7j\2\2\u011f")
buf.write("\u0120\7c\2\2\u0120\u0121\7t\2\2\u0121\22\3\2\2\2\u0122")
buf.write("\u0123\7e\2\2\u0123\u0124\7n\2\2\u0124\u0125\7c\2\2\u0125")
buf.write("\u0126\7u\2\2\u0126\u0127\7u\2\2\u0127\24\3\2\2\2\u0128")
buf.write("\u0129\7e\2\2\u0129\u012a\7q\2\2\u012a\u012b\7p\2\2\u012b")
buf.write("\u012c\7u\2\2\u012c\u012d\7v\2\2\u012d\26\3\2\2\2\u012e")
buf.write("\u012f\7e\2\2\u012f\u0130\7q\2\2\u0130\u0131\7p\2\2\u0131")
buf.write("\u0132\7v\2\2\u0132\u0133\7k\2\2\u0133\u0134\7p\2\2\u0134")
buf.write("\u0135\7w\2\2\u0135\u0136\7g\2\2\u0136\30\3\2\2\2\u0137")
buf.write("\u0138\7f\2\2\u0138\u0139\7g\2\2\u0139\u013a\7h\2\2\u013a")
buf.write("\u013b\7c\2\2\u013b\u013c\7w\2\2\u013c\u013d\7n\2\2\u013d")
buf.write("\u013e\7v\2\2\u013e\32\3\2\2\2\u013f\u0140\7f\2\2\u0140")
buf.write("\u0141\7q\2\2\u0141\34\3\2\2\2\u0142\u0143\7f\2\2\u0143")
buf.write("\u0144\7q\2\2\u0144\u0145\7w\2\2\u0145\u0146\7d\2\2\u0146")
buf.write("\u0147\7n\2\2\u0147\u0148\7g\2\2\u0148\36\3\2\2\2\u0149")
buf.write("\u014a\7g\2\2\u014a\u014b\7n\2\2\u014b\u014c\7u\2\2\u014c")
buf.write("\u014d\7g\2\2\u014d \3\2\2\2\u014e\u014f\7g\2\2\u014f")
buf.write("\u0150\7p\2\2\u0150\u0151\7w\2\2\u0151\u0152\7o\2\2\u0152")
buf.write("\"\3\2\2\2\u0153\u0154\7g\2\2\u0154\u0155\7z\2\2\u0155")
buf.write("\u0156\7v\2\2\u0156\u0157\7g\2\2\u0157\u0158\7p\2\2\u0158")
buf.write("\u0159\7f\2\2\u0159\u015a\7u\2\2\u015a$\3\2\2\2\u015b")
buf.write("\u015c\7h\2\2\u015c\u015d\7k\2\2\u015d\u015e\7p\2\2\u015e")
buf.write("\u015f\7c\2\2\u015f\u0160\7n\2\2\u0160&\3\2\2\2\u0161")
buf.write("\u0162\7h\2\2\u0162\u0163\7k\2\2\u0163\u0164\7p\2\2\u0164")
buf.write("\u0165\7c\2\2\u0165\u0166\7n\2\2\u0166\u0167\7n\2\2\u0167")
buf.write("\u0168\7{\2\2\u0168(\3\2\2\2\u0169\u016a\7h\2\2\u016a")
buf.write("\u016b\7n\2\2\u016b\u016c\7q\2\2\u016c\u016d\7c\2\2\u016d")
buf.write("\u016e\7v\2\2\u016e*\3\2\2\2\u016f\u0170\7h\2\2\u0170")
buf.write("\u0171\7q\2\2\u0171\u0172\7t\2\2\u0172,\3\2\2\2\u0173")
buf.write("\u0174\7k\2\2\u0174\u0175\7h\2\2\u0175.\3\2\2\2\u0176")
buf.write("\u0177\7i\2\2\u0177\u0178\7q\2\2\u0178\u0179\7v\2\2\u0179")
buf.write("\u017a\7q\2\2\u017a\60\3\2\2\2\u017b\u017c\7k\2\2\u017c")
buf.write("\u017d\7o\2\2\u017d\u017e\7r\2\2\u017e\u017f\7n\2\2\u017f")
buf.write("\u0180\7g\2\2\u0180\u0181\7o\2\2\u0181\u0182\7g\2\2\u0182")
buf.write("\u0183\7p\2\2\u0183\u0184\7v\2\2\u0184\u0185\7u\2\2\u0185")
buf.write("\62\3\2\2\2\u0186\u0187\7k\2\2\u0187\u0188\7o\2\2\u0188")
buf.write("\u0189\7r\2\2\u0189\u018a\7q\2\2\u018a\u018b\7t\2\2\u018b")
buf.write("\u018c\7v\2\2\u018c\64\3\2\2\2\u018d\u018e\7k\2\2\u018e")
buf.write("\u018f\7p\2\2\u018f\u0190\7u\2\2\u0190\u0191\7v\2\2\u0191")
buf.write("\u0192\7c\2\2\u0192\u0193\7p\2\2\u0193\u0194\7e\2\2\u0194")
buf.write("\u0195\7g\2\2\u0195\u0196\7q\2\2\u0196\u0197\7h\2\2\u0197")
buf.write("\66\3\2\2\2\u0198\u0199\7k\2\2\u0199\u019a\7p\2\2\u019a")
buf.write("\u019b\7v\2\2\u019b8\3\2\2\2\u019c\u019d\7k\2\2\u019d")
buf.write("\u019e\7p\2\2\u019e\u019f\7v\2\2\u019f\u01a0\7g\2\2\u01a0")
buf.write("\u01a1\7t\2\2\u01a1\u01a2\7h\2\2\u01a2\u01a3\7c\2\2\u01a3")
buf.write("\u01a4\7e\2\2\u01a4\u01a5\7g\2\2\u01a5:\3\2\2\2\u01a6")
buf.write("\u01a7\7n\2\2\u01a7\u01a8\7q\2\2\u01a8\u01a9\7p\2\2\u01a9")
buf.write("\u01aa\7i\2\2\u01aa<\3\2\2\2\u01ab\u01ac\7p\2\2\u01ac")
buf.write("\u01ad\7c\2\2\u01ad\u01ae\7v\2\2\u01ae\u01af\7k\2\2\u01af")
buf.write("\u01b0\7x\2\2\u01b0\u01b1\7g\2\2\u01b1>\3\2\2\2\u01b2")
buf.write("\u01b3\7p\2\2\u01b3\u01b4\7g\2\2\u01b4\u01b5\7y\2\2\u01b5")
buf.write("@\3\2\2\2\u01b6\u01b7\7r\2\2\u01b7\u01b8\7c\2\2\u01b8")
buf.write("\u01b9\7e\2\2\u01b9\u01ba\7m\2\2\u01ba\u01bb\7c\2\2\u01bb")
buf.write("\u01bc\7i\2\2\u01bc\u01bd\7g\2\2\u01bdB\3\2\2\2\u01be")
buf.write("\u01bf\7r\2\2\u01bf\u01c0\7t\2\2\u01c0\u01c1\7k\2\2\u01c1")
buf.write("\u01c2\7x\2\2\u01c2\u01c3\7c\2\2\u01c3\u01c4\7v\2\2\u01c4")
buf.write("\u01c5\7g\2\2\u01c5D\3\2\2\2\u01c6\u01c7\7r\2\2\u01c7")
buf.write("\u01c8\7t\2\2\u01c8\u01c9\7q\2\2\u01c9\u01ca\7v\2\2\u01ca")
buf.write("\u01cb\7g\2\2\u01cb\u01cc\7e\2\2\u01cc\u01cd\7v\2\2\u01cd")
buf.write("\u01ce\7g\2\2\u01ce\u01cf\7f\2\2\u01cfF\3\2\2\2\u01d0")
buf.write("\u01d1\7r\2\2\u01d1\u01d2\7w\2\2\u01d2\u01d3\7d\2\2\u01d3")
buf.write("\u01d4\7n\2\2\u01d4\u01d5\7k\2\2\u01d5\u01d6\7e\2\2\u01d6")
buf.write("H\3\2\2\2\u01d7\u01d8\7t\2\2\u01d8\u01d9\7g\2\2\u01d9")
buf.write("\u01da\7v\2\2\u01da\u01db\7w\2\2\u01db\u01dc\7t\2\2\u01dc")
buf.write("\u01dd\7p\2\2\u01ddJ\3\2\2\2\u01de\u01df\7u\2\2\u01df")
buf.write("\u01e0\7j\2\2\u01e0\u01e1\7q\2\2\u01e1\u01e2\7t\2\2\u01e2")
buf.write("\u01e3\7v\2\2\u01e3L\3\2\2\2\u01e4\u01e5\7u\2\2\u01e5")
buf.write("\u01e6\7v\2\2\u01e6\u01e7\7c\2\2\u01e7\u01e8\7v\2\2\u01e8")
buf.write("\u01e9\7k\2\2\u01e9\u01ea\7e\2\2\u01eaN\3\2\2\2\u01eb")
buf.write("\u01ec\7u\2\2\u01ec\u01ed\7v\2\2\u01ed\u01ee\7t\2\2\u01ee")
buf.write("\u01ef\7k\2\2\u01ef\u01f0\7e\2\2\u01f0\u01f1\7v\2\2\u01f1")
buf.write("\u01f2\7h\2\2\u01f2\u01f3\7r\2\2\u01f3P\3\2\2\2\u01f4")
buf.write("\u01f5\7u\2\2\u01f5\u01f6\7w\2\2\u01f6\u01f7\7r\2\2\u01f7")
buf.write("\u01f8\7g\2\2\u01f8\u01f9\7t\2\2\u01f9R\3\2\2\2\u01fa")
buf.write("\u01fb\7u\2\2\u01fb\u01fc\7y\2\2\u01fc\u01fd\7k\2\2\u01fd")
buf.write("\u01fe\7v\2\2\u01fe\u01ff\7e\2\2\u01ff\u0200\7j\2\2\u0200")
buf.write("T\3\2\2\2\u0201\u0202\7u\2\2\u0202\u0203\7{\2\2\u0203")
buf.write("\u0204\7p\2\2\u0204\u0205\7e\2\2\u0205\u0206\7j\2\2\u0206")
buf.write("\u0207\7t\2\2\u0207\u0208\7q\2\2\u0208\u0209\7p\2\2\u0209")
buf.write("\u020a\7k\2\2\u020a\u020b\7|\2\2\u020b\u020c\7g\2\2\u020c")
buf.write("\u020d\7f\2\2\u020dV\3\2\2\2\u020e\u020f\7v\2\2\u020f")
buf.write("\u0210\7j\2\2\u0210\u0211\7k\2\2\u0211\u0212\7u\2\2\u0212")
buf.write("X\3\2\2\2\u0213\u0214\7v\2\2\u0214\u0215\7j\2\2\u0215")
buf.write("\u0216\7t\2\2\u0216\u0217\7q\2\2\u0217\u0218\7y\2\2\u0218")
buf.write("Z\3\2\2\2\u0219\u021a\7v\2\2\u021a\u021b\7j\2\2\u021b")
buf.write("\u021c\7t\2\2\u021c\u021d\7q\2\2\u021d\u021e\7y\2\2\u021e")
buf.write("\u021f\7u\2\2\u021f\\\3\2\2\2\u0220\u0221\7v\2\2\u0221")
buf.write("\u0222\7t\2\2\u0222\u0223\7c\2\2\u0223\u0224\7p\2\2\u0224")
buf.write("\u0225\7u\2\2\u0225\u0226\7k\2\2\u0226\u0227\7g\2\2\u0227")
buf.write("\u0228\7p\2\2\u0228\u0229\7v\2\2\u0229^\3\2\2\2\u022a")
buf.write("\u022b\7v\2\2\u022b\u022c\7t\2\2\u022c\u022d\7{\2\2\u022d")
buf.write("`\3\2\2\2\u022e\u022f\7x\2\2\u022f\u0230\7q\2\2\u0230")
buf.write("\u0231\7k\2\2\u0231\u0232\7f\2\2\u0232b\3\2\2\2\u0233")
buf.write("\u0234\7x\2\2\u0234\u0235\7q\2\2\u0235\u0236\7n\2\2\u0236")
buf.write("\u0237\7c\2\2\u0237\u0238\7v\2\2\u0238\u0239\7k\2\2\u0239")
buf.write("\u023a\7n\2\2\u023a\u023b\7g\2\2\u023bd\3\2\2\2\u023c")
buf.write("\u023d\7y\2\2\u023d\u023e\7j\2\2\u023e\u023f\7k\2\2\u023f")
buf.write("\u0240\7n\2\2\u0240\u0241\7g\2\2\u0241f\3\2\2\2\u0242")
buf.write("\u0250\7\62\2\2\u0243\u024d\t\2\2\2\u0244\u0246\5\u00e9")
buf.write("u\2\u0245\u0244\3\2\2\2\u0245\u0246\3\2\2\2\u0246\u024e")
buf.write("\3\2\2\2\u0247\u0249\7a\2\2\u0248\u0247\3\2\2\2\u0249")
buf.write("\u024a\3\2\2\2\u024a\u0248\3\2\2\2\u024a\u024b\3\2\2\2")
buf.write("\u024b\u024c\3\2\2\2\u024c\u024e\5\u00e9u\2\u024d\u0245")
buf.write("\3\2\2\2\u024d\u0248\3\2\2\2\u024e\u0250\3\2\2\2\u024f")
buf.write("\u0242\3\2\2\2\u024f\u0243\3\2\2\2\u0250\u0252\3\2\2\2")
buf.write("\u0251\u0253\t\3\2\2\u0252\u0251\3\2\2\2\u0252\u0253\3")
buf.write("\2\2\2\u0253h\3\2\2\2\u0254\u0255\7\62\2\2\u0255\u0256")
buf.write("\t\4\2\2\u0256\u025e\t\5\2\2\u0257\u0259\t\6\2\2\u0258")
buf.write("\u0257\3\2\2\2\u0259\u025c\3\2\2\2\u025a\u0258\3\2\2\2")
buf.write("\u025a\u025b\3\2\2\2\u025b\u025d\3\2\2\2\u025c\u025a\3")
buf.write("\2\2\2\u025d\u025f\t\5\2\2\u025e\u025a\3\2\2\2\u025e\u025f")
buf.write("\3\2\2\2\u025f\u0261\3\2\2\2\u0260\u0262\t\3\2\2\u0261")
buf.write("\u0260\3\2\2\2\u0261\u0262\3\2\2\2\u0262j\3\2\2\2\u0263")
buf.write("\u0267\7\62\2\2\u0264\u0266\7a\2\2\u0265\u0264\3\2\2\2")
buf.write("\u0266\u0269\3\2\2\2\u0267\u0265\3\2\2\2\u0267\u0268\3")
buf.write("\2\2\2\u0268\u026a\3\2\2\2\u0269\u0267\3\2\2\2\u026a\u0272")
buf.write("\t\7\2\2\u026b\u026d\t\b\2\2\u026c\u026b\3\2\2\2\u026d")
buf.write("\u0270\3\2\2\2\u026e\u026c\3\2\2\2\u026e\u026f\3\2\2\2")
buf.write("\u026f\u0271\3\2\2\2\u0270\u026e\3\2\2\2\u0271\u0273\t")
buf.write("\7\2\2\u0272\u026e\3\2\2\2\u0272\u0273\3\2\2\2\u0273\u0275")
buf.write("\3\2\2\2\u0274\u0276\t\3\2\2\u0275\u0274\3\2\2\2\u0275")
buf.write("\u0276\3\2\2\2\u0276l\3\2\2\2\u0277\u0278\7\62\2\2\u0278")
buf.write("\u0279\t\t\2\2\u0279\u0281\t\n\2\2\u027a\u027c\t\13\2")
buf.write("\2\u027b\u027a\3\2\2\2\u027c\u027f\3\2\2\2\u027d\u027b")
buf.write("\3\2\2\2\u027d\u027e\3\2\2\2\u027e\u0280\3\2\2\2\u027f")
buf.write("\u027d\3\2\2\2\u0280\u0282\t\n\2\2\u0281\u027d\3\2\2\2")
buf.write("\u0281\u0282\3\2\2\2\u0282\u0284\3\2\2\2\u0283\u0285\t")
buf.write("\3\2\2\u0284\u0283\3\2\2\2\u0284\u0285\3\2\2\2\u0285n")
buf.write("\3\2\2\2\u0286\u0287\5\u00e9u\2\u0287\u0289\7\60\2\2\u0288")
buf.write("\u028a\5\u00e9u\2\u0289\u0288\3\2\2\2\u0289\u028a\3\2")
buf.write("\2\2\u028a\u028e\3\2\2\2\u028b\u028c\7\60\2\2\u028c\u028e")
buf.write("\5\u00e9u\2\u028d\u0286\3\2\2\2\u028d\u028b\3\2\2\2\u028e")
buf.write("\u0290\3\2\2\2\u028f\u0291\5\u00e1q\2\u0290\u028f\3\2")
buf.write("\2\2\u0290\u0291\3\2\2\2\u0291\u0293\3\2\2\2\u0292\u0294")
buf.write("\t\f\2\2\u0293\u0292\3\2\2\2\u0293\u0294\3\2\2\2\u0294")
buf.write("\u029e\3\2\2\2\u0295\u029b\5\u00e9u\2\u0296\u0298\5\u00e1")
buf.write("q\2\u0297\u0299\t\f\2\2\u0298\u0297\3\2\2\2\u0298\u0299")
buf.write("\3\2\2\2\u0299\u029c\3\2\2\2\u029a\u029c\t\f\2\2\u029b")
buf.write("\u0296\3\2\2\2\u029b\u029a\3\2\2\2\u029c\u029e\3\2\2\2")
buf.write("\u029d\u028d\3\2\2\2\u029d\u0295\3\2\2\2\u029ep\3\2\2")
buf.write("\2\u029f\u02a0\7\62\2\2\u02a0\u02aa\t\4\2\2\u02a1\u02a3")
buf.write("\5\u00e5s\2\u02a2\u02a4\7\60\2\2\u02a3\u02a2\3\2\2\2\u02a3")
buf.write("\u02a4\3\2\2\2\u02a4\u02ab\3\2\2\2\u02a5\u02a7\5\u00e5")
buf.write("s\2\u02a6\u02a5\3\2\2\2\u02a6\u02a7\3\2\2\2\u02a7\u02a8")
buf.write("\3\2\2\2\u02a8\u02a9\7\60\2\2\u02a9\u02ab\5\u00e5s\2\u02aa")
buf.write("\u02a1\3\2\2\2\u02aa\u02a6\3\2\2\2\u02ab\u02ac\3\2\2\2")
buf.write("\u02ac\u02ae\t\r\2\2\u02ad\u02af\t\16\2\2\u02ae\u02ad")
buf.write("\3\2\2\2\u02ae\u02af\3\2\2\2\u02af\u02b0\3\2\2\2\u02b0")
buf.write("\u02b2\5\u00e9u\2\u02b1\u02b3\t\f\2\2\u02b2\u02b1\3\2")
buf.write("\2\2\u02b2\u02b3\3\2\2\2\u02b3r\3\2\2\2\u02b4\u02b5\7")
buf.write("v\2\2\u02b5\u02b6\7t\2\2\u02b6\u02b7\7w\2\2\u02b7\u02be")
buf.write("\7g\2\2\u02b8\u02b9\7h\2\2\u02b9\u02ba\7c\2\2\u02ba\u02bb")
buf.write("\7n\2\2\u02bb\u02bc\7u\2\2\u02bc\u02be\7g\2\2\u02bd\u02b4")
buf.write("\3\2\2\2\u02bd\u02b8\3\2\2\2\u02bet\3\2\2\2\u02bf\u02c2")
buf.write("\7)\2\2\u02c0\u02c3\n\17\2\2\u02c1\u02c3\5\u00e3r\2\u02c2")
buf.write("\u02c0\3\2\2\2\u02c2\u02c1\3\2\2\2\u02c3\u02c4\3\2\2\2")
buf.write("\u02c4\u02c5\7)\2\2\u02c5v\3\2\2\2\u02c6\u02cb\7$\2\2")
buf.write("\u02c7\u02ca\n\20\2\2\u02c8\u02ca\5\u00e3r\2\u02c9\u02c7")
buf.write("\3\2\2\2\u02c9\u02c8\3\2\2\2\u02ca\u02cd\3\2\2\2\u02cb")
buf.write("\u02c9\3\2\2\2\u02cb\u02cc\3\2\2\2\u02cc\u02ce\3\2\2\2")
buf.write("\u02cd\u02cb\3\2\2\2\u02ce\u02cf\7$\2\2\u02cfx\3\2\2\2")
buf.write("\u02d0\u02d1\7p\2\2\u02d1\u02d2\7w\2\2\u02d2\u02d3\7n")
buf.write("\2\2\u02d3\u02d4\7n\2\2\u02d4z\3\2\2\2\u02d5\u02d6\7*")
buf.write("\2\2\u02d6|\3\2\2\2\u02d7\u02d8\7+\2\2\u02d8~\3\2\2\2")
buf.write("\u02d9\u02da\7}\2\2\u02da\u0080\3\2\2\2\u02db\u02dc\7")
buf.write("\177\2\2\u02dc\u0082\3\2\2\2\u02dd\u02de\7]\2\2\u02de")
buf.write("\u0084\3\2\2\2\u02df\u02e0\7_\2\2\u02e0\u0086\3\2\2\2")
buf.write("\u02e1\u02e2\7=\2\2\u02e2\u0088\3\2\2\2\u02e3\u02e4\7")
buf.write(".\2\2\u02e4\u008a\3\2\2\2\u02e5\u02e6\7\60\2\2\u02e6\u008c")
buf.write("\3\2\2\2\u02e7\u02e8\7?\2\2\u02e8\u008e\3\2\2\2\u02e9")
buf.write("\u02ea\7@\2\2\u02ea\u0090\3\2\2\2\u02eb\u02ec\7>\2\2\u02ec")
buf.write("\u0092\3\2\2\2\u02ed\u02ee\7#\2\2\u02ee\u0094\3\2\2\2")
buf.write("\u02ef\u02f0\7\u0080\2\2\u02f0\u0096\3\2\2\2\u02f1\u02f2")
buf.write("\7A\2\2\u02f2\u0098\3\2\2\2\u02f3\u02f4\7<\2\2\u02f4\u009a")
buf.write("\3\2\2\2\u02f5\u02f6\7?\2\2\u02f6\u02f7\7?\2\2\u02f7\u009c")
buf.write("\3\2\2\2\u02f8\u02f9\7>\2\2\u02f9\u02fa\7?\2\2\u02fa\u009e")
buf.write("\3\2\2\2\u02fb\u02fc\7@\2\2\u02fc\u02fd\7?\2\2\u02fd\u00a0")
buf.write("\3\2\2\2\u02fe\u02ff\7#\2\2\u02ff\u0300\7?\2\2\u0300\u00a2")
buf.write("\3\2\2\2\u0301\u0302\7(\2\2\u0302\u0303\7(\2\2\u0303\u00a4")
buf.write("\3\2\2\2\u0304\u0305\7~\2\2\u0305\u0306\7~\2\2\u0306\u00a6")
buf.write("\3\2\2\2\u0307\u0308\7-\2\2\u0308\u0309\7-\2\2\u0309\u00a8")
buf.write("\3\2\2\2\u030a\u030b\7/\2\2\u030b\u030c\7/\2\2\u030c\u00aa")
buf.write("\3\2\2\2\u030d\u030e\7-\2\2\u030e\u00ac\3\2\2\2\u030f")
buf.write("\u0310\7/\2\2\u0310\u00ae\3\2\2\2\u0311\u0312\7,\2\2\u0312")
buf.write("\u00b0\3\2\2\2\u0313\u0314\7\61\2\2\u0314\u00b2\3\2\2")
buf.write("\2\u0315\u0316\7(\2\2\u0316\u00b4\3\2\2\2\u0317\u0318")
buf.write("\7~\2\2\u0318\u00b6\3\2\2\2\u0319\u031a\7`\2\2\u031a\u00b8")
buf.write("\3\2\2\2\u031b\u031c\7\'\2\2\u031c\u00ba\3\2\2\2\u031d")
buf.write("\u031e\7-\2\2\u031e\u031f\7?\2\2\u031f\u00bc\3\2\2\2\u0320")
buf.write("\u0321\7/\2\2\u0321\u0322\7?\2\2\u0322\u00be\3\2\2\2\u0323")
buf.write("\u0324\7,\2\2\u0324\u0325\7?\2\2\u0325\u00c0\3\2\2\2\u0326")
buf.write("\u0327\7\61\2\2\u0327\u0328\7?\2\2\u0328\u00c2\3\2\2\2")
buf.write("\u0329\u032a\7(\2\2\u032a\u032b\7?\2\2\u032b\u00c4\3\2")
buf.write("\2\2\u032c\u032d\7~\2\2\u032d\u032e\7?\2\2\u032e\u00c6")
buf.write("\3\2\2\2\u032f\u0330\7`\2\2\u0330\u0331\7?\2\2\u0331\u00c8")
buf.write("\3\2\2\2\u0332\u0333\7\'\2\2\u0333\u0334\7?\2\2\u0334")
buf.write("\u00ca\3\2\2\2\u0335\u0336\7>\2\2\u0336\u0337\7>\2\2\u0337")
buf.write("\u0338\7?\2\2\u0338\u00cc\3\2\2\2\u0339\u033a\7@\2\2\u033a")
buf.write("\u033b\7@\2\2\u033b\u033c\7?\2\2\u033c\u00ce\3\2\2\2\u033d")
buf.write("\u033e\7@\2\2\u033e\u033f\7@\2\2\u033f\u0340\7@\2\2\u0340")
buf.write("\u0341\7?\2\2\u0341\u00d0\3\2\2\2\u0342\u0343\7/\2\2\u0343")
buf.write("\u0344\7@\2\2\u0344\u00d2\3\2\2\2\u0345\u0346\7<\2\2\u0346")
buf.write("\u0347\7<\2\2\u0347\u00d4\3\2\2\2\u0348\u0349\7B\2\2\u0349")
buf.write("\u00d6\3\2\2\2\u034a\u034b\7\60\2\2\u034b\u034c\7\60\2")
buf.write("\2\u034c\u034d\7\60\2\2\u034d\u00d8\3\2\2\2\u034e\u0350")
buf.write("\t\21\2\2\u034f\u034e\3\2\2\2\u0350\u0351\3\2\2\2\u0351")
buf.write("\u034f\3\2\2\2\u0351\u0352\3\2\2\2\u0352\u0353\3\2\2\2")
buf.write("\u0353\u0354\bm\2\2\u0354\u00da\3\2\2\2\u0355\u0356\7")
buf.write("\61\2\2\u0356\u0357\7,\2\2\u0357\u035b\3\2\2\2\u0358\u035a")
buf.write("\13\2\2\2\u0359\u0358\3\2\2\2\u035a\u035d\3\2\2\2\u035b")
buf.write("\u035c\3\2\2\2\u035b\u0359\3\2\2\2\u035c\u035e\3\2\2\2")
buf.write("\u035d\u035b\3\2\2\2\u035e\u035f\7,\2\2\u035f\u0360\7")
buf.write("\61\2\2\u0360\u0361\3\2\2\2\u0361\u0362\bn\2\2\u0362\u00dc")
buf.write("\3\2\2\2\u0363\u0364\7\61\2\2\u0364\u0365\7\61\2\2\u0365")
buf.write("\u0369\3\2\2\2\u0366\u0368\n\22\2\2\u0367\u0366\3\2\2")
buf.write("\2\u0368\u036b\3\2\2\2\u0369\u0367\3\2\2\2\u0369\u036a")
buf.write("\3\2\2\2\u036a\u036c\3\2\2\2\u036b\u0369\3\2\2\2\u036c")
buf.write("\u036d\bo\2\2\u036d\u00de\3\2\2\2\u036e\u0372\5\u00ed")
buf.write("w\2\u036f\u0371\5\u00ebv\2\u0370\u036f\3\2\2\2\u0371\u0374")
buf.write("\3\2\2\2\u0372\u0370\3\2\2\2\u0372\u0373\3\2\2\2\u0373")
buf.write("\u00e0\3\2\2\2\u0374\u0372\3\2\2\2\u0375\u0377\t\23\2")
buf.write("\2\u0376\u0378\t\16\2\2\u0377\u0376\3\2\2\2\u0377\u0378")
buf.write("\3\2\2\2\u0378\u0379\3\2\2\2\u0379\u037a\5\u00e9u\2\u037a")
buf.write("\u00e2\3\2\2\2\u037b\u037c\7^\2\2\u037c\u0391\t\24\2\2")
buf.write("\u037d\u0382\7^\2\2\u037e\u0380\t\25\2\2\u037f\u037e\3")
buf.write("\2\2\2\u037f\u0380\3\2\2\2\u0380\u0381\3\2\2\2\u0381\u0383")
buf.write("\t\7\2\2\u0382\u037f\3\2\2\2\u0382\u0383\3\2\2\2\u0383")
buf.write("\u0384\3\2\2\2\u0384\u0391\t\7\2\2\u0385\u0387\7^\2\2")
buf.write("\u0386\u0388\7w\2\2\u0387\u0386\3\2\2\2\u0388\u0389\3")
buf.write("\2\2\2\u0389\u0387\3\2\2\2\u0389\u038a\3\2\2\2\u038a\u038b")
buf.write("\3\2\2\2\u038b\u038c\5\u00e7t\2\u038c\u038d\5\u00e7t\2")
buf.write("\u038d\u038e\5\u00e7t\2\u038e\u038f\5\u00e7t\2\u038f\u0391")
buf.write("\3\2\2\2\u0390\u037b\3\2\2\2\u0390\u037d\3\2\2\2\u0390")
buf.write("\u0385\3\2\2\2\u0391\u00e4\3\2\2\2\u0392\u039b\5\u00e7")
buf.write("t\2\u0393\u0396\5\u00e7t\2\u0394\u0396\7a\2\2\u0395\u0393")
buf.write("\3\2\2\2\u0395\u0394\3\2\2\2\u0396\u0399\3\2\2\2\u0397")
buf.write("\u0395\3\2\2\2\u0397\u0398\3\2\2\2\u0398\u039a\3\2\2\2")
buf.write("\u0399\u0397\3\2\2\2\u039a\u039c\5\u00e7t\2\u039b\u0397")
buf.write("\3\2\2\2\u039b\u039c\3\2\2\2\u039c\u00e6\3\2\2\2\u039d")
buf.write("\u039e\t\5\2\2\u039e\u00e8\3\2\2\2\u039f\u03a7\t\26\2")
buf.write("\2\u03a0\u03a2\t\27\2\2\u03a1\u03a0\3\2\2\2\u03a2\u03a5")
buf.write("\3\2\2\2\u03a3\u03a1\3\2\2\2\u03a3\u03a4\3\2\2\2\u03a4")
buf.write("\u03a6\3\2\2\2\u03a5\u03a3\3\2\2\2\u03a6\u03a8\t\26\2")
buf.write("\2\u03a7\u03a3\3\2\2\2\u03a7\u03a8\3\2\2\2\u03a8\u00ea")
buf.write("\3\2\2\2\u03a9\u03ac\5\u00edw\2\u03aa\u03ac\t\26\2\2\u03ab")
buf.write("\u03a9\3\2\2\2\u03ab\u03aa\3\2\2\2\u03ac\u00ec\3\2\2\2")
buf.write("\u03ad\u03b2\t\30\2\2\u03ae\u03b2\n\31\2\2\u03af\u03b0")
buf.write("\t\32\2\2\u03b0\u03b2\t\33\2\2\u03b1\u03ad\3\2\2\2\u03b1")
buf.write("\u03ae\3\2\2\2\u03b1\u03af\3\2\2\2\u03b2\u00ee\3\2\2\2")
buf.write("\62\2\u0245\u024a\u024d\u024f\u0252\u025a\u025e\u0261")
buf.write("\u0267\u026e\u0272\u0275\u027d\u0281\u0284\u0289\u028d")
buf.write("\u0290\u0293\u0298\u029b\u029d\u02a3\u02a6\u02aa\u02ae")
buf.write("\u02b2\u02bd\u02c2\u02c9\u02cb\u0351\u035b\u0369\u0372")
buf.write("\u0377\u037f\u0382\u0389\u0390\u0395\u0397\u039b\u03a3")
buf.write("\u03a7\u03ab\u03b1\3\2\3\2")
return buf.getvalue()
class JavaLexer(Lexer):
atn = ATNDeserializer().deserialize(serializedATN())
decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
ABSTRACT = 1
ASSERT = 2
BOOLEAN = 3
BREAK = 4
BYTE = 5
CASE = 6
CATCH = 7
CHAR = 8
CLASS = 9
CONST = 10
CONTINUE = 11
DEFAULT = 12
DO = 13
DOUBLE = 14
ELSE = 15
ENUM = 16
EXTENDS = 17
FINAL = 18
FINALLY = 19
FLOAT = 20
FOR = 21
IF = 22
GOTO = 23
IMPLEMENTS = 24
IMPORT = 25
INSTANCEOF = 26
INT = 27
INTERFACE = 28
LONG = 29
NATIVE = 30
NEW = 31
PACKAGE = 32
PRIVATE = 33
PROTECTED = 34
PUBLIC = 35
RETURN = 36
SHORT = 37
STATIC = 38
STRICTFP = 39
SUPER = 40
SWITCH = 41
SYNCHRONIZED = 42
THIS = 43
THROW = 44
THROWS = 45
TRANSIENT = 46
TRY = 47
VOID = 48
VOLATILE = 49
WHILE = 50
DECIMAL_LITERAL = 51
HEX_LITERAL = 52
OCT_LITERAL = 53
BINARY_LITERAL = 54
FLOAT_LITERAL = 55
HEX_FLOAT_LITERAL = 56
BOOL_LITERAL = 57
CHAR_LITERAL = 58
STRING_LITERAL = 59
NULL_LITERAL = 60
LPAREN = 61
RPAREN = 62
LBRACE = 63
RBRACE = 64
LBRACK = 65
RBRACK = 66
SEMI = 67
COMMA = 68
DOT = 69
ASSIGN = 70
GT = 71
LT = 72
BANG = 73
TILDE = 74
QUESTION = 75
COLON = 76
EQUAL = 77
LE = 78
GE = 79
NOTEQUAL = 80
AND = 81
OR = 82
INC = 83
DEC = 84
ADD = 85
SUB = 86
MUL = 87
DIV = 88
BITAND = 89
BITOR = 90
CARET = 91
MOD = 92
ADD_ASSIGN = 93
SUB_ASSIGN = 94
MUL_ASSIGN = 95
DIV_ASSIGN = 96
AND_ASSIGN = 97
OR_ASSIGN = 98
XOR_ASSIGN = 99
MOD_ASSIGN = 100
LSHIFT_ASSIGN = 101
RSHIFT_ASSIGN = 102
URSHIFT_ASSIGN = 103
ARROW = 104
COLONCOLON = 105
AT = 106
ELLIPSIS = 107
WS = 108
COMMENT = 109
LINE_COMMENT = 110
IDENTIFIER = 111
channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ]
modeNames = [ "DEFAULT_MODE" ]
literalNames = [ "<INVALID>",
"'abstract'", "'assert'", "'boolean'", "'break'", "'byte'",
"'case'", "'catch'", "'char'", "'class'", "'const'", "'continue'",
"'default'", "'do'", "'double'", "'else'", "'enum'", "'extends'",
"'final'", "'finally'", "'float'", "'for'", "'if'", "'goto'",
"'implements'", "'import'", "'instanceof'", "'int'", "'interface'",
"'long'", "'native'", "'new'", "'package'", "'private'", "'protected'",
"'public'", "'return'", "'short'", "'static'", "'strictfp'",
"'super'", "'switch'", "'synchronized'", "'this'", "'throw'",
"'throws'", "'transient'", "'try'", "'void'", "'volatile'",
"'while'", "'null'", "'('", "')'", "'{'", "'}'", "'['", "']'",
"';'", "','", "'.'", "'='", "'>'", "'<'", "'!'", "'~'", "'?'",
"':'", "'=='", "'<='", "'>='", "'!='", "'&&'", "'||'", "'++'",
"'--'", "'+'", "'-'", "'*'", "'/'", "'&'", "'|'", "'^'", "'%'",
"'+='", "'-='", "'*='", "'/='", "'&='", "'|='", "'^='", "'%='",
"'<<='", "'>>='", "'>>>='", "'->'", "'::'", "'@'", "'...'" ]
symbolicNames = [ "<INVALID>",
"ABSTRACT", "ASSERT", "BOOLEAN", "BREAK", "BYTE", "CASE", "CATCH",
"CHAR", "CLASS", "CONST", "CONTINUE", "DEFAULT", "DO", "DOUBLE",
"ELSE", "ENUM", "EXTENDS", "FINAL", "FINALLY", "FLOAT", "FOR",
"IF", "GOTO", "IMPLEMENTS", "IMPORT", "INSTANCEOF", "INT", "INTERFACE",
"LONG", "NATIVE", "NEW", "PACKAGE", "PRIVATE", "PROTECTED",
"PUBLIC", "RETURN", "SHORT", "STATIC", "STRICTFP", "SUPER",
"SWITCH", "SYNCHRONIZED", "THIS", "THROW", "THROWS", "TRANSIENT",
"TRY", "VOID", "VOLATILE", "WHILE", "DECIMAL_LITERAL", "HEX_LITERAL",
"OCT_LITERAL", "BINARY_LITERAL", "FLOAT_LITERAL", "HEX_FLOAT_LITERAL",
"BOOL_LITERAL", "CHAR_LITERAL", "STRING_LITERAL", "NULL_LITERAL",
"LPAREN", "RPAREN", "LBRACE", "RBRACE", "LBRACK", "RBRACK",
"SEMI", "COMMA", "DOT", "ASSIGN", "GT", "LT", "BANG", "TILDE",
"QUESTION", "COLON", "EQUAL", "LE", "GE", "NOTEQUAL", "AND",
"OR", "INC", "DEC", "ADD", "SUB", "MUL", "DIV", "BITAND", "BITOR",
"CARET", "MOD", "ADD_ASSIGN", "SUB_ASSIGN", "MUL_ASSIGN", "DIV_ASSIGN",
"AND_ASSIGN", "OR_ASSIGN", "XOR_ASSIGN", "MOD_ASSIGN", "LSHIFT_ASSIGN",
"RSHIFT_ASSIGN", "URSHIFT_ASSIGN", "ARROW", "COLONCOLON", "AT",
"ELLIPSIS", "WS", "COMMENT", "LINE_COMMENT", "IDENTIFIER" ]
ruleNames = [ "ABSTRACT", "ASSERT", "BOOLEAN", "BREAK", "BYTE", "CASE",
"CATCH", "CHAR", "CLASS", "CONST", "CONTINUE", "DEFAULT",
"DO", "DOUBLE", "ELSE", "ENUM", "EXTENDS", "FINAL", "FINALLY",
"FLOAT", "FOR", "IF", "GOTO", "IMPLEMENTS", "IMPORT",
"INSTANCEOF", "INT", "INTERFACE", "LONG", "NATIVE", "NEW",
"PACKAGE", "PRIVATE", "PROTECTED", "PUBLIC", "RETURN",
"SHORT", "STATIC", "STRICTFP", "SUPER", "SWITCH", "SYNCHRONIZED",
"THIS", "THROW", "THROWS", "TRANSIENT", "TRY", "VOID",
"VOLATILE", "WHILE", "DECIMAL_LITERAL", "HEX_LITERAL",
"OCT_LITERAL", "BINARY_LITERAL", "FLOAT_LITERAL", "HEX_FLOAT_LITERAL",
"BOOL_LITERAL", "CHAR_LITERAL", "STRING_LITERAL", "NULL_LITERAL",
"LPAREN", "RPAREN", "LBRACE", "RBRACE", "LBRACK", "RBRACK",
"SEMI", "COMMA", "DOT", "ASSIGN", "GT", "LT", "BANG",
"TILDE", "QUESTION", "COLON", "EQUAL", "LE", "GE", "NOTEQUAL",
"AND", "OR", "INC", "DEC", "ADD", "SUB", "MUL", "DIV",
"BITAND", "BITOR", "CARET", "MOD", "ADD_ASSIGN", "SUB_ASSIGN",
"MUL_ASSIGN", "DIV_ASSIGN", "AND_ASSIGN", "OR_ASSIGN",
"XOR_ASSIGN", "MOD_ASSIGN", "LSHIFT_ASSIGN", "RSHIFT_ASSIGN",
"URSHIFT_ASSIGN", "ARROW", "COLONCOLON", "AT", "ELLIPSIS",
"WS", "COMMENT", "LINE_COMMENT", "IDENTIFIER", "ExponentPart",
"EscapeSequence", "HexDigits", "HexDigit", "Digits", "LetterOrDigit",
"Letter" ]
grammarFileName = "JavaLexer.g4"
def __init__(self, input=None, output:TextIO = sys.stdout):
super().__init__(input, output)
self.checkVersion("4.9.1")
self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())
self._actions = None
self._predicates = None
| 62.914557 | 103 | 0.571249 |
from antlr4 import *
from io import StringIO
from typing.io import TextIO
import sys
def serializedATN():
with StringIO() as buf:
buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2q")
buf.write("\u03b3\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7")
buf.write("\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r")
buf.write("\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22\4\23")
buf.write("\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30")
buf.write("\4\31\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t\35\4\36")
buf.write("\t\36\4\37\t\37\4 \t \4!\t!\4\"\t\"\4#\t#\4$\t$\4%\t%")
buf.write("\4&\t&\4\'\t\'\4(\t(\4)\t)\4*\t*\4+\t+\4,\t,\4-\t-\4.")
buf.write("\t.\4/\t/\4\60\t\60\4\61\t\61\4\62\t\62\4\63\t\63\4\64")
buf.write("\t\64\4\65\t\65\4\66\t\66\4\67\t\67\48\t8\49\t9\4:\t:")
buf.write("\4;\t;\4<\t<\4=\t=\4>\t>\4?\t?\4@\t@\4A\tA\4B\tB\4C\t")
buf.write("C\4D\tD\4E\tE\4F\tF\4G\tG\4H\tH\4I\tI\4J\tJ\4K\tK\4L\t")
buf.write("L\4M\tM\4N\tN\4O\tO\4P\tP\4Q\tQ\4R\tR\4S\tS\4T\tT\4U\t")
buf.write("U\4V\tV\4W\tW\4X\tX\4Y\tY\4Z\tZ\4[\t[\4\\\t\\\4]\t]\4")
buf.write("^\t^\4_\t_\4`\t`\4a\ta\4b\tb\4c\tc\4d\td\4e\te\4f\tf\4")
buf.write("g\tg\4h\th\4i\ti\4j\tj\4k\tk\4l\tl\4m\tm\4n\tn\4o\to\4")
buf.write("p\tp\4q\tq\4r\tr\4s\ts\4t\tt\4u\tu\4v\tv\4w\tw\3\2\3\2")
buf.write("\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\3\3\3\3\3\3\3\3\3\3\3\3")
buf.write("\3\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\5\3\5\3\5\3\5\3\5")
buf.write("\3\5\3\6\3\6\3\6\3\6\3\6\3\7\3\7\3\7\3\7\3\7\3\b\3\b\3")
buf.write("\b\3\b\3\b\3\b\3\t\3\t\3\t\3\t\3\t\3\n\3\n\3\n\3\n\3\n")
buf.write("\3\n\3\13\3\13\3\13\3\13\3\13\3\13\3\f\3\f\3\f\3\f\3\f")
buf.write("\3\f\3\f\3\f\3\f\3\r\3\r\3\r\3\r\3\r\3\r\3\r\3\r\3\16")
buf.write("\3\16\3\16\3\17\3\17\3\17\3\17\3\17\3\17\3\17\3\20\3\20")
buf.write("\3\20\3\20\3\20\3\21\3\21\3\21\3\21\3\21\3\22\3\22\3\22")
buf.write("\3\22\3\22\3\22\3\22\3\22\3\23\3\23\3\23\3\23\3\23\3\23")
buf.write("\3\24\3\24\3\24\3\24\3\24\3\24\3\24\3\24\3\25\3\25\3\25")
buf.write("\3\25\3\25\3\25\3\26\3\26\3\26\3\26\3\27\3\27\3\27\3\30")
buf.write("\3\30\3\30\3\30\3\30\3\31\3\31\3\31\3\31\3\31\3\31\3\31")
buf.write("\3\31\3\31\3\31\3\31\3\32\3\32\3\32\3\32\3\32\3\32\3\32")
buf.write("\3\33\3\33\3\33\3\33\3\33\3\33\3\33\3\33\3\33\3\33\3\33")
buf.write("\3\34\3\34\3\34\3\34\3\35\3\35\3\35\3\35\3\35\3\35\3\35")
buf.write("\3\35\3\35\3\35\3\36\3\36\3\36\3\36\3\36\3\37\3\37\3\37")
buf.write("\3\37\3\37\3\37\3\37\3 \3 \3 \3 \3!\3!\3!\3!\3!\3!\3!")
buf.write("\3!\3\"\3\"\3\"\3\"\3\"\3\"\3\"\3\"\3#\3#\3#\3#\3#\3#")
buf.write("\3#\3#\3#\3#\3$\3$\3$\3$\3$\3$\3$\3%\3%\3%\3%\3%\3%\3")
buf.write("%\3&\3&\3&\3&\3&\3&\3\'\3\'\3\'\3\'\3\'\3\'\3\'\3(\3(")
buf.write("\3(\3(\3(\3(\3(\3(\3(\3)\3)\3)\3)\3)\3)\3*\3*\3*\3*\3")
buf.write("*\3*\3*\3+\3+\3+\3+\3+\3+\3+\3+\3+\3+\3+\3+\3+\3,\3,\3")
buf.write(",\3,\3,\3-\3-\3-\3-\3-\3-\3.\3.\3.\3.\3.\3.\3.\3/\3/\3")
buf.write("/\3/\3/\3/\3/\3/\3/\3/\3\60\3\60\3\60\3\60\3\61\3\61\3")
buf.write("\61\3\61\3\61\3\62\3\62\3\62\3\62\3\62\3\62\3\62\3\62")
buf.write("\3\62\3\63\3\63\3\63\3\63\3\63\3\63\3\64\3\64\3\64\5\64")
buf.write("\u0246\n\64\3\64\6\64\u0249\n\64\r\64\16\64\u024a\3\64")
buf.write("\5\64\u024e\n\64\5\64\u0250\n\64\3\64\5\64\u0253\n\64")
buf.write("\3\65\3\65\3\65\3\65\7\65\u0259\n\65\f\65\16\65\u025c")
buf.write("\13\65\3\65\5\65\u025f\n\65\3\65\5\65\u0262\n\65\3\66")
buf.write("\3\66\7\66\u0266\n\66\f\66\16\66\u0269\13\66\3\66\3\66")
buf.write("\7\66\u026d\n\66\f\66\16\66\u0270\13\66\3\66\5\66\u0273")
buf.write("\n\66\3\66\5\66\u0276\n\66\3\67\3\67\3\67\3\67\7\67\u027c")
buf.write("\n\67\f\67\16\67\u027f\13\67\3\67\5\67\u0282\n\67\3\67")
buf.write("\5\67\u0285\n\67\38\38\38\58\u028a\n8\38\38\58\u028e\n")
buf.write("8\38\58\u0291\n8\38\58\u0294\n8\38\38\38\58\u0299\n8\3")
buf.write("8\58\u029c\n8\58\u029e\n8\39\39\39\39\59\u02a4\n9\39\5")
buf.write("9\u02a7\n9\39\39\59\u02ab\n9\39\39\59\u02af\n9\39\39\5")
buf.write("9\u02b3\n9\3:\3:\3:\3:\3:\3:\3:\3:\3:\5:\u02be\n:\3;\3")
buf.write(";\3;\5;\u02c3\n;\3;\3;\3<\3<\3<\7<\u02ca\n<\f<\16<\u02cd")
buf.write("\13<\3<\3<\3=\3=\3=\3=\3=\3>\3>\3?\3?\3@\3@\3A\3A\3B\3")
buf.write("B\3C\3C\3D\3D\3E\3E\3F\3F\3G\3G\3H\3H\3I\3I\3J\3J\3K\3")
buf.write("K\3L\3L\3M\3M\3N\3N\3N\3O\3O\3O\3P\3P\3P\3Q\3Q\3Q\3R\3")
buf.write("R\3R\3S\3S\3S\3T\3T\3T\3U\3U\3U\3V\3V\3W\3W\3X\3X\3Y\3")
buf.write("Y\3Z\3Z\3[\3[\3\\\3\\\3]\3]\3^\3^\3^\3_\3_\3_\3`\3`\3")
buf.write("`\3a\3a\3a\3b\3b\3b\3c\3c\3c\3d\3d\3d\3e\3e\3e\3f\3f\3")
buf.write("f\3f\3g\3g\3g\3g\3h\3h\3h\3h\3h\3i\3i\3i\3j\3j\3j\3k\3")
buf.write("k\3l\3l\3l\3l\3m\6m\u0350\nm\rm\16m\u0351\3m\3m\3n\3n")
buf.write("\3n\3n\7n\u035a\nn\fn\16n\u035d\13n\3n\3n\3n\3n\3n\3o")
buf.write("\3o\3o\3o\7o\u0368\no\fo\16o\u036b\13o\3o\3o\3p\3p\7p")
buf.write("\u0371\np\fp\16p\u0374\13p\3q\3q\5q\u0378\nq\3q\3q\3r")
buf.write("\3r\3r\3r\5r\u0380\nr\3r\5r\u0383\nr\3r\3r\3r\6r\u0388")
buf.write("\nr\rr\16r\u0389\3r\3r\3r\3r\3r\5r\u0391\nr\3s\3s\3s\7")
buf.write("s\u0396\ns\fs\16s\u0399\13s\3s\5s\u039c\ns\3t\3t\3u\3")
buf.write("u\7u\u03a2\nu\fu\16u\u03a5\13u\3u\5u\u03a8\nu\3v\3v\5")
buf.write("v\u03ac\nv\3w\3w\3w\3w\5w\u03b2\nw\3\u035b\2x\3\3\5\4")
buf.write("\7\5\t\6\13\7\r\b\17\t\21\n\23\13\25\f\27\r\31\16\33\17")
buf.write("\35\20\37\21!\22#\23%\24\'\25)\26+\27-\30/\31\61\32\63")
buf.write("\33\65\34\67\359\36;\37= ?!A\"C
buf.write("Y.[/]\60_\61a\62c\63e\64g\65i\66k\67m8o9q:s;u<w=y>{?}")
buf.write("@\177A\u0081B\u0083C\u0085D\u0087E\u0089F\u008bG\u008d")
buf.write("H\u008fI\u0091J\u0093K\u0095L\u0097M\u0099N\u009bO\u009d")
buf.write("P\u009fQ\u00a1R\u00a3S\u00a5T\u00a7U\u00a9V\u00abW\u00ad")
buf.write("X\u00afY\u00b1Z\u00b3[\u00b5\\\u00b7]\u00b9^\u00bb_\u00bd")
buf.write("`\u00bfa\u00c1b\u00c3c\u00c5d\u00c7e\u00c9f\u00cbg\u00cd")
buf.write("h\u00cfi\u00d1j\u00d3k\u00d5l\u00d7m\u00d9n\u00dbo\u00dd")
buf.write("p\u00dfq\u00e1\2\u00e3\2\u00e5\2\u00e7\2\u00e9\2\u00eb")
buf.write("\2\u00ed\2\3\2\34\3\2\63;\4\2NNnn\4\2ZZzz\5\2\62;CHch")
buf.write("\6\2\62;CHaach\3\2\629\4\2\629aa\4\2DDdd\3\2\62\63\4\2")
buf.write("\62\63aa\6\2FFHHffhh\4\2RRrr\4\2--//\6\2\f\f\17\17))^")
buf.write("^\6\2\f\f\17\17$$^^\5\2\13\f\16\17\"\"\4\2\f\f\17\17\4")
buf.write("\2GGgg\n\2$$))^^ddhhppttvv\3\2\62\65\3\2\62;\4\2\62;a")
buf.write("a\6\2&&C\\aac|\4\2\2\u0081\ud802\udc01\3\2\ud802\udc01")
buf.write("\3\2\udc02\ue001\2\u03dc\2\3\3\2\2\2\2\5\3\2\2\2\2\7\3")
buf.write("\2\2\2\2\t\3\2\2\2\2\13\3\2\2\2\2\r\3\2\2\2\2\17\3\2\2")
buf.write("\2\2\21\3\2\2\2\2\23\3\2\2\2\2\25\3\2\2\2\2\27\3\2\2\2")
buf.write("\2\31\3\2\2\2\2\33\3\2\2\2\2\35\3\2\2\2\2\37\3\2\2\2\2")
buf.write("!\3\2\2\2\2#\3\2\2\2\2%\3\2\2\2\2\'\3\2\2\2\2)\3\2\2\2")
buf.write("\2+\3\2\2\2\2-\3\2\2\2\2/\3\2\2\2\2\61\3\2\2\2\2\63\3")
buf.write("\2\2\2\2\65\3\2\2\2\2\67\3\2\2\2\29\3\2\2\2\2;\3\2\2\2")
buf.write("\2=\3\2\2\2\2?\3\2\2\2\2A\3\2\2\2\2C\3\2\2\2\2E\3\2\2")
buf.write("\2\2G\3\2\2\2\2I\3\2\2\2\2K\3\2\2\2\2M\3\2\2\2\2O\3\2")
buf.write("\2\2\2Q\3\2\2\2\2S\3\2\2\2\2U\3\2\2\2\2W\3\2\2\2\2Y\3")
buf.write("\2\2\2\2[\3\2\2\2\2]\3\2\2\2\2_\3\2\2\2\2a\3\2\2\2\2c")
buf.write("\3\2\2\2\2e\3\2\2\2\2g\3\2\2\2\2i\3\2\2\2\2k\3\2\2\2\2")
buf.write("m\3\2\2\2\2o\3\2\2\2\2q\3\2\2\2\2s\3\2\2\2\2u\3\2\2\2")
buf.write("\2w\3\2\2\2\2y\3\2\2\2\2{\3\2\2\2\2}\3\2\2\2\2\177\3\2")
buf.write("\2\2\2\u0081\3\2\2\2\2\u0083\3\2\2\2\2\u0085\3\2\2\2\2")
buf.write("\u0087\3\2\2\2\2\u0089\3\2\2\2\2\u008b\3\2\2\2\2\u008d")
buf.write("\3\2\2\2\2\u008f\3\2\2\2\2\u0091\3\2\2\2\2\u0093\3\2\2")
buf.write("\2\2\u0095\3\2\2\2\2\u0097\3\2\2\2\2\u0099\3\2\2\2\2\u009b")
buf.write("\3\2\2\2\2\u009d\3\2\2\2\2\u009f\3\2\2\2\2\u00a1\3\2\2")
buf.write("\2\2\u00a3\3\2\2\2\2\u00a5\3\2\2\2\2\u00a7\3\2\2\2\2\u00a9")
buf.write("\3\2\2\2\2\u00ab\3\2\2\2\2\u00ad\3\2\2\2\2\u00af\3\2\2")
buf.write("\2\2\u00b1\3\2\2\2\2\u00b3\3\2\2\2\2\u00b5\3\2\2\2\2\u00b7")
buf.write("\3\2\2\2\2\u00b9\3\2\2\2\2\u00bb\3\2\2\2\2\u00bd\3\2\2")
buf.write("\2\2\u00bf\3\2\2\2\2\u00c1\3\2\2\2\2\u00c3\3\2\2\2\2\u00c5")
buf.write("\3\2\2\2\2\u00c7\3\2\2\2\2\u00c9\3\2\2\2\2\u00cb\3\2\2")
buf.write("\2\2\u00cd\3\2\2\2\2\u00cf\3\2\2\2\2\u00d1\3\2\2\2\2\u00d3")
buf.write("\3\2\2\2\2\u00d5\3\2\2\2\2\u00d7\3\2\2\2\2\u00d9\3\2\2")
buf.write("\2\2\u00db\3\2\2\2\2\u00dd\3\2\2\2\2\u00df\3\2\2\2\3\u00ef")
buf.write("\3\2\2\2\5\u00f8\3\2\2\2\7\u00ff\3\2\2\2\t\u0107\3\2\2")
buf.write("\2\13\u010d\3\2\2\2\r\u0112\3\2\2\2\17\u0117\3\2\2\2\21")
buf.write("\u011d\3\2\2\2\23\u0122\3\2\2\2\25\u0128\3\2\2\2\27\u012e")
buf.write("\3\2\2\2\31\u0137\3\2\2\2\33\u013f\3\2\2\2\35\u0142\3")
buf.write("\2\2\2\37\u0149\3\2\2\2!\u014e\3\2\2\2
buf.write("%\u015b\3\2\2\2\'\u0161\3\2\2\2)\u0169\3\2\2\2+\u016f")
buf.write("\3\2\2\2-\u0173\3\2\2\2/\u0176\3\2\2\2\61\u017b\3\2\2")
buf.write("\2\63\u0186\3\2\2\2\65\u018d\3\2\2\2\67\u0198\3\2\2\2")
buf.write("9\u019c\3\2\2\2;\u01a6\3\2\2\2=\u01ab\3\2\2\2?\u01b2\3")
buf.write("\2\2\2A\u01b6\3\2\2\2C\u01be\3\2\2\2E\u01c6\3\2\2\2G\u01d0")
buf.write("\3\2\2\2I\u01d7\3\2\2\2K\u01de\3\2\2\2M\u01e4\3\2\2\2")
buf.write("O\u01eb\3\2\2\2Q\u01f4\3\2\2\2S\u01fa\3\2\2\2U\u0201\3")
buf.write("\2\2\2W\u020e\3\2\2\2Y\u0213\3\2\2\2[\u0219\3\2\2\2]\u0220")
buf.write("\3\2\2\2_\u022a\3\2\2\2a\u022e\3\2\2\2c\u0233\3\2\2\2")
buf.write("e\u023c\3\2\2\2g\u024f\3\2\2\2i\u0254\3\2\2\2k\u0263\3")
buf.write("\2\2\2m\u0277\3\2\2\2o\u029d\3\2\2\2q\u029f\3\2\2\2s\u02bd")
buf.write("\3\2\2\2u\u02bf\3\2\2\2w\u02c6\3\2\2\2y\u02d0\3\2\2\2")
buf.write("{\u02d5\3\2\2\2}\u02d7\3\2\2\2\177\u02d9\3\2\2\2\u0081")
buf.write("\u02db\3\2\2\2\u0083\u02dd\3\2\2\2\u0085\u02df\3\2\2\2")
buf.write("\u0087\u02e1\3\2\2\2\u0089\u02e3\3\2\2\2\u008b\u02e5\3")
buf.write("\2\2\2\u008d\u02e7\3\2\2\2\u008f\u02e9\3\2\2\2\u0091\u02eb")
buf.write("\3\2\2\2\u0093\u02ed\3\2\2\2\u0095\u02ef\3\2\2\2\u0097")
buf.write("\u02f1\3\2\2\2\u0099\u02f3\3\2\2\2\u009b\u02f5\3\2\2\2")
buf.write("\u009d\u02f8\3\2\2\2\u009f\u02fb\3\2\2\2\u00a1\u02fe\3")
buf.write("\2\2\2\u00a3\u0301\3\2\2\2\u00a5\u0304\3\2\2\2\u00a7\u0307")
buf.write("\3\2\2\2\u00a9\u030a\3\2\2\2\u00ab\u030d\3\2\2\2\u00ad")
buf.write("\u030f\3\2\2\2\u00af\u0311\3\2\2\2\u00b1\u0313\3\2\2\2")
buf.write("\u00b3\u0315\3\2\2\2\u00b5\u0317\3\2\2\2\u00b7\u0319\3")
buf.write("\2\2\2\u00b9\u031b\3\2\2\2\u00bb\u031d\3\2\2\2\u00bd\u0320")
buf.write("\3\2\2\2\u00bf\u0323\3\2\2\2\u00c1\u0326\3\2\2\2\u00c3")
buf.write("\u0329\3\2\2\2\u00c5\u032c\3\2\2\2\u00c7\u032f\3\2\2\2")
buf.write("\u00c9\u0332\3\2\2\2\u00cb\u0335\3\2\2\2\u00cd\u0339\3")
buf.write("\2\2\2\u00cf\u033d\3\2\2\2\u00d1\u0342\3\2\2\2\u00d3\u0345")
buf.write("\3\2\2\2\u00d5\u0348\3\2\2\2\u00d7\u034a\3\2\2\2\u00d9")
buf.write("\u034f\3\2\2\2\u00db\u0355\3\2\2\2\u00dd\u0363\3\2\2\2")
buf.write("\u00df\u036e\3\2\2\2\u00e1\u0375\3\2\2\2\u00e3\u0390\3")
buf.write("\2\2\2\u00e5\u0392\3\2\2\2\u00e7\u039d\3\2\2\2\u00e9\u039f")
buf.write("\3\2\2\2\u00eb\u03ab\3\2\2\2\u00ed\u03b1\3\2\2\2\u00ef")
buf.write("\u00f0\7c\2\2\u00f0\u00f1\7d\2\2\u00f1\u00f2\7u\2\2\u00f2")
buf.write("\u00f3\7v\2\2\u00f3\u00f4\7t\2\2\u00f4\u00f5\7c\2\2\u00f5")
buf.write("\u00f6\7e\2\2\u00f6\u00f7\7v\2\2\u00f7\4\3\2\2\2\u00f8")
buf.write("\u00f9\7c\2\2\u00f9\u00fa\7u\2\2\u00fa\u00fb\7u\2\2\u00fb")
buf.write("\u00fc\7g\2\2\u00fc\u00fd\7t\2\2\u00fd\u00fe\7v\2\2\u00fe")
buf.write("\6\3\2\2\2\u00ff\u0100\7d\2\2\u0100\u0101\7q\2\2\u0101")
buf.write("\u0102\7q\2\2\u0102\u0103\7n\2\2\u0103\u0104\7g\2\2\u0104")
buf.write("\u0105\7c\2\2\u0105\u0106\7p\2\2\u0106\b\3\2\2\2\u0107")
buf.write("\u0108\7d\2\2\u0108\u0109\7t\2\2\u0109\u010a\7g\2\2\u010a")
buf.write("\u010b\7c\2\2\u010b\u010c\7m\2\2\u010c\n\3\2\2\2\u010d")
buf.write("\u010e\7d\2\2\u010e\u010f\7{\2\2\u010f\u0110\7v\2\2\u0110")
buf.write("\u0111\7g\2\2\u0111\f\3\2\2\2\u0112\u0113\7e\2\2\u0113")
buf.write("\u0114\7c\2\2\u0114\u0115\7u\2\2\u0115\u0116\7g\2\2\u0116")
buf.write("\16\3\2\2\2\u0117\u0118\7e\2\2\u0118\u0119\7c\2\2\u0119")
buf.write("\u011a\7v\2\2\u011a\u011b\7e\2\2\u011b\u011c\7j\2\2\u011c")
buf.write("\20\3\2\2\2\u011d\u011e\7e\2\2\u011e\u011f\7j\2\2\u011f")
buf.write("\u0120\7c\2\2\u0120\u0121\7t\2\2\u0121\22\3\2\2\2\u0122")
buf.write("\u0123\7e\2\2\u0123\u0124\7n\2\2\u0124\u0125\7c\2\2\u0125")
buf.write("\u0126\7u\2\2\u0126\u0127\7u\2\2\u0127\24\3\2\2\2\u0128")
buf.write("\u0129\7e\2\2\u0129\u012a\7q\2\2\u012a\u012b\7p\2\2\u012b")
buf.write("\u012c\7u\2\2\u012c\u012d\7v\2\2\u012d\26\3\2\2\2\u012e")
buf.write("\u012f\7e\2\2\u012f\u0130\7q\2\2\u0130\u0131\7p\2\2\u0131")
buf.write("\u0132\7v\2\2\u0132\u0133\7k\2\2\u0133\u0134\7p\2\2\u0134")
buf.write("\u0135\7w\2\2\u0135\u0136\7g\2\2\u0136\30\3\2\2\2\u0137")
buf.write("\u0138\7f\2\2\u0138\u0139\7g\2\2\u0139\u013a\7h\2\2\u013a")
buf.write("\u013b\7c\2\2\u013b\u013c\7w\2\2\u013c\u013d\7n\2\2\u013d")
buf.write("\u013e\7v\2\2\u013e\32\3\2\2\2\u013f\u0140\7f\2\2\u0140")
buf.write("\u0141\7q\2\2\u0141\34\3\2\2\2\u0142\u0143\7f\2\2\u0143")
buf.write("\u0144\7q\2\2\u0144\u0145\7w\2\2\u0145\u0146\7d\2\2\u0146")
buf.write("\u0147\7n\2\2\u0147\u0148\7g\2\2\u0148\36\3\2\2\2\u0149")
buf.write("\u014a\7g\2\2\u014a\u014b\7n\2\2\u014b\u014c\7u\2\2\u014c")
buf.write("\u014d\7g\2\2\u014d \3\2\2\2\u014e\u014f\7g\2\2\u014f")
buf.write("\u0150\7p\2\2\u0150\u0151\7w\2\2\u0151\u0152\7o\2\2\u0152")
buf.write("\"\3\2\2\2\u0153\u0154\7g\2\2\u0154\u0155\7z\2\2\u0155")
buf.write("\u0156\7v\2\2\u0156\u0157\7g\2\2\u0157\u0158\7p\2\2\u0158")
buf.write("\u0159\7f\2\2\u0159\u015a\7u\2\2\u015a$\3\2\2\2\u015b")
buf.write("\u015c\7h\2\2\u015c\u015d\7k\2\2\u015d\u015e\7p\2\2\u015e")
buf.write("\u015f\7c\2\2\u015f\u0160\7n\2\2\u0160&\3\2\2\2\u0161")
buf.write("\u0162\7h\2\2\u0162\u0163\7k\2\2\u0163\u0164\7p\2\2\u0164")
buf.write("\u0165\7c\2\2\u0165\u0166\7n\2\2\u0166\u0167\7n\2\2\u0167")
buf.write("\u0168\7{\2\2\u0168(\3\2\2\2\u0169\u016a\7h\2\2\u016a")
buf.write("\u016b\7n\2\2\u016b\u016c\7q\2\2\u016c\u016d\7c\2\2\u016d")
buf.write("\u016e\7v\2\2\u016e*\3\2\2\2\u016f\u0170\7h\2\2\u0170")
buf.write("\u0171\7q\2\2\u0171\u0172\7t\2\2\u0172,\3\2\2\2\u0173")
buf.write("\u0174\7k\2\2\u0174\u0175\7h\2\2\u0175.\3\2\2\2\u0176")
buf.write("\u0177\7i\2\2\u0177\u0178\7q\2\2\u0178\u0179\7v\2\2\u0179")
buf.write("\u017a\7q\2\2\u017a\60\3\2\2\2\u017b\u017c\7k\2\2\u017c")
buf.write("\u017d\7o\2\2\u017d\u017e\7r\2\2\u017e\u017f\7n\2\2\u017f")
buf.write("\u0180\7g\2\2\u0180\u0181\7o\2\2\u0181\u0182\7g\2\2\u0182")
buf.write("\u0183\7p\2\2\u0183\u0184\7v\2\2\u0184\u0185\7u\2\2\u0185")
buf.write("\62\3\2\2\2\u0186\u0187\7k\2\2\u0187\u0188\7o\2\2\u0188")
buf.write("\u0189\7r\2\2\u0189\u018a\7q\2\2\u018a\u018b\7t\2\2\u018b")
buf.write("\u018c\7v\2\2\u018c\64\3\2\2\2\u018d\u018e\7k\2\2\u018e")
buf.write("\u018f\7p\2\2\u018f\u0190\7u\2\2\u0190\u0191\7v\2\2\u0191")
buf.write("\u0192\7c\2\2\u0192\u0193\7p\2\2\u0193\u0194\7e\2\2\u0194")
buf.write("\u0195\7g\2\2\u0195\u0196\7q\2\2\u0196\u0197\7h\2\2\u0197")
buf.write("\66\3\2\2\2\u0198\u0199\7k\2\2\u0199\u019a\7p\2\2\u019a")
buf.write("\u019b\7v\2\2\u019b8\3\2\2\2\u019c\u019d\7k\2\2\u019d")
buf.write("\u019e\7p\2\2\u019e\u019f\7v\2\2\u019f\u01a0\7g\2\2\u01a0")
buf.write("\u01a1\7t\2\2\u01a1\u01a2\7h\2\2\u01a2\u01a3\7c\2\2\u01a3")
buf.write("\u01a4\7e\2\2\u01a4\u01a5\7g\2\2\u01a5:\3\2\2\2\u01a6")
buf.write("\u01a7\7n\2\2\u01a7\u01a8\7q\2\2\u01a8\u01a9\7p\2\2\u01a9")
buf.write("\u01aa\7i\2\2\u01aa<\3\2\2\2\u01ab\u01ac\7p\2\2\u01ac")
buf.write("\u01ad\7c\2\2\u01ad\u01ae\7v\2\2\u01ae\u01af\7k\2\2\u01af")
buf.write("\u01b0\7x\2\2\u01b0\u01b1\7g\2\2\u01b1>\3\2\2\2\u01b2")
buf.write("\u01b3\7p\2\2\u01b3\u01b4\7g\2\2\u01b4\u01b5\7y\2\2\u01b5")
buf.write("@\3\2\2\2\u01b6\u01b7\7r\2\2\u01b7\u01b8\7c\2\2\u01b8")
buf.write("\u01b9\7e\2\2\u01b9\u01ba\7m\2\2\u01ba\u01bb\7c\2\2\u01bb")
buf.write("\u01bc\7i\2\2\u01bc\u01bd\7g\2\2\u01bdB\3\2\2\2\u01be")
buf.write("\u01bf\7r\2\2\u01bf\u01c0\7t\2\2\u01c0\u01c1\7k\2\2\u01c1")
buf.write("\u01c2\7x\2\2\u01c2\u01c3\7c\2\2\u01c3\u01c4\7v\2\2\u01c4")
buf.write("\u01c5\7g\2\2\u01c5D\3\2\2\2\u01c6\u01c7\7r\2\2\u01c7")
buf.write("\u01c8\7t\2\2\u01c8\u01c9\7q\2\2\u01c9\u01ca\7v\2\2\u01ca")
buf.write("\u01cb\7g\2\2\u01cb\u01cc\7e\2\2\u01cc\u01cd\7v\2\2\u01cd")
buf.write("\u01ce\7g\2\2\u01ce\u01cf\7f\2\2\u01cfF\3\2\2\2\u01d0")
buf.write("\u01d1\7r\2\2\u01d1\u01d2\7w\2\2\u01d2\u01d3\7d\2\2\u01d3")
buf.write("\u01d4\7n\2\2\u01d4\u01d5\7k\2\2\u01d5\u01d6\7e\2\2\u01d6")
buf.write("H\3\2\2\2\u01d7\u01d8\7t\2\2\u01d8\u01d9\7g\2\2\u01d9")
buf.write("\u01da\7v\2\2\u01da\u01db\7w\2\2\u01db\u01dc\7t\2\2\u01dc")
buf.write("\u01dd\7p\2\2\u01ddJ\3\2\2\2\u01de\u01df\7u\2\2\u01df")
buf.write("\u01e0\7j\2\2\u01e0\u01e1\7q\2\2\u01e1\u01e2\7t\2\2\u01e2")
buf.write("\u01e3\7v\2\2\u01e3L\3\2\2\2\u01e4\u01e5\7u\2\2\u01e5")
buf.write("\u01e6\7v\2\2\u01e6\u01e7\7c\2\2\u01e7\u01e8\7v\2\2\u01e8")
buf.write("\u01e9\7k\2\2\u01e9\u01ea\7e\2\2\u01eaN\3\2\2\2\u01eb")
buf.write("\u01ec\7u\2\2\u01ec\u01ed\7v\2\2\u01ed\u01ee\7t\2\2\u01ee")
buf.write("\u01ef\7k\2\2\u01ef\u01f0\7e\2\2\u01f0\u01f1\7v\2\2\u01f1")
buf.write("\u01f2\7h\2\2\u01f2\u01f3\7r\2\2\u01f3P\3\2\2\2\u01f4")
buf.write("\u01f5\7u\2\2\u01f5\u01f6\7w\2\2\u01f6\u01f7\7r\2\2\u01f7")
buf.write("\u01f8\7g\2\2\u01f8\u01f9\7t\2\2\u01f9R\3\2\2\2\u01fa")
buf.write("\u01fb\7u\2\2\u01fb\u01fc\7y\2\2\u01fc\u01fd\7k\2\2\u01fd")
buf.write("\u01fe\7v\2\2\u01fe\u01ff\7e\2\2\u01ff\u0200\7j\2\2\u0200")
buf.write("T\3\2\2\2\u0201\u0202\7u\2\2\u0202\u0203\7{\2\2\u0203")
buf.write("\u0204\7p\2\2\u0204\u0205\7e\2\2\u0205\u0206\7j\2\2\u0206")
buf.write("\u0207\7t\2\2\u0207\u0208\7q\2\2\u0208\u0209\7p\2\2\u0209")
buf.write("\u020a\7k\2\2\u020a\u020b\7|\2\2\u020b\u020c\7g\2\2\u020c")
buf.write("\u020d\7f\2\2\u020dV\3\2\2\2\u020e\u020f\7v\2\2\u020f")
buf.write("\u0210\7j\2\2\u0210\u0211\7k\2\2\u0211\u0212\7u\2\2\u0212")
buf.write("X\3\2\2\2\u0213\u0214\7v\2\2\u0214\u0215\7j\2\2\u0215")
buf.write("\u0216\7t\2\2\u0216\u0217\7q\2\2\u0217\u0218\7y\2\2\u0218")
buf.write("Z\3\2\2\2\u0219\u021a\7v\2\2\u021a\u021b\7j\2\2\u021b")
buf.write("\u021c\7t\2\2\u021c\u021d\7q\2\2\u021d\u021e\7y\2\2\u021e")
buf.write("\u021f\7u\2\2\u021f\\\3\2\2\2\u0220\u0221\7v\2\2\u0221")
buf.write("\u0222\7t\2\2\u0222\u0223\7c\2\2\u0223\u0224\7p\2\2\u0224")
buf.write("\u0225\7u\2\2\u0225\u0226\7k\2\2\u0226\u0227\7g\2\2\u0227")
buf.write("\u0228\7p\2\2\u0228\u0229\7v\2\2\u0229^\3\2\2\2\u022a")
buf.write("\u022b\7v\2\2\u022b\u022c\7t\2\2\u022c\u022d\7{\2\2\u022d")
buf.write("`\3\2\2\2\u022e\u022f\7x\2\2\u022f\u0230\7q\2\2\u0230")
buf.write("\u0231\7k\2\2\u0231\u0232\7f\2\2\u0232b\3\2\2\2\u0233")
buf.write("\u0234\7x\2\2\u0234\u0235\7q\2\2\u0235\u0236\7n\2\2\u0236")
buf.write("\u0237\7c\2\2\u0237\u0238\7v\2\2\u0238\u0239\7k\2\2\u0239")
buf.write("\u023a\7n\2\2\u023a\u023b\7g\2\2\u023bd\3\2\2\2\u023c")
buf.write("\u023d\7y\2\2\u023d\u023e\7j\2\2\u023e\u023f\7k\2\2\u023f")
buf.write("\u0240\7n\2\2\u0240\u0241\7g\2\2\u0241f\3\2\2\2\u0242")
buf.write("\u0250\7\62\2\2\u0243\u024d\t\2\2\2\u0244\u0246\5\u00e9")
buf.write("u\2\u0245\u0244\3\2\2\2\u0245\u0246\3\2\2\2\u0246\u024e")
buf.write("\3\2\2\2\u0247\u0249\7a\2\2\u0248\u0247\3\2\2\2\u0249")
buf.write("\u024a\3\2\2\2\u024a\u0248\3\2\2\2\u024a\u024b\3\2\2\2")
buf.write("\u024b\u024c\3\2\2\2\u024c\u024e\5\u00e9u\2\u024d\u0245")
buf.write("\3\2\2\2\u024d\u0248\3\2\2\2\u024e\u0250\3\2\2\2\u024f")
buf.write("\u0242\3\2\2\2\u024f\u0243\3\2\2\2\u0250\u0252\3\2\2\2")
buf.write("\u0251\u0253\t\3\2\2\u0252\u0251\3\2\2\2\u0252\u0253\3")
buf.write("\2\2\2\u0253h\3\2\2\2\u0254\u0255\7\62\2\2\u0255\u0256")
buf.write("\t\4\2\2\u0256\u025e\t\5\2\2\u0257\u0259\t\6\2\2\u0258")
buf.write("\u0257\3\2\2\2\u0259\u025c\3\2\2\2\u025a\u0258\3\2\2\2")
buf.write("\u025a\u025b\3\2\2\2\u025b\u025d\3\2\2\2\u025c\u025a\3")
buf.write("\2\2\2\u025d\u025f\t\5\2\2\u025e\u025a\3\2\2\2\u025e\u025f")
buf.write("\3\2\2\2\u025f\u0261\3\2\2\2\u0260\u0262\t\3\2\2\u0261")
buf.write("\u0260\3\2\2\2\u0261\u0262\3\2\2\2\u0262j\3\2\2\2\u0263")
buf.write("\u0267\7\62\2\2\u0264\u0266\7a\2\2\u0265\u0264\3\2\2\2")
buf.write("\u0266\u0269\3\2\2\2\u0267\u0265\3\2\2\2\u0267\u0268\3")
buf.write("\2\2\2\u0268\u026a\3\2\2\2\u0269\u0267\3\2\2\2\u026a\u0272")
buf.write("\t\7\2\2\u026b\u026d\t\b\2\2\u026c\u026b\3\2\2\2\u026d")
buf.write("\u0270\3\2\2\2\u026e\u026c\3\2\2\2\u026e\u026f\3\2\2\2")
buf.write("\u026f\u0271\3\2\2\2\u0270\u026e\3\2\2\2\u0271\u0273\t")
buf.write("\7\2\2\u0272\u026e\3\2\2\2\u0272\u0273\3\2\2\2\u0273\u0275")
buf.write("\3\2\2\2\u0274\u0276\t\3\2\2\u0275\u0274\3\2\2\2\u0275")
buf.write("\u0276\3\2\2\2\u0276l\3\2\2\2\u0277\u0278\7\62\2\2\u0278")
buf.write("\u0279\t\t\2\2\u0279\u0281\t\n\2\2\u027a\u027c\t\13\2")
buf.write("\2\u027b\u027a\3\2\2\2\u027c\u027f\3\2\2\2\u027d\u027b")
buf.write("\3\2\2\2\u027d\u027e\3\2\2\2\u027e\u0280\3\2\2\2\u027f")
buf.write("\u027d\3\2\2\2\u0280\u0282\t\n\2\2\u0281\u027d\3\2\2\2")
buf.write("\u0281\u0282\3\2\2\2\u0282\u0284\3\2\2\2\u0283\u0285\t")
buf.write("\3\2\2\u0284\u0283\3\2\2\2\u0284\u0285\3\2\2\2\u0285n")
buf.write("\3\2\2\2\u0286\u0287\5\u00e9u\2\u0287\u0289\7\60\2\2\u0288")
buf.write("\u028a\5\u00e9u\2\u0289\u0288\3\2\2\2\u0289\u028a\3\2")
buf.write("\2\2\u028a\u028e\3\2\2\2\u028b\u028c\7\60\2\2\u028c\u028e")
buf.write("\5\u00e9u\2\u028d\u0286\3\2\2\2\u028d\u028b\3\2\2\2\u028e")
buf.write("\u0290\3\2\2\2\u028f\u0291\5\u00e1q\2\u0290\u028f\3\2")
buf.write("\2\2\u0290\u0291\3\2\2\2\u0291\u0293\3\2\2\2\u0292\u0294")
buf.write("\t\f\2\2\u0293\u0292\3\2\2\2\u0293\u0294\3\2\2\2\u0294")
buf.write("\u029e\3\2\2\2\u0295\u029b\5\u00e9u\2\u0296\u0298\5\u00e1")
buf.write("q\2\u0297\u0299\t\f\2\2\u0298\u0297\3\2\2\2\u0298\u0299")
buf.write("\3\2\2\2\u0299\u029c\3\2\2\2\u029a\u029c\t\f\2\2\u029b")
buf.write("\u0296\3\2\2\2\u029b\u029a\3\2\2\2\u029c\u029e\3\2\2\2")
buf.write("\u029d\u028d\3\2\2\2\u029d\u0295\3\2\2\2\u029ep\3\2\2")
buf.write("\2\u029f\u02a0\7\62\2\2\u02a0\u02aa\t\4\2\2\u02a1\u02a3")
buf.write("\5\u00e5s\2\u02a2\u02a4\7\60\2\2\u02a3\u02a2\3\2\2\2\u02a3")
buf.write("\u02a4\3\2\2\2\u02a4\u02ab\3\2\2\2\u02a5\u02a7\5\u00e5")
buf.write("s\2\u02a6\u02a5\3\2\2\2\u02a6\u02a7\3\2\2\2\u02a7\u02a8")
buf.write("\3\2\2\2\u02a8\u02a9\7\60\2\2\u02a9\u02ab\5\u00e5s\2\u02aa")
buf.write("\u02a1\3\2\2\2\u02aa\u02a6\3\2\2\2\u02ab\u02ac\3\2\2\2")
buf.write("\u02ac\u02ae\t\r\2\2\u02ad\u02af\t\16\2\2\u02ae\u02ad")
buf.write("\3\2\2\2\u02ae\u02af\3\2\2\2\u02af\u02b0\3\2\2\2\u02b0")
buf.write("\u02b2\5\u00e9u\2\u02b1\u02b3\t\f\2\2\u02b2\u02b1\3\2")
buf.write("\2\2\u02b2\u02b3\3\2\2\2\u02b3r\3\2\2\2\u02b4\u02b5\7")
buf.write("v\2\2\u02b5\u02b6\7t\2\2\u02b6\u02b7\7w\2\2\u02b7\u02be")
buf.write("\7g\2\2\u02b8\u02b9\7h\2\2\u02b9\u02ba\7c\2\2\u02ba\u02bb")
buf.write("\7n\2\2\u02bb\u02bc\7u\2\2\u02bc\u02be\7g\2\2\u02bd\u02b4")
buf.write("\3\2\2\2\u02bd\u02b8\3\2\2\2\u02bet\3\2\2\2\u02bf\u02c2")
buf.write("\7)\2\2\u02c0\u02c3\n\17\2\2\u02c1\u02c3\5\u00e3r\2\u02c2")
buf.write("\u02c0\3\2\2\2\u02c2\u02c1\3\2\2\2\u02c3\u02c4\3\2\2\2")
buf.write("\u02c4\u02c5\7)\2\2\u02c5v\3\2\2\2\u02c6\u02cb\7$\2\2")
buf.write("\u02c7\u02ca\n\20\2\2\u02c8\u02ca\5\u00e3r\2\u02c9\u02c7")
buf.write("\3\2\2\2\u02c9\u02c8\3\2\2\2\u02ca\u02cd\3\2\2\2\u02cb")
buf.write("\u02c9\3\2\2\2\u02cb\u02cc\3\2\2\2\u02cc\u02ce\3\2\2\2")
buf.write("\u02cd\u02cb\3\2\2\2\u02ce\u02cf\7$\2\2\u02cfx\3\2\2\2")
buf.write("\u02d0\u02d1\7p\2\2\u02d1\u02d2\7w\2\2\u02d2\u02d3\7n")
buf.write("\2\2\u02d3\u02d4\7n\2\2\u02d4z\3\2\2\2\u02d5\u02d6\7*")
buf.write("\2\2\u02d6|\3\2\2\2\u02d7\u02d8\7+\2\2\u02d8~\3\2\2\2")
buf.write("\u02d9\u02da\7}\2\2\u02da\u0080\3\2\2\2\u02db\u02dc\7")
buf.write("\177\2\2\u02dc\u0082\3\2\2\2\u02dd\u02de\7]\2\2\u02de")
buf.write("\u0084\3\2\2\2\u02df\u02e0\7_\2\2\u02e0\u0086\3\2\2\2")
buf.write("\u02e1\u02e2\7=\2\2\u02e2\u0088\3\2\2\2\u02e3\u02e4\7")
buf.write(".\2\2\u02e4\u008a\3\2\2\2\u02e5\u02e6\7\60\2\2\u02e6\u008c")
buf.write("\3\2\2\2\u02e7\u02e8\7?\2\2\u02e8\u008e\3\2\2\2\u02e9")
buf.write("\u02ea\7@\2\2\u02ea\u0090\3\2\2\2\u02eb\u02ec\7>\2\2\u02ec")
buf.write("\u0092\3\2\2\2\u02ed\u02ee\7#\2\2\u02ee\u0094\3\2\2\2")
buf.write("\u02ef\u02f0\7\u0080\2\2\u02f0\u0096\3\2\2\2\u02f1\u02f2")
buf.write("\7A\2\2\u02f2\u0098\3\2\2\2\u02f3\u02f4\7<\2\2\u02f4\u009a")
buf.write("\3\2\2\2\u02f5\u02f6\7?\2\2\u02f6\u02f7\7?\2\2\u02f7\u009c")
buf.write("\3\2\2\2\u02f8\u02f9\7>\2\2\u02f9\u02fa\7?\2\2\u02fa\u009e")
buf.write("\3\2\2\2\u02fb\u02fc\7@\2\2\u02fc\u02fd\7?\2\2\u02fd\u00a0")
buf.write("\3\2\2\2\u02fe\u02ff\7#\2\2\u02ff\u0300\7?\2\2\u0300\u00a2")
buf.write("\3\2\2\2\u0301\u0302\7(\2\2\u0302\u0303\7(\2\2\u0303\u00a4")
buf.write("\3\2\2\2\u0304\u0305\7~\2\2\u0305\u0306\7~\2\2\u0306\u00a6")
buf.write("\3\2\2\2\u0307\u0308\7-\2\2\u0308\u0309\7-\2\2\u0309\u00a8")
buf.write("\3\2\2\2\u030a\u030b\7/\2\2\u030b\u030c\7/\2\2\u030c\u00aa")
buf.write("\3\2\2\2\u030d\u030e\7-\2\2\u030e\u00ac\3\2\2\2\u030f")
buf.write("\u0310\7/\2\2\u0310\u00ae\3\2\2\2\u0311\u0312\7,\2\2\u0312")
buf.write("\u00b0\3\2\2\2\u0313\u0314\7\61\2\2\u0314\u00b2\3\2\2")
buf.write("\2\u0315\u0316\7(\2\2\u0316\u00b4\3\2\2\2\u0317\u0318")
buf.write("\7~\2\2\u0318\u00b6\3\2\2\2\u0319\u031a\7`\2\2\u031a\u00b8")
buf.write("\3\2\2\2\u031b\u031c\7\'\2\2\u031c\u00ba\3\2\2\2\u031d")
buf.write("\u031e\7-\2\2\u031e\u031f\7?\2\2\u031f\u00bc\3\2\2\2\u0320")
buf.write("\u0321\7/\2\2\u0321\u0322\7?\2\2\u0322\u00be\3\2\2\2\u0323")
buf.write("\u0324\7,\2\2\u0324\u0325\7?\2\2\u0325\u00c0\3\2\2\2\u0326")
buf.write("\u0327\7\61\2\2\u0327\u0328\7?\2\2\u0328\u00c2\3\2\2\2")
buf.write("\u0329\u032a\7(\2\2\u032a\u032b\7?\2\2\u032b\u00c4\3\2")
buf.write("\2\2\u032c\u032d\7~\2\2\u032d\u032e\7?\2\2\u032e\u00c6")
buf.write("\3\2\2\2\u032f\u0330\7`\2\2\u0330\u0331\7?\2\2\u0331\u00c8")
buf.write("\3\2\2\2\u0332\u0333\7\'\2\2\u0333\u0334\7?\2\2\u0334")
buf.write("\u00ca\3\2\2\2\u0335\u0336\7>\2\2\u0336\u0337\7>\2\2\u0337")
buf.write("\u0338\7?\2\2\u0338\u00cc\3\2\2\2\u0339\u033a\7@\2\2\u033a")
buf.write("\u033b\7@\2\2\u033b\u033c\7?\2\2\u033c\u00ce\3\2\2\2\u033d")
buf.write("\u033e\7@\2\2\u033e\u033f\7@\2\2\u033f\u0340\7@\2\2\u0340")
buf.write("\u0341\7?\2\2\u0341\u00d0\3\2\2\2\u0342\u0343\7/\2\2\u0343")
buf.write("\u0344\7@\2\2\u0344\u00d2\3\2\2\2\u0345\u0346\7<\2\2\u0346")
buf.write("\u0347\7<\2\2\u0347\u00d4\3\2\2\2\u0348\u0349\7B\2\2\u0349")
buf.write("\u00d6\3\2\2\2\u034a\u034b\7\60\2\2\u034b\u034c\7\60\2")
buf.write("\2\u034c\u034d\7\60\2\2\u034d\u00d8\3\2\2\2\u034e\u0350")
buf.write("\t\21\2\2\u034f\u034e\3\2\2\2\u0350\u0351\3\2\2\2\u0351")
buf.write("\u034f\3\2\2\2\u0351\u0352\3\2\2\2\u0352\u0353\3\2\2\2")
buf.write("\u0353\u0354\bm\2\2\u0354\u00da\3\2\2\2\u0355\u0356\7")
buf.write("\61\2\2\u0356\u0357\7,\2\2\u0357\u035b\3\2\2\2\u0358\u035a")
buf.write("\13\2\2\2\u0359\u0358\3\2\2\2\u035a\u035d\3\2\2\2\u035b")
buf.write("\u035c\3\2\2\2\u035b\u0359\3\2\2\2\u035c\u035e\3\2\2\2")
buf.write("\u035d\u035b\3\2\2\2\u035e\u035f\7,\2\2\u035f\u0360\7")
buf.write("\61\2\2\u0360\u0361\3\2\2\2\u0361\u0362\bn\2\2\u0362\u00dc")
buf.write("\3\2\2\2\u0363\u0364\7\61\2\2\u0364\u0365\7\61\2\2\u0365")
buf.write("\u0369\3\2\2\2\u0366\u0368\n\22\2\2\u0367\u0366\3\2\2")
buf.write("\2\u0368\u036b\3\2\2\2\u0369\u0367\3\2\2\2\u0369\u036a")
buf.write("\3\2\2\2\u036a\u036c\3\2\2\2\u036b\u0369\3\2\2\2\u036c")
buf.write("\u036d\bo\2\2\u036d\u00de\3\2\2\2\u036e\u0372\5\u00ed")
buf.write("w\2\u036f\u0371\5\u00ebv\2\u0370\u036f\3\2\2\2\u0371\u0374")
buf.write("\3\2\2\2\u0372\u0370\3\2\2\2\u0372\u0373\3\2\2\2\u0373")
buf.write("\u00e0\3\2\2\2\u0374\u0372\3\2\2\2\u0375\u0377\t\23\2")
buf.write("\2\u0376\u0378\t\16\2\2\u0377\u0376\3\2\2\2\u0377\u0378")
buf.write("\3\2\2\2\u0378\u0379\3\2\2\2\u0379\u037a\5\u00e9u\2\u037a")
buf.write("\u00e2\3\2\2\2\u037b\u037c\7^\2\2\u037c\u0391\t\24\2\2")
buf.write("\u037d\u0382\7^\2\2\u037e\u0380\t\25\2\2\u037f\u037e\3")
buf.write("\2\2\2\u037f\u0380\3\2\2\2\u0380\u0381\3\2\2\2\u0381\u0383")
buf.write("\t\7\2\2\u0382\u037f\3\2\2\2\u0382\u0383\3\2\2\2\u0383")
buf.write("\u0384\3\2\2\2\u0384\u0391\t\7\2\2\u0385\u0387\7^\2\2")
buf.write("\u0386\u0388\7w\2\2\u0387\u0386\3\2\2\2\u0388\u0389\3")
buf.write("\2\2\2\u0389\u0387\3\2\2\2\u0389\u038a\3\2\2\2\u038a\u038b")
buf.write("\3\2\2\2\u038b\u038c\5\u00e7t\2\u038c\u038d\5\u00e7t\2")
buf.write("\u038d\u038e\5\u00e7t\2\u038e\u038f\5\u00e7t\2\u038f\u0391")
buf.write("\3\2\2\2\u0390\u037b\3\2\2\2\u0390\u037d\3\2\2\2\u0390")
buf.write("\u0385\3\2\2\2\u0391\u00e4\3\2\2\2\u0392\u039b\5\u00e7")
buf.write("t\2\u0393\u0396\5\u00e7t\2\u0394\u0396\7a\2\2\u0395\u0393")
buf.write("\3\2\2\2\u0395\u0394\3\2\2\2\u0396\u0399\3\2\2\2\u0397")
buf.write("\u0395\3\2\2\2\u0397\u0398\3\2\2\2\u0398\u039a\3\2\2\2")
buf.write("\u0399\u0397\3\2\2\2\u039a\u039c\5\u00e7t\2\u039b\u0397")
buf.write("\3\2\2\2\u039b\u039c\3\2\2\2\u039c\u00e6\3\2\2\2\u039d")
buf.write("\u039e\t\5\2\2\u039e\u00e8\3\2\2\2\u039f\u03a7\t\26\2")
buf.write("\2\u03a0\u03a2\t\27\2\2\u03a1\u03a0\3\2\2\2\u03a2\u03a5")
buf.write("\3\2\2\2\u03a3\u03a1\3\2\2\2\u03a3\u03a4\3\2\2\2\u03a4")
buf.write("\u03a6\3\2\2\2\u03a5\u03a3\3\2\2\2\u03a6\u03a8\t\26\2")
buf.write("\2\u03a7\u03a3\3\2\2\2\u03a7\u03a8\3\2\2\2\u03a8\u00ea")
buf.write("\3\2\2\2\u03a9\u03ac\5\u00edw\2\u03aa\u03ac\t\26\2\2\u03ab")
buf.write("\u03a9\3\2\2\2\u03ab\u03aa\3\2\2\2\u03ac\u00ec\3\2\2\2")
buf.write("\u03ad\u03b2\t\30\2\2\u03ae\u03b2\n\31\2\2\u03af\u03b0")
buf.write("\t\32\2\2\u03b0\u03b2\t\33\2\2\u03b1\u03ad\3\2\2\2\u03b1")
buf.write("\u03ae\3\2\2\2\u03b1\u03af\3\2\2\2\u03b2\u00ee\3\2\2\2")
buf.write("\62\2\u0245\u024a\u024d\u024f\u0252\u025a\u025e\u0261")
buf.write("\u0267\u026e\u0272\u0275\u027d\u0281\u0284\u0289\u028d")
buf.write("\u0290\u0293\u0298\u029b\u029d\u02a3\u02a6\u02aa\u02ae")
buf.write("\u02b2\u02bd\u02c2\u02c9\u02cb\u0351\u035b\u0369\u0372")
buf.write("\u0377\u037f\u0382\u0389\u0390\u0395\u0397\u039b\u03a3")
buf.write("\u03a7\u03ab\u03b1\3\2\3\2")
return buf.getvalue()
class JavaLexer(Lexer):
atn = ATNDeserializer().deserialize(serializedATN())
decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
ABSTRACT = 1
ASSERT = 2
BOOLEAN = 3
BREAK = 4
BYTE = 5
CASE = 6
CATCH = 7
CHAR = 8
CLASS = 9
CONST = 10
CONTINUE = 11
DEFAULT = 12
DO = 13
DOUBLE = 14
ELSE = 15
ENUM = 16
EXTENDS = 17
FINAL = 18
FINALLY = 19
FLOAT = 20
FOR = 21
IF = 22
GOTO = 23
IMPLEMENTS = 24
IMPORT = 25
INSTANCEOF = 26
INT = 27
INTERFACE = 28
LONG = 29
NATIVE = 30
NEW = 31
PACKAGE = 32
PRIVATE = 33
PROTECTED = 34
PUBLIC = 35
RETURN = 36
SHORT = 37
STATIC = 38
STRICTFP = 39
SUPER = 40
SWITCH = 41
SYNCHRONIZED = 42
THIS = 43
THROW = 44
THROWS = 45
TRANSIENT = 46
TRY = 47
VOID = 48
VOLATILE = 49
WHILE = 50
DECIMAL_LITERAL = 51
HEX_LITERAL = 52
OCT_LITERAL = 53
BINARY_LITERAL = 54
FLOAT_LITERAL = 55
HEX_FLOAT_LITERAL = 56
BOOL_LITERAL = 57
CHAR_LITERAL = 58
STRING_LITERAL = 59
NULL_LITERAL = 60
LPAREN = 61
RPAREN = 62
LBRACE = 63
RBRACE = 64
LBRACK = 65
RBRACK = 66
SEMI = 67
COMMA = 68
DOT = 69
ASSIGN = 70
GT = 71
LT = 72
BANG = 73
TILDE = 74
QUESTION = 75
COLON = 76
EQUAL = 77
LE = 78
GE = 79
NOTEQUAL = 80
AND = 81
OR = 82
INC = 83
DEC = 84
ADD = 85
SUB = 86
MUL = 87
DIV = 88
BITAND = 89
BITOR = 90
CARET = 91
MOD = 92
ADD_ASSIGN = 93
SUB_ASSIGN = 94
MUL_ASSIGN = 95
DIV_ASSIGN = 96
AND_ASSIGN = 97
OR_ASSIGN = 98
XOR_ASSIGN = 99
MOD_ASSIGN = 100
LSHIFT_ASSIGN = 101
RSHIFT_ASSIGN = 102
URSHIFT_ASSIGN = 103
ARROW = 104
COLONCOLON = 105
AT = 106
ELLIPSIS = 107
WS = 108
COMMENT = 109
LINE_COMMENT = 110
IDENTIFIER = 111
channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ]
modeNames = [ "DEFAULT_MODE" ]
literalNames = [ "<INVALID>",
"'abstract'", "'assert'", "'boolean'", "'break'", "'byte'",
"'case'", "'catch'", "'char'", "'class'", "'const'", "'continue'",
"'default'", "'do'", "'double'", "'else'", "'enum'", "'extends'",
"'final'", "'finally'", "'float'", "'for'", "'if'", "'goto'",
"'implements'", "'import'", "'instanceof'", "'int'", "'interface'",
"'long'", "'native'", "'new'", "'package'", "'private'", "'protected'",
"'public'", "'return'", "'short'", "'static'", "'strictfp'",
"'super'", "'switch'", "'synchronized'", "'this'", "'throw'",
"'throws'", "'transient'", "'try'", "'void'", "'volatile'",
"'while'", "'null'", "'('", "')'", "'{'", "'}'", "'['", "']'",
"';'", "','", "'.'", "'='", "'>'", "'<'", "'!'", "'~'", "'?'",
"':'", "'=='", "'<='", "'>='", "'!='", "'&&'", "'||'", "'++'",
"'--'", "'+'", "'-'", "'*'", "'/'", "'&'", "'|'", "'^'", "'%'",
"'+='", "'-='", "'*='", "'/='", "'&='", "'|='", "'^='", "'%='",
"'<<='", "'>>='", "'>>>='", "'->'", "'::'", "'@'", "'...'" ]
symbolicNames = [ "<INVALID>",
"ABSTRACT", "ASSERT", "BOOLEAN", "BREAK", "BYTE", "CASE", "CATCH",
"CHAR", "CLASS", "CONST", "CONTINUE", "DEFAULT", "DO", "DOUBLE",
"ELSE", "ENUM", "EXTENDS", "FINAL", "FINALLY", "FLOAT", "FOR",
"IF", "GOTO", "IMPLEMENTS", "IMPORT", "INSTANCEOF", "INT", "INTERFACE",
"LONG", "NATIVE", "NEW", "PACKAGE", "PRIVATE", "PROTECTED",
"PUBLIC", "RETURN", "SHORT", "STATIC", "STRICTFP", "SUPER",
"SWITCH", "SYNCHRONIZED", "THIS", "THROW", "THROWS", "TRANSIENT",
"TRY", "VOID", "VOLATILE", "WHILE", "DECIMAL_LITERAL", "HEX_LITERAL",
"OCT_LITERAL", "BINARY_LITERAL", "FLOAT_LITERAL", "HEX_FLOAT_LITERAL",
"BOOL_LITERAL", "CHAR_LITERAL", "STRING_LITERAL", "NULL_LITERAL",
"LPAREN", "RPAREN", "LBRACE", "RBRACE", "LBRACK", "RBRACK",
"SEMI", "COMMA", "DOT", "ASSIGN", "GT", "LT", "BANG", "TILDE",
"QUESTION", "COLON", "EQUAL", "LE", "GE", "NOTEQUAL", "AND",
"OR", "INC", "DEC", "ADD", "SUB", "MUL", "DIV", "BITAND", "BITOR",
"CARET", "MOD", "ADD_ASSIGN", "SUB_ASSIGN", "MUL_ASSIGN", "DIV_ASSIGN",
"AND_ASSIGN", "OR_ASSIGN", "XOR_ASSIGN", "MOD_ASSIGN", "LSHIFT_ASSIGN",
"RSHIFT_ASSIGN", "URSHIFT_ASSIGN", "ARROW", "COLONCOLON", "AT",
"ELLIPSIS", "WS", "COMMENT", "LINE_COMMENT", "IDENTIFIER" ]
ruleNames = [ "ABSTRACT", "ASSERT", "BOOLEAN", "BREAK", "BYTE", "CASE",
"CATCH", "CHAR", "CLASS", "CONST", "CONTINUE", "DEFAULT",
"DO", "DOUBLE", "ELSE", "ENUM", "EXTENDS", "FINAL", "FINALLY",
"FLOAT", "FOR", "IF", "GOTO", "IMPLEMENTS", "IMPORT",
"INSTANCEOF", "INT", "INTERFACE", "LONG", "NATIVE", "NEW",
"PACKAGE", "PRIVATE", "PROTECTED", "PUBLIC", "RETURN",
"SHORT", "STATIC", "STRICTFP", "SUPER", "SWITCH", "SYNCHRONIZED",
"THIS", "THROW", "THROWS", "TRANSIENT", "TRY", "VOID",
"VOLATILE", "WHILE", "DECIMAL_LITERAL", "HEX_LITERAL",
"OCT_LITERAL", "BINARY_LITERAL", "FLOAT_LITERAL", "HEX_FLOAT_LITERAL",
"BOOL_LITERAL", "CHAR_LITERAL", "STRING_LITERAL", "NULL_LITERAL",
"LPAREN", "RPAREN", "LBRACE", "RBRACE", "LBRACK", "RBRACK",
"SEMI", "COMMA", "DOT", "ASSIGN", "GT", "LT", "BANG",
"TILDE", "QUESTION", "COLON", "EQUAL", "LE", "GE", "NOTEQUAL",
"AND", "OR", "INC", "DEC", "ADD", "SUB", "MUL", "DIV",
"BITAND", "BITOR", "CARET", "MOD", "ADD_ASSIGN", "SUB_ASSIGN",
"MUL_ASSIGN", "DIV_ASSIGN", "AND_ASSIGN", "OR_ASSIGN",
"XOR_ASSIGN", "MOD_ASSIGN", "LSHIFT_ASSIGN", "RSHIFT_ASSIGN",
"URSHIFT_ASSIGN", "ARROW", "COLONCOLON", "AT", "ELLIPSIS",
"WS", "COMMENT", "LINE_COMMENT", "IDENTIFIER", "ExponentPart",
"EscapeSequence", "HexDigits", "HexDigit", "Digits", "LetterOrDigit",
"Letter" ]
grammarFileName = "JavaLexer.g4"
def __init__(self, input=None, output:TextIO = sys.stdout):
super().__init__(input, output)
self.checkVersion("4.9.1")
self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())
self._actions = None
self._predicates = None
| true | true |
1c36c8ef1d2c867a47fb7450d8b3d130c7d9cb6f | 260 | py | Python | students/K33401/Nikitin_michael/lab2/django_project_nikitin/project_first_app/forms.py | mexannik1998/ITMO_ICT_WebDevelopment_2021-2022 | 0894edd7d49a73abba31f72266fdeb35fc3f6367 | [
"MIT"
] | null | null | null | students/K33401/Nikitin_michael/lab2/django_project_nikitin/project_first_app/forms.py | mexannik1998/ITMO_ICT_WebDevelopment_2021-2022 | 0894edd7d49a73abba31f72266fdeb35fc3f6367 | [
"MIT"
] | null | null | null | students/K33401/Nikitin_michael/lab2/django_project_nikitin/project_first_app/forms.py | mexannik1998/ITMO_ICT_WebDevelopment_2021-2022 | 0894edd7d49a73abba31f72266fdeb35fc3f6367 | [
"MIT"
] | null | null | null | from django import forms
from .models import Driver
# creating a form
class DriverForm(forms.ModelForm):
class Meta:
model = Driver
fields = [
'surname',
'name',
'date_of_birth',
] | 18.571429 | 35 | 0.519231 | from django import forms
from .models import Driver
class DriverForm(forms.ModelForm):
class Meta:
model = Driver
fields = [
'surname',
'name',
'date_of_birth',
] | true | true |
1c36c92e1f9c4840b2c0b0d747da1272c853fedb | 504 | py | Python | crops/about.py | jjavier-bm/crops | 658a98f9c168cc27b3f967e7a60a0df896ef5ac6 | [
"BSD-3-Clause"
] | null | null | null | crops/about.py | jjavier-bm/crops | 658a98f9c168cc27b3f967e7a60a0df896ef5ac6 | [
"BSD-3-Clause"
] | 5 | 2020-07-17T08:45:22.000Z | 2022-03-11T13:39:26.000Z | crops/about.py | jjavier-bm/crops | 658a98f9c168cc27b3f967e7a60a0df896ef5ac6 | [
"BSD-3-Clause"
] | 1 | 2020-07-07T15:42:07.000Z | 2020-07-07T15:42:07.000Z | """This is CROPS: Cropping and Renumbering Operations for PDB structure and Sequence files"""
"""About CROPS. Package information is recorded here"""
import datetime
__prog__="CROPS"
__description__="Cropping and Renumbering Operations for PDB structure and Sequence files"
__author__ = "J. Javier Burgos-Mármol"
__date__ = "Jul 2020"
__copyright__='2020-{}, University of Liverpool'.format(datetime.datetime.now().year)
__version_info__ = (0, 1, 1)
__version__ = ".".join(map(str, __version_info__))
| 36 | 93 | 0.769841 |
import datetime
__prog__="CROPS"
__description__="Cropping and Renumbering Operations for PDB structure and Sequence files"
__author__ = "J. Javier Burgos-Mármol"
__date__ = "Jul 2020"
__copyright__='2020-{}, University of Liverpool'.format(datetime.datetime.now().year)
__version_info__ = (0, 1, 1)
__version__ = ".".join(map(str, __version_info__))
| true | true |
1c36ce662cb03a57e4e8b1aff3c1632c3ff06d32 | 3,066 | py | Python | ROAR/agent_module/mark_agent.py | RyanC1681/RCAI1122 | c9683110b58c255a7a78d880ff73df7ff2329405 | [
"Apache-2.0"
] | 18 | 2020-10-16T00:38:55.000Z | 2022-03-03T06:01:49.000Z | ROAR/agent_module/mark_agent.py | Jaish567/ROAR | 75b0bc819abbe676f518070da3fa8043422c7cb7 | [
"Apache-2.0"
] | 20 | 2020-07-23T03:50:50.000Z | 2021-11-09T04:00:26.000Z | ROAR/agent_module/mark_agent.py | Jaish567/ROAR | 75b0bc819abbe676f518070da3fa8043422c7cb7 | [
"Apache-2.0"
] | 140 | 2019-11-20T22:46:02.000Z | 2022-03-29T13:26:17.000Z | from ROAR.agent_module.agent import Agent
from pathlib import Path
from ROAR.control_module.pid_controller import PIDController
from ROAR.planning_module.local_planner.simple_waypoint_following_local_planner import \
SimpleWaypointFollowingLocalPlanner
from ROAR.planning_module.behavior_planner.behavior_planner import BehaviorPlanner
from ROAR.planning_module.mission_planner.waypoint_following_mission_planner import WaypointFollowingMissionPlanner
from ROAR.utilities_module.data_structures_models import SensorsData
from ROAR.utilities_module.vehicle_models import VehicleControl, Vehicle
from ROAR.planning_module.local_planner.dwa_planner import DWAPlanner
from ROAR.utilities_module.occupancy_map import OccupancyGridMap
import logging
from ROAR.perception_module.obstacle_from_depth import ObstacleFromDepth
class MarkAgent(Agent):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.route_file_path = Path(self.agent_settings.waypoint_file_path)
self.pid_controller = PIDController(agent=self,
steering_boundary=(-1, 1), throttle_boundary=(0, 1))
self.mission_planner = WaypointFollowingMissionPlanner(agent=self)
# initiated right after mission plan
self.behavior_planner = BehaviorPlanner(agent=self)
self.local_planner = DWAPlanner(
agent=self,
controller=self.pid_controller,
mission_planner=self.mission_planner,
behavior_planner=self.behavior_planner,
closeness_threshold=1)
self.occupancy_map = OccupancyGridMap(absolute_maximum_map_size=1000,
world_coord_resolution=1,
occu_prob=0.99,
max_points_to_convert=5000,
threaded=True)
self.obstacle_from_depth_detector = ObstacleFromDepth(agent=self,
threaded=True,
max_detectable_distance=0.3,
max_points_to_convert=10000,
min_obstacle_height=2)
self.add_threaded_module(self.obstacle_from_depth_detector)
self.add_threaded_module(self.occupancy_map)
def run_step(self, sensors_data: SensorsData, vehicle: Vehicle) -> VehicleControl:
super(MarkAgent, self).run_step(vehicle=vehicle,
sensors_data=sensors_data)
control = self.local_planner.run_in_series()
option = "obstacle_coords" # ground_coords, point_cloud_obstacle_from_depth
if self.kwargs.get(option, None) is not None:
points = self.kwargs[option]
self.occupancy_map.update_async(points)
self.occupancy_map.visualize()
self.occupancy_map.get_map()
return control
| 51.1 | 115 | 0.646445 | from ROAR.agent_module.agent import Agent
from pathlib import Path
from ROAR.control_module.pid_controller import PIDController
from ROAR.planning_module.local_planner.simple_waypoint_following_local_planner import \
SimpleWaypointFollowingLocalPlanner
from ROAR.planning_module.behavior_planner.behavior_planner import BehaviorPlanner
from ROAR.planning_module.mission_planner.waypoint_following_mission_planner import WaypointFollowingMissionPlanner
from ROAR.utilities_module.data_structures_models import SensorsData
from ROAR.utilities_module.vehicle_models import VehicleControl, Vehicle
from ROAR.planning_module.local_planner.dwa_planner import DWAPlanner
from ROAR.utilities_module.occupancy_map import OccupancyGridMap
import logging
from ROAR.perception_module.obstacle_from_depth import ObstacleFromDepth
class MarkAgent(Agent):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.route_file_path = Path(self.agent_settings.waypoint_file_path)
self.pid_controller = PIDController(agent=self,
steering_boundary=(-1, 1), throttle_boundary=(0, 1))
self.mission_planner = WaypointFollowingMissionPlanner(agent=self)
self.behavior_planner = BehaviorPlanner(agent=self)
self.local_planner = DWAPlanner(
agent=self,
controller=self.pid_controller,
mission_planner=self.mission_planner,
behavior_planner=self.behavior_planner,
closeness_threshold=1)
self.occupancy_map = OccupancyGridMap(absolute_maximum_map_size=1000,
world_coord_resolution=1,
occu_prob=0.99,
max_points_to_convert=5000,
threaded=True)
self.obstacle_from_depth_detector = ObstacleFromDepth(agent=self,
threaded=True,
max_detectable_distance=0.3,
max_points_to_convert=10000,
min_obstacle_height=2)
self.add_threaded_module(self.obstacle_from_depth_detector)
self.add_threaded_module(self.occupancy_map)
def run_step(self, sensors_data: SensorsData, vehicle: Vehicle) -> VehicleControl:
super(MarkAgent, self).run_step(vehicle=vehicle,
sensors_data=sensors_data)
control = self.local_planner.run_in_series()
option = "obstacle_coords"
if self.kwargs.get(option, None) is not None:
points = self.kwargs[option]
self.occupancy_map.update_async(points)
self.occupancy_map.visualize()
self.occupancy_map.get_map()
return control
| true | true |
1c36d0a425fc91d76368d674fcae1e02ca450e66 | 15,319 | py | Python | src/idea/tests/listview_tests.py | m3brown/idea-box | 3a0300be849be62b138aefd0197f667b980f6e28 | [
"CC0-1.0"
] | null | null | null | src/idea/tests/listview_tests.py | m3brown/idea-box | 3a0300be849be62b138aefd0197f667b980f6e28 | [
"CC0-1.0"
] | null | null | null | src/idea/tests/listview_tests.py | m3brown/idea-box | 3a0300be849be62b138aefd0197f667b980f6e28 | [
"CC0-1.0"
] | null | null | null | import datetime
from django.contrib.auth import get_user_model
from django.utils.timezone import get_default_timezone
from django.contrib.comments.models import Comment
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.test import TestCase
from idea import models, views
from idea.tests.utils import mock_req, random_user
from mock import patch
import string
def get_relative_date(delta_days=0):
return datetime.date.today() + datetime.timedelta(days=delta_days)
def create_banner(title, delta_days=0):
banner = models.Banner(title=title, text=title+' Text',
start_date=get_relative_date(-delta_days),
end_date=get_relative_date(delta_days))
banner.save()
return banner
class ListViewTest(TestCase):
"""
Tests for idea.views.list
"""
fixtures = ['state']
def _generate_data(self, paramfn=lambda x,y:None, postfn=lambda x,y:None,
entry_data=[(5, 'AAAA'), (9, 'BBBB'), (3, 'CCCC'), (7, 'DDDD'),
(1, 'EEEE'), (11, 'FFFF')]):
"""
Helper function to handle the idea (and related models) creation.
"""
user = get_user_model().objects.create_user('example')
state = models.State.objects.get(name='Active')
state.save()
def make_idea(nonce, title):
kwargs = {'creator': user, 'title': title,
'text': title + ' Text', 'state': state}
paramfn(kwargs, nonce)
idea = models.Idea(**kwargs)
idea.save()
postfn(idea, nonce)
return idea
ideas = [make_idea(pair[0], pair[1]) for pair in entry_data]
def _verify_order(self, render):
"""
Given a patched render, verify the order of the ideas.
"""
context = render.call_args[0][2]
self.assertTrue('ideas' in context)
self.assertEqual(6, len(context['ideas']))
self.assertEqual('FFFF', context['ideas'][0].title)
self.assertEqual('BBBB', context['ideas'][1].title)
self.assertEqual('DDDD', context['ideas'][2].title)
self.assertEqual('AAAA', context['ideas'][3].title)
self.assertEqual('CCCC', context['ideas'][4].title)
self.assertEqual('EEEE', context['ideas'][5].title)
@patch('idea.views.render')
def test_sort_recent(self, render):
"""
Verify that the recent sort params works.
"""
def add_time(kwargs, nonce):
kwargs['time'] = datetime.datetime(2013, 1, nonce, tzinfo=get_default_timezone())
self._generate_data(paramfn=add_time)
views.list(mock_req(), sort_or_state='recent')
self._verify_order(render)
@patch('idea.views.render')
def test_sort_trending(self, render):
"""
Verify that the comments sort works.
"""
idea_type = ContentType.objects.get(app_label="idea", model="idea")
site = Site.objects.get_current()
def add_time(kwargs, nonce):
# add future timestamp for item 3
if nonce == 3:
kwargs['time'] = datetime.datetime(2050, 1, nonce, tzinfo=get_default_timezone())
def create_timestamp_event(idea, nonce):
# add future timestamp for vote for items 0, 2, 4
if nonce % 2 == 0:
models.Vote(creator=idea.creator,
idea=idea,
time=datetime.datetime(2050, 1, nonce, tzinfo=get_default_timezone())
).save()
# add future timestamp for comment for items 1, 5
elif nonce != 3:
Comment(content_type=idea_type, site=site,
object_pk=idea.pk, user=idea.creator,
comment='Blah',
submit_date=datetime.datetime(2050, 1, nonce, tzinfo=get_default_timezone())
).save()
self._generate_data(postfn=create_timestamp_event, paramfn=add_time)
views.list(mock_req(), sort_or_state='trending')
self._verify_order(render)
@patch('idea.views.render')
def test_sort_vote(self, render):
"""
Verify that the votes sort works.
"""
def create_votes(idea, nonce):
for _ in range(nonce):
models.Vote(creator=idea.creator, idea=idea).save()
self._generate_data(postfn=create_votes)
views.list(mock_req(), sort_or_state='vote')
self._verify_order(render)
@patch('idea.views.render')
def test_paging(self, render):
"""
Verify that paging works as we would expect.
"""
letters = string.uppercase
entry_data = []
## current default ordering is based on most recently modified
## Count down from 12 to 1, so A has the most recent timestamp
for i in range(12, -1, -1):
entry_data.append((i+1, letters[i]*4))
self._generate_data(entry_data=entry_data)
views.list(mock_req())
context = render.call_args[0][2]
self.assertTrue('ideas' in context)
self.assertEqual(10, len(context['ideas']))
self.assertEqual('AAAA', context['ideas'][0].title)
self.assertEqual('EEEE', context['ideas'][4].title)
views.list(mock_req('/?page_num=1'))
context = render.call_args[0][2]
self.assertTrue('ideas' in context)
self.assertEqual(10, len(context['ideas']))
self.assertEqual('AAAA', context['ideas'][0].title)
self.assertEqual('EEEE', context['ideas'][4].title)
views.list(mock_req('/?page_num=sadasds'))
context = render.call_args[0][2]
self.assertTrue('ideas' in context)
self.assertEqual(10, len(context['ideas']))
self.assertEqual('AAAA', context['ideas'][0].title)
self.assertEqual('EEEE', context['ideas'][4].title)
views.list(mock_req('/?page_num=2'))
context = render.call_args[0][2]
self.assertTrue('ideas' in context)
self.assertEqual(3, len(context['ideas']))
self.assertEqual('KKKK', context['ideas'][0].title)
self.assertEqual('MMMM', context['ideas'][2].title)
views.list(mock_req('/?page_num=232432'))
context = render.call_args[0][2]
self.assertTrue('ideas' in context)
self.assertEqual(3, len(context['ideas']))
self.assertEqual('KKKK', context['ideas'][0].title)
self.assertEqual('MMMM', context['ideas'][2].title)
@patch('idea.views.render')
def test_idea_fields(self, render):
"""
Verify that the fields needed by the ui are available on all ideas.
"""
self._generate_data()
views.list(mock_req())
context = render.call_args[0][2]
self.assertTrue('ideas' in context)
self.assertEqual(6, len(context['ideas']))
for idea in context['ideas']:
self.assertTrue(hasattr(idea, 'title'))
self.assertTrue(hasattr(idea, 'url'))
self.assertTrue(hasattr(idea.creator, 'first_name'))
self.assertTrue(hasattr(idea.creator, 'last_name'))
#self.assertTrue(hasattr(idea.creator, 'photo'))
#self.assertTrue(hasattr(idea, 'comment_count'))
self.assertTrue(hasattr(idea, 'vote_count'))
self.assertTrue(hasattr(idea, 'time'))
@patch('idea.views.render')
def test_idea_state_filter(self, render):
"""
Verify that state filters work as we expect.
"""
def check_state(kwargs, nonce):
if nonce % 2 == 0:
kwargs['state'] = models.State.objects.get(name='Archive')
self._generate_data(entry_data=[(1,'AAAA'), (2,'BBBB'), (3,'CCCC')],
paramfn=check_state)
# defaults to active
views.list(mock_req())
context = render.call_args[0][2]
self.assertTrue('ideas' in context)
self.assertEqual(2, len(context['ideas']))
# But archive works
views.list(mock_req(), sort_or_state='archived')
context = render.call_args[0][2]
self.assertTrue('ideas' in context)
self.assertEqual(1, len(context['ideas']))
@patch('idea.views.render')
def test_current_banner(self, render):
"""
Check that the current banner is populated
"""
views.list(mock_req())
context = render.call_args[0][2]
self.assertTrue('banner' in context)
self.assertIsNone(context['banner'])
banner = create_banner('AAAA')
views.list(mock_req())
context = render.call_args[0][2]
self.assertTrue('banner' in context)
self.assertEqual(context['banner'], banner)
@patch('idea.views.render')
def test_browse_banners(self, render):
"""
Check that the banner list is populated if more than one active banner
"""
views.list(mock_req())
context = render.call_args[0][2]
self.assertTrue('browse_banners' in context)
self.assertIsNone(context['browse_banners'])
create_banner('AAAA', 3)
create_banner('BBBB', 2)
create_banner('CCCC', 1)
create_banner('DDDD', 6)
create_banner('EEEE', 5)
create_banner('FFFF', 4)
views.list(mock_req())
context = render.call_args[0][2]
self.assertTrue('browse_banners' in context)
self.assertEqual(len(context['browse_banners']), 4)
self.assertEqual(context['browse_banners'][0].title, 'BBBB')
self.assertEqual(context['browse_banners'][1].title, 'AAAA')
self.assertEqual(context['browse_banners'][2].title, 'FFFF')
self.assertEqual(context['browse_banners'][3].title, 'EEEE')
@patch('idea.views.render')
def test_tags_exist(self, render):
"""
Check that the tag list is populated and only shows the top ten
tags.
"""
user = random_user()
state = models.State.objects.get(name='Active')
state.save()
idea = models.Idea(creator=user, title='AAAA', text='AAAA Text',
state=state)
idea.save()
idea.tags.add('bbb', 'ccc', 'ddd')
views.list(mock_req())
context = render.call_args[0][2]
self.assertTrue('tags' in context)
self.assertEqual(3, len(context['tags']))
self.assertEqual(set(['bbb', 'ccc', 'ddd']),
set([t.name for t in context['tags']]))
@patch('idea.views.render')
def test_tags_top_list(self, render):
"""
Tag list should be in proper order.
"""
user = random_user()
state = models.State.objects.get(name='Active')
state.save()
# Make 13 tags, and assign each to a set of ideas
for count in range(30):
tag = str(count)*4
for i in range(count+1):
idea = models.Idea(creator=user, title=str(i)*4,
text=str(i)*4 +' Text', state=state)
idea.save()
idea.tags.add(tag)
views.list(mock_req())
context = render.call_args[0][2]
self.assertTrue('tags' in context)
self.assertEqual(25, len(context['tags']))
# 29292929, 28282828, 27272727, ...
self.assertEqual([str(i)*4 for i in range(29,4,-1)],
[t.name for t in context['tags']])
@patch('idea.views.render')
def test_tags_count(self, render):
"""
Tag list should include tag count.
"""
user = random_user()
state = models.State.objects.get(name='Active')
state.save()
# Make 13 tags, and assign each to a set of ideas
for count in range(13):
tag = str(count)*4
for i in range(count+1):
idea = models.Idea(creator=user, title=str(i)*4,
text=str(i)*4 +' Text', state=state)
idea.save()
idea.tags.add(tag)
views.list(mock_req())
context = render.call_args[0][2]
self.assertTrue('tags' in context)
for i in range(12,2,-1):
tag = context['tags'][12-i]
self.assertTrue(hasattr(tag, 'count'))
self.assertEqual(i+1, tag.count)
@patch('idea.views.render')
def test_tags_active(self, render):
"""
Tag list should include if tag was active in this search.
"""
def add_tag(idea, nonce):
tag = str(nonce % 3)
idea.tags.add(tag)
self._generate_data(postfn=add_tag)
views.list(mock_req())
context = render.call_args[0][2]
self.assertTrue('tags' in context)
for tag in context['tags']:
self.assertFalse(tag.active)
views.list(mock_req('/?tags=0'))
context = render.call_args[0][2]
for tag in context['tags']:
self.assertEqual(tag.name == '0', tag.active)
views.list(mock_req('/?tags=1'))
context = render.call_args[0][2]
for tag in context['tags']:
self.assertEqual(tag.name == '1', tag.active)
views.list(mock_req('/?tags=1,2'))
context = render.call_args[0][2]
for tag in context['tags']:
self.assertEqual(tag.name in ['1','2'], tag.active)
@patch('idea.views.render')
def test_tag_filter(self, render):
"""
List of ideas should be filterable by tag.
"""
def add_tag(idea, nonce):
tag = str(nonce % 3) # results: 2 0 0 1 1 2
idea.tags.add(tag)
tag = str(nonce % 7) # results: 5 2 3 0 1 4
idea.tags.add(tag)
self._generate_data(postfn=add_tag)
views.list(mock_req())
context = render.call_args[0][2]
self.assertTrue('ideas' in context)
self.assertEqual(6, len(context['ideas']))
self.assertEqual(6, len(context['tags']))
self.assertEqual(set(['0','1','2','3','4','5']),
set([t.name for t in context['tags']]))
views.list(mock_req('/?tags=0'))
context = render.call_args[0][2]
self.assertEqual(3, len(context['ideas']))
self.assertEqual(set(['BBBB', 'CCCC', 'DDDD']),
set([i.title for i in context['ideas']]))
self.assertEqual(4, len(context['tags']))
self.assertEqual(set(['0','1','2','3']),
set([t.name for t in context['tags']]))
views.list(mock_req('/?tags=2'))
context = render.call_args[0][2]
self.assertEqual(3, len(context['ideas']))
self.assertEqual(set(['AAAA', 'BBBB', 'FFFF']),
set([i.title for i in context['ideas']]))
self.assertEqual(4, len(context['tags']))
self.assertEqual(set(['0','2','4','5']),
set([t.name for t in context['tags']]))
views.list(mock_req('/?tags=0,2'))
context = render.call_args[0][2]
self.assertEqual(1, len(context['ideas']))
self.assertEqual(set(['BBBB']),
set([i.title for i in context['ideas']]))
self.assertEqual(2, len(context['tags']))
self.assertEqual(set(['0','2']),
set([t.name for t in context['tags']]))
| 38.012407 | 100 | 0.576343 | import datetime
from django.contrib.auth import get_user_model
from django.utils.timezone import get_default_timezone
from django.contrib.comments.models import Comment
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.test import TestCase
from idea import models, views
from idea.tests.utils import mock_req, random_user
from mock import patch
import string
def get_relative_date(delta_days=0):
return datetime.date.today() + datetime.timedelta(days=delta_days)
def create_banner(title, delta_days=0):
banner = models.Banner(title=title, text=title+' Text',
start_date=get_relative_date(-delta_days),
end_date=get_relative_date(delta_days))
banner.save()
return banner
class ListViewTest(TestCase):
fixtures = ['state']
def _generate_data(self, paramfn=lambda x,y:None, postfn=lambda x,y:None,
entry_data=[(5, 'AAAA'), (9, 'BBBB'), (3, 'CCCC'), (7, 'DDDD'),
(1, 'EEEE'), (11, 'FFFF')]):
user = get_user_model().objects.create_user('example')
state = models.State.objects.get(name='Active')
state.save()
def make_idea(nonce, title):
kwargs = {'creator': user, 'title': title,
'text': title + ' Text', 'state': state}
paramfn(kwargs, nonce)
idea = models.Idea(**kwargs)
idea.save()
postfn(idea, nonce)
return idea
ideas = [make_idea(pair[0], pair[1]) for pair in entry_data]
def _verify_order(self, render):
context = render.call_args[0][2]
self.assertTrue('ideas' in context)
self.assertEqual(6, len(context['ideas']))
self.assertEqual('FFFF', context['ideas'][0].title)
self.assertEqual('BBBB', context['ideas'][1].title)
self.assertEqual('DDDD', context['ideas'][2].title)
self.assertEqual('AAAA', context['ideas'][3].title)
self.assertEqual('CCCC', context['ideas'][4].title)
self.assertEqual('EEEE', context['ideas'][5].title)
@patch('idea.views.render')
def test_sort_recent(self, render):
def add_time(kwargs, nonce):
kwargs['time'] = datetime.datetime(2013, 1, nonce, tzinfo=get_default_timezone())
self._generate_data(paramfn=add_time)
views.list(mock_req(), sort_or_state='recent')
self._verify_order(render)
@patch('idea.views.render')
def test_sort_trending(self, render):
idea_type = ContentType.objects.get(app_label="idea", model="idea")
site = Site.objects.get_current()
def add_time(kwargs, nonce):
if nonce == 3:
kwargs['time'] = datetime.datetime(2050, 1, nonce, tzinfo=get_default_timezone())
def create_timestamp_event(idea, nonce):
if nonce % 2 == 0:
models.Vote(creator=idea.creator,
idea=idea,
time=datetime.datetime(2050, 1, nonce, tzinfo=get_default_timezone())
).save()
elif nonce != 3:
Comment(content_type=idea_type, site=site,
object_pk=idea.pk, user=idea.creator,
comment='Blah',
submit_date=datetime.datetime(2050, 1, nonce, tzinfo=get_default_timezone())
).save()
self._generate_data(postfn=create_timestamp_event, paramfn=add_time)
views.list(mock_req(), sort_or_state='trending')
self._verify_order(render)
@patch('idea.views.render')
def test_sort_vote(self, render):
def create_votes(idea, nonce):
for _ in range(nonce):
models.Vote(creator=idea.creator, idea=idea).save()
self._generate_data(postfn=create_votes)
views.list(mock_req(), sort_or_state='vote')
self._verify_order(render)
@patch('idea.views.render')
def test_paging(self, render):
letters = string.uppercase
entry_data = []
ta(entry_data=entry_data)
views.list(mock_req())
context = render.call_args[0][2]
self.assertTrue('ideas' in context)
self.assertEqual(10, len(context['ideas']))
self.assertEqual('AAAA', context['ideas'][0].title)
self.assertEqual('EEEE', context['ideas'][4].title)
views.list(mock_req('/?page_num=1'))
context = render.call_args[0][2]
self.assertTrue('ideas' in context)
self.assertEqual(10, len(context['ideas']))
self.assertEqual('AAAA', context['ideas'][0].title)
self.assertEqual('EEEE', context['ideas'][4].title)
views.list(mock_req('/?page_num=sadasds'))
context = render.call_args[0][2]
self.assertTrue('ideas' in context)
self.assertEqual(10, len(context['ideas']))
self.assertEqual('AAAA', context['ideas'][0].title)
self.assertEqual('EEEE', context['ideas'][4].title)
views.list(mock_req('/?page_num=2'))
context = render.call_args[0][2]
self.assertTrue('ideas' in context)
self.assertEqual(3, len(context['ideas']))
self.assertEqual('KKKK', context['ideas'][0].title)
self.assertEqual('MMMM', context['ideas'][2].title)
views.list(mock_req('/?page_num=232432'))
context = render.call_args[0][2]
self.assertTrue('ideas' in context)
self.assertEqual(3, len(context['ideas']))
self.assertEqual('KKKK', context['ideas'][0].title)
self.assertEqual('MMMM', context['ideas'][2].title)
@patch('idea.views.render')
def test_idea_fields(self, render):
self._generate_data()
views.list(mock_req())
context = render.call_args[0][2]
self.assertTrue('ideas' in context)
self.assertEqual(6, len(context['ideas']))
for idea in context['ideas']:
self.assertTrue(hasattr(idea, 'title'))
self.assertTrue(hasattr(idea, 'url'))
self.assertTrue(hasattr(idea.creator, 'first_name'))
self.assertTrue(hasattr(idea.creator, 'last_name'))
self.assertTrue(hasattr(idea, 'vote_count'))
self.assertTrue(hasattr(idea, 'time'))
@patch('idea.views.render')
def test_idea_state_filter(self, render):
def check_state(kwargs, nonce):
if nonce % 2 == 0:
kwargs['state'] = models.State.objects.get(name='Archive')
self._generate_data(entry_data=[(1,'AAAA'), (2,'BBBB'), (3,'CCCC')],
paramfn=check_state)
views.list(mock_req())
context = render.call_args[0][2]
self.assertTrue('ideas' in context)
self.assertEqual(2, len(context['ideas']))
views.list(mock_req(), sort_or_state='archived')
context = render.call_args[0][2]
self.assertTrue('ideas' in context)
self.assertEqual(1, len(context['ideas']))
@patch('idea.views.render')
def test_current_banner(self, render):
views.list(mock_req())
context = render.call_args[0][2]
self.assertTrue('banner' in context)
self.assertIsNone(context['banner'])
banner = create_banner('AAAA')
views.list(mock_req())
context = render.call_args[0][2]
self.assertTrue('banner' in context)
self.assertEqual(context['banner'], banner)
@patch('idea.views.render')
def test_browse_banners(self, render):
views.list(mock_req())
context = render.call_args[0][2]
self.assertTrue('browse_banners' in context)
self.assertIsNone(context['browse_banners'])
create_banner('AAAA', 3)
create_banner('BBBB', 2)
create_banner('CCCC', 1)
create_banner('DDDD', 6)
create_banner('EEEE', 5)
create_banner('FFFF', 4)
views.list(mock_req())
context = render.call_args[0][2]
self.assertTrue('browse_banners' in context)
self.assertEqual(len(context['browse_banners']), 4)
self.assertEqual(context['browse_banners'][0].title, 'BBBB')
self.assertEqual(context['browse_banners'][1].title, 'AAAA')
self.assertEqual(context['browse_banners'][2].title, 'FFFF')
self.assertEqual(context['browse_banners'][3].title, 'EEEE')
@patch('idea.views.render')
def test_tags_exist(self, render):
user = random_user()
state = models.State.objects.get(name='Active')
state.save()
idea = models.Idea(creator=user, title='AAAA', text='AAAA Text',
state=state)
idea.save()
idea.tags.add('bbb', 'ccc', 'ddd')
views.list(mock_req())
context = render.call_args[0][2]
self.assertTrue('tags' in context)
self.assertEqual(3, len(context['tags']))
self.assertEqual(set(['bbb', 'ccc', 'ddd']),
set([t.name for t in context['tags']]))
@patch('idea.views.render')
def test_tags_top_list(self, render):
user = random_user()
state = models.State.objects.get(name='Active')
state.save()
for count in range(30):
tag = str(count)*4
for i in range(count+1):
idea = models.Idea(creator=user, title=str(i)*4,
text=str(i)*4 +' Text', state=state)
idea.save()
idea.tags.add(tag)
views.list(mock_req())
context = render.call_args[0][2]
self.assertTrue('tags' in context)
self.assertEqual(25, len(context['tags']))
self.assertEqual([str(i)*4 for i in range(29,4,-1)],
[t.name for t in context['tags']])
@patch('idea.views.render')
def test_tags_count(self, render):
user = random_user()
state = models.State.objects.get(name='Active')
state.save()
for count in range(13):
tag = str(count)*4
for i in range(count+1):
idea = models.Idea(creator=user, title=str(i)*4,
text=str(i)*4 +' Text', state=state)
idea.save()
idea.tags.add(tag)
views.list(mock_req())
context = render.call_args[0][2]
self.assertTrue('tags' in context)
for i in range(12,2,-1):
tag = context['tags'][12-i]
self.assertTrue(hasattr(tag, 'count'))
self.assertEqual(i+1, tag.count)
@patch('idea.views.render')
def test_tags_active(self, render):
def add_tag(idea, nonce):
tag = str(nonce % 3)
idea.tags.add(tag)
self._generate_data(postfn=add_tag)
views.list(mock_req())
context = render.call_args[0][2]
self.assertTrue('tags' in context)
for tag in context['tags']:
self.assertFalse(tag.active)
views.list(mock_req('/?tags=0'))
context = render.call_args[0][2]
for tag in context['tags']:
self.assertEqual(tag.name == '0', tag.active)
views.list(mock_req('/?tags=1'))
context = render.call_args[0][2]
for tag in context['tags']:
self.assertEqual(tag.name == '1', tag.active)
views.list(mock_req('/?tags=1,2'))
context = render.call_args[0][2]
for tag in context['tags']:
self.assertEqual(tag.name in ['1','2'], tag.active)
@patch('idea.views.render')
def test_tag_filter(self, render):
def add_tag(idea, nonce):
tag = str(nonce % 3)
idea.tags.add(tag)
tag = str(nonce % 7)
idea.tags.add(tag)
self._generate_data(postfn=add_tag)
views.list(mock_req())
context = render.call_args[0][2]
self.assertTrue('ideas' in context)
self.assertEqual(6, len(context['ideas']))
self.assertEqual(6, len(context['tags']))
self.assertEqual(set(['0','1','2','3','4','5']),
set([t.name for t in context['tags']]))
views.list(mock_req('/?tags=0'))
context = render.call_args[0][2]
self.assertEqual(3, len(context['ideas']))
self.assertEqual(set(['BBBB', 'CCCC', 'DDDD']),
set([i.title for i in context['ideas']]))
self.assertEqual(4, len(context['tags']))
self.assertEqual(set(['0','1','2','3']),
set([t.name for t in context['tags']]))
views.list(mock_req('/?tags=2'))
context = render.call_args[0][2]
self.assertEqual(3, len(context['ideas']))
self.assertEqual(set(['AAAA', 'BBBB', 'FFFF']),
set([i.title for i in context['ideas']]))
self.assertEqual(4, len(context['tags']))
self.assertEqual(set(['0','2','4','5']),
set([t.name for t in context['tags']]))
views.list(mock_req('/?tags=0,2'))
context = render.call_args[0][2]
self.assertEqual(1, len(context['ideas']))
self.assertEqual(set(['BBBB']),
set([i.title for i in context['ideas']]))
self.assertEqual(2, len(context['tags']))
self.assertEqual(set(['0','2']),
set([t.name for t in context['tags']]))
| true | true |
1c36d0e5821dff116091b3bad792fb50edfcc0e7 | 2,937 | py | Python | tests/unit/modules/test_root_mean_squared_error.py | pavelzw/pyWATTS | 423f5eba7a54b4ced0876454e2f24a1840210076 | [
"MIT"
] | null | null | null | tests/unit/modules/test_root_mean_squared_error.py | pavelzw/pyWATTS | 423f5eba7a54b4ced0876454e2f24a1840210076 | [
"MIT"
] | null | null | null | tests/unit/modules/test_root_mean_squared_error.py | pavelzw/pyWATTS | 423f5eba7a54b4ced0876454e2f24a1840210076 | [
"MIT"
] | null | null | null | import unittest
import pytest
import xarray as xr
import pandas as pd
from pywatts.core.exceptions.input_not_available import InputNotAvailable
from pywatts.modules.root_mean_squared_error import RmseCalculator
import numpy as np
class TestRMSECalculator(unittest.TestCase):
def setUp(self) -> None:
self.rmse_calculator = RmseCalculator()
def tearDown(self) -> None:
self.rmse_calculator = None
def test_get_params(self):
self.assertEqual(self.rmse_calculator.get_params(),
{"offset" : 0})
def test_set_params(self):
self.rmse_calculator.set_params(offset=24)
self.assertEqual(self.rmse_calculator.get_params(),
{"offset": 24})
def test_transform(self):
self.rmse_calculator.set_params()
time = pd.to_datetime(['2015-06-03 00:00:00', '2015-06-03 01:00:00',
'2015-06-03 02:00:00', '2015-06-03 03:00:00',
'2015-06-03 04:00:00'])
result_time = pd.to_datetime(['2015-06-03 04:00:00'])
test_data = xr.Dataset({"testCol": ("time", xr.DataArray([-2, -1, 0, 1, 2])),
"predictCol1": ("time", xr.DataArray([2, -3, 3, 1, -2])),
"predictCol2": ("time", xr.DataArray([4, 4, 3, -2, 1])), "time": time})
test_result = self.rmse_calculator.transform(y=test_data['testCol'], gt=test_data['testCol'],
pred1=test_data['predictCol1'],
pred2=test_data['predictCol2'])
expected_result = xr.DataArray(np.array([[0.0, 3.0, 4.0]]),
coords={"time": result_time, "predictions": ["gt", "pred1", "pred2"]},
dims=["time", "predictions"])
xr.testing.assert_equal(test_result, expected_result)
def test_transform_without_predictions(self):
self.rmse_calculator.set_params()
time = pd.to_datetime(['2015-06-03 00:00:00', '2015-06-03 01:00:00',
'2015-06-03 02:00:00', '2015-06-03 03:00:00',
'2015-06-03 04:00:00'])
test_data = xr.Dataset({"testCol": ("time", xr.DataArray([-2, -1, 0, 1, 2])),
"predictCol1": ("time", xr.DataArray([2, -3, 3, 1, -2])),
"predictCol2": ("time", xr.DataArray([4, 4, 3, -2, 1])), "time": time})
with pytest.raises(InputNotAvailable) as e_info:
self.rmse_calculator.transform(y=test_data['testCol'])
self.assertEqual(e_info.value.message,
"No predictions are provided as input for the RMSE Calculator. You should add the predictions "
"by a seperate key word arguments if you add the RMSECalculator to the pipeline.")
| 41.957143 | 120 | 0.548519 | import unittest
import pytest
import xarray as xr
import pandas as pd
from pywatts.core.exceptions.input_not_available import InputNotAvailable
from pywatts.modules.root_mean_squared_error import RmseCalculator
import numpy as np
class TestRMSECalculator(unittest.TestCase):
def setUp(self) -> None:
self.rmse_calculator = RmseCalculator()
def tearDown(self) -> None:
self.rmse_calculator = None
def test_get_params(self):
self.assertEqual(self.rmse_calculator.get_params(),
{"offset" : 0})
def test_set_params(self):
self.rmse_calculator.set_params(offset=24)
self.assertEqual(self.rmse_calculator.get_params(),
{"offset": 24})
def test_transform(self):
self.rmse_calculator.set_params()
time = pd.to_datetime(['2015-06-03 00:00:00', '2015-06-03 01:00:00',
'2015-06-03 02:00:00', '2015-06-03 03:00:00',
'2015-06-03 04:00:00'])
result_time = pd.to_datetime(['2015-06-03 04:00:00'])
test_data = xr.Dataset({"testCol": ("time", xr.DataArray([-2, -1, 0, 1, 2])),
"predictCol1": ("time", xr.DataArray([2, -3, 3, 1, -2])),
"predictCol2": ("time", xr.DataArray([4, 4, 3, -2, 1])), "time": time})
test_result = self.rmse_calculator.transform(y=test_data['testCol'], gt=test_data['testCol'],
pred1=test_data['predictCol1'],
pred2=test_data['predictCol2'])
expected_result = xr.DataArray(np.array([[0.0, 3.0, 4.0]]),
coords={"time": result_time, "predictions": ["gt", "pred1", "pred2"]},
dims=["time", "predictions"])
xr.testing.assert_equal(test_result, expected_result)
def test_transform_without_predictions(self):
self.rmse_calculator.set_params()
time = pd.to_datetime(['2015-06-03 00:00:00', '2015-06-03 01:00:00',
'2015-06-03 02:00:00', '2015-06-03 03:00:00',
'2015-06-03 04:00:00'])
test_data = xr.Dataset({"testCol": ("time", xr.DataArray([-2, -1, 0, 1, 2])),
"predictCol1": ("time", xr.DataArray([2, -3, 3, 1, -2])),
"predictCol2": ("time", xr.DataArray([4, 4, 3, -2, 1])), "time": time})
with pytest.raises(InputNotAvailable) as e_info:
self.rmse_calculator.transform(y=test_data['testCol'])
self.assertEqual(e_info.value.message,
"No predictions are provided as input for the RMSE Calculator. You should add the predictions "
"by a seperate key word arguments if you add the RMSECalculator to the pipeline.")
| true | true |
1c36d11def359c273abb51d7a435d3c5e71d2ed3 | 13,293 | py | Python | py/get_fit_data.py | shibaji7/Tdiff_Validation | 0e143a53763ea4eb965760c83239b5232326d91e | [
"MIT"
] | null | null | null | py/get_fit_data.py | shibaji7/Tdiff_Validation | 0e143a53763ea4eb965760c83239b5232326d91e | [
"MIT"
] | null | null | null | py/get_fit_data.py | shibaji7/Tdiff_Validation | 0e143a53763ea4eb965760c83239b5232326d91e | [
"MIT"
] | 1 | 2022-03-14T16:38:23.000Z | 2022-03-14T16:38:23.000Z | #!/usr/bin/env python
"""get_fit_data.py: utility module to fetch fitacf<v> level data."""
__author__ = "Chakraborty, S."
__copyright__ = "Copyright 2020, SuperDARN@VT"
__credits__ = []
__license__ = "MIT"
__version__ = "1.0."
__maintainer__ = "Chakraborty, S."
__email__ = "shibaji7@vt.edu"
__status__ = "Research"
import numpy as np
import pandas as pd
import datetime as dt
import glob
import bz2
import pydarnio as pydarn
from loguru import logger
import copy
class Gate(object):
"""Class object to hold each range cell value"""
def __init__(self, bm, i, params=["v", "w_l", "gflg", "p_l", "v_e"], gflg_type=-1):
"""
initialize the parameters which will be stored
bm: beam object
i: index to store
params: parameters to store
"""
for p in params:
if len(getattr(bm, p)) > i : setattr(self, p, getattr(bm, p)[i])
else: setattr(self, p, np.nan)
if gflg_type >= 0 and len(getattr(bm, "gsflg")[gflg_type]) > 0: setattr(self, "gflg", getattr(bm, "gsflg")[gflg_type][i])
return
class Beam(object):
"""Class to hold one beam object"""
def __init__(self):
""" initialize the instance """
return
def set(self, time, d, s_params=["bmnum", "noise.sky", "tfreq", "scan", "nrang"],
v_params=["v", "w_l", "gflg", "p_l", "slist", "v_e"], k=None):
"""
Set all parameters
time: datetime of beam
d: data dict for other parameters
s_param: other scalar params
v_params: other list params
"""
for p in s_params:
if p in d.keys():
if p == "scan" and d[p] != 0: setattr(self, p, 1)
else: setattr(self, p, d[p]) if k is None else setattr(self, p, d[p][k])
else: setattr(self, p, None)
for p in v_params:
if p in d.keys(): setattr(self, p, d[p])
else: setattr(self, p, [])
self.time = time
return
def set_nc(self, time, d, i, s_params, v_params):
"""
Set all parameters
time: datetime of beam
d: data dict for other parameters
s_param: other scalar params
v_params: other list params
"""
for p in s_params:
if p in d.keys(): setattr(self, p, d[p][i])
else: setattr(self, p, None)
for p in v_params:
if p in d.keys():
setattr(self, p, np.array(d[p])[i,:])
if "slist" not in v_params and p=="v": setattr(self, "slist", np.argwhere(~np.isnan(getattr(self, "v"))))
setattr(self, p, getattr(self, p)[~np.isnan(getattr(self, p))])
else: setattr(self, p, [])
self.time = time
return
def copy(self, bm):
""" Copy all parameters """
for p in bm.__dict__.keys(): setattr(self, p, getattr(bm, p))
return
def gs_estimation(self):
"""
Estimate GS flag using different criterion
Cases -
0. Sundeen et al. |v| + w/3 < 30 m/s
1. Blanchard et al. |v| + 0.4w < 60 m/s
2. Blanchard et al. [2009] |v| - 0.139w + 0.00113w^2 < 33.1 m/s
"""
self.gsflg = {}
if len(self.v) > 0 and len(self.w_l) > 0: self.gsflg[0] = ((np.abs(self.v) + self.w_l/3.) < 30.).astype(int)
if len(self.v) > 0 and len(self.w_l) > 0: self.gsflg[1] = ((np.abs(self.v) + self.w_l*0.4) < 60.).astype(int)
if len(self.v) > 0 and len(self.w_l) > 0: self.gsflg[2] = ((np.abs(self.v) - 0.139*self.w_l + 0.00113*self.w_l**2) < 33.1).astype(int)
# Modified defination by S. Chakraborty: {W-[50-(0.7*(V+5)**2)]} < 0
self.gsflg[3] = ((np.array(self.w_l)-(50-(0.7*(np.array(self.v)+5)**2))<0)).astype(int)
return
class Scan(object):
"""Class to hold one scan (multiple beams)"""
def __init__(self, stime=None, etime=None, s_mode="normal"):
"""
initialize the parameters which will be stored
stime: start time of scan
etime: end time of scan
s_mode: scan type
"""
self.stime = stime
self.etime = etime
self.s_mode = s_mode
self.beams = []
return
def update_time(self):
"""
Update stime and etime of the scan.
up: Update average parameters if True
"""
self.stime = min([b.time for b in self.beams])
self.etime = max([b.time for b in self.beams])
self._populate_avg_params()
return
def _populate_avg_params(self):
"""
Polulate average parameetrs
"""
f, nsky = [], []
for b in self.beams:
f.append(getattr(b, "tfreq"))
nsky.append(getattr(b, "noise.sky"))
self.f, self.nsky = np.mean(f), np.mean(nsky)
return
class FetchData(object):
"""Class to fetch data from fitacf files for one radar for atleast a day"""
def __init__(self, rad, date_range, ftype="fitacf", files=None, verbose=True):
"""
initialize the vars
rad = radar code
date_range = [ start_date, end_date ]
files = List of files to load the data from
e.x : rad = "sas"
date_range = [
datetime.datetime(2017,3,17),
datetime.datetime(2017,3,18),
]
"""
self.rad = rad
self.date_range = date_range
self.files = files
self.verbose = verbose
self.regex = "/sd-data/{year}/{ftype}/{rad}/{date}.*{ftype}*.bz2"
self.ftype = ftype
if (rad is not None) and (date_range is not None) and (len(date_range) == 2):
self._create_files()
return
def _create_files(self):
"""
Create file names from date and radar code
"""
if self.files is None: self.files = []
reg_ex = self.regex
days = (self.date_range[1] - self.date_range[0]).days + 2
for d in range(-1,days):
e = self.date_range[0] + dt.timedelta(days=d)
fnames = glob.glob(reg_ex.format(year=e.year, rad=self.rad, ftype=self.ftype, date=e.strftime("%Y%m%d")))
fnames.sort()
for fname in fnames:
tm = fname.split(".")[1]
sc = fname.split(".")[2]
d0 = dt.datetime.strptime(fname.split(".")[0].split("/")[-1] + tm + sc, "%Y%m%d%H%M%S")
d1 = d0 + dt.timedelta(hours=2)
if (self.date_range[0] <= d0) and (d0 <= self.date_range[1]): self.files.append(fname)
elif (d0 <= self.date_range[0] <=d1): self.files.append(fname)
self.files = list(set(self.files))
self.files.sort()
return
def _parse_data(self, data, s_params, v_params, by, scan_prop):
"""
Parse data by data type
data: list of data dict
params: parameter list to fetch
by: sort data by beam or scan
scan_prop: provide scan properties if by='scan'
{"s_mode": type of scan, "s_time": duration in min}
"""
_b, _s = [], []
if self.verbose: logger.info("Started converting to beam data %02d."%len(data))
for d in data:
time = dt.datetime(d["time.yr"], d["time.mo"], d["time.dy"], d["time.hr"], d["time.mt"], d["time.sc"], d["time.us"])
if time >= self.date_range[0] and time <= self.date_range[1]:
bm = Beam()
bm.set(time, d, s_params, v_params)
_b.append(bm)
if self.verbose: logger.info("Converted to beam data.")
if by == "scan":
if self.verbose: logger.info("Started converting to scan data.")
scan, sc = 0, Scan(None, None, scan_prop["s_mode"])
sc.beams.append(_b[0])
for _ix, d in enumerate(_b[1:]):
if d.scan == 1 and d.time != _b[_ix].time:
sc.update_time()
_s.append(sc)
sc = Scan(None, None, scan_prop["s_mode"])
sc.beams.append(d)
else: sc.beams.append(d)
_s.append(sc)
if self.verbose: logger.info("Converted to scan data.")
return _b, _s
def convert_to_pandas(self, beams, s_params=["bmnum", "noise.sky", "tfreq", "scan", "nrang",
"time", "rsep", "frang"],
v_params=["v", "w_l", "gflg", "p_l", "slist", "v_e", "phi0", "elv"]):
"""
Convert the beam data into dataframe
"""
_o = dict(zip(s_params+v_params, ([] for _ in s_params+v_params)))
for b in beams:
l = len(getattr(b, "slist"))
for p in v_params:
_o[p].extend(getattr(b, p))
for p in s_params:
_o[p].extend([getattr(b, p)]*l)
L = len(_o["slist"])
for p in s_params+v_params:
if len(_o[p]) < L:
l = len(_o[p])
_o[p].extend([np.nan]*(L-l))
return pd.DataFrame.from_records(_o)
def scans_to_pandas(self, scans, s_params=["bmnum", "noise.sky", "tfreq", "scan", "nrang", "time", "channel"],
v_params=["v", "w_l", "gflg", "p_l", "slist", "v_e", "phi0", "elv"], start_scnum=0):
"""
Convert the scan data into dataframe
"""
new_cols = ["scnum","sbnum"]
_o = dict(zip(s_params+v_params+new_cols, ([] for _ in s_params+v_params+new_cols)))
for idn, s in enumerate(scans):
for idh, b in enumerate(s.beams):
l = len(getattr(b, "slist"))
for p in v_params:
_o[p].extend(getattr(b, p))
for p in s_params:
_o[p].extend([getattr(b, p)]*l)
_o["scnum"].extend([idn + start_scnum]*l)
_o["sbnum"].extend([idh]*l)
L = len(_o["slist"])
for p in s_params+v_params+new_cols:
if len(_o[p]) < L:
l = len(_o[p])
_o[p].extend([np.nan]*(L-l))
return pd.DataFrame.from_records(_o)
def pandas_to_beams(self, df, s_params=["bmnum", "noise.sky", "tfreq", "scan", "nrang", "time"],
v_params=["v", "w_l", "gflg", "p_l", "slist", "v_e", "phi0", "elv"]):
"""
Convert the dataframe to beam
"""
beams = []
for bm in np.unique(df.bmnum):
o = df[df.bmnum==bm]
d = o.to_dict(orient="list")
for p in s_params:
d[p] = d[p][0]
b = Beam()
b.set(o.time.tolist()[0], d, s_params, v_params)
beams.append(b)
return beams
def pandas_to_scans(self, df, smode, s_params=["bmnum", "noise.sky", "tfreq", "scan", "nrang", "time"],
v_params=["v", "w_l", "gflg", "p_l", "slist", "v_e", "phi0", "elv"]):
"""
Convert the dataframe to scans
"""
bmax = 0
scans = []
for sn in np.unique(df.scnum):
o = df[df.scnum==sn]
beams = []
for bn in np.unique(o.sbnum):
ox = o[o.sbnum==bn]
b = self.pandas_to_beams(ox, s_params, v_params)
beams.extend(b)
bmax = len(beams) if bmax < len(beams) else bmax
sc = Scan(None, None, smode)
sc.beams.extend(beams)
sc.update_time()
scans.append(sc)
mscans = []
if len(scans[0].beams) + len(scans[1].beams) == len(scans[2].beams):
sc = Scan(None, None, scans[0].s_mode)
sc.beams.extend(scans[0].beams)
sc.beams.extend(scans[1].beams)
sc.update_time()
mscans.append(sc)
for i in range(2,len(scans)):
mscans.append(scans[i])
scans = copy.copy(mscans) if len(mscans) > 0 else scans
return scans, bmax
def fetch_data(self, s_params=["bmnum", "noise.sky", "tfreq", "scan", "nrang", "intt.sc", "intt.us",\
"mppul", "nrang", "rsep", "cp", "frang", "smsep", "lagfr", "channel"],
v_params=["v", "w_l", "gflg", "p_l", "slist", "v_e", "phi0", "elv"],
by="beam", scan_prop={"s_time": 1, "s_mode": "normal"}):
"""
Fetch data from file list and return the dataset
params: parameter list to fetch
by: sort data by beam or scan
scan_prop: provide scan properties if by='scan'
{"s_mode": type of scan, "s_time": duration in min}
"""
data = []
for f in self.files:
with bz2.open(f) as fp:
fs = fp.read()
if self.verbose: logger.info(f"Read file - {f}")
reader = pydarn.SDarnRead(fs, True)
records = reader.read_fitacf()
data += records
if by is not None: data = self._parse_data(data, s_params, v_params, by, scan_prop)
return data
if __name__ == "__main__":
fdata = FetchData( "sas", [dt.datetime(2015,3,17,3),
dt.datetime(2015,3,17,3,20)] )
fdata.fetch_data()
fdata.fetch_data(by="scan", scan_prop={"s_time": 2, "s_mode": "themis"}) | 38.982405 | 142 | 0.515911 |
__author__ = "Chakraborty, S."
__copyright__ = "Copyright 2020, SuperDARN@VT"
__credits__ = []
__license__ = "MIT"
__version__ = "1.0."
__maintainer__ = "Chakraborty, S."
__email__ = "shibaji7@vt.edu"
__status__ = "Research"
import numpy as np
import pandas as pd
import datetime as dt
import glob
import bz2
import pydarnio as pydarn
from loguru import logger
import copy
class Gate(object):
def __init__(self, bm, i, params=["v", "w_l", "gflg", "p_l", "v_e"], gflg_type=-1):
for p in params:
if len(getattr(bm, p)) > i : setattr(self, p, getattr(bm, p)[i])
else: setattr(self, p, np.nan)
if gflg_type >= 0 and len(getattr(bm, "gsflg")[gflg_type]) > 0: setattr(self, "gflg", getattr(bm, "gsflg")[gflg_type][i])
return
class Beam(object):
def __init__(self):
return
def set(self, time, d, s_params=["bmnum", "noise.sky", "tfreq", "scan", "nrang"],
v_params=["v", "w_l", "gflg", "p_l", "slist", "v_e"], k=None):
for p in s_params:
if p in d.keys():
if p == "scan" and d[p] != 0: setattr(self, p, 1)
else: setattr(self, p, d[p]) if k is None else setattr(self, p, d[p][k])
else: setattr(self, p, None)
for p in v_params:
if p in d.keys(): setattr(self, p, d[p])
else: setattr(self, p, [])
self.time = time
return
def set_nc(self, time, d, i, s_params, v_params):
for p in s_params:
if p in d.keys(): setattr(self, p, d[p][i])
else: setattr(self, p, None)
for p in v_params:
if p in d.keys():
setattr(self, p, np.array(d[p])[i,:])
if "slist" not in v_params and p=="v": setattr(self, "slist", np.argwhere(~np.isnan(getattr(self, "v"))))
setattr(self, p, getattr(self, p)[~np.isnan(getattr(self, p))])
else: setattr(self, p, [])
self.time = time
return
def copy(self, bm):
for p in bm.__dict__.keys(): setattr(self, p, getattr(bm, p))
return
def gs_estimation(self):
self.gsflg = {}
if len(self.v) > 0 and len(self.w_l) > 0: self.gsflg[0] = ((np.abs(self.v) + self.w_l/3.) < 30.).astype(int)
if len(self.v) > 0 and len(self.w_l) > 0: self.gsflg[1] = ((np.abs(self.v) + self.w_l*0.4) < 60.).astype(int)
if len(self.v) > 0 and len(self.w_l) > 0: self.gsflg[2] = ((np.abs(self.v) - 0.139*self.w_l + 0.00113*self.w_l**2) < 33.1).astype(int)
self.gsflg[3] = ((np.array(self.w_l)-(50-(0.7*(np.array(self.v)+5)**2))<0)).astype(int)
return
class Scan(object):
def __init__(self, stime=None, etime=None, s_mode="normal"):
self.stime = stime
self.etime = etime
self.s_mode = s_mode
self.beams = []
return
def update_time(self):
self.stime = min([b.time for b in self.beams])
self.etime = max([b.time for b in self.beams])
self._populate_avg_params()
return
def _populate_avg_params(self):
f, nsky = [], []
for b in self.beams:
f.append(getattr(b, "tfreq"))
nsky.append(getattr(b, "noise.sky"))
self.f, self.nsky = np.mean(f), np.mean(nsky)
return
class FetchData(object):
def __init__(self, rad, date_range, ftype="fitacf", files=None, verbose=True):
self.rad = rad
self.date_range = date_range
self.files = files
self.verbose = verbose
self.regex = "/sd-data/{year}/{ftype}/{rad}/{date}.*{ftype}*.bz2"
self.ftype = ftype
if (rad is not None) and (date_range is not None) and (len(date_range) == 2):
self._create_files()
return
def _create_files(self):
if self.files is None: self.files = []
reg_ex = self.regex
days = (self.date_range[1] - self.date_range[0]).days + 2
for d in range(-1,days):
e = self.date_range[0] + dt.timedelta(days=d)
fnames = glob.glob(reg_ex.format(year=e.year, rad=self.rad, ftype=self.ftype, date=e.strftime("%Y%m%d")))
fnames.sort()
for fname in fnames:
tm = fname.split(".")[1]
sc = fname.split(".")[2]
d0 = dt.datetime.strptime(fname.split(".")[0].split("/")[-1] + tm + sc, "%Y%m%d%H%M%S")
d1 = d0 + dt.timedelta(hours=2)
if (self.date_range[0] <= d0) and (d0 <= self.date_range[1]): self.files.append(fname)
elif (d0 <= self.date_range[0] <=d1): self.files.append(fname)
self.files = list(set(self.files))
self.files.sort()
return
def _parse_data(self, data, s_params, v_params, by, scan_prop):
_b, _s = [], []
if self.verbose: logger.info("Started converting to beam data %02d."%len(data))
for d in data:
time = dt.datetime(d["time.yr"], d["time.mo"], d["time.dy"], d["time.hr"], d["time.mt"], d["time.sc"], d["time.us"])
if time >= self.date_range[0] and time <= self.date_range[1]:
bm = Beam()
bm.set(time, d, s_params, v_params)
_b.append(bm)
if self.verbose: logger.info("Converted to beam data.")
if by == "scan":
if self.verbose: logger.info("Started converting to scan data.")
scan, sc = 0, Scan(None, None, scan_prop["s_mode"])
sc.beams.append(_b[0])
for _ix, d in enumerate(_b[1:]):
if d.scan == 1 and d.time != _b[_ix].time:
sc.update_time()
_s.append(sc)
sc = Scan(None, None, scan_prop["s_mode"])
sc.beams.append(d)
else: sc.beams.append(d)
_s.append(sc)
if self.verbose: logger.info("Converted to scan data.")
return _b, _s
def convert_to_pandas(self, beams, s_params=["bmnum", "noise.sky", "tfreq", "scan", "nrang",
"time", "rsep", "frang"],
v_params=["v", "w_l", "gflg", "p_l", "slist", "v_e", "phi0", "elv"]):
_o = dict(zip(s_params+v_params, ([] for _ in s_params+v_params)))
for b in beams:
l = len(getattr(b, "slist"))
for p in v_params:
_o[p].extend(getattr(b, p))
for p in s_params:
_o[p].extend([getattr(b, p)]*l)
L = len(_o["slist"])
for p in s_params+v_params:
if len(_o[p]) < L:
l = len(_o[p])
_o[p].extend([np.nan]*(L-l))
return pd.DataFrame.from_records(_o)
def scans_to_pandas(self, scans, s_params=["bmnum", "noise.sky", "tfreq", "scan", "nrang", "time", "channel"],
v_params=["v", "w_l", "gflg", "p_l", "slist", "v_e", "phi0", "elv"], start_scnum=0):
new_cols = ["scnum","sbnum"]
_o = dict(zip(s_params+v_params+new_cols, ([] for _ in s_params+v_params+new_cols)))
for idn, s in enumerate(scans):
for idh, b in enumerate(s.beams):
l = len(getattr(b, "slist"))
for p in v_params:
_o[p].extend(getattr(b, p))
for p in s_params:
_o[p].extend([getattr(b, p)]*l)
_o["scnum"].extend([idn + start_scnum]*l)
_o["sbnum"].extend([idh]*l)
L = len(_o["slist"])
for p in s_params+v_params+new_cols:
if len(_o[p]) < L:
l = len(_o[p])
_o[p].extend([np.nan]*(L-l))
return pd.DataFrame.from_records(_o)
def pandas_to_beams(self, df, s_params=["bmnum", "noise.sky", "tfreq", "scan", "nrang", "time"],
v_params=["v", "w_l", "gflg", "p_l", "slist", "v_e", "phi0", "elv"]):
beams = []
for bm in np.unique(df.bmnum):
o = df[df.bmnum==bm]
d = o.to_dict(orient="list")
for p in s_params:
d[p] = d[p][0]
b = Beam()
b.set(o.time.tolist()[0], d, s_params, v_params)
beams.append(b)
return beams
def pandas_to_scans(self, df, smode, s_params=["bmnum", "noise.sky", "tfreq", "scan", "nrang", "time"],
v_params=["v", "w_l", "gflg", "p_l", "slist", "v_e", "phi0", "elv"]):
bmax = 0
scans = []
for sn in np.unique(df.scnum):
o = df[df.scnum==sn]
beams = []
for bn in np.unique(o.sbnum):
ox = o[o.sbnum==bn]
b = self.pandas_to_beams(ox, s_params, v_params)
beams.extend(b)
bmax = len(beams) if bmax < len(beams) else bmax
sc = Scan(None, None, smode)
sc.beams.extend(beams)
sc.update_time()
scans.append(sc)
mscans = []
if len(scans[0].beams) + len(scans[1].beams) == len(scans[2].beams):
sc = Scan(None, None, scans[0].s_mode)
sc.beams.extend(scans[0].beams)
sc.beams.extend(scans[1].beams)
sc.update_time()
mscans.append(sc)
for i in range(2,len(scans)):
mscans.append(scans[i])
scans = copy.copy(mscans) if len(mscans) > 0 else scans
return scans, bmax
def fetch_data(self, s_params=["bmnum", "noise.sky", "tfreq", "scan", "nrang", "intt.sc", "intt.us",\
"mppul", "nrang", "rsep", "cp", "frang", "smsep", "lagfr", "channel"],
v_params=["v", "w_l", "gflg", "p_l", "slist", "v_e", "phi0", "elv"],
by="beam", scan_prop={"s_time": 1, "s_mode": "normal"}):
data = []
for f in self.files:
with bz2.open(f) as fp:
fs = fp.read()
if self.verbose: logger.info(f"Read file - {f}")
reader = pydarn.SDarnRead(fs, True)
records = reader.read_fitacf()
data += records
if by is not None: data = self._parse_data(data, s_params, v_params, by, scan_prop)
return data
if __name__ == "__main__":
fdata = FetchData( "sas", [dt.datetime(2015,3,17,3),
dt.datetime(2015,3,17,3,20)] )
fdata.fetch_data()
fdata.fetch_data(by="scan", scan_prop={"s_time": 2, "s_mode": "themis"}) | true | true |
1c36d12b4aecf3ea63f9835763dd471a888f3ac1 | 11,122 | py | Python | indico/web/http_api/hooks/base.py | UNOG-Indico/UNOG-Indico-v2 | 4fa4393cc1f3b453a69f5e0ea3b52c18337831a5 | [
"MIT"
] | null | null | null | indico/web/http_api/hooks/base.py | UNOG-Indico/UNOG-Indico-v2 | 4fa4393cc1f3b453a69f5e0ea3b52c18337831a5 | [
"MIT"
] | null | null | null | indico/web/http_api/hooks/base.py | UNOG-Indico/UNOG-Indico-v2 | 4fa4393cc1f3b453a69f5e0ea3b52c18337831a5 | [
"MIT"
] | null | null | null | # This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
"""
Base export interface
"""
import re
import urllib
from datetime import datetime, time, timedelta
from types import GeneratorType
import pytz
from flask import current_app, request
from indico.core.config import config
from indico.core.db import db
from indico.core.logger import Logger
from indico.core.notifications import flush_email_queue, init_email_queue
from indico.util.date_time import now_utc
from indico.web.http_api.exceptions import ArgumentParseError, LimitExceededException
from indico.web.http_api.metadata import Serializer
from indico.web.http_api.metadata.atom import AtomSerializer
from indico.web.http_api.metadata.html import HTML4Serializer
from indico.web.http_api.metadata.ical import ICalSerializer
from indico.web.http_api.metadata.jsonp import JSONPSerializer
from indico.web.http_api.responses import HTTPAPIError
from indico.web.http_api.util import get_query_parameter
class HTTPAPIHook(object):
"""This class is the hook between the query (path+params) and the generator of the results (fossil).
It is also in charge of checking the parameters and the access rights.
"""
HOOK_LIST = []
TYPES = None # abstract
PREFIX = 'export' # url prefix. must exist in indico.web.flask.blueprints.api, too! also used as function prefix
RE = None # abstract
METHOD_NAME = None # overrides method name derived from prefix+type
DEFAULT_DETAIL = None # abstract
MAX_RECORDS = {}
SERIALIZER_TYPE_MAP = {} # maps fossil type names to friendly names (useful for plugins e.g. RoomCERN --> Room)
VALID_FORMATS = None # None = all formats
GUEST_ALLOWED = True # When False, it forces authentication
COMMIT = False # commit database changes
HTTP_POST = False # require (and allow) HTTP POST
NO_CACHE = False
@classmethod
def parseRequest(cls, path, queryParams):
"""Parse a request path and return a hook and the requested data type."""
path = urllib.unquote(path)
hooks = cls.HOOK_LIST
for expCls in hooks:
Logger.get('HTTPAPIHook.parseRequest').debug(expCls)
m = expCls._matchPath(path)
if m:
gd = m.groupdict()
g = m.groups()
type = g[0]
format = g[-1]
if format not in DataFetcher.getAllowedFormats():
return None, None
elif expCls.VALID_FORMATS and format not in expCls.VALID_FORMATS:
return None, None
return expCls(queryParams, type, gd, format), format
return None, None
@staticmethod
def register(cls):
"""Register a hook.
To use it, simply decorate the hook class with this method."""
assert cls.RE is not None
HTTPAPIHook.HOOK_LIST.append(cls)
return cls
@classmethod
def _matchPath(cls, path):
if not hasattr(cls, '_RE'):
types = '|'.join(cls.TYPES)
cls._RE = re.compile(r'/' + cls.PREFIX + '/(' + types + r')' + ('/' + cls.RE).rstrip('/') + r'\.(\w+)$')
return cls._RE.match(path)
def __init__(self, queryParams, type, pathParams, format):
self._format = format
self._queryParams = queryParams
self._type = type
self._pathParams = pathParams
def _getParams(self):
self._offset = get_query_parameter(self._queryParams, ['O', 'offset'], 0, integer=True)
if self._offset < 0:
raise HTTPAPIError('Offset must be a positive number', 400)
self._orderBy = get_query_parameter(self._queryParams, ['o', 'order'])
self._descending = get_query_parameter(self._queryParams, ['c', 'descending'], 'no') == 'yes'
self._detail = get_query_parameter(self._queryParams, ['d', 'detail'], self.DEFAULT_DETAIL)
tzName = get_query_parameter(self._queryParams, ['tz'], None)
if tzName is None:
tzName = config.DEFAULT_TIMEZONE
try:
self._tz = pytz.timezone(tzName)
except pytz.UnknownTimeZoneError as e:
raise HTTPAPIError("Bad timezone: '%s'" % e.message, 400)
max = self.MAX_RECORDS.get(self._detail, 1000)
self._userLimit = get_query_parameter(self._queryParams, ['n', 'limit'], 0, integer=True)
if self._userLimit > max:
raise HTTPAPIError("You can only request up to %d records per request with the detail level '%s'" %
(max, self._detail), 400)
self._limit = self._userLimit if self._userLimit > 0 else max
fromDT = get_query_parameter(self._queryParams, ['f', 'from'])
toDT = get_query_parameter(self._queryParams, ['t', 'to'])
dayDT = get_query_parameter(self._queryParams, ['day'])
if (fromDT or toDT) and dayDT:
raise HTTPAPIError("'day' can only be used without 'from' and 'to'", 400)
elif dayDT:
fromDT = toDT = dayDT
self._fromDT = DataFetcher._getDateTime('from', fromDT, self._tz) if fromDT else None
self._toDT = DataFetcher._getDateTime('to', toDT, self._tz, aux=self._fromDT) if toDT else None
def _has_access(self, user):
return True
@property
def serializer_args(self):
return {}
def _getMethodName(self):
if self.METHOD_NAME:
return self.METHOD_NAME
return self.PREFIX + '_' + self._type.replace('-', '_')
def _performCall(self, func, user):
resultList = []
complete = True
try:
res = func(user)
if isinstance(res, GeneratorType):
for obj in res:
resultList.append(obj)
else:
resultList = res
except LimitExceededException:
complete = (self._limit == self._userLimit)
return resultList, complete
def _perform(self, user, func, extra_func):
self._getParams()
if not self._has_access(user):
raise HTTPAPIError('Access to this resource is restricted.', 403)
resultList, complete = self._performCall(func, user)
if isinstance(resultList, current_app.response_class):
return True, resultList, None, None
extra = extra_func(user, resultList) if extra_func else None
return False, resultList, complete, extra
def __call__(self, user):
"""Perform the actual exporting."""
if self.HTTP_POST != (request.method == 'POST'):
# XXX: this should never happen, since HTTP_POST is only used within /api/,
# where the flask url rule requires POST
raise HTTPAPIError('This action requires %s' % ('POST' if self.HTTP_POST else 'GET'), 405)
if not self.GUEST_ALLOWED and not user:
raise HTTPAPIError('Guest access to this resource is forbidden.', 403)
method_name = self._getMethodName()
func = getattr(self, method_name, None)
extra_func = getattr(self, method_name + '_extra', None)
if not func:
raise NotImplementedError(method_name)
if not self.COMMIT:
is_response, resultList, complete, extra = self._perform(user, func, extra_func)
db.session.rollback()
else:
try:
init_email_queue()
is_response, resultList, complete, extra = self._perform(user, func, extra_func)
db.session.commit()
flush_email_queue()
except Exception:
db.session.rollback()
raise
if is_response:
return resultList
return resultList, extra, complete, self.SERIALIZER_TYPE_MAP
class DataFetcher(object):
_deltas = {'yesterday': timedelta(-1),
'tomorrow': timedelta(1)}
def __init__(self, user, hook):
self._user = user
self._hook = hook
@classmethod
def getAllowedFormats(cls):
return Serializer.getAllFormats()
@classmethod
def _parseDateTime(cls, dateTime, allowNegativeOffset):
"""
Accepted formats:
* ISO 8601 subset - YYYY-MM-DD[THH:MM]
* 'today', 'yesterday', 'tomorrow' and 'now'
* days in the future/past: '[+/-]DdHHhMMm'
'ctx' means that the date will change according to its function
('from' or 'to')
"""
# if it's a an "alias", return immediately
now = now_utc()
if dateTime in cls._deltas:
return ('ctx', now + cls._deltas[dateTime])
elif dateTime == 'now':
return ('abs', now)
elif dateTime == 'today':
return ('ctx', now)
m = re.match(r'^([+-])?(?:(\d{1,3})d)?(?:(\d{1,2})h)?(?:(\d{1,2})m)?$', dateTime)
if m:
mod = -1 if m.group(1) == '-' else 1
if not allowNegativeOffset and mod == -1:
raise ArgumentParseError('End date cannot be a negative offset')
atoms = list(0 if a is None else int(a) * mod for a in m.groups()[1:])
if atoms[1] > 23 or atoms[2] > 59:
raise ArgumentParseError("Invalid time!")
return ('ctx', timedelta(days=atoms[0], hours=atoms[1], minutes=atoms[2]))
else:
# iso 8601 subset
try:
return ('abs', datetime.strptime(dateTime, "%Y-%m-%dT%H:%M"))
except ValueError:
pass
try:
return ('ctx', datetime.strptime(dateTime, "%Y-%m-%d"))
except ValueError:
raise ArgumentParseError("Impossible to parse '%s'" % dateTime)
@classmethod
def _getDateTime(cls, ctx, dateTime, tz, aux=None):
try:
rel, value = cls._parseDateTime(dateTime, ctx == 'from')
except ArgumentParseError as e:
raise HTTPAPIError(e.message, 400)
if rel == 'abs':
return tz.localize(value) if not value.tzinfo else value
elif rel == 'ctx' and isinstance(value, timedelta):
value = now_utc() + value
# from here on, 'value' has to be a datetime
if ctx == 'from':
return tz.localize(value.combine(value.date(), time(0, 0, 0)))
else:
return tz.localize(value.combine(value.date(), time(23, 59, 59)))
class IteratedDataFetcher(DataFetcher):
def __init__(self, user, hook):
super(IteratedDataFetcher, self).__init__(user, hook)
self._tz = hook._tz
self._offset = hook._offset
self._limit = hook._limit
self._detail = hook._detail
self._orderBy = hook._orderBy
self._descending = hook._descending
self._fromDT = hook._fromDT
self._toDT = hook._toDT
Serializer.register('html', HTML4Serializer)
Serializer.register('jsonp', JSONPSerializer)
Serializer.register('ics', ICalSerializer)
Serializer.register('atom', AtomSerializer)
| 38.484429 | 117 | 0.616346 |
import re
import urllib
from datetime import datetime, time, timedelta
from types import GeneratorType
import pytz
from flask import current_app, request
from indico.core.config import config
from indico.core.db import db
from indico.core.logger import Logger
from indico.core.notifications import flush_email_queue, init_email_queue
from indico.util.date_time import now_utc
from indico.web.http_api.exceptions import ArgumentParseError, LimitExceededException
from indico.web.http_api.metadata import Serializer
from indico.web.http_api.metadata.atom import AtomSerializer
from indico.web.http_api.metadata.html import HTML4Serializer
from indico.web.http_api.metadata.ical import ICalSerializer
from indico.web.http_api.metadata.jsonp import JSONPSerializer
from indico.web.http_api.responses import HTTPAPIError
from indico.web.http_api.util import get_query_parameter
class HTTPAPIHook(object):
HOOK_LIST = []
TYPES = None
PREFIX = 'export'
RE = None
METHOD_NAME = None
DEFAULT_DETAIL = None
MAX_RECORDS = {}
SERIALIZER_TYPE_MAP = {}
VALID_FORMATS = None
GUEST_ALLOWED = True
COMMIT = False
HTTP_POST = False
NO_CACHE = False
@classmethod
def parseRequest(cls, path, queryParams):
path = urllib.unquote(path)
hooks = cls.HOOK_LIST
for expCls in hooks:
Logger.get('HTTPAPIHook.parseRequest').debug(expCls)
m = expCls._matchPath(path)
if m:
gd = m.groupdict()
g = m.groups()
type = g[0]
format = g[-1]
if format not in DataFetcher.getAllowedFormats():
return None, None
elif expCls.VALID_FORMATS and format not in expCls.VALID_FORMATS:
return None, None
return expCls(queryParams, type, gd, format), format
return None, None
@staticmethod
def register(cls):
assert cls.RE is not None
HTTPAPIHook.HOOK_LIST.append(cls)
return cls
@classmethod
def _matchPath(cls, path):
if not hasattr(cls, '_RE'):
types = '|'.join(cls.TYPES)
cls._RE = re.compile(r'/' + cls.PREFIX + '/(' + types + r')' + ('/' + cls.RE).rstrip('/') + r'\.(\w+)$')
return cls._RE.match(path)
def __init__(self, queryParams, type, pathParams, format):
self._format = format
self._queryParams = queryParams
self._type = type
self._pathParams = pathParams
def _getParams(self):
self._offset = get_query_parameter(self._queryParams, ['O', 'offset'], 0, integer=True)
if self._offset < 0:
raise HTTPAPIError('Offset must be a positive number', 400)
self._orderBy = get_query_parameter(self._queryParams, ['o', 'order'])
self._descending = get_query_parameter(self._queryParams, ['c', 'descending'], 'no') == 'yes'
self._detail = get_query_parameter(self._queryParams, ['d', 'detail'], self.DEFAULT_DETAIL)
tzName = get_query_parameter(self._queryParams, ['tz'], None)
if tzName is None:
tzName = config.DEFAULT_TIMEZONE
try:
self._tz = pytz.timezone(tzName)
except pytz.UnknownTimeZoneError as e:
raise HTTPAPIError("Bad timezone: '%s'" % e.message, 400)
max = self.MAX_RECORDS.get(self._detail, 1000)
self._userLimit = get_query_parameter(self._queryParams, ['n', 'limit'], 0, integer=True)
if self._userLimit > max:
raise HTTPAPIError("You can only request up to %d records per request with the detail level '%s'" %
(max, self._detail), 400)
self._limit = self._userLimit if self._userLimit > 0 else max
fromDT = get_query_parameter(self._queryParams, ['f', 'from'])
toDT = get_query_parameter(self._queryParams, ['t', 'to'])
dayDT = get_query_parameter(self._queryParams, ['day'])
if (fromDT or toDT) and dayDT:
raise HTTPAPIError("'day' can only be used without 'from' and 'to'", 400)
elif dayDT:
fromDT = toDT = dayDT
self._fromDT = DataFetcher._getDateTime('from', fromDT, self._tz) if fromDT else None
self._toDT = DataFetcher._getDateTime('to', toDT, self._tz, aux=self._fromDT) if toDT else None
def _has_access(self, user):
return True
@property
def serializer_args(self):
return {}
def _getMethodName(self):
if self.METHOD_NAME:
return self.METHOD_NAME
return self.PREFIX + '_' + self._type.replace('-', '_')
def _performCall(self, func, user):
resultList = []
complete = True
try:
res = func(user)
if isinstance(res, GeneratorType):
for obj in res:
resultList.append(obj)
else:
resultList = res
except LimitExceededException:
complete = (self._limit == self._userLimit)
return resultList, complete
def _perform(self, user, func, extra_func):
self._getParams()
if not self._has_access(user):
raise HTTPAPIError('Access to this resource is restricted.', 403)
resultList, complete = self._performCall(func, user)
if isinstance(resultList, current_app.response_class):
return True, resultList, None, None
extra = extra_func(user, resultList) if extra_func else None
return False, resultList, complete, extra
def __call__(self, user):
if self.HTTP_POST != (request.method == 'POST'):
raise HTTPAPIError('This action requires %s' % ('POST' if self.HTTP_POST else 'GET'), 405)
if not self.GUEST_ALLOWED and not user:
raise HTTPAPIError('Guest access to this resource is forbidden.', 403)
method_name = self._getMethodName()
func = getattr(self, method_name, None)
extra_func = getattr(self, method_name + '_extra', None)
if not func:
raise NotImplementedError(method_name)
if not self.COMMIT:
is_response, resultList, complete, extra = self._perform(user, func, extra_func)
db.session.rollback()
else:
try:
init_email_queue()
is_response, resultList, complete, extra = self._perform(user, func, extra_func)
db.session.commit()
flush_email_queue()
except Exception:
db.session.rollback()
raise
if is_response:
return resultList
return resultList, extra, complete, self.SERIALIZER_TYPE_MAP
class DataFetcher(object):
_deltas = {'yesterday': timedelta(-1),
'tomorrow': timedelta(1)}
def __init__(self, user, hook):
self._user = user
self._hook = hook
@classmethod
def getAllowedFormats(cls):
return Serializer.getAllFormats()
@classmethod
def _parseDateTime(cls, dateTime, allowNegativeOffset):
now = now_utc()
if dateTime in cls._deltas:
return ('ctx', now + cls._deltas[dateTime])
elif dateTime == 'now':
return ('abs', now)
elif dateTime == 'today':
return ('ctx', now)
m = re.match(r'^([+-])?(?:(\d{1,3})d)?(?:(\d{1,2})h)?(?:(\d{1,2})m)?$', dateTime)
if m:
mod = -1 if m.group(1) == '-' else 1
if not allowNegativeOffset and mod == -1:
raise ArgumentParseError('End date cannot be a negative offset')
atoms = list(0 if a is None else int(a) * mod for a in m.groups()[1:])
if atoms[1] > 23 or atoms[2] > 59:
raise ArgumentParseError("Invalid time!")
return ('ctx', timedelta(days=atoms[0], hours=atoms[1], minutes=atoms[2]))
else:
# iso 8601 subset
try:
return ('abs', datetime.strptime(dateTime, "%Y-%m-%dT%H:%M"))
except ValueError:
pass
try:
return ('ctx', datetime.strptime(dateTime, "%Y-%m-%d"))
except ValueError:
raise ArgumentParseError("Impossible to parse '%s'" % dateTime)
@classmethod
def _getDateTime(cls, ctx, dateTime, tz, aux=None):
try:
rel, value = cls._parseDateTime(dateTime, ctx == 'from')
except ArgumentParseError as e:
raise HTTPAPIError(e.message, 400)
if rel == 'abs':
return tz.localize(value) if not value.tzinfo else value
elif rel == 'ctx' and isinstance(value, timedelta):
value = now_utc() + value
# from here on, 'value' has to be a datetime
if ctx == 'from':
return tz.localize(value.combine(value.date(), time(0, 0, 0)))
else:
return tz.localize(value.combine(value.date(), time(23, 59, 59)))
class IteratedDataFetcher(DataFetcher):
def __init__(self, user, hook):
super(IteratedDataFetcher, self).__init__(user, hook)
self._tz = hook._tz
self._offset = hook._offset
self._limit = hook._limit
self._detail = hook._detail
self._orderBy = hook._orderBy
self._descending = hook._descending
self._fromDT = hook._fromDT
self._toDT = hook._toDT
Serializer.register('html', HTML4Serializer)
Serializer.register('jsonp', JSONPSerializer)
Serializer.register('ics', ICalSerializer)
Serializer.register('atom', AtomSerializer)
| true | true |
1c36d334e5ad6fa55c2d5e0bb2de68b24cd63f18 | 148 | py | Python | urop/gen_quality_rate_charts.py | giterator/PCCArena | 243841351e94baa9b0db126de49f2e251eacc83f | [
"MIT"
] | null | null | null | urop/gen_quality_rate_charts.py | giterator/PCCArena | 243841351e94baa9b0db126de49f2e251eacc83f | [
"MIT"
] | null | null | null | urop/gen_quality_rate_charts.py | giterator/PCCArena | 243841351e94baa9b0db126de49f2e251eacc83f | [
"MIT"
] | null | null | null | from urop_experiments_metrics import *
if __name__ == '__main__':
collate_quality_rate()
print("Quality vs rate collated for all datasets") | 29.6 | 54 | 0.756757 | from urop_experiments_metrics import *
if __name__ == '__main__':
collate_quality_rate()
print("Quality vs rate collated for all datasets") | true | true |
1c36d39ccd5fda892045aa2a2b067b31ada6e585 | 60,924 | py | Python | palaver/test/memcache_storage.py | twonds/palaver | fcaa1884bc206e0aba7c88d9614e38b492c59285 | [
"MIT"
] | 4 | 2015-01-20T17:25:12.000Z | 2020-02-12T08:24:05.000Z | palaver/test/memcache_storage.py | twonds/palaver | fcaa1884bc206e0aba7c88d9614e38b492c59285 | [
"MIT"
] | 1 | 2016-01-27T16:13:18.000Z | 2016-01-27T19:11:21.000Z | palaver/test/memcache_storage.py | twonds/palaver | fcaa1884bc206e0aba7c88d9614e38b492c59285 | [
"MIT"
] | null | null | null | # -*- coding: utf8 -*-
# Copyright (c) 2005 - 2007 OGG, LLC
# See LICENSE.txt for details
import os
import sys, sha
from twisted.trial import unittest
import time
from twisted.words.protocols.jabber import jid
from twisted.internet import defer, protocol, reactor
from twisted.application import internet, service
from twisted.words.xish import domish, xpath
from twisted.python import log
try:
from twisted.words.protocols.jabber.component import IService
except:
from twisted.words.protocols.jabber.ijabber import IService
from twisted.words.protocols.jabber import component, xmlstream
from palaver import storage, groupchat, palaver
from palaver import memcache_storage
from palaver.test import readlog
PASSWORD = 'palaveriscool'
HOSTNAME = 'palaver.localhost'
PORT = 5437
MEMCACHE_SERVERS = ['127.0.0.1:11211']
class DummyTransport:
def __init__(self, xmlparser):
#self.list = list
self.xmlparser = xmlparser
def write(self, bytes):
# should we reset or use the stream?
self.xmlparser.parse(bytes)
#self.list.append(elem)
def loseConnection(self, *args, **kwargs):
self.xmlparser._reset()
#import twisted
#twisted.internet.base.DelayedCall.debug = True
class ProtocolTests(unittest.TestCase):
"""
"""
def setUp(self):
"""
Set up harness and palaver connection to the harness
"""
# PALAVER set up
# set up Jabber Component
sm = component.buildServiceManager(HOSTNAME, PASSWORD,
("tcp:"+HOSTNAME+":"+str(PORT) ))
# Turn on verbose mode
palaver.LogService().setServiceParent(sm)
# allow for other storage in tests
self.st = memcache_storage.Storage(MEMCACHE_SERVERS)
self.groupchat_service = groupchat.GroupchatService(self.st)
c = IService(self.groupchat_service)
c.setServiceParent(sm)
self.room_service = groupchat.RoomService()
self.room_service.setServiceParent(self.groupchat_service)
IService(self.room_service).setServiceParent(sm)
self.admin_service = groupchat.AdminService()
self.admin_service.setServiceParent(self.groupchat_service)
IService(self.admin_service).setServiceParent(sm)
self.palaver_service = palaver.PalaverService()
self.palaver_service.setServiceParent(sm)
self.palaver_factory = sm.getFactory()
# set up xmlstream for palaver
self.wstream = readlog.XmlParser()
self.palaver_xs = self.palaver_factory.buildProtocol(None)
self.palaver_xs.transport = DummyTransport(self.wstream)
# Indicate that palaver is connected
self.palaver_xs.connectionMade()
self.palaver_xs.dataReceived("<stream:stream xmlns='jabber:component:accept' xmlns:stream='http://etherx.jabber.org/streams' from='localhost' id='12345'>")
hv = sha.new("%s%s" % ("12345", PASSWORD)).hexdigest()
self.assertEquals(str(self.wstream.entity.handshake), hv)
self.palaver_xs.dataReceived("<handshake/>")
# now trigger authd event
self.palaver_xs.dispatch(self.palaver_xs, xmlstream.STREAM_AUTHD_EVENT)
# check if the xmlstream was set and jabber id
self.assertEquals(self.palaver_service.xmlstream, self.palaver_xs)
self.assertEquals(self.palaver_service.jid, HOSTNAME)
def _waitForData(self, childNumber, d, timeout):
timeout -= 0.25
if len(self.wstream.entity.children)>=childNumber or timeout <= 0:
d.callback(True)
else:
reactor.callLater(0.25, self._waitForData, childNumber, d, timeout)
def _testCreate(self, test_elem, frm):
self.assertEquals(xpath.matches("/presence[@from='"+frm+"']/x[@xmlns='http://jabber.org/protocol/muc#user']/item[@role='moderator']", test_elem), 1)
def doWait(self, cb, num, timeout=5):
d = defer.Deferred()
self._waitForData(num,d, timeout)
d.addCallback(cb)
return d
def _createRoom(self, frm, to):
CLIENT_XML = """<presence from='%s' to='%s'/>""" % (frm, to, )
self.palaver_xs.dataReceived(CLIENT_XML)
def test10000stCreateRoom(self):
""" Test Create a Room .........................................................."""
def _cbCreateRoom(t):
self.assertEquals(t, True)
test_elem = self.wstream.entity.children.pop()
# Next element should be a presence broadcast
self.assertEquals(test_elem.name, 'presence')
frm = 'darkcave@%s/thirdwitch' % HOSTNAME
self._testCreate(test_elem, frm)
if len(self.wstream.entity.children)>1:
# Joining room instead of creating it
child_count = len(self.wstream.entity.children)
for i in range(1, child_count):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem.name, 'presence')
self._createRoom('hag66@shakespeare.lit/pda', 'darkcave@%s/thirdwitch' % (HOSTNAME, ))
return self.doWait(_cbCreateRoom, 2)
def testLeaveAndDeleteRoom(self):
""" Test leave and delete a room .........................................................."""
def test109(t):
test_elem = self.wstream.entity.children.pop()
self.failUnless(xpath.matches("/presence/x/status[@code='201']", test_elem), 'Invalid room create.')
def testRoom(t):
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
# join the room again and see if we get the status code
CLIENT_XML = """<presence from='%s' to='%s'>
<x xmlns='http://jabber.org/protocol/muc'/>
</presence>""" % ('hag66@shakespeare.lit/pda', 'delete@%s/thirdwitch' % (HOSTNAME, ))
self.palaver_xs.dataReceived(CLIENT_XML)
return self.doWait(test109, 2)
def leaveRoom(t):
test_elem = self.wstream.entity.children.pop()
self.failUnless(xpath.matches("/iq[@type='result']", test_elem), 'Invalid iq result.')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
CLIENT_XML = """<presence from='%s' to='%s' type='unavailable'>
<x xmlns='http://jabber.org/protocol/muc'/>
</presence>""" % ('hag66@shakespeare.lit/pda', 'delete@%s/thirdwitch' % (HOSTNAME, ))
self.palaver_xs.dataReceived(CLIENT_XML)
return self.doWait(testRoom, 2)
def _cbCreateRoom(t):
self.assertEquals(t, True)
test_elem = self.wstream.entity.children.pop()
frm = 'delete@%s/thirdwitch' % HOSTNAME
self._testCreate(test_elem, frm)
# send config
CONFIG_XML = """<iq from='hag66@shakespeare.lit/pda' id='arbiter_kds_9877' type='set' to='delete@%s'>
<query xmlns='http://jabber.org/protocol/muc#admin'>
<x xmlns='jabber:x:data' type='submit'>
<field var='FORM_TYPE'>
<value>http://jabber.org/protocol/muc#roomconfig</value>
</field>
<field var='muc#roomconfig_whois'><value>anyone</value></field>
</x></query></iq>""" % (HOSTNAME, )
self.palaver_xs.dataReceived(CONFIG_XML)
return self.doWait(leaveRoom, 2)
CLIENT_XML = """<presence from='%s' to='%s'>
<x xmlns='http://jabber.org/protocol/muc'/>
</presence>""" % ('hag66@shakespeare.lit/pda', 'delete@%s/thirdwitch' % (HOSTNAME, ))
self.palaver_xs.dataReceived(CLIENT_XML)
return self.doWait(_cbCreateRoom, 2)
def testRoomNotFound(self):
"""
Test a strange bug that happens when lots of presence comes in.
"""
def doChecks(t):
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
self.failUnless(xpath.matches("/presence[@type='error']", test_elem)==0, 'Should not get presence errors')
def doPresence(t):
PRESENCE_XML = """<presence xmlns='jabber:client' to='centralpark@chat.chesspark.com/attila_turzo@chesspark.com' from='attila_turzo@chesspark.com/cpc'>
<x xmlns='http://jabber.org/protocol/muc'/>
<show>away</show>
<status>Busy</status>
</presence>
<presence xmlns='jabber:client' to='help@chat.chesspark.com/attila_turzo@chesspark.com' from='attila_turzo@chesspark.com/cpc'>
<x xmlns='http://jabber.org/protocol/muc'/>
<show>away</show>
<status>Busy</status>
</presence>
<presence xmlns='jabber:client' to='magyarok@chat.chesspark.com/attila_turzo@chesspark.com' from='attila_turzo@chesspark.com/cpc'>
<x xmlns='http://jabber.org/protocol/muc'/>
<show>away</show>
<status>Busy</status>
</presence>
<presence xmlns='jabber:client' to='freestyle@chat.chesspark.com/attila_turzo@chesspark.com' from='attila_turzo@chesspark.com/cpc'>
<x xmlns='http://jabber.org/protocol/muc'/>
<show>away</show>
<status>Busy</status></presence>
<presence xmlns='jabber:client' to='tournament@chat.chesspark.com/attila_turzo@chesspark.com' from='attila_turzo@chesspark.com/cpc'>
<x xmlns='http://jabber.org/protocol/muc'/>
<show>away</show>
<status>Busy</status>
</presence>
<presence xmlns='jabber:client' to='dev@chat.chesspark.com/attila_turzo@chesspark.com' from='attila_turzo@chesspark.com/cpc'>
<x xmlns='http://jabber.org/protocol/muc'/>
<show>away</show>
<status>Busy</status>
</presence>
"""
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(doChecks, 10)
CREATE_XML = """<presence xmlns='jabber:client' to='centralpark@chat.chesspark.com/createadmin@chesspark.com' from='createadmin@chesspark.com/cpc'/>
<presence xmlns='jabber:client' to='help@chat.chesspark.com/createadmin@chesspark.com' from='createadmin@chesspark.com/cpc' />
<presence xmlns='jabber:client' to='magyarok@chat.chesspark.com/createadmin@chesspark.com' from='createadmin@chesspark.com/cpc' />
<presence xmlns='jabber:client' to='freestyle@chat.chesspark.com/createadmin@chesspark.com' from='createadmin@chesspark.com/cpc' />
<presence xmlns='jabber:client' to='tournament@chat.chesspark.com/createadmin@chesspark.com' from='createadmin@chesspark.com/cpc' />
<presence xmlns='jabber:client' to='dev@chat.chesspark.com/createadmin@chesspark.com' from='createadmin@chesspark.com/cpc' />
"""
self.palaver_xs.dataReceived(CREATE_XML)
return self.doWait(doPresence, 10)
def test61(self):
""" Test Section 6.1 http://www.xmpp.org/extensions/xep-0045.html#disco-component """
def _cb61(t):
test_elem = self.wstream.entity.children.pop()
self.assertNotEquals(test_elem['type'],'error')
# test for correct namespace
self.assertEquals(test_elem.query.uri,'http://jabber.org/protocol/disco#info')
got_muc = False
for f in test_elem.query.elements():
if f.name == 'feature' and f['var'] == 'http://jabber.org/protocol/muc':
got_muc = True
self.assertEquals(got_muc, True)
CLIENT_XML = """
<iq from='hag66@shakespeare.lit/pda' xmlns='jabber:client'
id='disco1'
to='%s'
type='get'>
<query xmlns='http://jabber.org/protocol/disco#info'/>
</iq>
""" % (HOSTNAME)
self.palaver_xs.dataReceived(CLIENT_XML)
return self.doWait(_cb61, 2)
def test62(self):
""" Test Section 6.2 http://www.xmpp.org/extensions/xep-0045.html#disco-rooms ..."""
def _cb62(t):
test_elem = self.wstream.entity.children.pop()
self.assertNotEquals(test_elem['type'],'error')
# test for correct namespace
self.assertEquals(test_elem.query.uri,'http://jabber.org/protocol/disco#items')
def _doDisco(t):
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
CLIENT_XML = """
<iq from='hag66@shakespeare.lit/pda' xmlns='jabber:client'
id='disco1'
to='%s'
type='get'>
<query xmlns='http://jabber.org/protocol/disco#items'/>
</iq>
""" % (HOSTNAME)
self.palaver_xs.dataReceived(CLIENT_XML)
return self.doWait(_cb62, 2)
PRESENCE_XML = """
<presence
from='kinghenryv@shakespeare.lit/throne'
to='lusófonos@%s/king' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_doDisco, 2)
def test63(self):
""" Test Section 6.3 http://www.xmpp.org/extensions/xep-0045.html#disco-roominfo."""
def _cb63(t):
test_elem = self.wstream.entity.children.pop()
self.assertNotEquals(test_elem['type'],'error')
# test for correct namespace
self.assertEquals(test_elem.query.uri,'http://jabber.org/protocol/disco#info')
# TODO - add more tests to this
# palaver returns extended disco
def _doTest(t):
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
CLIENT_XML = """
<iq from='hag66@shakespeare.lit/pda' xmlns='jabber:client'
id='disco3'
to='darkcave@%s'
type='get'>
<query xmlns='http://jabber.org/protocol/disco#info'/>
</iq>
""" % (HOSTNAME)
self.palaver_xs.dataReceived(CLIENT_XML)
return self.doWait(_cb63, 2)
PRESENCE_XML = """<presence
from='palaver@shakespeare.lit/pda'
to='darkcave@%s/palaver'/> """ % (HOSTNAME,)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_doTest, 2)
def test64(self):
""" Test Section 6.4 http://www.xmpp.org/extensions/xep-0045.html#disco-roomitems"""
def _cb64(t):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem['type'],'result')
self.assertEquals(test_elem['id'],'disco4')
# TODO - add test for public and private items
def _doTest(t):
test_elem = self.wstream.entity.children.pop()
DISCO_ITEMS_XML = """
<iq from='hag66@shakespeare.lit/pda'
id='disco4'
to='darkcave@%s'
type='get'>
<query xmlns='http://jabber.org/protocol/disco#items'/>
</iq>
""" % (HOSTNAME,)
self.palaver_xs.dataReceived(DISCO_ITEMS_XML)
return self.doWait(_cb64, 2)
PRESENCE_XML = """<presence
from='palaver@shakespeare.lit/pda'
to='darkcave@%s/palaver'/> """ % (HOSTNAME,)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_doTest, 2)
def test65(self):
""" Test Section 6.5 http://www.xmpp.org/extensions/xep-0045.html#disco-occupant."""
def _eb65(t):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem['type'],'error')
self.assertEquals(test_elem['id'],'disco6')
self.assertEquals(getattr(test_elem.error,'bad-request').name,'bad-request')
def _cb65(t):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem['type'],'result')
self.assertEquals(test_elem['id'],'disco5')
# TODO - add test for public and private items
DISCO_ITEMS_XML = """
<iq from='lordscroop@shakespeare.lit/pda'
id='disco6'
to='darkcave@%s/oldhag'
type='get'>
<query xmlns='http://jabber.org/protocol/disco#items'/>
</iq>
""" % (HOSTNAME,)
self.palaver_xs.dataReceived(DISCO_ITEMS_XML)
return self.doWait(_eb65, 2)
def _doTest(t):
test_elem = self.wstream.entity.children.pop()
DISCO_ITEMS_XML = """
<iq from='hag66@shakespeare.lit/pda'
id='disco5'
to='darkcave@%s/oldhag'
type='get'>
<query xmlns='http://jabber.org/protocol/disco#items'/>
</iq>
""" % (HOSTNAME,)
self.palaver_xs.dataReceived(DISCO_ITEMS_XML)
return self.doWait(_cb65, 2)
PRESENCE_XML = """<presence
from='hag66@shakespeare.lit/pda'
to='darkcave@%s/palaver'/> """ % (HOSTNAME,)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_doTest, 2)
def test71(self):
""" Test Section 7.1 http://www.xmpp.org/extensions/xep-0045.html#enter ........."""
def _cbJoin(t):
child_count = len(self.wstream.entity.children)
found_from = False
for i in range(1, child_count):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem.name, 'presence')
frm = 'darkcave@%s/palaver' % HOSTNAME
if test_elem['from'] == frm:
found_from = xpath.matches("/presence/x[@xmlns='http://jabber.org/protocol/muc#user']/item[@role='participant']", test_elem)
# TODO - add the rest of the section
self.failUnless(found_from, 'Did not find correct from presence.')
def sendJoin(t):
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
PRESENCE_XML = """
<presence
from='palaver@shakespeare.lit/pda'
to='darkcave@%s/palaver'/>
""" % (HOSTNAME,)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_cbJoin, 2)
PRESENCE_XML = """
<presence
from='test71@shakespeare.lit/pda'
to='darkcave@%s/test71'/>
""" % (HOSTNAME,)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(sendJoin, 2)
def test71a(self):
""" Test Section 7.1.1 http://www.xmpp.org/extensions/xep-0045.html#enter-gc ...."""
def _cbJoin(t):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(xpath.matches("/presence[@type='error']/error[@code='400']/jid-malformed", test_elem), 1)
PRESENCE_XML = """
<presence
from='nonick@shakespeare.lit/pda'
to='darkcave@%s'/>
""" % (HOSTNAME,)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_cbJoin, 2)
def test71b(self):
""" Test Section 7.1.3 http://www.xmpp.org/extensions/xep-0045.html#enter-pres ."""
def _cbJoin(t):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(xpath.matches("/presence[@from='newcave@%s/palaver']/x[@xmlns='http://jabber.org/protocol/muc#user']/item[@affiliation='owner']"%(HOSTNAME,), test_elem), 1)
PRESENCE_XML = """
<presence
from='palaver@shakespeare.lit/pda'
to='newcave@%s/palaver'/>
""" % (HOSTNAME,)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_cbJoin, 2)
def testHistoryOrder(self):
""" Test to make sure presence comes before history. ."""
def finish(t):
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
self.assertEqual(test_elem.name, 'presence')
def testHistory(t):
test_elem = self.wstream.entity.children.pop()
self.failUnless(test_elem.name == 'message', 'Messages need to be last')
mtest = filter(lambda el: xpath.matches("/message" , el), self.wstream.entity.children)
#self.failUnless(len(mtest)==4,'Did not get the correct number of messages')
ptest = filter(lambda el: xpath.matches("/presence" , el), self.wstream.entity.children)
#self.failUnless(len(ptest)==10,'Did not get the correct number of presence stanzas')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
# leave room
PRESENCE_XML = """
<presence
from='palaver@shakespeare.lit/pda'
to='darkcave@%s/palaverHistory' type='unavailable'/>
<presence
from='history@shakespeare.lit/pda'
to='darkcave@%s/history' type='unavailable'/>
""" % (HOSTNAME, HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(finish, 4)
def sendPresence(t):
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
self.assertEqual(test_elem.name, 'message')
PRESENCE_XML = """
<presence
from='history@shakespeare.lit/pda'
to='darkcave@%s/history'/>
""" % (HOSTNAME,)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(testHistory, 14)
def sendMessages(t):
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
# send messages
MESSAGE_XML = """
<message xmlns='jabber:client' to='darkcave@%s' from='palaver@shakespeare.lit/pda' type='groupchat'>
<body>3</body>
</message>
<message xmlns='jabber:client' to='darkcave@%s' from='palaver@shakespeare.lit/pda' type='groupchat'>
<body>2</body>
</message>
<message xmlns='jabber:client' to='darkcave@%s' from='palaver@shakespeare.lit/pda' type='groupchat'>
<body>1</body>
</message>
<message xmlns='jabber:client' to='darkcave@%s' from='palaver@shakespeare.lit/pda' type='groupchat'>
<body>contact</body>
</message>
""" % (HOSTNAME, HOSTNAME, HOSTNAME, HOSTNAME)
self.palaver_xs.dataReceived(MESSAGE_XML)
return self.doWait(sendPresence, 16)
PRESENCE_XML = """
<presence
from='palaver@shakespeare.lit/pda'
to='darkcave@%s/palaverHistory'/>
""" % (HOSTNAME,)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(sendMessages, 2)
def testInvalidNick(self):
""" Test for no resource to='darkcave@chat.chesspark.com@chat.chesspark.com' .... """
def _cbJoin(t):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(xpath.matches("/presence[@type='error']/error[@code='400']/jid-malformed", test_elem), 1)
PRESENCE_XML = """
<presence
from='nonick@shakespeare.lit/pda'
to='darkcave@%s@%s'/>
""" % (HOSTNAME, HOSTNAME)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_cbJoin, 2)
def test72(self):
""" Test Section 7.2 http://www.xmpp.org/extensions/xep-0045.html#exit .........."""
def _cbLeave(t):
child_count = len(self.wstream.entity.children)
for i in range(1, child_count):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem.name, 'presence')
if test_elem['from'] == 'darkcave@%s/palaver' % (HOSTNAME,):
self.assertEquals(xpath.matches("/presence[@type='unavailable']/x[@xmlns='http://jabber.org/protocol/muc#user']/item[@role='none']", test_elem), 1)
PRESENCE_XML = """<presence
from='palaver@shakespeare.lit/pda'
to='darkcave@%s/palaver'
type='unavailable'/>""" % (HOSTNAME,)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_cbLeave, 2)
def test73(self):
""" Test Section 7.3 http://www.xmpp.org/extensions/xep-0045.html#changenick ...."""
def _cbJoin(t):
child_count = len(self.wstream.entity.children)
for i in range(1, child_count):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem.name, 'presence')
frm = 'darkcave@%s/change_nick' % HOSTNAME
if test_elem['from'] == frm:
self.assertEquals(xpath.matches("/presence/x[@xmlns='http://jabber.org/protocol/muc#user']/item[@role='participant']", test_elem), 1)
if test_elem['from'] == 'darkcave@%s/palaver' % (HOSTNAME,):
self.assertEquals(xpath.matches("/presence[@type='unavailable']/x[@xmlns='http://jabber.org/protocol/muc#user']/item[@role='participant']", test_elem), 1)
self.assertEquals(xpath.matches("/presence[@type='unavailable']/x[@xmlns='http://jabber.org/protocol/muc#user']/status[@code='303']", test_elem), 1)
# TODO - add the rest of the section
def _cbChange(t):
test_elem = self.wstream.entity.children.pop()
PRESENCE_XML = """
<presence
from='palaver@shakespeare.lit/pda'
to='darkcave@%s/change_nick'/>
""" % (HOSTNAME,)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_cbJoin, 2)
def _doTest(t):
test_elem = self.wstream.entity.children.pop()
PRESENCE_XML = """
<presence
from='palaver@shakespeare.lit/pda'
to='darkcave@%s/my_nick'/>
""" % (HOSTNAME,)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_cbChange, 2)
PRESENCE_XML = """<presence
from='hag66@shakespeare.lit/pda'
to='darkcave@%s/palaver'/> """ % (HOSTNAME,)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_doTest, 2)
def test74(self):
""" Test Section 7.4 http://www.xmpp.org/extensions/xep-0045.html#changepres ...."""
def _cb74(t):
# grab elements to test
child_count = len(self.wstream.entity.children)
for i in range(1, child_count):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem.name, 'presence')
if test_elem['from'] == 'darkcave@%s/oldhag' % (HOSTNAME,):
self.assertEquals(str(test_elem.status),'I am ready to discuss wikka')
self.assertEquals(str(test_elem.show),'chat')
if test_elem['from'] == 'darkcave@%s/testhag' % (HOSTNAME,):
self.assertEquals(xpath.matches("/presence/x[@xmlns='http://jabber.org/protocol/muc#user']/item[@role='participant']", test_elem), 1)
def _cbChangeStatus(t):
child_count = len(self.wstream.entity.children)
for i in range(1, child_count):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem.name, 'presence')
if test_elem['from'] == 'darkcave@%s/oldhag' % (HOSTNAME,):
self.assertEquals(str(test_elem.status),'I am ready to discuss wikka')
self.assertEquals(str(test_elem.show),'chat')
PRESENCE_XML = """
<presence
from='test@shakespeare.lit/laptop'
to='darkcave@%s/testhag' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_cb74, 3)
def _cbJoin(t):
child_count = len(self.wstream.entity.children)
for i in range(1, child_count):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem.name, 'presence')
if test_elem['from'] == 'darkcave@%s/oldhag' % (HOSTNAME,):
self.assertEquals(str(test_elem.status),'gone where the goblins go')
self.assertEquals(str(test_elem.show),'xa')
CHANGE_STATUS_XML = """
<presence
from='wiccarocks@shakespeare.lit/laptop'
to='darkcave@%s/oldhag'>
<show>chat</show>
<status>I am ready to discuss wikka</status>
</presence>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(CHANGE_STATUS_XML)
return self.doWait(_cbChangeStatus, 3)
JOIN_STATUS_XML = """
<presence
from='wiccarocks@shakespeare.lit/laptop'
to='darkcave@%s/oldhag'>
<show>xa</show>
<status>gone where the goblins go</status>
</presence>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(JOIN_STATUS_XML)
return self.doWait(_cbJoin, 3)
def test75(self):
""" Test Section 7.5 http://www.xmpp.org/extensions/xep-0045.html#invite ...."""
def _cbInvite(t):
child_count = len(self.wstream.entity.children)
test_elem = self.wstream.entity.children.pop()
self.failUnless(test_elem.name=='message',
'Not a message returned')
self.failUnless(test_elem['to']=='hecate@shakespeare.lit',
'The message was sent to the wrong person')
return True
def _cbJoin(t):
child_count = len(self.wstream.entity.children)
for i in range(1, child_count):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem.name, 'presence')
if test_elem['from'] == 'darkcave@%s/oldhag' % (HOSTNAME,):
self.assertEquals(str(test_elem.status),'gone where the goblins go')
self.assertEquals(str(test_elem.show),'xa')
INVITE_XML = """
<message
from='wiccarocks@shakespeare.lit/desktop'
to='darkcave@%s'>
<x xmlns='http://jabber.org/protocol/muc#user'>
<invite to='hecate@shakespeare.lit'>
<reason>
Hey Hecate, this is the place for all good witches!
</reason>
</invite>
</x>
</message>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(INVITE_XML)
return self.doWait(_cbInvite, 2)
JOIN_STATUS_XML = """
<presence
from='wiccarocks@shakespeare.lit/laptop'
to='darkcave@%s/oldhag'>
<show>xa</show>
<status>gone where the goblins go</status>
</presence>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(JOIN_STATUS_XML)
return self.doWait(_cbJoin, 3)
def test79(self):
""" Test Section 7.9 http://www.xmpp.org/extensions/xep-0045.html#message ...."""
def _cbInvite(t):
mtest = filter(lambda el: xpath.matches("/message", el), self.wstream.entity.children)
self.failUnless(len(mtest)==2,'Did not get the correct number of messages')
user1 = filter(lambda el: xpath.matches("/message[@to='wiccarocks@shakespeare.lit/laptop']", el), mtest)
self.failUnless(len(user1)==1,'Did not get the correct number of messages')
user2 = filter(lambda el: xpath.matches("/message[@to='79@shakespeare.lit/laptop']", el), mtest)
self.failUnless(len(user2)==1,'Did not get the correct number of messages')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
def _cbJoin(t):
ptest = filter(lambda el: xpath.matches("/presence", el), self.wstream.entity.children)
self.failUnless(len(ptest)>1, 'Invalid number of presence stanzas')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
MESSAGE_XML = """
<message
from='wiccarocks@shakespeare.lit/laptop'
to='test79@%s' type='groupchat'>
<x xmlns='http://jabber.org/protocol/muc#user' />
<body>This is a test of the palaver broadcast system.</body>
</message>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(MESSAGE_XML)
return self.doWait(_cbInvite, 3)
def _cbJoin1(t):
JOIN_STATUS_XML = """
<presence
from='79@shakespeare.lit/laptop'
to='test79@%s/79'>
</presence>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(JOIN_STATUS_XML)
return self.doWait(_cbJoin, 5)
JOIN_STATUS_XML = """
<presence
from='wiccarocks@shakespeare.lit/laptop'
to='test79@%s/oldhag'>
<show>xa</show>
<status>gone where the goblins go</status>
</presence>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(JOIN_STATUS_XML)
return self.doWait(_cbJoin1, 5)
def test81(self):
""" Test Section 8.1 http://www.xmpp.org/extensions/xep-0045.html#subject-mod """
def _cbInvite(t):
mtest = filter(lambda el: xpath.matches("/message", el), self.wstream.entity.children)
self.failUnless(len(mtest)==2,'Did not get the correct number of messages')
user1 = filter(lambda el: xpath.matches("/message[@to='wiccarocks@shakespeare.lit/laptop']/subject", el), mtest)
self.failUnless(len(user1)==1,'Did not get the correct number of messages')
user2 = filter(lambda el: xpath.matches("/message[@to='79@shakespeare.lit/laptop']/subject[text()='This is a test of the palaver broadcast system.']", el), mtest)
self.failUnless(len(user2)==1,'Did not get the correct number of messages')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
def _cbJoin(t):
ptest = filter(lambda el: xpath.matches("/presence", el), self.wstream.entity.children)
self.failUnless(len(ptest)>1, 'Invalid number of presence stanzas')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
MESSAGE_XML = """
<message
from='wiccarocks@shakespeare.lit/laptop'
to='test79@%s' type='groupchat'>
<x xmlns='http://jabber.org/protocol/muc#user' />
<subject>This is a test of the palaver broadcast system.</subject>
</message>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(MESSAGE_XML)
return self.doWait(_cbInvite, 3)
def _cbJoin1(t):
JOIN_STATUS_XML = """
<presence
from='79@shakespeare.lit/laptop'
to='test79@%s/79'>
</presence>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(JOIN_STATUS_XML)
return self.doWait(_cbJoin, 5)
JOIN_STATUS_XML = """
<presence
from='wiccarocks@shakespeare.lit/laptop'
to='test79@%s/oldhag'>
<show>xa</show>
<status>gone where the goblins go</status>
</presence>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(JOIN_STATUS_XML)
return self.doWait(_cbJoin1, 5)
def testKickMessage(self):
""" Test if user can still chat after kicking ."""
def _checkError(t):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem['type'],'error')
self.failUnless(getattr(test_elem.error,'not-authorized',False),
'Bad error result')
def _cbTestKick(t):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem['type'],'result')
test_elem = self.wstream.entity.children.pop()
self.failUnless(test_elem.hasAttribute('type'),
'Presence does not have a type attribute')
self.assertEquals(test_elem['type'],'unavailable')
for c in test_elem.elements():
if c.name == 'x' and c.uri == 'http://jabber.org/protocol/muc#user':
self.assertEquals(c.item['affiliation'],'none')
self.assertEquals(c.item['role'],'none')
test_elem = self.wstream.entity.children.pop()
self.failUnless(test_elem.hasAttribute('type'),
'Presence does not have a type attribute')
self.assertEquals(test_elem['type'],'unavailable')
for c in test_elem.elements():
if c.name == 'x' and c.uri == 'http://jabber.org/protocol/muc#user':
self.assertEquals(c.item['affiliation'],'none')
self.assertEquals(c.item['role'],'none')
# send messages
MESSAGE_XML = """
<message xmlns='jabber:client' to='testkick@%s' from='earlofcambridge@shakespeare.lit/throne' type='groupchat'>
<body>3</body>
</message>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(MESSAGE_XML)
return self.doWait(_checkError, 2)
def _kick(t):
for i in range(0, 3):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem.name, 'presence')
BAN_XML = """<iq from='kinghenryv@shakespeare.lit/throne'
id='ban1'
to='testkick@%s'
type='set'>
<query xmlns='http://jabber.org/protocol/muc#admin'>
<item role='none'
jid='earlofcambridge@shakespeare.lit'>
<reason>Treason</reason>
</item>
</query>
</iq>""" % (HOSTNAME,)
self.palaver_xs.dataReceived(BAN_XML)
return self.doWait(_cbTestKick, 4)
def _create(t):
test_elem = self.wstream.entity.children.pop()
frm = 'testkick@%s/king' % HOSTNAME
self._testCreate(test_elem, frm)
PRESENCE_XML = """
<presence
from='earlofcambridge@shakespeare.lit/throne'
to='testkick@%s/kingoftown' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_kick, 3)
PRESENCE_XML = """
<presence
from='kinghenryv@shakespeare.lit/throne'
to='testkick@%s/king' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_create, 2)
def test91(self):
""" Test section 9.1 http://www.xmpp.org/extensions/xep-0045.html#ban """
def _checkDestroy(r):
miq = filter(lambda el: xpath.matches("/iq[@type='result']" , el), self.wstream.entity.children)
self.failUnless(len(miq)==1, 'Did not get a destroy result')
def _checkPresenceError(t):
test_elem = self.wstream.entity.children.pop()
self.failUnless(xpath.matches("/presence[@type='error']/error", test_elem), 'Presence needs to be an error')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
ADMIN_XML = """<iq from='kinghenryv@shakespeare.lit/throne'
id='admin1'
to='southhampton@%s'
type='set'>
<query xmlns='http://jabber.org/protocol/muc#admin'>
<destroy jid='southhampton@%s'>
<reason>Macbeth doth come.</reason>
</destroy>
</query>
</iq>""" % (HOSTNAME, HOSTNAME)
self.palaver_xs.dataReceived(ADMIN_XML)
return self.doWait(_checkDestroy, 2)
def _checkMessageError(t):
test_elem = self.wstream.entity.children.pop()
self.failUnless(xpath.matches("/message[@type='error']/error", test_elem), 'Message needs to be an error')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
PRESENCE_XML = """
<presence
from='earlofcambridge@shakespeare.lit/throne'
to='southhampton@%s/kingoftown' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_checkPresenceError, 3)
def _cb91(t):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem['type'],'result')
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem['type'],'unavailable')
for c in test_elem.elements():
if c.name == 'x' and c.uri == 'http://jabber.org/protocol/muc#user':
self.assertEquals(c.item['affiliation'],'outcast')
self.assertEquals(c.item['role'],'none')
self.assertEquals(str(c.item.reason),'Treason')
self.assertEquals(c.status['code'],'301')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
# test if we can send a message after the ban
MESSAGE_XML = """
<message xmlns='jabber:client' to='southhampton@%s' from='earlofcambridge@shakespeare.lit/throne' type='groupchat'>
<body>3</body>
</message>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(MESSAGE_XML)
return self.doWait(_checkMessageError, 3)
def _ban(t):
for i in range(0, 3):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem.name, 'presence')
BAN_XML = """<iq from='kinghenryv@shakespeare.lit/throne'
id='ban1'
to='southhampton@%s'
type='set'>
<query xmlns='http://jabber.org/protocol/muc#admin'>
<item affiliation='outcast'
jid='earlofcambridge@shakespeare.lit'>
<reason>Treason</reason>
</item>
</query>
</iq>""" % (HOSTNAME,)
self.palaver_xs.dataReceived(BAN_XML)
return self.doWait(_cb91, 3)
def _create(t):
test_elem = self.wstream.entity.children.pop()
frm = 'southhampton@%s/king' % HOSTNAME
self._testCreate(test_elem, frm)
PRESENCE_XML = """
<presence
from='earlofcambridge@shakespeare.lit/throne'
to='southhampton@%s/kingoftown' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_ban, 3)
PRESENCE_XML = """
<presence
from='kinghenryv@shakespeare.lit/throne'
to='southhampton@%s/king' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_create, 2)
def testE100ToE103(self):
""" Test section 9.2 http://www.xmpp.org/extensions/xep-0045.html#modifyban ....."""
def _removeNoneParticipant(t):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(jid.internJID(test_elem['from']).userhost(),'southhampton@%s' % (HOSTNAME,))
self.assertEquals(test_elem['type'],'result')
self.assertEquals(test_elem['id'],'removeban4')
def _checkRemove(t):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(jid.internJID(test_elem['from']).userhost(),'southhampton@%s' % (HOSTNAME,))
self.assertEquals(test_elem['type'],'result')
test_elem = self.wstream.entity.children.pop()
REMOVE_XML = """
<iq from='kinghenryv@shakespeare.lit/throne'
id='removeban4'
to='southhampton@%s'
type='set'>
<query xmlns='http://jabber.org/protocol/muc#admin'>
<item affiliation='none'
jid='lordscroop@shakespeare.lit' />
</query>
</iq>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(REMOVE_XML)
return self.doWait(_removeNoneParticipant, 3)
def _remove(t):
miq = filter(lambda el: xpath.matches("/iq[@type='result']" , el), self.wstream.entity.children)
self.failUnless(len(miq)==1, 'Did not get a result')
self.assertEquals(jid.internJID(miq[0]['from']).userhost(),'southhampton@%s' % (HOSTNAME,))
self.assertEquals(miq[0]['type'],'result')
# pop the rest
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
REMOVE_XML = """
<iq from='kinghenryv@shakespeare.lit/throne'
id='removeban3'
to='southhampton@%s'
type='set'>
<query xmlns='http://jabber.org/protocol/muc#admin'>
<item affiliation='none'
jid='earlofcambridge@shakespeare.lit' />
</query>
</iq>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(REMOVE_XML)
return self.doWait(_checkRemove, 3)
def _modify(t):
miq = filter(lambda el: xpath.matches("/iq[@type='result']/query[@xmlns='http://jabber.org/protocol/muc#admin']" % (), el), self.wstream.entity.children)
self.failUnless(len(miq)==1, 'Did not get the correct outcast result')
self.assertEquals(jid.internJID(miq[0]['from']).userhost(),'southhampton@%s' % (HOSTNAME,))
self.failUnless(miq[0].hasAttribute('type'), 'Wrong Attribute Type')
self.assertEquals(miq[0]['type'],'result')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
MODIFY_XML = """
<iq from='kinghenryv@shakespeare.lit/throne'
id='ban3'
to='southhampton@%s'
type='set'>
<query xmlns='http://jabber.org/protocol/muc#admin'>
<item affiliation='outcast'
jid='earlofcambridge@shakespeare.lit'>
<reason>Treason</reason>
</item>
<item affiliation='outcast'>
jid='lordscroop@shakespeare.lit'>
<reason>Treason</reason>
</item>
<item affiliation='outcast'
jid='sirthomasgrey@shakespeare.lit'>
<reason>Treason</reason>
</item>
</query>
</iq>
""" % (HOSTNAME,)
self.palaver_xs.dataReceived(MODIFY_XML)
return self.doWait(_remove, 3)
def _first_ban_result(t):
test_elem = self.wstream.entity.children.pop()
self.failUnless(xpath.matches("/iq[@type='result']", test_elem), 'Error in ban result.')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
GET_XML = """
<iq from='kinghenryv@shakespeare.lit/throne'
id='ban2'
to='southhampton@%s'
type='get'>
<query xmlns='http://jabber.org/protocol/muc#admin'>
<item affiliation='outcast' />
</query>
</iq>""" % (HOSTNAME,)
self.palaver_xs.dataReceived(GET_XML)
return self.doWait(_modify, 4)
def _do_first_ban(t):
# pop off presence
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
BAN_XML = """<iq from='kinghenryv@shakespeare.lit/throne'
id='ban1'
to='southhampton@%s'
type='set'>
<query xmlns='http://jabber.org/protocol/muc#admin'>
<item affiliation='outcast'
jid='earlofcambridge@shakespeare.lit'>
<reason>Treason</reason>
</item>
</query>
</iq>""" % (HOSTNAME,)
self.palaver_xs.dataReceived(BAN_XML)
return self.doWait(_first_ban_result, 4)
PRESENCE_XML = """
<presence
from='kinghenryv@shakespeare.lit/throne'
to='southhampton@%s/king' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_do_first_ban, 3)
def test93(self):
""" Test section 9.3 http://www.xmpp.org/extensions/xep-0045.html#grantmember ..........."""
def _testJoin(r):
self.failUnless(len(self.wstream.entity.children)>1, 'No elements found')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
self.failUnless(xpath.matches("/presence[not(@type)]", test_elem), 'Error joining room.')
def _cb93(t):
test_elem = self.wstream.entity.children.pop()
self.failUnless(xpath.matches("/iq[@type='result']/query", test_elem), 'Error in member add result.')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
# join after we are made a member
PRESENCE_XML = """
<presence
from='hag66@shakespeare.lit/throne'
to='membertest@%s/ha66' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_testJoin, 2)
def _create(t):
test_elem = self.wstream.entity.children.pop()
frm = 'membertest@%s/king' % HOSTNAME
self._testCreate(test_elem, frm)
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
MEMBER_XML = """
<iq from='kinghenryv@shakespeare.lit/throne'
id='member1'
to='membertest@%s'
type='set'>
<query xmlns='http://jabber.org/protocol/muc#admin'>
<item affiliation='member'
jid='hag66@shakespeare.lit'/>
</query>
</iq>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(MEMBER_XML)
return self.doWait(_cb93, 3)
PRESENCE_XML = """
<presence
from='kinghenryv@shakespeare.lit/throne'
to='membertest@%s/king' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_create, 2, timeout=20)
def test96(self):
""" Test section 9.6 http://www.xmpp.org/extensions/xep-0045.html#grantmod ..........."""
def _cb96(t):
test_elem = self.wstream.entity.children.pop()
self.failUnless(xpath.matches("/iq[@type='result']/query", test_elem), 'Error in moderator result.')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
self.failUnless(xpath.matches("/presence[@from='modtest@%s/witch']/x/item[@role='moderator']" % (HOSTNAME,), test_elem), 'Error in presence.')
def _setRole(t):
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
MEMBER_XML = """
<iq from='kinghenryv@shakespeare.lit/throne'
id='member1'
to='modtest@%s'
type='set'>
<query xmlns='http://jabber.org/protocol/muc#admin'>
<item role='moderator'
nick='witch'/>
</query>
</iq>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(MEMBER_XML)
return self.doWait(_cb96, 3)
def _create(t):
test_elem = self.wstream.entity.children.pop()
frm = 'modtest@%s/king' % HOSTNAME
self._testCreate(test_elem, frm)
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
PRESENCE_XML = """
<presence
from='hag66@shakespeare.lit/witch'
to='modtest@%s/witch' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_setRole, 2)
PRESENCE_XML = """
<presence
from='kinghenryv@shakespeare.lit/throne'
to='modtest@%s/king' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_create, 2)
def test106(self):
""" Test section 10.6 http://www.xmpp.org/extensions/xep-0045.html#grantadmin ..........."""
def _cb106(t):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem['type'],'result')
test_elem = self.wstream.entity.children.pop()
for c in test_elem.elements():
if c.name == 'x' and c.uri == 'http://jabber.org/protocol/muc#user':
self.assertEquals(c.item['affiliation'],'admin')
self.assertEquals(c.item['role'],'moderator')
def _admin(t):
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem.name, 'presence')
ADMIN_XML = """<iq from='kinghenryv@shakespeare.lit/throne'
id='admin1'
to='admintest@%s'
type='set'>
<query xmlns='http://jabber.org/protocol/muc#admin'>
<item affiliation='admin'
jid='earlofcambridge@shakespeare.lit'/>
</query>
</iq>""" % (HOSTNAME,)
self.palaver_xs.dataReceived(ADMIN_XML)
return self.doWait(_cb106, 4)
def _create(t):
test_elem = self.wstream.entity.children.pop()
frm = 'admintest@%s/king' % HOSTNAME
self._testCreate(test_elem, frm)
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
PRESENCE_XML = """
<presence
from='earlofcambridge@shakespeare.lit/throne'
to='admintest@%s/kingoftown' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_admin, 3)
PRESENCE_XML = """
<presence
from='kinghenryv@shakespeare.lit/throne'
to='admintest@%s/king' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_create, 2)
def test109(self):
""" Test section 10.9 http://www.xmpp.org/extensions/xep-0045.html#destroyroom ..........."""
def _cb109(t):
ptest = filter(lambda el: xpath.matches("/presence[@type='unavailable']/x/item[@role='none']", el), self.wstream.entity.children)
self.failUnless(len(ptest)==1, 'Presence was not sent that use left the room.')
iqtest = filter(lambda el: xpath.matches("/iq[@type='result']", el), self.wstream.entity.children)
self.failUnless(len(iqtest)==1, 'Invalid iq result.')
def _admin(t):
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem.name, 'presence')
ADMIN_XML = """<iq from='kinghenryv@shakespeare.lit/throne'
id='admin1'
to='destroytest@%s'
type='set'>
<query xmlns='http://jabber.org/protocol/muc#admin'>
<destroy jid='destroytest@%s'>
<reason>Macbeth doth come.</reason>
</destroy>
</query>
</iq>""" % (HOSTNAME, HOSTNAME)
self.palaver_xs.dataReceived(ADMIN_XML)
return self.doWait(_cb109, 4)
PRESENCE_XML = """
<presence
from='kinghenryv@shakespeare.lit/throne'
to='destroytest@%s/king' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_admin, 2)
def testPresenceLeak(self):
""" Test to make sure presence does not leak. ."""
user_list = {}
def testLeave(t):
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem['type'], 'unavailable')
self.failUnless(test_elem['to'].lower() in user_list)
if user_list.has_key(test_elem['to'].lower()):
del user_list[test_elem['to'].lower()]
# Test for leak, if all users did not get unavailable then there is a leak
self.failUnless(len(user_list)==0, 'Not all users got unavailable presence')
def testJoin(t):
send_one_to_users = 0
send_one_to_member = 0
send_two_to_users = 0
send_two_to_member = 0
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
if test_elem.name =='presence' and test_elem['from'] == 'leak@%s/One' % (HOSTNAME,) \
and test_elem['to'] != '2@shakespeare.lit/testing':
send_one_to_users += 1
if test_elem.name =='presence' and test_elem['from'] == 'leak@%s/two' % (HOSTNAME,):
send_two_to_users += 1
user_list[test_elem['to'].lower()] = True
self.failUnless(send_one_to_users >= 2, 'Not enough presence elements')
#self.assertEquals(send_one_to_users, 5)
self.failUnless(send_two_to_users >= 3, 'Not enough presence elements')
#self.assertEquals(send_two_to_users, 6)
PRESENCE_XML = """
<presence from='one@shakespeare.lit/testing' to='leak@%s/one' type='unavailable'/>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(testLeave, 7)
def testLeak(t):
PRESENCE_XML = """
<presence from='One@shakespeare.lit/testing' to='leak@%s/One' />
<presence from='2@shakespeare.lit/testing' to='leak@%s/two' />
""" % (HOSTNAME, HOSTNAME)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(testJoin, 16)
self._createRoom('hag66@shakespeare.lit/pda', 'leak@%s/thirdwitch' % (HOSTNAME, ))
return self.doWait(testLeak, 3)
def testPresenceRaceCondition(self):
"""
This is a test for a race condition when someone leaves the room immediatly after they join.
"""
def testJoin(t):
unavailable = False
test_elem = self.wstream.entity.children.pop()
if test_elem.name == 'presence' and \
test_elem.hasAttribute('type') and \
test_elem['type'] == 'unavailable':
unavailable = True
self.failUnless(unavailable,'Did NOT leave the room')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
def testRace(t):
PRESENCE_XML = """
<presence from='race@shakespeare.lit/testing' to='racetest@%s/RaceTest' />
<presence from='race@shakespeare.lit/testing' type='unavailable' to='racetest@%s/RaceTest' />
""" % (HOSTNAME, HOSTNAME)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(testJoin, 18)
self._createRoom('hag66@shakespeare.lit/pda', 'racetest@%s/thirdwitch' % (HOSTNAME, ))
return self.doWait(testRace, 3)
def testZDisconnect(self):
""" Test Disconnect ............................................................."""
self.palaver_xs.connectionLost(None)
def tearDown(self):
self.st._flush()
pending = reactor.getDelayedCalls()
if pending:
for p in pending:
if p.active():
p.cancel()
#self.st.threadpool.close()
def tearDownClass(self):
pending = reactor.getDelayedCalls()
if pending:
for p in pending:
if p.active():
p.cancel()
class StorageTests(unittest.TestCase):
pass
| 36.178147 | 186 | 0.575504 |
import os
import sys, sha
from twisted.trial import unittest
import time
from twisted.words.protocols.jabber import jid
from twisted.internet import defer, protocol, reactor
from twisted.application import internet, service
from twisted.words.xish import domish, xpath
from twisted.python import log
try:
from twisted.words.protocols.jabber.component import IService
except:
from twisted.words.protocols.jabber.ijabber import IService
from twisted.words.protocols.jabber import component, xmlstream
from palaver import storage, groupchat, palaver
from palaver import memcache_storage
from palaver.test import readlog
PASSWORD = 'palaveriscool'
HOSTNAME = 'palaver.localhost'
PORT = 5437
MEMCACHE_SERVERS = ['127.0.0.1:11211']
class DummyTransport:
def __init__(self, xmlparser):
self.xmlparser = xmlparser
def write(self, bytes):
self.xmlparser.parse(bytes)
def loseConnection(self, *args, **kwargs):
self.xmlparser._reset()
class ProtocolTests(unittest.TestCase):
def setUp(self):
sm = component.buildServiceManager(HOSTNAME, PASSWORD,
("tcp:"+HOSTNAME+":"+str(PORT) ))
palaver.LogService().setServiceParent(sm)
self.st = memcache_storage.Storage(MEMCACHE_SERVERS)
self.groupchat_service = groupchat.GroupchatService(self.st)
c = IService(self.groupchat_service)
c.setServiceParent(sm)
self.room_service = groupchat.RoomService()
self.room_service.setServiceParent(self.groupchat_service)
IService(self.room_service).setServiceParent(sm)
self.admin_service = groupchat.AdminService()
self.admin_service.setServiceParent(self.groupchat_service)
IService(self.admin_service).setServiceParent(sm)
self.palaver_service = palaver.PalaverService()
self.palaver_service.setServiceParent(sm)
self.palaver_factory = sm.getFactory()
self.wstream = readlog.XmlParser()
self.palaver_xs = self.palaver_factory.buildProtocol(None)
self.palaver_xs.transport = DummyTransport(self.wstream)
self.palaver_xs.connectionMade()
self.palaver_xs.dataReceived("<stream:stream xmlns='jabber:component:accept' xmlns:stream='http://etherx.jabber.org/streams' from='localhost' id='12345'>")
hv = sha.new("%s%s" % ("12345", PASSWORD)).hexdigest()
self.assertEquals(str(self.wstream.entity.handshake), hv)
self.palaver_xs.dataReceived("<handshake/>")
self.palaver_xs.dispatch(self.palaver_xs, xmlstream.STREAM_AUTHD_EVENT)
self.assertEquals(self.palaver_service.xmlstream, self.palaver_xs)
self.assertEquals(self.palaver_service.jid, HOSTNAME)
def _waitForData(self, childNumber, d, timeout):
timeout -= 0.25
if len(self.wstream.entity.children)>=childNumber or timeout <= 0:
d.callback(True)
else:
reactor.callLater(0.25, self._waitForData, childNumber, d, timeout)
def _testCreate(self, test_elem, frm):
self.assertEquals(xpath.matches("/presence[@from='"+frm+"']/x[@xmlns='http://jabber.org/protocol/muc#user']/item[@role='moderator']", test_elem), 1)
def doWait(self, cb, num, timeout=5):
d = defer.Deferred()
self._waitForData(num,d, timeout)
d.addCallback(cb)
return d
def _createRoom(self, frm, to):
CLIENT_XML = """<presence from='%s' to='%s'/>""" % (frm, to, )
self.palaver_xs.dataReceived(CLIENT_XML)
def test10000stCreateRoom(self):
def _cbCreateRoom(t):
self.assertEquals(t, True)
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem.name, 'presence')
frm = 'darkcave@%s/thirdwitch' % HOSTNAME
self._testCreate(test_elem, frm)
if len(self.wstream.entity.children)>1:
child_count = len(self.wstream.entity.children)
for i in range(1, child_count):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem.name, 'presence')
self._createRoom('hag66@shakespeare.lit/pda', 'darkcave@%s/thirdwitch' % (HOSTNAME, ))
return self.doWait(_cbCreateRoom, 2)
def testLeaveAndDeleteRoom(self):
def test109(t):
test_elem = self.wstream.entity.children.pop()
self.failUnless(xpath.matches("/presence/x/status[@code='201']", test_elem), 'Invalid room create.')
def testRoom(t):
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
CLIENT_XML = """<presence from='%s' to='%s'>
<x xmlns='http://jabber.org/protocol/muc'/>
</presence>""" % ('hag66@shakespeare.lit/pda', 'delete@%s/thirdwitch' % (HOSTNAME, ))
self.palaver_xs.dataReceived(CLIENT_XML)
return self.doWait(test109, 2)
def leaveRoom(t):
test_elem = self.wstream.entity.children.pop()
self.failUnless(xpath.matches("/iq[@type='result']", test_elem), 'Invalid iq result.')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
CLIENT_XML = """<presence from='%s' to='%s' type='unavailable'>
<x xmlns='http://jabber.org/protocol/muc'/>
</presence>""" % ('hag66@shakespeare.lit/pda', 'delete@%s/thirdwitch' % (HOSTNAME, ))
self.palaver_xs.dataReceived(CLIENT_XML)
return self.doWait(testRoom, 2)
def _cbCreateRoom(t):
self.assertEquals(t, True)
test_elem = self.wstream.entity.children.pop()
frm = 'delete@%s/thirdwitch' % HOSTNAME
self._testCreate(test_elem, frm)
CONFIG_XML = """<iq from='hag66@shakespeare.lit/pda' id='arbiter_kds_9877' type='set' to='delete@%s'>
<query xmlns='http://jabber.org/protocol/muc#admin'>
<x xmlns='jabber:x:data' type='submit'>
<field var='FORM_TYPE'>
<value>http://jabber.org/protocol/muc#roomconfig</value>
</field>
<field var='muc#roomconfig_whois'><value>anyone</value></field>
</x></query></iq>""" % (HOSTNAME, )
self.palaver_xs.dataReceived(CONFIG_XML)
return self.doWait(leaveRoom, 2)
CLIENT_XML = """<presence from='%s' to='%s'>
<x xmlns='http://jabber.org/protocol/muc'/>
</presence>""" % ('hag66@shakespeare.lit/pda', 'delete@%s/thirdwitch' % (HOSTNAME, ))
self.palaver_xs.dataReceived(CLIENT_XML)
return self.doWait(_cbCreateRoom, 2)
def testRoomNotFound(self):
def doChecks(t):
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
self.failUnless(xpath.matches("/presence[@type='error']", test_elem)==0, 'Should not get presence errors')
def doPresence(t):
PRESENCE_XML = """<presence xmlns='jabber:client' to='centralpark@chat.chesspark.com/attila_turzo@chesspark.com' from='attila_turzo@chesspark.com/cpc'>
<x xmlns='http://jabber.org/protocol/muc'/>
<show>away</show>
<status>Busy</status>
</presence>
<presence xmlns='jabber:client' to='help@chat.chesspark.com/attila_turzo@chesspark.com' from='attila_turzo@chesspark.com/cpc'>
<x xmlns='http://jabber.org/protocol/muc'/>
<show>away</show>
<status>Busy</status>
</presence>
<presence xmlns='jabber:client' to='magyarok@chat.chesspark.com/attila_turzo@chesspark.com' from='attila_turzo@chesspark.com/cpc'>
<x xmlns='http://jabber.org/protocol/muc'/>
<show>away</show>
<status>Busy</status>
</presence>
<presence xmlns='jabber:client' to='freestyle@chat.chesspark.com/attila_turzo@chesspark.com' from='attila_turzo@chesspark.com/cpc'>
<x xmlns='http://jabber.org/protocol/muc'/>
<show>away</show>
<status>Busy</status></presence>
<presence xmlns='jabber:client' to='tournament@chat.chesspark.com/attila_turzo@chesspark.com' from='attila_turzo@chesspark.com/cpc'>
<x xmlns='http://jabber.org/protocol/muc'/>
<show>away</show>
<status>Busy</status>
</presence>
<presence xmlns='jabber:client' to='dev@chat.chesspark.com/attila_turzo@chesspark.com' from='attila_turzo@chesspark.com/cpc'>
<x xmlns='http://jabber.org/protocol/muc'/>
<show>away</show>
<status>Busy</status>
</presence>
"""
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(doChecks, 10)
CREATE_XML = """<presence xmlns='jabber:client' to='centralpark@chat.chesspark.com/createadmin@chesspark.com' from='createadmin@chesspark.com/cpc'/>
<presence xmlns='jabber:client' to='help@chat.chesspark.com/createadmin@chesspark.com' from='createadmin@chesspark.com/cpc' />
<presence xmlns='jabber:client' to='magyarok@chat.chesspark.com/createadmin@chesspark.com' from='createadmin@chesspark.com/cpc' />
<presence xmlns='jabber:client' to='freestyle@chat.chesspark.com/createadmin@chesspark.com' from='createadmin@chesspark.com/cpc' />
<presence xmlns='jabber:client' to='tournament@chat.chesspark.com/createadmin@chesspark.com' from='createadmin@chesspark.com/cpc' />
<presence xmlns='jabber:client' to='dev@chat.chesspark.com/createadmin@chesspark.com' from='createadmin@chesspark.com/cpc' />
"""
self.palaver_xs.dataReceived(CREATE_XML)
return self.doWait(doPresence, 10)
def test61(self):
def _cb61(t):
test_elem = self.wstream.entity.children.pop()
self.assertNotEquals(test_elem['type'],'error')
self.assertEquals(test_elem.query.uri,'http://jabber.org/protocol/disco#info')
got_muc = False
for f in test_elem.query.elements():
if f.name == 'feature' and f['var'] == 'http://jabber.org/protocol/muc':
got_muc = True
self.assertEquals(got_muc, True)
CLIENT_XML = """
<iq from='hag66@shakespeare.lit/pda' xmlns='jabber:client'
id='disco1'
to='%s'
type='get'>
<query xmlns='http://jabber.org/protocol/disco#info'/>
</iq>
""" % (HOSTNAME)
self.palaver_xs.dataReceived(CLIENT_XML)
return self.doWait(_cb61, 2)
def test62(self):
def _cb62(t):
test_elem = self.wstream.entity.children.pop()
self.assertNotEquals(test_elem['type'],'error')
self.assertEquals(test_elem.query.uri,'http://jabber.org/protocol/disco#items')
def _doDisco(t):
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
CLIENT_XML = """
<iq from='hag66@shakespeare.lit/pda' xmlns='jabber:client'
id='disco1'
to='%s'
type='get'>
<query xmlns='http://jabber.org/protocol/disco#items'/>
</iq>
""" % (HOSTNAME)
self.palaver_xs.dataReceived(CLIENT_XML)
return self.doWait(_cb62, 2)
PRESENCE_XML = """
<presence
from='kinghenryv@shakespeare.lit/throne'
to='lusófonos@%s/king' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_doDisco, 2)
def test63(self):
def _cb63(t):
test_elem = self.wstream.entity.children.pop()
self.assertNotEquals(test_elem['type'],'error')
self.assertEquals(test_elem.query.uri,'http://jabber.org/protocol/disco#info')
def _doTest(t):
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
CLIENT_XML = """
<iq from='hag66@shakespeare.lit/pda' xmlns='jabber:client'
id='disco3'
to='darkcave@%s'
type='get'>
<query xmlns='http://jabber.org/protocol/disco#info'/>
</iq>
""" % (HOSTNAME)
self.palaver_xs.dataReceived(CLIENT_XML)
return self.doWait(_cb63, 2)
PRESENCE_XML = """<presence
from='palaver@shakespeare.lit/pda'
to='darkcave@%s/palaver'/> """ % (HOSTNAME,)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_doTest, 2)
def test64(self):
def _cb64(t):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem['type'],'result')
self.assertEquals(test_elem['id'],'disco4')
def _doTest(t):
test_elem = self.wstream.entity.children.pop()
DISCO_ITEMS_XML = """
<iq from='hag66@shakespeare.lit/pda'
id='disco4'
to='darkcave@%s'
type='get'>
<query xmlns='http://jabber.org/protocol/disco#items'/>
</iq>
""" % (HOSTNAME,)
self.palaver_xs.dataReceived(DISCO_ITEMS_XML)
return self.doWait(_cb64, 2)
PRESENCE_XML = """<presence
from='palaver@shakespeare.lit/pda'
to='darkcave@%s/palaver'/> """ % (HOSTNAME,)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_doTest, 2)
def test65(self):
def _eb65(t):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem['type'],'error')
self.assertEquals(test_elem['id'],'disco6')
self.assertEquals(getattr(test_elem.error,'bad-request').name,'bad-request')
def _cb65(t):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem['type'],'result')
self.assertEquals(test_elem['id'],'disco5')
DISCO_ITEMS_XML = """
<iq from='lordscroop@shakespeare.lit/pda'
id='disco6'
to='darkcave@%s/oldhag'
type='get'>
<query xmlns='http://jabber.org/protocol/disco#items'/>
</iq>
""" % (HOSTNAME,)
self.palaver_xs.dataReceived(DISCO_ITEMS_XML)
return self.doWait(_eb65, 2)
def _doTest(t):
test_elem = self.wstream.entity.children.pop()
DISCO_ITEMS_XML = """
<iq from='hag66@shakespeare.lit/pda'
id='disco5'
to='darkcave@%s/oldhag'
type='get'>
<query xmlns='http://jabber.org/protocol/disco#items'/>
</iq>
""" % (HOSTNAME,)
self.palaver_xs.dataReceived(DISCO_ITEMS_XML)
return self.doWait(_cb65, 2)
PRESENCE_XML = """<presence
from='hag66@shakespeare.lit/pda'
to='darkcave@%s/palaver'/> """ % (HOSTNAME,)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_doTest, 2)
def test71(self):
def _cbJoin(t):
child_count = len(self.wstream.entity.children)
found_from = False
for i in range(1, child_count):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem.name, 'presence')
frm = 'darkcave@%s/palaver' % HOSTNAME
if test_elem['from'] == frm:
found_from = xpath.matches("/presence/x[@xmlns='http://jabber.org/protocol/muc#user']/item[@role='participant']", test_elem)
self.failUnless(found_from, 'Did not find correct from presence.')
def sendJoin(t):
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
PRESENCE_XML = """
<presence
from='palaver@shakespeare.lit/pda'
to='darkcave@%s/palaver'/>
""" % (HOSTNAME,)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_cbJoin, 2)
PRESENCE_XML = """
<presence
from='test71@shakespeare.lit/pda'
to='darkcave@%s/test71'/>
""" % (HOSTNAME,)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(sendJoin, 2)
def test71a(self):
def _cbJoin(t):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(xpath.matches("/presence[@type='error']/error[@code='400']/jid-malformed", test_elem), 1)
PRESENCE_XML = """
<presence
from='nonick@shakespeare.lit/pda'
to='darkcave@%s'/>
""" % (HOSTNAME,)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_cbJoin, 2)
def test71b(self):
def _cbJoin(t):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(xpath.matches("/presence[@from='newcave@%s/palaver']/x[@xmlns='http://jabber.org/protocol/muc#user']/item[@affiliation='owner']"%(HOSTNAME,), test_elem), 1)
PRESENCE_XML = """
<presence
from='palaver@shakespeare.lit/pda'
to='newcave@%s/palaver'/>
""" % (HOSTNAME,)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_cbJoin, 2)
def testHistoryOrder(self):
def finish(t):
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
self.assertEqual(test_elem.name, 'presence')
def testHistory(t):
test_elem = self.wstream.entity.children.pop()
self.failUnless(test_elem.name == 'message', 'Messages need to be last')
mtest = filter(lambda el: xpath.matches("/message" , el), self.wstream.entity.children)
ptest = filter(lambda el: xpath.matches("/presence" , el), self.wstream.entity.children)
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
PRESENCE_XML = """
<presence
from='palaver@shakespeare.lit/pda'
to='darkcave@%s/palaverHistory' type='unavailable'/>
<presence
from='history@shakespeare.lit/pda'
to='darkcave@%s/history' type='unavailable'/>
""" % (HOSTNAME, HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(finish, 4)
def sendPresence(t):
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
self.assertEqual(test_elem.name, 'message')
PRESENCE_XML = """
<presence
from='history@shakespeare.lit/pda'
to='darkcave@%s/history'/>
""" % (HOSTNAME,)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(testHistory, 14)
def sendMessages(t):
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
MESSAGE_XML = """
<message xmlns='jabber:client' to='darkcave@%s' from='palaver@shakespeare.lit/pda' type='groupchat'>
<body>3</body>
</message>
<message xmlns='jabber:client' to='darkcave@%s' from='palaver@shakespeare.lit/pda' type='groupchat'>
<body>2</body>
</message>
<message xmlns='jabber:client' to='darkcave@%s' from='palaver@shakespeare.lit/pda' type='groupchat'>
<body>1</body>
</message>
<message xmlns='jabber:client' to='darkcave@%s' from='palaver@shakespeare.lit/pda' type='groupchat'>
<body>contact</body>
</message>
""" % (HOSTNAME, HOSTNAME, HOSTNAME, HOSTNAME)
self.palaver_xs.dataReceived(MESSAGE_XML)
return self.doWait(sendPresence, 16)
PRESENCE_XML = """
<presence
from='palaver@shakespeare.lit/pda'
to='darkcave@%s/palaverHistory'/>
""" % (HOSTNAME,)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(sendMessages, 2)
def testInvalidNick(self):
def _cbJoin(t):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(xpath.matches("/presence[@type='error']/error[@code='400']/jid-malformed", test_elem), 1)
PRESENCE_XML = """
<presence
from='nonick@shakespeare.lit/pda'
to='darkcave@%s@%s'/>
""" % (HOSTNAME, HOSTNAME)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_cbJoin, 2)
def test72(self):
def _cbLeave(t):
child_count = len(self.wstream.entity.children)
for i in range(1, child_count):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem.name, 'presence')
if test_elem['from'] == 'darkcave@%s/palaver' % (HOSTNAME,):
self.assertEquals(xpath.matches("/presence[@type='unavailable']/x[@xmlns='http://jabber.org/protocol/muc#user']/item[@role='none']", test_elem), 1)
PRESENCE_XML = """<presence
from='palaver@shakespeare.lit/pda'
to='darkcave@%s/palaver'
type='unavailable'/>""" % (HOSTNAME,)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_cbLeave, 2)
def test73(self):
def _cbJoin(t):
child_count = len(self.wstream.entity.children)
for i in range(1, child_count):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem.name, 'presence')
frm = 'darkcave@%s/change_nick' % HOSTNAME
if test_elem['from'] == frm:
self.assertEquals(xpath.matches("/presence/x[@xmlns='http://jabber.org/protocol/muc#user']/item[@role='participant']", test_elem), 1)
if test_elem['from'] == 'darkcave@%s/palaver' % (HOSTNAME,):
self.assertEquals(xpath.matches("/presence[@type='unavailable']/x[@xmlns='http://jabber.org/protocol/muc#user']/item[@role='participant']", test_elem), 1)
self.assertEquals(xpath.matches("/presence[@type='unavailable']/x[@xmlns='http://jabber.org/protocol/muc#user']/status[@code='303']", test_elem), 1)
def _cbChange(t):
test_elem = self.wstream.entity.children.pop()
PRESENCE_XML = """
<presence
from='palaver@shakespeare.lit/pda'
to='darkcave@%s/change_nick'/>
""" % (HOSTNAME,)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_cbJoin, 2)
def _doTest(t):
test_elem = self.wstream.entity.children.pop()
PRESENCE_XML = """
<presence
from='palaver@shakespeare.lit/pda'
to='darkcave@%s/my_nick'/>
""" % (HOSTNAME,)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_cbChange, 2)
PRESENCE_XML = """<presence
from='hag66@shakespeare.lit/pda'
to='darkcave@%s/palaver'/> """ % (HOSTNAME,)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_doTest, 2)
def test74(self):
def _cb74(t):
child_count = len(self.wstream.entity.children)
for i in range(1, child_count):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem.name, 'presence')
if test_elem['from'] == 'darkcave@%s/oldhag' % (HOSTNAME,):
self.assertEquals(str(test_elem.status),'I am ready to discuss wikka')
self.assertEquals(str(test_elem.show),'chat')
if test_elem['from'] == 'darkcave@%s/testhag' % (HOSTNAME,):
self.assertEquals(xpath.matches("/presence/x[@xmlns='http://jabber.org/protocol/muc#user']/item[@role='participant']", test_elem), 1)
def _cbChangeStatus(t):
child_count = len(self.wstream.entity.children)
for i in range(1, child_count):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem.name, 'presence')
if test_elem['from'] == 'darkcave@%s/oldhag' % (HOSTNAME,):
self.assertEquals(str(test_elem.status),'I am ready to discuss wikka')
self.assertEquals(str(test_elem.show),'chat')
PRESENCE_XML = """
<presence
from='test@shakespeare.lit/laptop'
to='darkcave@%s/testhag' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_cb74, 3)
def _cbJoin(t):
child_count = len(self.wstream.entity.children)
for i in range(1, child_count):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem.name, 'presence')
if test_elem['from'] == 'darkcave@%s/oldhag' % (HOSTNAME,):
self.assertEquals(str(test_elem.status),'gone where the goblins go')
self.assertEquals(str(test_elem.show),'xa')
CHANGE_STATUS_XML = """
<presence
from='wiccarocks@shakespeare.lit/laptop'
to='darkcave@%s/oldhag'>
<show>chat</show>
<status>I am ready to discuss wikka</status>
</presence>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(CHANGE_STATUS_XML)
return self.doWait(_cbChangeStatus, 3)
JOIN_STATUS_XML = """
<presence
from='wiccarocks@shakespeare.lit/laptop'
to='darkcave@%s/oldhag'>
<show>xa</show>
<status>gone where the goblins go</status>
</presence>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(JOIN_STATUS_XML)
return self.doWait(_cbJoin, 3)
def test75(self):
def _cbInvite(t):
child_count = len(self.wstream.entity.children)
test_elem = self.wstream.entity.children.pop()
self.failUnless(test_elem.name=='message',
'Not a message returned')
self.failUnless(test_elem['to']=='hecate@shakespeare.lit',
'The message was sent to the wrong person')
return True
def _cbJoin(t):
child_count = len(self.wstream.entity.children)
for i in range(1, child_count):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem.name, 'presence')
if test_elem['from'] == 'darkcave@%s/oldhag' % (HOSTNAME,):
self.assertEquals(str(test_elem.status),'gone where the goblins go')
self.assertEquals(str(test_elem.show),'xa')
INVITE_XML = """
<message
from='wiccarocks@shakespeare.lit/desktop'
to='darkcave@%s'>
<x xmlns='http://jabber.org/protocol/muc#user'>
<invite to='hecate@shakespeare.lit'>
<reason>
Hey Hecate, this is the place for all good witches!
</reason>
</invite>
</x>
</message>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(INVITE_XML)
return self.doWait(_cbInvite, 2)
JOIN_STATUS_XML = """
<presence
from='wiccarocks@shakespeare.lit/laptop'
to='darkcave@%s/oldhag'>
<show>xa</show>
<status>gone where the goblins go</status>
</presence>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(JOIN_STATUS_XML)
return self.doWait(_cbJoin, 3)
def test79(self):
def _cbInvite(t):
mtest = filter(lambda el: xpath.matches("/message", el), self.wstream.entity.children)
self.failUnless(len(mtest)==2,'Did not get the correct number of messages')
user1 = filter(lambda el: xpath.matches("/message[@to='wiccarocks@shakespeare.lit/laptop']", el), mtest)
self.failUnless(len(user1)==1,'Did not get the correct number of messages')
user2 = filter(lambda el: xpath.matches("/message[@to='79@shakespeare.lit/laptop']", el), mtest)
self.failUnless(len(user2)==1,'Did not get the correct number of messages')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
def _cbJoin(t):
ptest = filter(lambda el: xpath.matches("/presence", el), self.wstream.entity.children)
self.failUnless(len(ptest)>1, 'Invalid number of presence stanzas')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
MESSAGE_XML = """
<message
from='wiccarocks@shakespeare.lit/laptop'
to='test79@%s' type='groupchat'>
<x xmlns='http://jabber.org/protocol/muc#user' />
<body>This is a test of the palaver broadcast system.</body>
</message>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(MESSAGE_XML)
return self.doWait(_cbInvite, 3)
def _cbJoin1(t):
JOIN_STATUS_XML = """
<presence
from='79@shakespeare.lit/laptop'
to='test79@%s/79'>
</presence>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(JOIN_STATUS_XML)
return self.doWait(_cbJoin, 5)
JOIN_STATUS_XML = """
<presence
from='wiccarocks@shakespeare.lit/laptop'
to='test79@%s/oldhag'>
<show>xa</show>
<status>gone where the goblins go</status>
</presence>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(JOIN_STATUS_XML)
return self.doWait(_cbJoin1, 5)
def test81(self):
def _cbInvite(t):
mtest = filter(lambda el: xpath.matches("/message", el), self.wstream.entity.children)
self.failUnless(len(mtest)==2,'Did not get the correct number of messages')
user1 = filter(lambda el: xpath.matches("/message[@to='wiccarocks@shakespeare.lit/laptop']/subject", el), mtest)
self.failUnless(len(user1)==1,'Did not get the correct number of messages')
user2 = filter(lambda el: xpath.matches("/message[@to='79@shakespeare.lit/laptop']/subject[text()='This is a test of the palaver broadcast system.']", el), mtest)
self.failUnless(len(user2)==1,'Did not get the correct number of messages')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
def _cbJoin(t):
ptest = filter(lambda el: xpath.matches("/presence", el), self.wstream.entity.children)
self.failUnless(len(ptest)>1, 'Invalid number of presence stanzas')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
MESSAGE_XML = """
<message
from='wiccarocks@shakespeare.lit/laptop'
to='test79@%s' type='groupchat'>
<x xmlns='http://jabber.org/protocol/muc#user' />
<subject>This is a test of the palaver broadcast system.</subject>
</message>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(MESSAGE_XML)
return self.doWait(_cbInvite, 3)
def _cbJoin1(t):
JOIN_STATUS_XML = """
<presence
from='79@shakespeare.lit/laptop'
to='test79@%s/79'>
</presence>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(JOIN_STATUS_XML)
return self.doWait(_cbJoin, 5)
JOIN_STATUS_XML = """
<presence
from='wiccarocks@shakespeare.lit/laptop'
to='test79@%s/oldhag'>
<show>xa</show>
<status>gone where the goblins go</status>
</presence>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(JOIN_STATUS_XML)
return self.doWait(_cbJoin1, 5)
def testKickMessage(self):
def _checkError(t):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem['type'],'error')
self.failUnless(getattr(test_elem.error,'not-authorized',False),
'Bad error result')
def _cbTestKick(t):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem['type'],'result')
test_elem = self.wstream.entity.children.pop()
self.failUnless(test_elem.hasAttribute('type'),
'Presence does not have a type attribute')
self.assertEquals(test_elem['type'],'unavailable')
for c in test_elem.elements():
if c.name == 'x' and c.uri == 'http://jabber.org/protocol/muc#user':
self.assertEquals(c.item['affiliation'],'none')
self.assertEquals(c.item['role'],'none')
test_elem = self.wstream.entity.children.pop()
self.failUnless(test_elem.hasAttribute('type'),
'Presence does not have a type attribute')
self.assertEquals(test_elem['type'],'unavailable')
for c in test_elem.elements():
if c.name == 'x' and c.uri == 'http://jabber.org/protocol/muc#user':
self.assertEquals(c.item['affiliation'],'none')
self.assertEquals(c.item['role'],'none')
MESSAGE_XML = """
<message xmlns='jabber:client' to='testkick@%s' from='earlofcambridge@shakespeare.lit/throne' type='groupchat'>
<body>3</body>
</message>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(MESSAGE_XML)
return self.doWait(_checkError, 2)
def _kick(t):
for i in range(0, 3):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem.name, 'presence')
BAN_XML = """<iq from='kinghenryv@shakespeare.lit/throne'
id='ban1'
to='testkick@%s'
type='set'>
<query xmlns='http://jabber.org/protocol/muc#admin'>
<item role='none'
jid='earlofcambridge@shakespeare.lit'>
<reason>Treason</reason>
</item>
</query>
</iq>""" % (HOSTNAME,)
self.palaver_xs.dataReceived(BAN_XML)
return self.doWait(_cbTestKick, 4)
def _create(t):
test_elem = self.wstream.entity.children.pop()
frm = 'testkick@%s/king' % HOSTNAME
self._testCreate(test_elem, frm)
PRESENCE_XML = """
<presence
from='earlofcambridge@shakespeare.lit/throne'
to='testkick@%s/kingoftown' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_kick, 3)
PRESENCE_XML = """
<presence
from='kinghenryv@shakespeare.lit/throne'
to='testkick@%s/king' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_create, 2)
def test91(self):
def _checkDestroy(r):
miq = filter(lambda el: xpath.matches("/iq[@type='result']" , el), self.wstream.entity.children)
self.failUnless(len(miq)==1, 'Did not get a destroy result')
def _checkPresenceError(t):
test_elem = self.wstream.entity.children.pop()
self.failUnless(xpath.matches("/presence[@type='error']/error", test_elem), 'Presence needs to be an error')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
ADMIN_XML = """<iq from='kinghenryv@shakespeare.lit/throne'
id='admin1'
to='southhampton@%s'
type='set'>
<query xmlns='http://jabber.org/protocol/muc#admin'>
<destroy jid='southhampton@%s'>
<reason>Macbeth doth come.</reason>
</destroy>
</query>
</iq>""" % (HOSTNAME, HOSTNAME)
self.palaver_xs.dataReceived(ADMIN_XML)
return self.doWait(_checkDestroy, 2)
def _checkMessageError(t):
test_elem = self.wstream.entity.children.pop()
self.failUnless(xpath.matches("/message[@type='error']/error", test_elem), 'Message needs to be an error')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
PRESENCE_XML = """
<presence
from='earlofcambridge@shakespeare.lit/throne'
to='southhampton@%s/kingoftown' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_checkPresenceError, 3)
def _cb91(t):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem['type'],'result')
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem['type'],'unavailable')
for c in test_elem.elements():
if c.name == 'x' and c.uri == 'http://jabber.org/protocol/muc#user':
self.assertEquals(c.item['affiliation'],'outcast')
self.assertEquals(c.item['role'],'none')
self.assertEquals(str(c.item.reason),'Treason')
self.assertEquals(c.status['code'],'301')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
MESSAGE_XML = """
<message xmlns='jabber:client' to='southhampton@%s' from='earlofcambridge@shakespeare.lit/throne' type='groupchat'>
<body>3</body>
</message>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(MESSAGE_XML)
return self.doWait(_checkMessageError, 3)
def _ban(t):
for i in range(0, 3):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem.name, 'presence')
BAN_XML = """<iq from='kinghenryv@shakespeare.lit/throne'
id='ban1'
to='southhampton@%s'
type='set'>
<query xmlns='http://jabber.org/protocol/muc#admin'>
<item affiliation='outcast'
jid='earlofcambridge@shakespeare.lit'>
<reason>Treason</reason>
</item>
</query>
</iq>""" % (HOSTNAME,)
self.palaver_xs.dataReceived(BAN_XML)
return self.doWait(_cb91, 3)
def _create(t):
test_elem = self.wstream.entity.children.pop()
frm = 'southhampton@%s/king' % HOSTNAME
self._testCreate(test_elem, frm)
PRESENCE_XML = """
<presence
from='earlofcambridge@shakespeare.lit/throne'
to='southhampton@%s/kingoftown' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_ban, 3)
PRESENCE_XML = """
<presence
from='kinghenryv@shakespeare.lit/throne'
to='southhampton@%s/king' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_create, 2)
def testE100ToE103(self):
def _removeNoneParticipant(t):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(jid.internJID(test_elem['from']).userhost(),'southhampton@%s' % (HOSTNAME,))
self.assertEquals(test_elem['type'],'result')
self.assertEquals(test_elem['id'],'removeban4')
def _checkRemove(t):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(jid.internJID(test_elem['from']).userhost(),'southhampton@%s' % (HOSTNAME,))
self.assertEquals(test_elem['type'],'result')
test_elem = self.wstream.entity.children.pop()
REMOVE_XML = """
<iq from='kinghenryv@shakespeare.lit/throne'
id='removeban4'
to='southhampton@%s'
type='set'>
<query xmlns='http://jabber.org/protocol/muc#admin'>
<item affiliation='none'
jid='lordscroop@shakespeare.lit' />
</query>
</iq>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(REMOVE_XML)
return self.doWait(_removeNoneParticipant, 3)
def _remove(t):
miq = filter(lambda el: xpath.matches("/iq[@type='result']" , el), self.wstream.entity.children)
self.failUnless(len(miq)==1, 'Did not get a result')
self.assertEquals(jid.internJID(miq[0]['from']).userhost(),'southhampton@%s' % (HOSTNAME,))
self.assertEquals(miq[0]['type'],'result')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
REMOVE_XML = """
<iq from='kinghenryv@shakespeare.lit/throne'
id='removeban3'
to='southhampton@%s'
type='set'>
<query xmlns='http://jabber.org/protocol/muc#admin'>
<item affiliation='none'
jid='earlofcambridge@shakespeare.lit' />
</query>
</iq>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(REMOVE_XML)
return self.doWait(_checkRemove, 3)
def _modify(t):
miq = filter(lambda el: xpath.matches("/iq[@type='result']/query[@xmlns='http://jabber.org/protocol/muc#admin']" % (), el), self.wstream.entity.children)
self.failUnless(len(miq)==1, 'Did not get the correct outcast result')
self.assertEquals(jid.internJID(miq[0]['from']).userhost(),'southhampton@%s' % (HOSTNAME,))
self.failUnless(miq[0].hasAttribute('type'), 'Wrong Attribute Type')
self.assertEquals(miq[0]['type'],'result')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
MODIFY_XML = """
<iq from='kinghenryv@shakespeare.lit/throne'
id='ban3'
to='southhampton@%s'
type='set'>
<query xmlns='http://jabber.org/protocol/muc#admin'>
<item affiliation='outcast'
jid='earlofcambridge@shakespeare.lit'>
<reason>Treason</reason>
</item>
<item affiliation='outcast'>
jid='lordscroop@shakespeare.lit'>
<reason>Treason</reason>
</item>
<item affiliation='outcast'
jid='sirthomasgrey@shakespeare.lit'>
<reason>Treason</reason>
</item>
</query>
</iq>
""" % (HOSTNAME,)
self.palaver_xs.dataReceived(MODIFY_XML)
return self.doWait(_remove, 3)
def _first_ban_result(t):
test_elem = self.wstream.entity.children.pop()
self.failUnless(xpath.matches("/iq[@type='result']", test_elem), 'Error in ban result.')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
GET_XML = """
<iq from='kinghenryv@shakespeare.lit/throne'
id='ban2'
to='southhampton@%s'
type='get'>
<query xmlns='http://jabber.org/protocol/muc#admin'>
<item affiliation='outcast' />
</query>
</iq>""" % (HOSTNAME,)
self.palaver_xs.dataReceived(GET_XML)
return self.doWait(_modify, 4)
def _do_first_ban(t):
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
BAN_XML = """<iq from='kinghenryv@shakespeare.lit/throne'
id='ban1'
to='southhampton@%s'
type='set'>
<query xmlns='http://jabber.org/protocol/muc#admin'>
<item affiliation='outcast'
jid='earlofcambridge@shakespeare.lit'>
<reason>Treason</reason>
</item>
</query>
</iq>""" % (HOSTNAME,)
self.palaver_xs.dataReceived(BAN_XML)
return self.doWait(_first_ban_result, 4)
PRESENCE_XML = """
<presence
from='kinghenryv@shakespeare.lit/throne'
to='southhampton@%s/king' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_do_first_ban, 3)
def test93(self):
def _testJoin(r):
self.failUnless(len(self.wstream.entity.children)>1, 'No elements found')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
self.failUnless(xpath.matches("/presence[not(@type)]", test_elem), 'Error joining room.')
def _cb93(t):
test_elem = self.wstream.entity.children.pop()
self.failUnless(xpath.matches("/iq[@type='result']/query", test_elem), 'Error in member add result.')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
PRESENCE_XML = """
<presence
from='hag66@shakespeare.lit/throne'
to='membertest@%s/ha66' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_testJoin, 2)
def _create(t):
test_elem = self.wstream.entity.children.pop()
frm = 'membertest@%s/king' % HOSTNAME
self._testCreate(test_elem, frm)
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
MEMBER_XML = """
<iq from='kinghenryv@shakespeare.lit/throne'
id='member1'
to='membertest@%s'
type='set'>
<query xmlns='http://jabber.org/protocol/muc#admin'>
<item affiliation='member'
jid='hag66@shakespeare.lit'/>
</query>
</iq>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(MEMBER_XML)
return self.doWait(_cb93, 3)
PRESENCE_XML = """
<presence
from='kinghenryv@shakespeare.lit/throne'
to='membertest@%s/king' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_create, 2, timeout=20)
def test96(self):
def _cb96(t):
test_elem = self.wstream.entity.children.pop()
self.failUnless(xpath.matches("/iq[@type='result']/query", test_elem), 'Error in moderator result.')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
self.failUnless(xpath.matches("/presence[@from='modtest@%s/witch']/x/item[@role='moderator']" % (HOSTNAME,), test_elem), 'Error in presence.')
def _setRole(t):
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
MEMBER_XML = """
<iq from='kinghenryv@shakespeare.lit/throne'
id='member1'
to='modtest@%s'
type='set'>
<query xmlns='http://jabber.org/protocol/muc#admin'>
<item role='moderator'
nick='witch'/>
</query>
</iq>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(MEMBER_XML)
return self.doWait(_cb96, 3)
def _create(t):
test_elem = self.wstream.entity.children.pop()
frm = 'modtest@%s/king' % HOSTNAME
self._testCreate(test_elem, frm)
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
PRESENCE_XML = """
<presence
from='hag66@shakespeare.lit/witch'
to='modtest@%s/witch' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_setRole, 2)
PRESENCE_XML = """
<presence
from='kinghenryv@shakespeare.lit/throne'
to='modtest@%s/king' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_create, 2)
def test106(self):
def _cb106(t):
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem['type'],'result')
test_elem = self.wstream.entity.children.pop()
for c in test_elem.elements():
if c.name == 'x' and c.uri == 'http://jabber.org/protocol/muc#user':
self.assertEquals(c.item['affiliation'],'admin')
self.assertEquals(c.item['role'],'moderator')
def _admin(t):
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem.name, 'presence')
ADMIN_XML = """<iq from='kinghenryv@shakespeare.lit/throne'
id='admin1'
to='admintest@%s'
type='set'>
<query xmlns='http://jabber.org/protocol/muc#admin'>
<item affiliation='admin'
jid='earlofcambridge@shakespeare.lit'/>
</query>
</iq>""" % (HOSTNAME,)
self.palaver_xs.dataReceived(ADMIN_XML)
return self.doWait(_cb106, 4)
def _create(t):
test_elem = self.wstream.entity.children.pop()
frm = 'admintest@%s/king' % HOSTNAME
self._testCreate(test_elem, frm)
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
PRESENCE_XML = """
<presence
from='earlofcambridge@shakespeare.lit/throne'
to='admintest@%s/kingoftown' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_admin, 3)
PRESENCE_XML = """
<presence
from='kinghenryv@shakespeare.lit/throne'
to='admintest@%s/king' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_create, 2)
def test109(self):
def _cb109(t):
ptest = filter(lambda el: xpath.matches("/presence[@type='unavailable']/x/item[@role='none']", el), self.wstream.entity.children)
self.failUnless(len(ptest)==1, 'Presence was not sent that use left the room.')
iqtest = filter(lambda el: xpath.matches("/iq[@type='result']", el), self.wstream.entity.children)
self.failUnless(len(iqtest)==1, 'Invalid iq result.')
def _admin(t):
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem.name, 'presence')
ADMIN_XML = """<iq from='kinghenryv@shakespeare.lit/throne'
id='admin1'
to='destroytest@%s'
type='set'>
<query xmlns='http://jabber.org/protocol/muc#admin'>
<destroy jid='destroytest@%s'>
<reason>Macbeth doth come.</reason>
</destroy>
</query>
</iq>""" % (HOSTNAME, HOSTNAME)
self.palaver_xs.dataReceived(ADMIN_XML)
return self.doWait(_cb109, 4)
PRESENCE_XML = """
<presence
from='kinghenryv@shakespeare.lit/throne'
to='destroytest@%s/king' />
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(_admin, 2)
def testPresenceLeak(self):
user_list = {}
def testLeave(t):
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
self.assertEquals(test_elem['type'], 'unavailable')
self.failUnless(test_elem['to'].lower() in user_list)
if user_list.has_key(test_elem['to'].lower()):
del user_list[test_elem['to'].lower()]
self.failUnless(len(user_list)==0, 'Not all users got unavailable presence')
def testJoin(t):
send_one_to_users = 0
send_one_to_member = 0
send_two_to_users = 0
send_two_to_member = 0
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
if test_elem.name =='presence' and test_elem['from'] == 'leak@%s/One' % (HOSTNAME,) \
and test_elem['to'] != '2@shakespeare.lit/testing':
send_one_to_users += 1
if test_elem.name =='presence' and test_elem['from'] == 'leak@%s/two' % (HOSTNAME,):
send_two_to_users += 1
user_list[test_elem['to'].lower()] = True
self.failUnless(send_one_to_users >= 2, 'Not enough presence elements')
self.failUnless(send_two_to_users >= 3, 'Not enough presence elements')
PRESENCE_XML = """
<presence from='one@shakespeare.lit/testing' to='leak@%s/one' type='unavailable'/>
""" % (HOSTNAME, )
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(testLeave, 7)
def testLeak(t):
PRESENCE_XML = """
<presence from='One@shakespeare.lit/testing' to='leak@%s/One' />
<presence from='2@shakespeare.lit/testing' to='leak@%s/two' />
""" % (HOSTNAME, HOSTNAME)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(testJoin, 16)
self._createRoom('hag66@shakespeare.lit/pda', 'leak@%s/thirdwitch' % (HOSTNAME, ))
return self.doWait(testLeak, 3)
def testPresenceRaceCondition(self):
def testJoin(t):
unavailable = False
test_elem = self.wstream.entity.children.pop()
if test_elem.name == 'presence' and \
test_elem.hasAttribute('type') and \
test_elem['type'] == 'unavailable':
unavailable = True
self.failUnless(unavailable,'Did NOT leave the room')
while len(self.wstream.entity.children)>1:
test_elem = self.wstream.entity.children.pop()
def testRace(t):
PRESENCE_XML = """
<presence from='race@shakespeare.lit/testing' to='racetest@%s/RaceTest' />
<presence from='race@shakespeare.lit/testing' type='unavailable' to='racetest@%s/RaceTest' />
""" % (HOSTNAME, HOSTNAME)
self.palaver_xs.dataReceived(PRESENCE_XML)
return self.doWait(testJoin, 18)
self._createRoom('hag66@shakespeare.lit/pda', 'racetest@%s/thirdwitch' % (HOSTNAME, ))
return self.doWait(testRace, 3)
def testZDisconnect(self):
self.palaver_xs.connectionLost(None)
def tearDown(self):
self.st._flush()
pending = reactor.getDelayedCalls()
if pending:
for p in pending:
if p.active():
p.cancel()
def tearDownClass(self):
pending = reactor.getDelayedCalls()
if pending:
for p in pending:
if p.active():
p.cancel()
class StorageTests(unittest.TestCase):
pass
| true | true |
1c36d4ac05de72e185c9d192567f42529ea6a438 | 381 | py | Python | cookiecutter_django_test/users/apps.py | imsure/cookiecutter-django-test | 853a46e6410fc9814cadbef828987f2c5b24fe4d | [
"MIT"
] | null | null | null | cookiecutter_django_test/users/apps.py | imsure/cookiecutter-django-test | 853a46e6410fc9814cadbef828987f2c5b24fe4d | [
"MIT"
] | null | null | null | cookiecutter_django_test/users/apps.py | imsure/cookiecutter-django-test | 853a46e6410fc9814cadbef828987f2c5b24fe4d | [
"MIT"
] | null | null | null | from django.apps import AppConfig
class UsersConfig(AppConfig):
name = "cookiecutter_django_test.users"
verbose_name = "Users"
def ready(self):
"""Override this to put in:
Users system checks
Users signal registration
"""
try:
import users.signals # noqa F401
except ImportError:
pass
| 22.411765 | 45 | 0.590551 | from django.apps import AppConfig
class UsersConfig(AppConfig):
name = "cookiecutter_django_test.users"
verbose_name = "Users"
def ready(self):
try:
import users.signals
except ImportError:
pass
| true | true |
1c36d5757e7eb9e5baf0d65904a538f60fd08f9a | 7,986 | py | Python | lfs/customer/models.py | restless/django-lfs | 4058f9d45b416ef2e8c28a87856ea0f1550b523d | [
"BSD-3-Clause"
] | 1 | 2020-02-26T03:07:39.000Z | 2020-02-26T03:07:39.000Z | lfs/customer/models.py | mxins/django-lfs | bf42ed80ce0e1ec96db6ab985adcc614ea79dfc8 | [
"BSD-3-Clause"
] | null | null | null | lfs/customer/models.py | mxins/django-lfs | bf42ed80ce0e1ec96db6ab985adcc614ea79dfc8 | [
"BSD-3-Clause"
] | null | null | null | # django imports
from copy import deepcopy
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.db import models
from django.utils.translation import ugettext_lazy as _
# lfs imports
from lfs.core.models import Country
from lfs.shipping.models import ShippingMethod
from lfs.payment.models import PaymentMethod
from lfs.addresses import settings
class Customer(models.Model):
"""
A customer holds all shop customer related information and is assigned to
a Django user and/or a session dependend on the login state of the current
user.
A customer is only created when it needs to. Either when:
* The cart is refreshed (this is because some of the customer related
information could be changed like shipping/payment method or shipping
address).
* The customer browses to the check out page.
"""
user = models.ForeignKey(User, blank=True, null=True)
session = models.CharField(blank=True, max_length=100)
selected_shipping_method = models.ForeignKey(ShippingMethod, verbose_name=_(u"Selected shipping method"), blank=True, null=True, related_name="selected_shipping_method")
selected_payment_method = models.ForeignKey(PaymentMethod, verbose_name=_(u"Selected payment method"), blank=True, null=True, related_name="selected_payment_method")
selected_bank_account = models.ForeignKey("BankAccount", verbose_name=_(u"Bank account"), blank=True, null=True, related_name="selected_bank_account")
selected_credit_card = models.ForeignKey("CreditCard", verbose_name=_(u"Credit card"), blank=True, null=True, related_name="selected_credit_card")
sa_content_type = models.ForeignKey(ContentType, related_name="sa_content_type")
sa_object_id = models.PositiveIntegerField()
selected_shipping_address = generic.GenericForeignKey('sa_content_type', 'sa_object_id')
dsa_object_id = models.PositiveIntegerField()
default_shipping_address = generic.GenericForeignKey('sa_content_type', 'dsa_object_id')
ia_content_type = models.ForeignKey(ContentType, related_name="ia_content_type")
ia_object_id = models.PositiveIntegerField()
selected_invoice_address = generic.GenericForeignKey('ia_content_type', 'ia_object_id')
dia_object_id = models.PositiveIntegerField()
default_invoice_address = generic.GenericForeignKey('ia_content_type', 'dia_object_id')
selected_country = models.ForeignKey(Country, verbose_name=_(u"Selected country"), blank=True, null=True)
def __unicode__(self):
return u"%s/%s" % (self.user, self.session)
def get_email_address(self):
"""Returns the email address of the customer dependend on the user is
registered or not.
"""
if self.user:
return self.user.email
elif self.selected_invoice_address:
return self.selected_invoice_address.email
else:
return None
def set_email_address(self, email):
"""Returns the email address of the customer dependend on the user is
registered or not.
"""
if self.user:
self.user.email = email
self.user.save()
else:
self.selected_invoice_address.email = email
self.selected_invoice_address.save()
def get_selected_shipping_address(self):
"""Returns the selected shipping address.
"""
return self.selected_shipping_address or \
self.selected_invoice_address or \
None
def sync_default_to_selected_addresses(self, force=False):
# Synchronize selected addresses with default addresses
auto_update = settings.AUTO_UPDATE_DEFAULT_ADDRESSES
if force or not auto_update:
shipping_address = deepcopy(self.default_shipping_address)
if self.selected_shipping_address:
shipping_address.id = self.selected_shipping_address.id
shipping_address.pk = self.selected_shipping_address.pk
shipping_address.save()
else:
shipping_address.id = None
shipping_address.pk = None
shipping_address.save()
self.save() # save customer to set generic key id
invoice_address = deepcopy(self.default_invoice_address)
if self.selected_invoice_address:
invoice_address.id = self.selected_invoice_address.id
invoice_address.pk = self.selected_invoice_address.pk
invoice_address.save()
else:
invoice_address.id = None
invoice_address.pk = None
invoice_address.save()
self.save()
def sync_selected_to_default_invoice_address(self, force=False):
# Synchronize default invoice address with selected address
auto_update = settings.AUTO_UPDATE_DEFAULT_ADDRESSES
if force or auto_update:
address = deepcopy(self.selected_invoice_address)
address.id = self.default_invoice_address.id
address.pk = self.default_invoice_address.pk
address.save()
def sync_selected_to_default_shipping_address(self, force=False):
# Synchronize default shipping address with selected address
auto_update = settings.AUTO_UPDATE_DEFAULT_ADDRESSES
if force or auto_update:
address = deepcopy(self.selected_shipping_address)
address.id = self.default_shipping_address.id
address.pk = self.default_shipping_address.pk
address.save()
def sync_selected_to_default_addresses(self, force=False):
# Synchronize default addresses with selected addresses
self.sync_selected_to_default_invoice_address(force)
self.sync_selected_to_default_shipping_address(force)
class BankAccount(models.Model):
"""
Stores all shop relevant data of a credit card.
**Attributes**
customer
The customer the bank accoun belongs to.
account_number
The account number of the bank account.
bank_identification_code
The bank identification code of the bank account.
depositor
The depositor of the bank account.
"""
customer = models.ForeignKey(Customer, verbose_name=_(u"Customer"), blank=True, null=True, related_name="bank_accounts")
account_number = models.CharField(_(u"Account number"), blank=True, max_length=30)
bank_identification_code = models.CharField(_(u"Bank identification code"), blank=True, max_length=30)
bank_name = models.CharField(_(u"Bank name"), blank=True, max_length=100)
depositor = models.CharField(_(u"Depositor"), blank=True, max_length=100)
def __unicode__(self):
return u"%s / %s" % (self.account_number, self.bank_name)
class CreditCard(models.Model):
"""
Stores all shop relevant data of a credit card.
**Attributes:**
type
The type of the credit card, like Master Card, Visa, etc.
owner
The owner of the credit card.
number
The number of the credit card.
expiration_date_month
The month of the expiration date of the credit card.
expiration_date_year
The year of the expiration date of the credit card.
"""
customer = models.ForeignKey(Customer, verbose_name=_(u"Customer"), blank=True, null=True, related_name="credit_cards")
type = models.CharField(_(u"Type"), blank=True, max_length=30)
owner = models.CharField(_(u"Owner"), blank=True, max_length=100)
number = models.CharField(_(u"Number"), blank=True, max_length=30)
expiration_date_month = models.IntegerField(_(u"Expiration date month"), blank=True, null=True)
expiration_date_year = models.IntegerField(_(u"Expiration date year"), blank=True, null=True)
def __unicode__(self):
return u"%s / %s" % (self.type, self.owner)
| 40.953846 | 173 | 0.702605 |
from copy import deepcopy
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.db import models
from django.utils.translation import ugettext_lazy as _
from lfs.core.models import Country
from lfs.shipping.models import ShippingMethod
from lfs.payment.models import PaymentMethod
from lfs.addresses import settings
class Customer(models.Model):
user = models.ForeignKey(User, blank=True, null=True)
session = models.CharField(blank=True, max_length=100)
selected_shipping_method = models.ForeignKey(ShippingMethod, verbose_name=_(u"Selected shipping method"), blank=True, null=True, related_name="selected_shipping_method")
selected_payment_method = models.ForeignKey(PaymentMethod, verbose_name=_(u"Selected payment method"), blank=True, null=True, related_name="selected_payment_method")
selected_bank_account = models.ForeignKey("BankAccount", verbose_name=_(u"Bank account"), blank=True, null=True, related_name="selected_bank_account")
selected_credit_card = models.ForeignKey("CreditCard", verbose_name=_(u"Credit card"), blank=True, null=True, related_name="selected_credit_card")
sa_content_type = models.ForeignKey(ContentType, related_name="sa_content_type")
sa_object_id = models.PositiveIntegerField()
selected_shipping_address = generic.GenericForeignKey('sa_content_type', 'sa_object_id')
dsa_object_id = models.PositiveIntegerField()
default_shipping_address = generic.GenericForeignKey('sa_content_type', 'dsa_object_id')
ia_content_type = models.ForeignKey(ContentType, related_name="ia_content_type")
ia_object_id = models.PositiveIntegerField()
selected_invoice_address = generic.GenericForeignKey('ia_content_type', 'ia_object_id')
dia_object_id = models.PositiveIntegerField()
default_invoice_address = generic.GenericForeignKey('ia_content_type', 'dia_object_id')
selected_country = models.ForeignKey(Country, verbose_name=_(u"Selected country"), blank=True, null=True)
def __unicode__(self):
return u"%s/%s" % (self.user, self.session)
def get_email_address(self):
if self.user:
return self.user.email
elif self.selected_invoice_address:
return self.selected_invoice_address.email
else:
return None
def set_email_address(self, email):
if self.user:
self.user.email = email
self.user.save()
else:
self.selected_invoice_address.email = email
self.selected_invoice_address.save()
def get_selected_shipping_address(self):
return self.selected_shipping_address or \
self.selected_invoice_address or \
None
def sync_default_to_selected_addresses(self, force=False):
auto_update = settings.AUTO_UPDATE_DEFAULT_ADDRESSES
if force or not auto_update:
shipping_address = deepcopy(self.default_shipping_address)
if self.selected_shipping_address:
shipping_address.id = self.selected_shipping_address.id
shipping_address.pk = self.selected_shipping_address.pk
shipping_address.save()
else:
shipping_address.id = None
shipping_address.pk = None
shipping_address.save()
self.save()
invoice_address = deepcopy(self.default_invoice_address)
if self.selected_invoice_address:
invoice_address.id = self.selected_invoice_address.id
invoice_address.pk = self.selected_invoice_address.pk
invoice_address.save()
else:
invoice_address.id = None
invoice_address.pk = None
invoice_address.save()
self.save()
def sync_selected_to_default_invoice_address(self, force=False):
auto_update = settings.AUTO_UPDATE_DEFAULT_ADDRESSES
if force or auto_update:
address = deepcopy(self.selected_invoice_address)
address.id = self.default_invoice_address.id
address.pk = self.default_invoice_address.pk
address.save()
def sync_selected_to_default_shipping_address(self, force=False):
auto_update = settings.AUTO_UPDATE_DEFAULT_ADDRESSES
if force or auto_update:
address = deepcopy(self.selected_shipping_address)
address.id = self.default_shipping_address.id
address.pk = self.default_shipping_address.pk
address.save()
def sync_selected_to_default_addresses(self, force=False):
self.sync_selected_to_default_invoice_address(force)
self.sync_selected_to_default_shipping_address(force)
class BankAccount(models.Model):
customer = models.ForeignKey(Customer, verbose_name=_(u"Customer"), blank=True, null=True, related_name="bank_accounts")
account_number = models.CharField(_(u"Account number"), blank=True, max_length=30)
bank_identification_code = models.CharField(_(u"Bank identification code"), blank=True, max_length=30)
bank_name = models.CharField(_(u"Bank name"), blank=True, max_length=100)
depositor = models.CharField(_(u"Depositor"), blank=True, max_length=100)
def __unicode__(self):
return u"%s / %s" % (self.account_number, self.bank_name)
class CreditCard(models.Model):
customer = models.ForeignKey(Customer, verbose_name=_(u"Customer"), blank=True, null=True, related_name="credit_cards")
type = models.CharField(_(u"Type"), blank=True, max_length=30)
owner = models.CharField(_(u"Owner"), blank=True, max_length=100)
number = models.CharField(_(u"Number"), blank=True, max_length=30)
expiration_date_month = models.IntegerField(_(u"Expiration date month"), blank=True, null=True)
expiration_date_year = models.IntegerField(_(u"Expiration date year"), blank=True, null=True)
def __unicode__(self):
return u"%s / %s" % (self.type, self.owner)
| true | true |
1c36d64543c9ae82fd1fedde5c61ca0052ed9091 | 982 | py | Python | apps/portalbase/macros/wiki/actors/1_main.py | jumpscale7/jumpscale_portal | 8c99265e48f85643f8a52bc40a23f5266fb09231 | [
"Apache-2.0"
] | 2 | 2016-04-14T14:05:01.000Z | 2016-04-21T07:20:36.000Z | apps/portalbase/macros/wiki/actors/1_main.py | Jumpscale/jumpscale6_core | 0502ddc1abab3c37ed982c142d21ea3955d471d3 | [
"BSD-2-Clause"
] | 13 | 2016-03-07T12:07:15.000Z | 2018-02-28T13:11:59.000Z | apps/portalbase/macros/wiki/actors/1_main.py | Jumpscale/jumpscale6_core | 0502ddc1abab3c37ed982c142d21ea3955d471d3 | [
"BSD-2-Clause"
] | 5 | 2016-03-08T07:49:51.000Z | 2018-10-19T13:57:04.000Z |
def main(j, args, params, tags, tasklet):
doc = args.doc
tags = args.tags
out = ""
bullets = args.tags.labelExists("bullets")
table = args.tags.labelExists("table")
if table:
rows = []
for item in sorted(j.core.portal.active.getActors()):
app, actor = item.split("__")
out += "|[%s|/rest/%s/%s]|\n" % (item, app.lower().strip("/"), actor.lower().strip("/"))
else:
for item in sorted(j.core.portal.active.getActors()):
if item[0] != "_" and item.strip() != "":
app, actor = item.split("__")
if bullets:
out += "* [%s|/rest/%s/%s]\n" % (item, app.lower().strip("/"), actor.lower().strip("/"))
else:
out += "|[%s|/rest/%s/%s]|\n" % (item, app.lower().strip("/"), actor.lower().strip("/"))
params.result = (out, doc)
return params
def match(j, args, params, tags, tasklet):
return True
| 27.277778 | 108 | 0.491853 |
def main(j, args, params, tags, tasklet):
doc = args.doc
tags = args.tags
out = ""
bullets = args.tags.labelExists("bullets")
table = args.tags.labelExists("table")
if table:
rows = []
for item in sorted(j.core.portal.active.getActors()):
app, actor = item.split("__")
out += "|[%s|/rest/%s/%s]|\n" % (item, app.lower().strip("/"), actor.lower().strip("/"))
else:
for item in sorted(j.core.portal.active.getActors()):
if item[0] != "_" and item.strip() != "":
app, actor = item.split("__")
if bullets:
out += "* [%s|/rest/%s/%s]\n" % (item, app.lower().strip("/"), actor.lower().strip("/"))
else:
out += "|[%s|/rest/%s/%s]|\n" % (item, app.lower().strip("/"), actor.lower().strip("/"))
params.result = (out, doc)
return params
def match(j, args, params, tags, tasklet):
return True
| true | true |
1c36d74a9862ed7d1ddc7e13a4e9b242b78dd32c | 3,481 | py | Python | python/src/nnabla/experimental/graph_converters/fused_batch_normalization.py | daniel-falk/nnabla | 3fe132ea52dc10521cc029a5d6ba8f565cf65ccf | [
"Apache-2.0"
] | 2,792 | 2017-06-26T13:05:44.000Z | 2022-03-28T07:55:26.000Z | python/src/nnabla/experimental/graph_converters/fused_batch_normalization.py | daniel-falk/nnabla | 3fe132ea52dc10521cc029a5d6ba8f565cf65ccf | [
"Apache-2.0"
] | 138 | 2017-06-27T07:04:44.000Z | 2022-02-28T01:37:15.000Z | python/src/nnabla/experimental/graph_converters/fused_batch_normalization.py | daniel-falk/nnabla | 3fe132ea52dc10521cc029a5d6ba8f565cf65ccf | [
"Apache-2.0"
] | 380 | 2017-06-26T13:23:52.000Z | 2022-03-25T16:51:30.000Z | # Copyright 2020,2021 Sony Corporation.
#
# 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 nnabla.parametric_functions as PF
from .graph_converter import FunctionModifier
class FusedBatchNormalizationModifier(FunctionModifier):
"""
Block `BatchNormalization -> Add2 -> Non-Linear` pass is fused into one `FusedBatchNormalization`.
If there is a block `BatchNormalization -> Add2 -> Non-Linear` pass,
remove all the block functions and replace the whole block to `FusedBatchNormalization`.
Examples:
.. code-block:: python
pred = Model(...)
import nnabla.experimental.graph_converters as GC
modifiers = [GC.FusedBatchNormalizationModifier()]
gc = GC.GraphConverter(modifiers)
pred = gc.convert(pred)
"""
def __init__(self):
super(FusedBatchNormalizationModifier, self).__init__()
self._name = ''
self._block = False
self._bn_args = None
self._add2_input1 = None
self._cnt = 1
self._fct_set = {
'ReLU': 'relu'
}
def modify(self, f, inputs):
outputs = f.outputs[0]
# Not end
if len(outputs.function_references) == 0:
return
# Check fused bn block start
if not self._block and self._is_fused_bn_block(f, inputs):
self._block = True
# Remove BatchNormalization
if self._block and f.info.type_name == 'BatchNormalization':
self._bn_args = f.info.args
self._name = self.get_parameter_scope(inputs[0])
return inputs[0]
# Remove Add2
if self._block and f.info.type_name == 'Add2':
self._add2_input1 = inputs[1]
return inputs[0]
# Remove non linear function then connect fused bn
if self._block and f.info.type_name in self._fct_set:
f_non_linear = self._fct_set[f.info.type_name]
h = PF.fused_batch_normalization(
inputs[0], self._add2_input1,
nonlinearity=f_non_linear, **self._bn_args,
name='fused{}-{}'.format(self._name, self._cnt))
self._cnt += 1
self._block = False
return h
def _is_fused_bn_block(self, f, inputs):
outputs = f.outputs[0]
# Function is BN whose next function is Add2,
# function after Add2 is not non-linear
next_func = outputs.function_references[0]
if len(next_func.outputs[0].function_references) == 0:
return False
nnext_func = next_func.outputs[0].function_references[0]
if f.info.type_name == 'BatchNormalization' \
and next_func.info.type_name == 'Add2' \
and nnext_func.info.type_name in self._fct_set:
return True
return False
def __finish__(self):
self._name = ''
self._block = False
self._bn_args = None
self._add2_input1 = None
self._cnt = 1
| 31.93578 | 102 | 0.634875 |
import nnabla.parametric_functions as PF
from .graph_converter import FunctionModifier
class FusedBatchNormalizationModifier(FunctionModifier):
def __init__(self):
super(FusedBatchNormalizationModifier, self).__init__()
self._name = ''
self._block = False
self._bn_args = None
self._add2_input1 = None
self._cnt = 1
self._fct_set = {
'ReLU': 'relu'
}
def modify(self, f, inputs):
outputs = f.outputs[0]
if len(outputs.function_references) == 0:
return
if not self._block and self._is_fused_bn_block(f, inputs):
self._block = True
if self._block and f.info.type_name == 'BatchNormalization':
self._bn_args = f.info.args
self._name = self.get_parameter_scope(inputs[0])
return inputs[0]
if self._block and f.info.type_name == 'Add2':
self._add2_input1 = inputs[1]
return inputs[0]
if self._block and f.info.type_name in self._fct_set:
f_non_linear = self._fct_set[f.info.type_name]
h = PF.fused_batch_normalization(
inputs[0], self._add2_input1,
nonlinearity=f_non_linear, **self._bn_args,
name='fused{}-{}'.format(self._name, self._cnt))
self._cnt += 1
self._block = False
return h
def _is_fused_bn_block(self, f, inputs):
outputs = f.outputs[0]
next_func = outputs.function_references[0]
if len(next_func.outputs[0].function_references) == 0:
return False
nnext_func = next_func.outputs[0].function_references[0]
if f.info.type_name == 'BatchNormalization' \
and next_func.info.type_name == 'Add2' \
and nnext_func.info.type_name in self._fct_set:
return True
return False
def __finish__(self):
self._name = ''
self._block = False
self._bn_args = None
self._add2_input1 = None
self._cnt = 1
| true | true |
1c36d7ce1132a3c5354a436cdb94877d31eb74c2 | 685 | py | Python | urlman/services/hashing.py | 4lexbit/url-manager-backend | 561ccaf9727872308d66cccb5838e4a997e2f986 | [
"MIT"
] | null | null | null | urlman/services/hashing.py | 4lexbit/url-manager-backend | 561ccaf9727872308d66cccb5838e4a997e2f986 | [
"MIT"
] | null | null | null | urlman/services/hashing.py | 4lexbit/url-manager-backend | 561ccaf9727872308d66cccb5838e4a997e2f986 | [
"MIT"
] | null | null | null | from passlib.hash import sha256_crypt
from urlman.settings import settings
def hash_password(password: str) -> str:
"""
Hashing password.
@param password:
@return: hashed password
"""
salted_password = password + settings.hash_salt
return sha256_crypt.hash(salted_password)
def verify_password(db_password: str, verifiable_password: str) -> bool:
"""
Verifying entered password.
@param db_password: user password hash
@param verifiable_password: comparison password
@return: password match
"""
verifiable_password = verifiable_password + settings.hash_salt
return sha256_crypt.verify(verifiable_password, db_password)
| 25.37037 | 72 | 0.735766 | from passlib.hash import sha256_crypt
from urlman.settings import settings
def hash_password(password: str) -> str:
salted_password = password + settings.hash_salt
return sha256_crypt.hash(salted_password)
def verify_password(db_password: str, verifiable_password: str) -> bool:
verifiable_password = verifiable_password + settings.hash_salt
return sha256_crypt.verify(verifiable_password, db_password)
| true | true |
1c36d8540e4cae52584c26b86abad49dce3ec2d2 | 298 | py | Python | python/dcp1.2.py | IamGiel/host-site | 2d68c8c97efd34e73500e6b90165a0b722707ccf | [
"MIT"
] | null | null | null | python/dcp1.2.py | IamGiel/host-site | 2d68c8c97efd34e73500e6b90165a0b722707ccf | [
"MIT"
] | null | null | null | python/dcp1.2.py | IamGiel/host-site | 2d68c8c97efd34e73500e6b90165a0b722707ccf | [
"MIT"
] | null | null | null | def window(array):
left, right = None, None
s = sorted(array, reverse=True)
print(s)
for i in range(len(array)):
if array[i] != s[i] and left is None:
left = i
elif array[i] != s[i]:
right = i
return left, right
print(window([1,7,3,4])) | 22.923077 | 45 | 0.520134 | def window(array):
left, right = None, None
s = sorted(array, reverse=True)
print(s)
for i in range(len(array)):
if array[i] != s[i] and left is None:
left = i
elif array[i] != s[i]:
right = i
return left, right
print(window([1,7,3,4])) | true | true |
1c36d92c55a11461a74a19668ed3646b3aa069eb | 4,533 | py | Python | tests/manage/monitoring/prometheusmetrics/test_monitoring_negative.py | tiffanyn108/ocs-ci | 30350e0958d14100edeadbbc5f3fe557954a76b8 | [
"MIT"
] | null | null | null | tests/manage/monitoring/prometheusmetrics/test_monitoring_negative.py | tiffanyn108/ocs-ci | 30350e0958d14100edeadbbc5f3fe557954a76b8 | [
"MIT"
] | null | null | null | tests/manage/monitoring/prometheusmetrics/test_monitoring_negative.py | tiffanyn108/ocs-ci | 30350e0958d14100edeadbbc5f3fe557954a76b8 | [
"MIT"
] | null | null | null | # -*- coding: utf8 -*-
"""
Test cases here performs Prometheus queries using negative workloads.
"""
import logging
import pytest
from ocs_ci.framework.testlib import tier3
from ocs_ci.utility.prometheus import PrometheusAPI
logger = logging.getLogger(__name__)
@tier3
@pytest.mark.polarion_id("OCS-1306")
def test_monitoring_shows_mon_down(measure_stop_ceph_mon):
"""
Make sure simple problems with MON daemons are reported via OCP Prometheus.
"""
prometheus = PrometheusAPI()
# time (in seconds) for monitoring to notice the change
expected_delay = 60
affected_mons = measure_stop_ceph_mon['result']
# we asked to stop just a single mon ... make this assumption explicit
assert len(affected_mons) == 1
affected_mon = affected_mons[0]
# translate this into ceph daemon name
ceph_daemon = "mon.{}".format(affected_mon[len('rook-ceph-mon-'):])
logger.info(
f"affected mon was {affected_mon}, aka {ceph_daemon} ceph daemon")
logger.info("let's check that ceph health was affected")
health_result = prometheus.query_range(
query='ceph_health_status',
start=measure_stop_ceph_mon['start'],
end=measure_stop_ceph_mon['stop'],
step=15)
health_validation = prometheus.check_query_range_result(
result=health_result,
good_values=[1],
bad_values=[0],
exp_metric_num=1,
exp_delay=expected_delay)
health_msg = "health status should be affected by missing mon"
assert health_validation, health_msg
logger.info("let's check that mon quorum status value was affected")
mon_result = prometheus.query_range(
query='ceph_mon_quorum_status{ceph_daemon="%s"}' % ceph_daemon,
start=measure_stop_ceph_mon['start'],
end=measure_stop_ceph_mon['stop'],
step=15)
mon_validation = prometheus.check_query_range_result(
result=mon_result,
good_values=[0],
bad_values=[1],
exp_metric_num=1,
exp_delay=expected_delay)
mon_msg = "ceph_osd_up value should be affected by missing osd"
assert mon_validation, mon_msg
@tier3
@pytest.mark.polarion_id("OCS-1307")
def test_monitoring_shows_osd_down(measure_stop_ceph_osd):
"""
Make sure simple problems with OSD daemons are reported via OCP Prometheus.
"""
prometheus = PrometheusAPI()
# time (in seconds) for monitoring to notice the change
expected_delay = 60
affected_osd = measure_stop_ceph_osd['result']
# translate this into ceph daemon name
ceph_daemon = "osd.{}".format(int(affected_osd[len('rook-ceph-osd-'):]))
logger.info(
f"affected osd was {affected_osd}, aka {ceph_daemon} ceph daemon")
logger.info("let's check that ceph health was affected")
health_result = prometheus.query_range(
query='ceph_health_status',
start=measure_stop_ceph_osd['start'],
end=measure_stop_ceph_osd['stop'],
step=15)
health_validation = prometheus.check_query_range_result(
result=health_result,
good_values=[1],
bad_values=[0],
exp_metric_num=1,
exp_delay=expected_delay)
health_msg = "health status should be affected by missing osd"
assert health_validation, health_msg
logger.info("let's check that osd up value was affected")
osd_up_result = prometheus.query_range(
query='ceph_osd_up{ceph_daemon="%s"}' % ceph_daemon,
start=measure_stop_ceph_osd['start'],
end=measure_stop_ceph_osd['stop'],
step=15)
osd_up_validation = prometheus.check_query_range_result(
result=osd_up_result,
good_values=[0],
bad_values=[1],
exp_metric_num=1,
exp_delay=expected_delay)
osd_up_msg = "ceph_osd_up value should be affected by missing osd"
assert osd_up_validation, osd_up_msg
logger.info("let's check that osd in value was not affected")
# osd in value is not affected because we just stopped the osd, we
# haven't removed it from the luster
osd_in_result = prometheus.query_range(
query='ceph_osd_in{ceph_daemon="%s"}' % ceph_daemon,
start=measure_stop_ceph_osd['start'],
end=measure_stop_ceph_osd['stop'],
step=15)
osd_in_validation = prometheus.check_query_range_result(
result=osd_in_result,
good_values=[1],
bad_values=[0],
exp_metric_num=1)
osd_in_msg = "ceph_osd_in value should not be affected by missing osd"
assert osd_in_validation, osd_in_msg
| 35.414063 | 79 | 0.696448 |
import logging
import pytest
from ocs_ci.framework.testlib import tier3
from ocs_ci.utility.prometheus import PrometheusAPI
logger = logging.getLogger(__name__)
@tier3
@pytest.mark.polarion_id("OCS-1306")
def test_monitoring_shows_mon_down(measure_stop_ceph_mon):
prometheus = PrometheusAPI()
expected_delay = 60
affected_mons = measure_stop_ceph_mon['result']
assert len(affected_mons) == 1
affected_mon = affected_mons[0]
ceph_daemon = "mon.{}".format(affected_mon[len('rook-ceph-mon-'):])
logger.info(
f"affected mon was {affected_mon}, aka {ceph_daemon} ceph daemon")
logger.info("let's check that ceph health was affected")
health_result = prometheus.query_range(
query='ceph_health_status',
start=measure_stop_ceph_mon['start'],
end=measure_stop_ceph_mon['stop'],
step=15)
health_validation = prometheus.check_query_range_result(
result=health_result,
good_values=[1],
bad_values=[0],
exp_metric_num=1,
exp_delay=expected_delay)
health_msg = "health status should be affected by missing mon"
assert health_validation, health_msg
logger.info("let's check that mon quorum status value was affected")
mon_result = prometheus.query_range(
query='ceph_mon_quorum_status{ceph_daemon="%s"}' % ceph_daemon,
start=measure_stop_ceph_mon['start'],
end=measure_stop_ceph_mon['stop'],
step=15)
mon_validation = prometheus.check_query_range_result(
result=mon_result,
good_values=[0],
bad_values=[1],
exp_metric_num=1,
exp_delay=expected_delay)
mon_msg = "ceph_osd_up value should be affected by missing osd"
assert mon_validation, mon_msg
@tier3
@pytest.mark.polarion_id("OCS-1307")
def test_monitoring_shows_osd_down(measure_stop_ceph_osd):
prometheus = PrometheusAPI()
expected_delay = 60
affected_osd = measure_stop_ceph_osd['result']
ceph_daemon = "osd.{}".format(int(affected_osd[len('rook-ceph-osd-'):]))
logger.info(
f"affected osd was {affected_osd}, aka {ceph_daemon} ceph daemon")
logger.info("let's check that ceph health was affected")
health_result = prometheus.query_range(
query='ceph_health_status',
start=measure_stop_ceph_osd['start'],
end=measure_stop_ceph_osd['stop'],
step=15)
health_validation = prometheus.check_query_range_result(
result=health_result,
good_values=[1],
bad_values=[0],
exp_metric_num=1,
exp_delay=expected_delay)
health_msg = "health status should be affected by missing osd"
assert health_validation, health_msg
logger.info("let's check that osd up value was affected")
osd_up_result = prometheus.query_range(
query='ceph_osd_up{ceph_daemon="%s"}' % ceph_daemon,
start=measure_stop_ceph_osd['start'],
end=measure_stop_ceph_osd['stop'],
step=15)
osd_up_validation = prometheus.check_query_range_result(
result=osd_up_result,
good_values=[0],
bad_values=[1],
exp_metric_num=1,
exp_delay=expected_delay)
osd_up_msg = "ceph_osd_up value should be affected by missing osd"
assert osd_up_validation, osd_up_msg
logger.info("let's check that osd in value was not affected")
# osd in value is not affected because we just stopped the osd, we
# haven't removed it from the luster
osd_in_result = prometheus.query_range(
query='ceph_osd_in{ceph_daemon="%s"}' % ceph_daemon,
start=measure_stop_ceph_osd['start'],
end=measure_stop_ceph_osd['stop'],
step=15)
osd_in_validation = prometheus.check_query_range_result(
result=osd_in_result,
good_values=[1],
bad_values=[0],
exp_metric_num=1)
osd_in_msg = "ceph_osd_in value should not be affected by missing osd"
assert osd_in_validation, osd_in_msg
| true | true |
1c36d9d7d7878643977a7e6e24fdb4668d79286c | 1,229 | py | Python | tests/programs/unify_args/path_ask.py | astraldawn/pylps | e9964a24bb38657b180d441223b4cdb9e1dadc8a | [
"MIT"
] | 1 | 2018-05-19T18:28:12.000Z | 2018-05-19T18:28:12.000Z | tests/programs/unify_args/path_ask.py | astraldawn/pylps | e9964a24bb38657b180d441223b4cdb9e1dadc8a | [
"MIT"
] | 12 | 2018-04-26T00:58:11.000Z | 2018-05-13T22:03:39.000Z | tests/programs/unify_args/path_ask.py | astraldawn/pylps | e9964a24bb38657b180d441223b4cdb9e1dadc8a | [
"MIT"
] | null | null | null | from pylps.core import *
initialise(max_time=3)
create_actions('say(_, _)', 'ask(_, _)')
create_events('respond(_, _)', 'path(_, _)', 'ask2(_, _)')
create_facts('arc(_, _)')
create_variables('X', 'Y', 'Z')
arc('a', 'b')
arc('b', 'c')
arc('a', 'd')
arc('d', 'e')
arc('a', 'c')
observe(ask('a', 'c').frm(1, 2))
observe(ask2('a', 'e').frm(1, 2))
reactive_rule(ask(X, Y).frm(T1, T2)).then(
respond(X, Y).frm(T2, T3),
)
reactive_rule(ask2(X, Y).frm(T1, T2)).then(
respond(X, Y).frm(T2, T3),
)
goal(respond(X, Y).frm(T1, T2)).requires(
path(X, Y).frm(T1, T2),
say(X, Y).frm(T1, T2)
)
goal(path(X, Y).frm(T, T)).requires(
arc(X, Y),
)
goal(path(X, Y).frm(T, T)).requires(
arc(X, Z),
path(Z, Y).frm(T, T),
)
execute(debug=False)
show_kb_log()
'''
maxTime(5).
actions say(_,_), ask2(_, _).
events ask(_,_).
observe ask(a, c) from 1 to 2.
observe ask2(a, e) from 1 to 2.
arc(a,b).
arc(b,c).
arc(a,d).
arc(d,e).
arc(a,c).
if ask(X,Y) from T1 to T2
then respond(X,Y) from T2 to T3.
if ask2(X,Y) from T1 to T2
then respond(X,Y) from T2 to T3.
respond(X,Y) from T1 to T2
if path(X,Y), say(X,Y) from T1 to T2.
path(X,Y) :- arc(X,Y).
path(X,Y):- arc(X,Z), path(Z,Y).
'''
| 17.069444 | 58 | 0.557364 | from pylps.core import *
initialise(max_time=3)
create_actions('say(_, _)', 'ask(_, _)')
create_events('respond(_, _)', 'path(_, _)', 'ask2(_, _)')
create_facts('arc(_, _)')
create_variables('X', 'Y', 'Z')
arc('a', 'b')
arc('b', 'c')
arc('a', 'd')
arc('d', 'e')
arc('a', 'c')
observe(ask('a', 'c').frm(1, 2))
observe(ask2('a', 'e').frm(1, 2))
reactive_rule(ask(X, Y).frm(T1, T2)).then(
respond(X, Y).frm(T2, T3),
)
reactive_rule(ask2(X, Y).frm(T1, T2)).then(
respond(X, Y).frm(T2, T3),
)
goal(respond(X, Y).frm(T1, T2)).requires(
path(X, Y).frm(T1, T2),
say(X, Y).frm(T1, T2)
)
goal(path(X, Y).frm(T, T)).requires(
arc(X, Y),
)
goal(path(X, Y).frm(T, T)).requires(
arc(X, Z),
path(Z, Y).frm(T, T),
)
execute(debug=False)
show_kb_log()
| true | true |
1c36daad5a7380ac317d648ad98a16e882280cae | 2,052 | py | Python | task.py | vishwasourab/quadcopter_project | 67b65e41a151fc2c24dd3905f33b73209157b52e | [
"MIT"
] | null | null | null | task.py | vishwasourab/quadcopter_project | 67b65e41a151fc2c24dd3905f33b73209157b52e | [
"MIT"
] | null | null | null | task.py | vishwasourab/quadcopter_project | 67b65e41a151fc2c24dd3905f33b73209157b52e | [
"MIT"
] | null | null | null | import numpy as np
from physics_sim import PhysicsSim
class Task():
"""Task (environment) that defines the goal and provides feedback to the agent."""
def __init__(self, init_pose=None, init_velocities=None,
init_angle_velocities=None, runtime=5., target_pos=None):
"""Initialize a Task object.
Params
======
init_pose: initial position of the quadcopter in (x,y,z) dimensions and the Euler angles
init_velocities: initial velocity of the quadcopter in (x,y,z) dimensions
init_angle_velocities: initial radians/second for each of the three Euler angles
runtime: time limit for each episode
target_pos: target/goal (x,y,z) position for the agent
"""
# Simulation
self.sim = PhysicsSim(init_pose, init_velocities, init_angle_velocities, runtime)
self.action_repeat = 3
self.state_size = self.action_repeat * 6
self.action_low = 0
self.action_high = 900
self.action_size = 4
# Goal
self.target_pos = target_pos if target_pos is not None else np.array([0., 0., 10.])
def get_reward(self):
"""Uses current pose of sim to return reward."""
reward = 1.-.17*(abs(self.sim.pose[:3] - self.target_pos)).sum()
if reward>1:
reward = 1
if reward<-1:
reward = -1
return reward
def step(self, rotor_speeds):
"""Uses action to obtain next state, reward, done."""
reward = 0
pose_all = []
for _ in range(self.action_repeat):
done = self.sim.next_timestep(rotor_speeds) # update the sim pose and velocities
reward += self.get_reward()
pose_all.append(self.sim.pose)
next_state = np.concatenate(pose_all)
return next_state, reward, done
def reset(self):
"""Reset the sim to start a new episode."""
self.sim.reset()
state = np.concatenate([self.sim.pose] * self.action_repeat)
return state | 38.716981 | 100 | 0.617934 | import numpy as np
from physics_sim import PhysicsSim
class Task():
def __init__(self, init_pose=None, init_velocities=None,
init_angle_velocities=None, runtime=5., target_pos=None):
self.sim = PhysicsSim(init_pose, init_velocities, init_angle_velocities, runtime)
self.action_repeat = 3
self.state_size = self.action_repeat * 6
self.action_low = 0
self.action_high = 900
self.action_size = 4
self.target_pos = target_pos if target_pos is not None else np.array([0., 0., 10.])
def get_reward(self):
reward = 1.-.17*(abs(self.sim.pose[:3] - self.target_pos)).sum()
if reward>1:
reward = 1
if reward<-1:
reward = -1
return reward
def step(self, rotor_speeds):
reward = 0
pose_all = []
for _ in range(self.action_repeat):
done = self.sim.next_timestep(rotor_speeds)
reward += self.get_reward()
pose_all.append(self.sim.pose)
next_state = np.concatenate(pose_all)
return next_state, reward, done
def reset(self):
self.sim.reset()
state = np.concatenate([self.sim.pose] * self.action_repeat)
return state | true | true |
1c36db81d413c6ee13f4c5ced592449b92f47b53 | 6,894 | py | Python | miaomiao.py | pyk1998/hpv4 | fc6893d0c015a997c462689e79671a0af11acebe | [
"Apache-2.0"
] | null | null | null | miaomiao.py | pyk1998/hpv4 | fc6893d0c015a997c462689e79671a0af11acebe | [
"Apache-2.0"
] | null | null | null | miaomiao.py | pyk1998/hpv4 | fc6893d0c015a997c462689e79671a0af11acebe | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import datetime
import requests
import copy
import logging
from hashlib import md5
import json
import os
from functools import wraps
# disable ssl warnings
requests.packages.urllib3.disable_warnings()
# url
URLS = {
# 获取代理IP
"IP_PROXY": "https://ip.jiangxianli.com/api/proxy_ips",
# 服务器当前时间戳
"SERVER_TIME": "https://miaomiao.scmttec.com/seckill/seckill/now2.do",
# 疫苗列表
"VACCINE_LIST": "https://miaomiao.scmttec.com/seckill/seckill/list.do",
# 校验库存
"CHECK_STOCK": "https://miaomiao.scmttec.com/seckill/seckill/checkstock2.do",
# 接种人信息
"USER_INFO": "https://miaomiao.scmttec.com/seckill/linkman/findByUserId.do",
# 秒杀疫苗
"SEC_KILL": "https://miaomiao.scmttec.com/seckill/seckill/subscribe.do"
}
# common headers
REQ_HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat",
"Referer": "https://servicewechat.com/wxff8cad2e9bf18719/10/page-frame.html",
"Accept": "application/json, text/plain, */*",
"Host": "miaomiao.scmttec.com"
}
# ecc_hs盐
ECC_HS_SALT = 'ux$ad70*b'
def cache_json(file_name):
"""
测试发现在开始秒杀前服务器对非核心秒杀接口做了降级处理(查询列表等接口直接返回502).
考虑提前缓存疫苗列表 秒杀开始后跳过查询列表等操作 直接调用秒杀接口
JSON文件缓存Decorator
:param file_name:
:return:
"""
def decorator(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
fn, suffix = os.path.splitext(file_name)
_file_name = f'{fn}_{self._region_code}{suffix}'
# 已缓存从缓存读取
if os.path.exists(_file_name) and os.path.getsize(_file_name):
with open(_file_name, 'r', encoding='utf-8') as f:
return json.load(f)
# 未缓存
data = func(self, *args, **kwargs)
with open(_file_name, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False)
return data
return wrapper
return decorator
class MiaoMiao():
def __init__(self, tk, cookie, region_code=5101):
self._region_code = region_code
self._headers = copy.deepcopy(REQ_HEADERS)
self._headers['tk'] = tk
self._headers['cookie'] = cookie
@staticmethod
def _get(url, params=None, error_exit=True, **kwargs):
"""
GET请求. 请求返回错误码(4XX,5XX)时退出
:param url: 请求路径
:param params: 请求参数
:param error_exit:返回4XX 5XX错误时 是否退出
:param kwargs: 附加信息
:return: 结果JSON
"""
try:
response = requests.get(url, params, **kwargs)
response.raise_for_status()
except Exception as err:
error_response = f'URL:{url} ERROR:{err}'
print(error_response)
logging.error(error_response)
if error_exit:
exit(1)
else:
res_json = response.json()
_suc_msg = f'{url}\n{"-" * 5 + "Request" + "-" * 5}\n{params}\n{"-" * 5 + "Response" + "-" * 5}\n{res_json}\nuseTime:{response.elapsed.total_seconds()}S\n'
'''
日志默认级别[WARNING] 考虑最大限度不影响秒杀效果此处以[INFO]记录正常响应的请求(正常响应不代表秒杀成功)\
即trace.log均不会记录正常响应日志\
若希望记录响应日志 使用--log指定日志级别
'''
print(_suc_msg)
logging.info(_suc_msg)
return res_json
@staticmethod
def get_server_time():
"""
获取服务器当前时间戳
秒杀开始时间由服务器控制
:return: 服务器时间戳
"""
res_json = MiaoMiao._get(URLS['SERVER_TIME'], verify=False)
return res_json['data']
@staticmethod
def get_proxy_ip(page=1):
"""
获取最新可用的代理IP
IP代理来源
1.使用收费的代理商提供
2.自建IP代理池
- 爬取免费IP代理
- 验证IP可用
- 持久化
- 定时更新可用IP
这里直接使用第三方提供的API(避免自建轮子、搭建环境。测试):https://github.com/jiangxianli/ProxyIpLib
:param page:
:return:
"""
return MiaoMiao._get(URLS['IP_PROXY'], params={'page': page, 'country': '中国', 'order_by': 'validated_at'},
error_exit=False,
verify=False)
def _get_vaccine_list(self):
"""
获取待秒杀疫苗列表
:return:疫苗列表
"""
# 分页查询可秒杀疫苗 regionCode:5101[四川成都区域编码]
req_param_list = {'offset': '0', 'limit': '10', 'regionCode': self._region_code}
res_vaccine = MiaoMiao._get(URLS['VACCINE_LIST'], params=req_param_list, headers=self._headers, verify=False)
if '0000' != res_vaccine['code']:
print(res_vaccine['msg'])
exit(1)
datas = res_vaccine['data']
if not datas:
print(f'---区域:{self._region_code}暂无可秒杀疫苗---')
_cache_file = f'cache/vaccines_{self._region_code}.json'
if os.path.exists(_cache_file):
os.remove(_cache_file)
exit(0)
return datas
@cache_json('cache/vaccines.json')
def get_vaccine_list_cache(self):
return self._get_vaccine_list()
def _get_user(self):
"""
获取用户信息(从微信小程序入口 使用微信tk和cookie查询指定用户信息)
:return: 用户信息
"""
res_json = MiaoMiao._get(URLS['USER_INFO'], headers=self._headers, verify=False)
if '0000' == res_json['code']:
return res_json['data']
print(f'{self._region_code}获取用户信息失败:{res_json}')
exit(1)
@cache_json('cache/user.json')
def get_user_cache(self):
return self._get_user()
def subscribe(self, req_param, proxies=None):
"""
秒杀请求
:param req_param: 请求参数
:param proxies: 代理配置
:return:
"""
# error_exit=False 忽略Server端使用5XX防爬策略
return MiaoMiao._get(URLS['SEC_KILL'], params=req_param, error_exit=False, headers=self._headers,
proxies=proxies, verify=False)
@staticmethod
def _ecc_hs_header(seckill_id, linkman_id):
"""
构造ecc-hs header
:param seckill_id: 疫苗ID
:param linkman_id: 接种人ID
:return: ecc-hs header
salt = 'ux$ad70*b';
md5Str = utilMd5.hexMD5(utilMd5.hexMD5(ms_id + defaultMember.id + st) + salt)
"""
_ori_md5 = md5(
f'{seckill_id}{linkman_id}{int(datetime.datetime.now().timestamp() * 1000)}'.encode('utf-8')).hexdigest()
_md5_salt = md5(f'{_ori_md5}{ECC_HS_SALT}'.encode('utf-8'))
return _md5_salt.hexdigest()
def init_data_json(self):
"""
初始化疫苗数据和接种人数据
缓存本地
"""
data_dict = {'user': self._get_user(), 'vaccines': self._get_vaccine_list()}
for k, v in data_dict.items():
with open(f'cache/{k}_{self._region_code}.json', 'w', encoding='utf-8') as f:
json.dump(v, f, ensure_ascii=False, indent=4)
| 31.623853 | 205 | 0.583261 |
import datetime
import requests
import copy
import logging
from hashlib import md5
import json
import os
from functools import wraps
requests.packages.urllib3.disable_warnings()
URLS = {
"IP_PROXY": "https://ip.jiangxianli.com/api/proxy_ips",
"SERVER_TIME": "https://miaomiao.scmttec.com/seckill/seckill/now2.do",
"VACCINE_LIST": "https://miaomiao.scmttec.com/seckill/seckill/list.do",
"CHECK_STOCK": "https://miaomiao.scmttec.com/seckill/seckill/checkstock2.do",
"USER_INFO": "https://miaomiao.scmttec.com/seckill/linkman/findByUserId.do",
"SEC_KILL": "https://miaomiao.scmttec.com/seckill/seckill/subscribe.do"
}
REQ_HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat",
"Referer": "https://servicewechat.com/wxff8cad2e9bf18719/10/page-frame.html",
"Accept": "application/json, text/plain, */*",
"Host": "miaomiao.scmttec.com"
}
ECC_HS_SALT = 'ux$ad70*b'
def cache_json(file_name):
def decorator(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
fn, suffix = os.path.splitext(file_name)
_file_name = f'{fn}_{self._region_code}{suffix}'
if os.path.exists(_file_name) and os.path.getsize(_file_name):
with open(_file_name, 'r', encoding='utf-8') as f:
return json.load(f)
data = func(self, *args, **kwargs)
with open(_file_name, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False)
return data
return wrapper
return decorator
class MiaoMiao():
def __init__(self, tk, cookie, region_code=5101):
self._region_code = region_code
self._headers = copy.deepcopy(REQ_HEADERS)
self._headers['tk'] = tk
self._headers['cookie'] = cookie
@staticmethod
def _get(url, params=None, error_exit=True, **kwargs):
try:
response = requests.get(url, params, **kwargs)
response.raise_for_status()
except Exception as err:
error_response = f'URL:{url} ERROR:{err}'
print(error_response)
logging.error(error_response)
if error_exit:
exit(1)
else:
res_json = response.json()
_suc_msg = f'{url}\n{"-" * 5 + "Request" + "-" * 5}\n{params}\n{"-" * 5 + "Response" + "-" * 5}\n{res_json}\nuseTime:{response.elapsed.total_seconds()}S\n'
'''
日志默认级别[WARNING] 考虑最大限度不影响秒杀效果此处以[INFO]记录正常响应的请求(正常响应不代表秒杀成功)\
即trace.log均不会记录正常响应日志\
若希望记录响应日志 使用--log指定日志级别
'''
print(_suc_msg)
logging.info(_suc_msg)
return res_json
@staticmethod
def get_server_time():
res_json = MiaoMiao._get(URLS['SERVER_TIME'], verify=False)
return res_json['data']
@staticmethod
def get_proxy_ip(page=1):
return MiaoMiao._get(URLS['IP_PROXY'], params={'page': page, 'country': '中国', 'order_by': 'validated_at'},
error_exit=False,
verify=False)
def _get_vaccine_list(self):
req_param_list = {'offset': '0', 'limit': '10', 'regionCode': self._region_code}
res_vaccine = MiaoMiao._get(URLS['VACCINE_LIST'], params=req_param_list, headers=self._headers, verify=False)
if '0000' != res_vaccine['code']:
print(res_vaccine['msg'])
exit(1)
datas = res_vaccine['data']
if not datas:
print(f'---区域:{self._region_code}暂无可秒杀疫苗---')
_cache_file = f'cache/vaccines_{self._region_code}.json'
if os.path.exists(_cache_file):
os.remove(_cache_file)
exit(0)
return datas
@cache_json('cache/vaccines.json')
def get_vaccine_list_cache(self):
return self._get_vaccine_list()
def _get_user(self):
res_json = MiaoMiao._get(URLS['USER_INFO'], headers=self._headers, verify=False)
if '0000' == res_json['code']:
return res_json['data']
print(f'{self._region_code}获取用户信息失败:{res_json}')
exit(1)
@cache_json('cache/user.json')
def get_user_cache(self):
return self._get_user()
def subscribe(self, req_param, proxies=None):
return MiaoMiao._get(URLS['SEC_KILL'], params=req_param, error_exit=False, headers=self._headers,
proxies=proxies, verify=False)
@staticmethod
def _ecc_hs_header(seckill_id, linkman_id):
_ori_md5 = md5(
f'{seckill_id}{linkman_id}{int(datetime.datetime.now().timestamp() * 1000)}'.encode('utf-8')).hexdigest()
_md5_salt = md5(f'{_ori_md5}{ECC_HS_SALT}'.encode('utf-8'))
return _md5_salt.hexdigest()
def init_data_json(self):
data_dict = {'user': self._get_user(), 'vaccines': self._get_vaccine_list()}
for k, v in data_dict.items():
with open(f'cache/{k}_{self._region_code}.json', 'w', encoding='utf-8') as f:
json.dump(v, f, ensure_ascii=False, indent=4)
| true | true |
1c36dbb40994007686cdf7c8fddfc7ab5edf3089 | 365 | py | Python | code/DataProcessingUtils/EventFrameGeneration/imfill.py | mywisdomfly/EVDodgeNet | 7d53a9c8e0e5883ac8ad2147da5981db5d9ba7a7 | [
"BSD-3-Clause"
] | 62 | 2020-05-22T03:00:11.000Z | 2022-03-16T02:26:35.000Z | code/DataProcessingUtils/EventFrameGeneration/imfill.py | mywisdomfly/EVDodgeNet | 7d53a9c8e0e5883ac8ad2147da5981db5d9ba7a7 | [
"BSD-3-Clause"
] | 8 | 2020-04-02T10:47:30.000Z | 2021-06-18T17:35:40.000Z | code/DataProcessingUtils/EventFrameGeneration/imfill.py | mywisdomfly/EVDodgeNet | 7d53a9c8e0e5883ac8ad2147da5981db5d9ba7a7 | [
"BSD-3-Clause"
] | 24 | 2020-04-14T14:49:56.000Z | 2022-03-19T09:20:28.000Z | import cv2;
import numpy as np;
# Read image
img = cv2.imread("label_00000054.png", cv2.IMREAD_GRAYSCALE);
# Threshold.
# Set values equal to or above 220 to 0.
# Set values below 220 to 255.
kernel = np.ones((5,5),np.uint8)
dilate = cv2.dilate(img,kernel,iterations = 2)
# Display images.
cv2.imshow("Foreground", dilate)
cv2.waitKey(0)
cv2.destroyAllWindows() | 21.470588 | 61 | 0.728767 | import cv2;
import numpy as np;
img = cv2.imread("label_00000054.png", cv2.IMREAD_GRAYSCALE);
kernel = np.ones((5,5),np.uint8)
dilate = cv2.dilate(img,kernel,iterations = 2)
cv2.imshow("Foreground", dilate)
cv2.waitKey(0)
cv2.destroyAllWindows() | true | true |
1c36dc089ba4b038063b8a83440aa86ba059834f | 8,871 | py | Python | egret/models/copperplate_dispatch.py | barguel/Egret | 2df021d08ca4c1722a7b16eab3f512ba0e7c6a1d | [
"BSD-3-Clause"
] | 71 | 2019-03-28T09:57:27.000Z | 2022-03-08T05:24:25.000Z | egret/models/copperplate_dispatch.py | shengrenhou/Egret | 8bcaa8697908a6c258b6361b69ffd73d6a658ccf | [
"BSD-3-Clause"
] | 139 | 2019-04-01T16:50:57.000Z | 2022-03-31T20:29:04.000Z | egret/models/copperplate_dispatch.py | shengrenhou/Egret | 8bcaa8697908a6c258b6361b69ffd73d6a658ccf | [
"BSD-3-Clause"
] | 44 | 2019-04-01T13:20:37.000Z | 2022-03-09T14:50:18.000Z | # ___________________________________________________________________________
#
# EGRET: Electrical Grid Research and Engineering Tools
# Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC
# (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
# Government retains certain rights in this software.
# This software is distributed under the Revised BSD License.
# ___________________________________________________________________________
"""
This module provides functions that create the modules for typical copperplate dispatch formulations.
#TODO: document this with examples
"""
import pyomo.environ as pe
import egret.model_library.transmission.tx_utils as tx_utils
import egret.model_library.transmission.tx_calc as tx_calc
import egret.model_library.transmission.bus as libbus
import egret.model_library.transmission.branch as libbranch
import egret.model_library.transmission.gen as libgen
from egret.model_library.defn import ApproximationType
from egret.data.data_utils import map_items, zip_items
from math import pi
def _include_system_feasibility_slack(model, bus_p_loads, gen_attrs, p_marginal_slack_penalty):
import egret.model_library.decl as decl
load = sum(bus_p_loads.values())
over_gen_bounds = (0, tx_utils.over_gen_limit(load, gen_attrs['names'], gen_attrs['p_max']))
decl.declare_var('p_over_generation', model=model, index_set=None,
initialize=0., bounds=over_gen_bounds
)
load_shed_bounds = (0, tx_utils.load_shed_limit(load, gen_attrs['names'], gen_attrs['p_min']))
decl.declare_var('p_load_shed', model=model, index_set=None,
initialize=0., bounds=load_shed_bounds
)
p_rhs_kwargs = {'include_feasibility_load_shed':'p_load_shed', 'include_feasibility_over_generation':'p_over_generation'}
penalty_expr = p_marginal_slack_penalty * (model.p_load_shed + model.p_over_generation)
return p_rhs_kwargs, penalty_expr
def _validate_and_extract_slack_penalty(model_data):
assert('load_mismatch_cost' in model_data.data['system'])
return model_data.data['system']['load_mismatch_cost']
def create_copperplate_dispatch_approx_model(model_data, include_feasibility_slack=False, pw_cost_model='delta'):
md = model_data.clone_in_service()
tx_utils.scale_ModelData_to_pu(md, inplace = True)
gens = dict(md.elements(element_type='generator'))
buses = dict(md.elements(element_type='bus'))
branches = dict(md.elements(element_type='branch'))
loads = dict(md.elements(element_type='load'))
shunts = dict(md.elements(element_type='shunt'))
gen_attrs = md.attributes(element_type='generator')
bus_attrs = md.attributes(element_type='bus')
inlet_branches_by_bus, outlet_branches_by_bus = \
tx_utils.inlet_outlet_branches_by_bus(branches, buses)
gens_by_bus = tx_utils.gens_by_bus(buses, gens)
model = pe.ConcreteModel()
### declare (and fix) the loads at the buses
bus_p_loads, _ = tx_utils.dict_of_bus_loads(buses, loads)
libbus.declare_var_pl(model, bus_attrs['names'], initialize=bus_p_loads)
model.pl.fix()
### declare the fixed shunts at the buses
_, bus_gs_fixed_shunts = tx_utils.dict_of_bus_fixed_shunts(buses, shunts)
### declare the generator real power
pg_init = {k: (gen_attrs['p_min'][k] + gen_attrs['p_max'][k]) / 2.0 for k in gen_attrs['pg']}
libgen.declare_var_pg(model, gen_attrs['names'], initialize=pg_init,
bounds=zip_items(gen_attrs['p_min'], gen_attrs['p_max'])
)
### include the feasibility slack for the system balance
p_rhs_kwargs = {}
if include_feasibility_slack:
p_marginal_slack_penalty = _validate_and_extract_slack_penalty(model_data)
p_rhs_kwargs, penalty_expr = _include_system_feasibility_slack(model, bus_p_loads, gen_attrs, p_marginal_slack_penalty)
### declare the p balance
libbus.declare_eq_p_balance_ed(model=model,
index_set=bus_attrs['names'],
bus_p_loads=bus_p_loads,
gens_by_bus=gens_by_bus,
bus_gs_fixed_shunts=bus_gs_fixed_shunts,
**p_rhs_kwargs
)
### declare the generator cost objective
p_costs = gen_attrs['p_cost']
pw_pg_cost_gens = list(libgen.pw_gen_generator(gen_attrs['names'], costs=p_costs))
if len(pw_pg_cost_gens) > 0:
if pw_cost_model == 'delta':
libgen.declare_var_delta_pg(model=model, index_set=pw_pg_cost_gens, p_costs=p_costs)
libgen.declare_pg_delta_pg_con(model=model, index_set=pw_pg_cost_gens, p_costs=p_costs)
else:
libgen.declare_var_pg_cost(model=model, index_set=pw_pg_cost_gens, p_costs=p_costs)
libgen.declare_piecewise_pg_cost_cons(model=model, index_set=pw_pg_cost_gens, p_costs=p_costs)
libgen.declare_expression_pg_operating_cost(model=model, index_set=gen_attrs['names'], p_costs=p_costs, pw_formulation=pw_cost_model)
obj_expr = sum(model.pg_operating_cost[gen_name] for gen_name in model.pg_operating_cost)
if include_feasibility_slack:
obj_expr += penalty_expr
model.obj = pe.Objective(expr=obj_expr)
return model, md
def solve_copperplate_dispatch(model_data,
solver,
timelimit = None,
solver_tee = True,
symbolic_solver_labels = False,
options = None,
copperplate_dispatch_model_generator = create_copperplate_dispatch_approx_model,
return_model = False,
return_results = False,
**kwargs):
'''
Create and solve a new copperplate dispatch model
Parameters
----------
model_data : egret.data.ModelData
An egret ModelData object with the appropriate data loaded.
solver : str or pyomo.opt.base.solvers.OptSolver
Either a string specifying a pyomo solver name, or an instantiated pyomo solver
timelimit : float (optional)
Time limit for dcopf run. Default of None results in no time
limit being set.
solver_tee : bool (optional)
Display solver log. Default is True.
symbolic_solver_labels : bool (optional)
Use symbolic solver labels. Useful for debugging; default is False.
options : dict (optional)
Other options to pass into the solver. Default is dict().
copperplate_dispatch_model_generator : function (optional)
Function for generating the copperplate dispatch model. Default is
egret.models.copperplate_dispatch.create_copperplate_dispatch_approx_model
return_model : bool (optional)
If True, returns the pyomo model object
return_results : bool (optional)
If True, returns the pyomo results object
kwargs : dictionary (optional)
Additional arguments for building model
'''
import pyomo.environ as pe
from pyomo.environ import value
from egret.common.solver_interface import _solve_model
from egret.model_library.transmission.tx_utils import \
scale_ModelData_to_pu, unscale_ModelData_to_pu
m, md = copperplate_dispatch_model_generator(model_data, **kwargs)
m.dual = pe.Suffix(direction=pe.Suffix.IMPORT)
m, results = _solve_model(m,solver,timelimit=timelimit,solver_tee=solver_tee,
symbolic_solver_labels=symbolic_solver_labels,solver_options=options)
md = model_data.clone_in_service()
# save results data to ModelData object
gens = dict(md.elements(element_type='generator'))
buses = dict(md.elements(element_type='bus'))
md.data['system']['total_cost'] = value(m.obj)
if hasattr(m, 'p_load_shed'):
md.data['system']['p_balance_violation'] = value(m.p_load_shed) - value(m.p_over_generation)
for g,g_dict in gens.items():
g_dict['pg'] = value(m.pg[g])
for b,b_dict in buses.items():
b_dict['pl'] = value(m.pl[b])
b_dict['lmp'] = value(m.dual[m.eq_p_balance])
unscale_ModelData_to_pu(md, inplace=True)
if return_model and return_results:
return md, m, results
elif return_model:
return md, m
elif return_results:
return md, results
return md
# if __name__ == '__main__':
# import os
# from egret.parsers.matpower_parser import create_ModelData
#
# path = os.path.dirname(__file__)
# filename = 'pglib_opf_case3_lmbd.m'
# matpower_file = os.path.join(path, '../../download/pglib-opf/', filename)
# md = create_ModelData(matpower_file)
# kwargs = {'include_feasibility_slack': 'True'}
# md = solve_copperplate_dispatch(md, "gurobi", **kwargs)
| 42.855072 | 137 | 0.702288 |
import pyomo.environ as pe
import egret.model_library.transmission.tx_utils as tx_utils
import egret.model_library.transmission.tx_calc as tx_calc
import egret.model_library.transmission.bus as libbus
import egret.model_library.transmission.branch as libbranch
import egret.model_library.transmission.gen as libgen
from egret.model_library.defn import ApproximationType
from egret.data.data_utils import map_items, zip_items
from math import pi
def _include_system_feasibility_slack(model, bus_p_loads, gen_attrs, p_marginal_slack_penalty):
import egret.model_library.decl as decl
load = sum(bus_p_loads.values())
over_gen_bounds = (0, tx_utils.over_gen_limit(load, gen_attrs['names'], gen_attrs['p_max']))
decl.declare_var('p_over_generation', model=model, index_set=None,
initialize=0., bounds=over_gen_bounds
)
load_shed_bounds = (0, tx_utils.load_shed_limit(load, gen_attrs['names'], gen_attrs['p_min']))
decl.declare_var('p_load_shed', model=model, index_set=None,
initialize=0., bounds=load_shed_bounds
)
p_rhs_kwargs = {'include_feasibility_load_shed':'p_load_shed', 'include_feasibility_over_generation':'p_over_generation'}
penalty_expr = p_marginal_slack_penalty * (model.p_load_shed + model.p_over_generation)
return p_rhs_kwargs, penalty_expr
def _validate_and_extract_slack_penalty(model_data):
assert('load_mismatch_cost' in model_data.data['system'])
return model_data.data['system']['load_mismatch_cost']
def create_copperplate_dispatch_approx_model(model_data, include_feasibility_slack=False, pw_cost_model='delta'):
md = model_data.clone_in_service()
tx_utils.scale_ModelData_to_pu(md, inplace = True)
gens = dict(md.elements(element_type='generator'))
buses = dict(md.elements(element_type='bus'))
branches = dict(md.elements(element_type='branch'))
loads = dict(md.elements(element_type='load'))
shunts = dict(md.elements(element_type='shunt'))
gen_attrs = md.attributes(element_type='generator')
bus_attrs = md.attributes(element_type='bus')
inlet_branches_by_bus, outlet_branches_by_bus = \
tx_utils.inlet_outlet_branches_by_bus(branches, buses)
gens_by_bus = tx_utils.gens_by_bus(buses, gens)
model = pe.ConcreteModel()
r_pl(model, bus_attrs['names'], initialize=bus_p_loads)
model.pl.fix()
2.0 for k in gen_attrs['pg']}
libgen.declare_var_pg(model, gen_attrs['names'], initialize=pg_init,
bounds=zip_items(gen_attrs['p_min'], gen_attrs['p_max'])
)
ract_slack_penalty(model_data)
p_rhs_kwargs, penalty_expr = _include_system_feasibility_slack(model, bus_p_loads, gen_attrs, p_marginal_slack_penalty)
,
index_set=bus_attrs['names'],
bus_p_loads=bus_p_loads,
gens_by_bus=gens_by_bus,
bus_gs_fixed_shunts=bus_gs_fixed_shunts,
**p_rhs_kwargs
)
enerator(gen_attrs['names'], costs=p_costs))
if len(pw_pg_cost_gens) > 0:
if pw_cost_model == 'delta':
libgen.declare_var_delta_pg(model=model, index_set=pw_pg_cost_gens, p_costs=p_costs)
libgen.declare_pg_delta_pg_con(model=model, index_set=pw_pg_cost_gens, p_costs=p_costs)
else:
libgen.declare_var_pg_cost(model=model, index_set=pw_pg_cost_gens, p_costs=p_costs)
libgen.declare_piecewise_pg_cost_cons(model=model, index_set=pw_pg_cost_gens, p_costs=p_costs)
libgen.declare_expression_pg_operating_cost(model=model, index_set=gen_attrs['names'], p_costs=p_costs, pw_formulation=pw_cost_model)
obj_expr = sum(model.pg_operating_cost[gen_name] for gen_name in model.pg_operating_cost)
if include_feasibility_slack:
obj_expr += penalty_expr
model.obj = pe.Objective(expr=obj_expr)
return model, md
def solve_copperplate_dispatch(model_data,
solver,
timelimit = None,
solver_tee = True,
symbolic_solver_labels = False,
options = None,
copperplate_dispatch_model_generator = create_copperplate_dispatch_approx_model,
return_model = False,
return_results = False,
**kwargs):
import pyomo.environ as pe
from pyomo.environ import value
from egret.common.solver_interface import _solve_model
from egret.model_library.transmission.tx_utils import \
scale_ModelData_to_pu, unscale_ModelData_to_pu
m, md = copperplate_dispatch_model_generator(model_data, **kwargs)
m.dual = pe.Suffix(direction=pe.Suffix.IMPORT)
m, results = _solve_model(m,solver,timelimit=timelimit,solver_tee=solver_tee,
symbolic_solver_labels=symbolic_solver_labels,solver_options=options)
md = model_data.clone_in_service()
gens = dict(md.elements(element_type='generator'))
buses = dict(md.elements(element_type='bus'))
md.data['system']['total_cost'] = value(m.obj)
if hasattr(m, 'p_load_shed'):
md.data['system']['p_balance_violation'] = value(m.p_load_shed) - value(m.p_over_generation)
for g,g_dict in gens.items():
g_dict['pg'] = value(m.pg[g])
for b,b_dict in buses.items():
b_dict['pl'] = value(m.pl[b])
b_dict['lmp'] = value(m.dual[m.eq_p_balance])
unscale_ModelData_to_pu(md, inplace=True)
if return_model and return_results:
return md, m, results
elif return_model:
return md, m
elif return_results:
return md, results
return md
| true | true |
1c36dc2259060920075378c4dceb6e079c6ff92a | 8,714 | py | Python | pycraft/mca.py | PapaMarky/pycraft | 919fe000ae7f1d2dd715d0468957d67ca61725b4 | [
"MIT"
] | null | null | null | pycraft/mca.py | PapaMarky/pycraft | 919fe000ae7f1d2dd715d0468957d67ca61725b4 | [
"MIT"
] | null | null | null | pycraft/mca.py | PapaMarky/pycraft | 919fe000ae7f1d2dd715d0468957d67ca61725b4 | [
"MIT"
] | null | null | null | """Code to read .mca region files
I modified the javascript library mca-js to create this file.
mca-js: https://github.com/thejonwithnoh/mca-js
This is largely just a python interpretation of that script.
-----------
MIT License
Copyright (c) 2019 Nicholas Westerhausen
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 gzip
import zlib
import os
from pycraft.error import PycraftException
class Mca:
"""Class used to read Minecraft region files and the chunk information contained within.
Use by creating a new object with the filepath for the region file. Then you can get_timestamp and get_data
for individual chunks in the region by specifying the chunkX or chunkY if they were to always go from 0 to 32
for each region.
region = Mca('/opt/mc/region/r.1.1.mca')
nbt = region.get_data(0,0) # gets the raw nbt data for chunk 0,0
# here you can do stuff with that nbt data. It is the same format as if you open('level.dat','r+b)
"""
SECTOR_OFFSET_SIZE = 3 # Chunk offset is a 3-byte value
SECTOR_COUNT_SIZE = 1 # Chunk size is a 1-byte value
TIMESTAMP_SIZE = 4 # Timestamp is a 4-byte value
DATA_SIZE_SIZE = 4 # First 4 bytes of the chunk data are its size
COMPRESSION_TYPE_SIZE = 1 # Compression type is a single byte
DIMENSION_SIZE_POWER = 5 # Used for bit shifting (2**5 = 32), 32 x or z values
DIMENSION_COUNT = 2 # There is only the X and Z dimension for the chunks.
SECTOR_SIZE_POWER = 12 # Used for bit shifting (2**12 = 4096), 4096 per sector of the file
SECTOR_DETAILS_SIZE = SECTOR_OFFSET_SIZE + SECTOR_COUNT_SIZE # Full size of the chunk details (4 bytes)
DATA_HEADER_SIZE = DATA_SIZE_SIZE + COMPRESSION_TYPE_SIZE # Full size of the chunk header (5 bytes)
DIMENSION_SIZE = 1 << DIMENSION_SIZE_POWER # Used for bitwise operations on the provided chunk x and z values
DIMENSION_SIZE_MASK = DIMENSION_SIZE - 1 # DIM_SIZE = 0b100000, MASK = -0b11111 and used for bitwise operations
INDEX_COUNT = DIMENSION_SIZE * DIMENSION_COUNT # How many indexes (32 * 2 = 64)
HEADER_SIZE = SECTOR_DETAILS_SIZE + INDEX_COUNT # 64 indexes + 4 byte details = 68
SECTOR_SIZE = 1 << SECTOR_SIZE_POWER # 4096 bytes
# Compression types
COMPRESSION_GZIP = 1
COMPRESSION_ZLIB = 2
def __init__(self, filepath):
"""Given a filename, returns an object to reference region file data.
We open the file as a binary file. Once you instantiate an object using this class,
you are likely to call get_data(chunkX, chunkZ) or get_timestamp(chunkX, chunkZ).
We frequently pass chunkX, chunkZ as *args in this Class.
filepath: full path to the region file (e.g. /opt/mc/region/r.1.1.mca)"""
if not os.path.isfile(filepath):
raise PycraftException(f'mca file missing: {filepath}')
self.data = open(filepath, 'r+b')
def get_index(self, *args):
"""Get the index for the chunk
This computes the index to locate both the chunk timestamp and size in the
size and timestamp tables at the beginning of the region file.
See https://minecraft.gamepedia.com/Region_file_format#Structure"""
index = 0
for dimension in range(self.DIMENSION_COUNT):
index |= (args[dimension] & self.DIMENSION_SIZE_MASK) << dimension * self.DIMENSION_SIZE_POWER
return index
def get_sector_offset_offset(self, *args):
"""Get the offset for the offset of the sector.
Returns the offset for the three-byte offset in 4KiB sectors from the start of the file
where the chunk data is stored.
See https://minecraft.gamepedia.com/Region_file_format#Chunk_location"""
return self.get_index(*args) * self.SECTOR_DETAILS_SIZE
def get_sector_count_offset(self, *args):
"""Return the offset for the size of the chunk.
Returns the offset for the byte which gives the length of the chunk (in 4KiB sectors, rounded up).
See https://minecraft.gamepedia.com/Region_file_format#Chunk_location"""
return self.get_sector_offset_offset(*args) + self.SECTOR_OFFSET_SIZE
def get_timestamp_offset(self, *args):
"""Return the offset for the last modification of the chunk.
Returns the offset for the 4 bytes which gives the timestamp of last modification for the chunk.
See https://minecraft.gamepedia.com/Region_file_format#Chunk_timestamps"""
return self.get_index(*args) * self.TIMESTAMP_SIZE + self.HEADER_SIZE
def get_sector_offset(self, *args):
"""Return the sector offset value.
Uses the earlier-defined function to seek appropriately in the file, and then it will return an int representing
how many 4096 byte offsets from the start of the file the chunk is at."""
offset = self.get_sector_offset_offset(*args)
self.data.seek(offset, 0)
return int.from_bytes(self.data.read(self.SECTOR_OFFSET_SIZE), 'big')
def get_data_offset(self, *args):
"""Return the byte offset for the chunk.
Basically multiplies the sector offset value by 4096. But we do it with bitshifting. This value is the location
of where the chunk data begins."""
return self.get_sector_offset(*args) << self.SECTOR_SIZE_POWER
def get_sector_count(self, *args):
"""Return the sector size value.
Uses the earlier-defined function to seek appropriately in the file, and then it will return an int representing
how many 4096 bytes the chunk data occupies."""
offset = self.get_sector_count_offset(*args)
self.data.seek(offset)
return int.from_bytes(self.data.read(self.SECTOR_COUNT_SIZE), 'big')
def get_timestamp(self, *args):
"""Return the last modified timestamp.
Seeks using the timestamp_offset and returns the timestamp as an int"""
offset = self.get_timestamp_offset(*args)
self.data.seek(offset, 0)
return int.from_bytes(self.data.read(self.TIMESTAMP_SIZE), 'big')
def get_data_size(self, *args):
"""Return the byte size for the chunk.
The first 4 bytes of the chunk data is the byte-length of the chunk data. We return that as an int.
See https://minecraft.gamepedia.com/Region_file_format#Chunk_data"""
offset = self.get_data_offset(*args)
self.data.seek(offset, 0)
return int.from_bytes(self.data.read(self.DATA_SIZE_SIZE), 'big')
def get_compression_type(self, *args):
"""Return the compression type for the chunk.
This value is either 1 or 2 for GZip or Zlib respectively"""
offset = self.get_data_offset(*args) + self.DATA_SIZE_SIZE
self.data.seek(offset, 0)
return int.from_bytes(self.data.read(self.COMPRESSION_TYPE_SIZE), 'big')
def get_data(self, *args):
"""Returns NBT data for the chunk specified by x and z in *args.
We get the start location of the chunk data. If that is valid, we skip the 4-byte header and read the size
learned from get_data_size. Based on the compression type, we either gzip or zlib decompress the data."""
datastart = self.get_data_offset(*args)
if datastart != 0:
payloadstart = datastart + self.DATA_HEADER_SIZE
payloadsize = self.get_data_size(*args)
self.data.seek(payloadstart, 0)
payload = self.data.read(payloadsize)
compressiontype = self.get_compression_type(*args)
if compressiontype == self.COMPRESSION_GZIP:
return gzip.decompress(payload)
elif compressiontype == self.COMPRESSION_ZLIB:
return zlib.decompress(payload)
| 47.358696 | 120 | 0.70599 |
import gzip
import zlib
import os
from pycraft.error import PycraftException
class Mca:
SECTOR_OFFSET_SIZE = 3
SECTOR_COUNT_SIZE = 1
TIMESTAMP_SIZE = 4
DATA_SIZE_SIZE = 4
COMPRESSION_TYPE_SIZE = 1
DIMENSION_SIZE_POWER = 5
DIMENSION_COUNT = 2
SECTOR_SIZE_POWER = 12
SECTOR_DETAILS_SIZE = SECTOR_OFFSET_SIZE + SECTOR_COUNT_SIZE
DATA_HEADER_SIZE = DATA_SIZE_SIZE + COMPRESSION_TYPE_SIZE
DIMENSION_SIZE = 1 << DIMENSION_SIZE_POWER
DIMENSION_SIZE_MASK = DIMENSION_SIZE - 1
INDEX_COUNT = DIMENSION_SIZE * DIMENSION_COUNT
HEADER_SIZE = SECTOR_DETAILS_SIZE + INDEX_COUNT
SECTOR_SIZE = 1 << SECTOR_SIZE_POWER
COMPRESSION_GZIP = 1
COMPRESSION_ZLIB = 2
def __init__(self, filepath):
if not os.path.isfile(filepath):
raise PycraftException(f'mca file missing: {filepath}')
self.data = open(filepath, 'r+b')
def get_index(self, *args):
index = 0
for dimension in range(self.DIMENSION_COUNT):
index |= (args[dimension] & self.DIMENSION_SIZE_MASK) << dimension * self.DIMENSION_SIZE_POWER
return index
def get_sector_offset_offset(self, *args):
return self.get_index(*args) * self.SECTOR_DETAILS_SIZE
def get_sector_count_offset(self, *args):
return self.get_sector_offset_offset(*args) + self.SECTOR_OFFSET_SIZE
def get_timestamp_offset(self, *args):
return self.get_index(*args) * self.TIMESTAMP_SIZE + self.HEADER_SIZE
def get_sector_offset(self, *args):
offset = self.get_sector_offset_offset(*args)
self.data.seek(offset, 0)
return int.from_bytes(self.data.read(self.SECTOR_OFFSET_SIZE), 'big')
def get_data_offset(self, *args):
return self.get_sector_offset(*args) << self.SECTOR_SIZE_POWER
def get_sector_count(self, *args):
offset = self.get_sector_count_offset(*args)
self.data.seek(offset)
return int.from_bytes(self.data.read(self.SECTOR_COUNT_SIZE), 'big')
def get_timestamp(self, *args):
offset = self.get_timestamp_offset(*args)
self.data.seek(offset, 0)
return int.from_bytes(self.data.read(self.TIMESTAMP_SIZE), 'big')
def get_data_size(self, *args):
offset = self.get_data_offset(*args)
self.data.seek(offset, 0)
return int.from_bytes(self.data.read(self.DATA_SIZE_SIZE), 'big')
def get_compression_type(self, *args):
offset = self.get_data_offset(*args) + self.DATA_SIZE_SIZE
self.data.seek(offset, 0)
return int.from_bytes(self.data.read(self.COMPRESSION_TYPE_SIZE), 'big')
def get_data(self, *args):
datastart = self.get_data_offset(*args)
if datastart != 0:
payloadstart = datastart + self.DATA_HEADER_SIZE
payloadsize = self.get_data_size(*args)
self.data.seek(payloadstart, 0)
payload = self.data.read(payloadsize)
compressiontype = self.get_compression_type(*args)
if compressiontype == self.COMPRESSION_GZIP:
return gzip.decompress(payload)
elif compressiontype == self.COMPRESSION_ZLIB:
return zlib.decompress(payload)
| true | true |
1c36dc2d81ac4aece50a4bb755b3cfe70c6d353a | 35,148 | py | Python | src/transformers/modeling_outputs.py | dmlap/transformers | 79588e6fdb5af8add092fc27dd695ea1ebc68b18 | [
"Apache-2.0"
] | 22 | 2020-10-14T01:10:23.000Z | 2022-03-28T23:56:46.000Z | src/transformers/modeling_outputs.py | dmlap/transformers | 79588e6fdb5af8add092fc27dd695ea1ebc68b18 | [
"Apache-2.0"
] | 6 | 2019-12-16T05:27:23.000Z | 2020-10-05T04:48:53.000Z | src/transformers/modeling_outputs.py | dmlap/transformers | 79588e6fdb5af8add092fc27dd695ea1ebc68b18 | [
"Apache-2.0"
] | 3 | 2021-01-29T11:31:10.000Z | 2021-03-16T07:45:02.000Z | from dataclasses import dataclass
from typing import List, Optional, Tuple
import torch
from .file_utils import ModelOutput
@dataclass
class BaseModelOutput(ModelOutput):
"""
Base class for model's outputs, with potential hidden states and attentions.
Args:
last_hidden_state (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the model.
hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
"""
last_hidden_state: torch.FloatTensor
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class BaseModelOutputWithPooling(ModelOutput):
"""
Base class for model's outputs that also contains a pooling of the last hidden states.
Args:
last_hidden_state (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the model.
pooler_output (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, hidden_size)`):
Last layer hidden-state of the first token of the sequence (classification token)
further processed by a Linear layer and a Tanh activation function. The Linear
layer weights are trained from the next sentence prediction (classification)
objective during pretraining.
hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
"""
last_hidden_state: torch.FloatTensor
pooler_output: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class BaseModelOutputWithPast(ModelOutput):
"""
Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding).
Args:
last_hidden_state (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the model.
If `past_key_values` is used only the last hidden-state of the sequences of shape :obj:`(batch_size, 1, hidden_size)` is output.
past_key_values (:obj:`List[torch.FloatTensor]`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``):
List of :obj:`torch.FloatTensor` of length :obj:`config.n_layers`, with each tensor of shape
:obj:`(2, batch_size, num_heads, sequence_length, embed_size_per_head)`).
Contains pre-computed hidden-states (key and values in the attention blocks) that can be used (see
``past_key_values`` input) to speed up sequential decoding.
hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
"""
last_hidden_state: torch.FloatTensor
past_key_values: Optional[List[torch.FloatTensor]] = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class Seq2SeqModelOutput(ModelOutput):
"""
Base class for model encoder's outputs that also contains : pre-computed hidden states that can speed up sequential
decoding.
Args:
last_hidden_state (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the decoder of the model.
If ``decoder_past_key_values`` is used only the last hidden-state of the sequences of shape :obj:`(batch_size, 1, hidden_size)` is output.
decoder_past_key_values (:obj:`List[torch.FloatTensor]`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``):
List of :obj:`torch.FloatTensor` of length :obj:`config.n_layers`, with each tensor of shape
:obj:`(2, batch_size, num_heads, sequence_length, embed_size_per_head)`).
Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be
used (see ``decoder_past_key_values`` input) to speed up sequential decoding.
decoder_hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.
decoder_attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the
self-attention heads.
encoder_last_hidden_state (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
Sequence of hidden-states at the output of the last layer of the encoder of the model.
encoder_hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
encoder_attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the
self-attention heads.
"""
last_hidden_state: torch.FloatTensor
decoder_past_key_values: Optional[List[torch.FloatTensor]] = None
decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
decoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
encoder_last_hidden_state: Optional[torch.FloatTensor] = None
encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class CausalLMOutput(ModelOutput):
"""
Base class for causal language model (or autoregressive) outputs.
Args:
loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`labels` is provided):
Language modeling loss (for next-token prediction).
logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, config.vocab_size)`):
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
"""
loss: Optional[torch.FloatTensor]
logits: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class CausalLMOutputWithPast(ModelOutput):
"""
Base class for causal language model (or autoregressive) outputs.
Args:
loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`labels` is provided):
Language modeling loss (for next-token prediction).
logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, config.vocab_size)`):
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
past_key_values (:obj:`List[torch.FloatTensor]`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``):
List of :obj:`torch.FloatTensor` of length :obj:`config.n_layers`, with each tensor of shape
:obj:`(2, batch_size, num_heads, sequence_length, embed_size_per_head)`).
Contains pre-computed hidden-states (key and values in the attention blocks) that can be used (see
``past_key_values`` input) to speed up sequential decoding.
hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
"""
loss: Optional[torch.FloatTensor] = None
logits: torch.FloatTensor = None
past_key_values: Optional[List[torch.FloatTensor]] = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class MaskedLMOutput(ModelOutput):
"""
Base class for masked language models outputs.
Args:
loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`labels` is provided):
Masked languaged modeling (MLM) loss.
logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, config.vocab_size)`):
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
"""
loss: Optional[torch.FloatTensor] = None
logits: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class Seq2SeqLMOutput(ModelOutput):
"""
Base class for sequence-to-sequence language models outputs.
Args:
loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`labels` is provided):
Languaged modeling loss.
logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, config.vocab_size)`):
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
decoder_past_key_values (:obj:`List[torch.FloatTensor]`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``):
List of :obj:`torch.FloatTensor` of length :obj:`config.n_layers`, with each tensor of shape
:obj:`(2, batch_size, num_heads, sequence_length, embed_size_per_head)`).
Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be
used (see ``decoder_past_key_values`` input) to speed up sequential decoding.
decoder_hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.
decoder_attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the
self-attention heads.
encoder_last_hidden_state (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
Sequence of hidden-states at the output of the last layer of the encoder of the model.
encoder_hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
encoder_attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the
self-attention heads.
"""
loss: Optional[torch.FloatTensor] = None
logits: torch.FloatTensor = None
decoder_past_key_values: Optional[List[torch.FloatTensor]] = None
decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
decoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
encoder_last_hidden_state: Optional[torch.FloatTensor] = None
encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class NextSentencePredictorOutput(ModelOutput):
"""
Base class for outputs of models predicting if two sentences are consecutive or not.
Args:
loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`next_sentence_label` is provided):
Next sequence prediction (classification) loss.
logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, 2)`):
Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation before SoftMax).
hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
"""
loss: Optional[torch.FloatTensor] = None
logits: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class SequenceClassifierOutput(ModelOutput):
"""
Base class for outputs of sentence classification models.
Args:
loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`labels` is provided):
Classification (or regression if config.num_labels==1) loss.
logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, config.num_labels)`):
Classification (or regression if config.num_labels==1) scores (before SoftMax).
hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
"""
loss: Optional[torch.FloatTensor] = None
logits: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class Seq2SeqSequenceClassifierOutput(ModelOutput):
"""
Base class for outputs of sequence-to-sequence sentence classification models.
Args:
loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`label` is provided):
Classification (or regression if config.num_labels==1) loss.
logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, config.num_labels)`):
Classification (or regression if config.num_labels==1) scores (before SoftMax).
decoder_past_key_values (:obj:`List[torch.FloatTensor]`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``):
List of :obj:`torch.FloatTensor` of length :obj:`config.n_layers`, with each tensor of shape
:obj:`(2, batch_size, num_heads, sequence_length, embed_size_per_head)`).
Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be
used (see ``decoder_past_key_values`` input) to speed up sequential decoding.
decoder_hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.
decoder_attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the
self-attention heads.
encoder_last_hidden_state (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
Sequence of hidden-states at the output of the last layer of the encoder of the model.
encoder_hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
encoder_attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the
self-attention heads.
"""
loss: Optional[torch.FloatTensor] = None
logits: torch.FloatTensor = None
decoder_past_key_values: Optional[List[torch.FloatTensor]] = None
decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
decoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
encoder_last_hidden_state: Optional[torch.FloatTensor] = None
encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class MultipleChoiceModelOutput(ModelOutput):
"""
Base class for outputs of multiple choice models.
Args:
loss (:obj:`torch.FloatTensor` of shape `(1,)`, `optional`, returned when :obj:`labels` is provided):
Classification loss.
logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, num_choices)`):
`num_choices` is the second dimension of the input tensors. (see `input_ids` above).
Classification scores (before SoftMax).
hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
"""
loss: Optional[torch.FloatTensor] = None
logits: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class TokenClassifierOutput(ModelOutput):
"""
Base class for outputs of token classification models.
Args:
loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when ``labels`` is provided) :
Classification loss.
logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, config.num_labels)`):
Classification scores (before SoftMax).
hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
"""
loss: Optional[torch.FloatTensor] = None
logits: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class QuestionAnsweringModelOutput(ModelOutput):
"""
Base class for outputs of question answering models.
Args:
loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`labels` is provided):
Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.
start_logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length,)`):
Span-start scores (before SoftMax).
end_logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length,)`):
Span-end scores (before SoftMax).
hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
"""
loss: Optional[torch.FloatTensor] = None
start_logits: torch.FloatTensor = None
end_logits: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class Seq2SeqQuestionAnsweringModelOutput(ModelOutput):
"""
Base class for outputs of sequence-to-sequence question answering models.
Args:
loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`labels` is provided):
Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.
start_logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length,)`):
Span-start scores (before SoftMax).
end_logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length,)`):
Span-end scores (before SoftMax).
decoder_past_key_values (:obj:`List[torch.FloatTensor]`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``):
List of :obj:`torch.FloatTensor` of length :obj:`config.n_layers`, with each tensor of shape
:obj:`(2, batch_size, num_heads, sequence_length, embed_size_per_head)`).
Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be
used (see ``decoder_past_key_values`` input) to speed up sequential decoding.
decoder_hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.
decoder_attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the
self-attention heads.
encoder_last_hidden_state (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
Sequence of hidden-states at the output of the last layer of the encoder of the model.
encoder_hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
encoder_attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the
self-attention heads.
"""
loss: Optional[torch.FloatTensor] = None
start_logits: torch.FloatTensor = None
end_logits: torch.FloatTensor = None
decoder_past_key_values: Optional[List[torch.FloatTensor]] = None
decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
decoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
encoder_last_hidden_state: Optional[torch.FloatTensor] = None
encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
| 63.32973 | 177 | 0.690366 | from dataclasses import dataclass
from typing import List, Optional, Tuple
import torch
from .file_utils import ModelOutput
@dataclass
class BaseModelOutput(ModelOutput):
last_hidden_state: torch.FloatTensor
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class BaseModelOutputWithPooling(ModelOutput):
last_hidden_state: torch.FloatTensor
pooler_output: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class BaseModelOutputWithPast(ModelOutput):
last_hidden_state: torch.FloatTensor
past_key_values: Optional[List[torch.FloatTensor]] = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class Seq2SeqModelOutput(ModelOutput):
last_hidden_state: torch.FloatTensor
decoder_past_key_values: Optional[List[torch.FloatTensor]] = None
decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
decoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
encoder_last_hidden_state: Optional[torch.FloatTensor] = None
encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class CausalLMOutput(ModelOutput):
loss: Optional[torch.FloatTensor]
logits: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class CausalLMOutputWithPast(ModelOutput):
loss: Optional[torch.FloatTensor] = None
logits: torch.FloatTensor = None
past_key_values: Optional[List[torch.FloatTensor]] = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class MaskedLMOutput(ModelOutput):
loss: Optional[torch.FloatTensor] = None
logits: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class Seq2SeqLMOutput(ModelOutput):
loss: Optional[torch.FloatTensor] = None
logits: torch.FloatTensor = None
decoder_past_key_values: Optional[List[torch.FloatTensor]] = None
decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
decoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
encoder_last_hidden_state: Optional[torch.FloatTensor] = None
encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class NextSentencePredictorOutput(ModelOutput):
loss: Optional[torch.FloatTensor] = None
logits: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class SequenceClassifierOutput(ModelOutput):
loss: Optional[torch.FloatTensor] = None
logits: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class Seq2SeqSequenceClassifierOutput(ModelOutput):
loss: Optional[torch.FloatTensor] = None
logits: torch.FloatTensor = None
decoder_past_key_values: Optional[List[torch.FloatTensor]] = None
decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
decoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
encoder_last_hidden_state: Optional[torch.FloatTensor] = None
encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class MultipleChoiceModelOutput(ModelOutput):
loss: Optional[torch.FloatTensor] = None
logits: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class TokenClassifierOutput(ModelOutput):
loss: Optional[torch.FloatTensor] = None
logits: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class QuestionAnsweringModelOutput(ModelOutput):
loss: Optional[torch.FloatTensor] = None
start_logits: torch.FloatTensor = None
end_logits: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class Seq2SeqQuestionAnsweringModelOutput(ModelOutput):
loss: Optional[torch.FloatTensor] = None
start_logits: torch.FloatTensor = None
end_logits: torch.FloatTensor = None
decoder_past_key_values: Optional[List[torch.FloatTensor]] = None
decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
decoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
encoder_last_hidden_state: Optional[torch.FloatTensor] = None
encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
| true | true |
1c36dc6a752384c61f718357143de928f62c6270 | 3,350 | py | Python | tests/cases/downsample.py | trivoldus28/gunpowder | 97e9e64709fb616e2c47567b22d5f11a9234fe48 | [
"MIT"
] | 43 | 2017-05-03T22:27:11.000Z | 2022-02-11T19:07:28.000Z | tests/cases/downsample.py | trivoldus28/gunpowder | 97e9e64709fb616e2c47567b22d5f11a9234fe48 | [
"MIT"
] | 102 | 2017-06-09T10:11:06.000Z | 2022-03-29T13:56:37.000Z | tests/cases/downsample.py | trivoldus28/gunpowder | 97e9e64709fb616e2c47567b22d5f11a9234fe48 | [
"MIT"
] | 43 | 2017-04-25T20:25:17.000Z | 2022-02-11T19:07:34.000Z | from .provider_test import ProviderTest
from gunpowder import *
import numpy as np
class DownSampleTestSource(BatchProvider):
def setup(self):
self.provides(
ArrayKeys.RAW,
ArraySpec(
roi=Roi((0, 0, 0), (1000, 1000, 1000)),
voxel_size=(4, 4, 4)))
self.provides(
ArrayKeys.GT_LABELS,
ArraySpec(
roi=Roi((0, 0, 0), (1000, 1000, 1000)),
voxel_size=(4, 4, 4)))
def provide(self, request):
batch = Batch()
# have the pixels encode their position
for (array_key, spec) in request.array_specs.items():
roi = spec.roi
for d in range(3):
assert roi.get_begin()[d]%4 == 0, "roi %s does not align with voxels"
data_roi = roi/4
# the z,y,x coordinates of the ROI
meshgrids = np.meshgrid(
range(data_roi.get_begin()[0], data_roi.get_end()[0]),
range(data_roi.get_begin()[1], data_roi.get_end()[1]),
range(data_roi.get_begin()[2], data_roi.get_end()[2]), indexing='ij')
data = meshgrids[0] + meshgrids[1] + meshgrids[2]
spec = self.spec[array_key].copy()
spec.roi = roi
batch.arrays[array_key] = Array(
data,
spec)
return batch
class TestDownSample(ProviderTest):
def test_output(self):
source = DownSampleTestSource()
ArrayKey('RAW_DOWNSAMPLED')
ArrayKey('GT_LABELS_DOWNSAMPLED')
request = BatchRequest()
request.add(ArrayKeys.RAW, (200,200,200))
request.add(ArrayKeys.RAW_DOWNSAMPLED, (120,120,120))
request.add(ArrayKeys.GT_LABELS, (200,200,200))
request.add(ArrayKeys.GT_LABELS_DOWNSAMPLED, (200,200,200))
pipeline = (
DownSampleTestSource() +
DownSample(ArrayKeys.RAW, 2, ArrayKeys.RAW_DOWNSAMPLED) +
DownSample(ArrayKeys.GT_LABELS, 2, ArrayKeys.GT_LABELS_DOWNSAMPLED)
)
with build(pipeline):
batch = pipeline.request_batch(request)
for (array_key, array) in batch.arrays.items():
# assert that pixels encode their position for supposedly unaltered
# arrays
if array_key in [ArrayKeys.RAW, ArrayKeys.GT_LABELS]:
# the z,y,x coordinates of the ROI
roi = array.spec.roi/4
meshgrids = np.meshgrid(
range(roi.get_begin()[0], roi.get_end()[0]),
range(roi.get_begin()[1], roi.get_end()[1]),
range(roi.get_begin()[2], roi.get_end()[2]), indexing='ij')
data = meshgrids[0] + meshgrids[1] + meshgrids[2]
self.assertTrue(np.array_equal(array.data, data), str(array_key))
elif array_key == ArrayKeys.RAW_DOWNSAMPLED:
self.assertTrue(array.data[0,0,0] == 30)
self.assertTrue(array.data[1,0,0] == 32)
elif array_key == ArrayKeys.GT_LABELS_DOWNSAMPLED:
self.assertTrue(array.data[0,0,0] == 0)
self.assertTrue(array.data[1,0,0] == 2)
else:
self.assertTrue(False, "unexpected array type")
| 32.843137 | 89 | 0.547463 | from .provider_test import ProviderTest
from gunpowder import *
import numpy as np
class DownSampleTestSource(BatchProvider):
def setup(self):
self.provides(
ArrayKeys.RAW,
ArraySpec(
roi=Roi((0, 0, 0), (1000, 1000, 1000)),
voxel_size=(4, 4, 4)))
self.provides(
ArrayKeys.GT_LABELS,
ArraySpec(
roi=Roi((0, 0, 0), (1000, 1000, 1000)),
voxel_size=(4, 4, 4)))
def provide(self, request):
batch = Batch()
for (array_key, spec) in request.array_specs.items():
roi = spec.roi
for d in range(3):
assert roi.get_begin()[d]%4 == 0, "roi %s does not align with voxels"
data_roi = roi/4
meshgrids = np.meshgrid(
range(data_roi.get_begin()[0], data_roi.get_end()[0]),
range(data_roi.get_begin()[1], data_roi.get_end()[1]),
range(data_roi.get_begin()[2], data_roi.get_end()[2]), indexing='ij')
data = meshgrids[0] + meshgrids[1] + meshgrids[2]
spec = self.spec[array_key].copy()
spec.roi = roi
batch.arrays[array_key] = Array(
data,
spec)
return batch
class TestDownSample(ProviderTest):
def test_output(self):
source = DownSampleTestSource()
ArrayKey('RAW_DOWNSAMPLED')
ArrayKey('GT_LABELS_DOWNSAMPLED')
request = BatchRequest()
request.add(ArrayKeys.RAW, (200,200,200))
request.add(ArrayKeys.RAW_DOWNSAMPLED, (120,120,120))
request.add(ArrayKeys.GT_LABELS, (200,200,200))
request.add(ArrayKeys.GT_LABELS_DOWNSAMPLED, (200,200,200))
pipeline = (
DownSampleTestSource() +
DownSample(ArrayKeys.RAW, 2, ArrayKeys.RAW_DOWNSAMPLED) +
DownSample(ArrayKeys.GT_LABELS, 2, ArrayKeys.GT_LABELS_DOWNSAMPLED)
)
with build(pipeline):
batch = pipeline.request_batch(request)
for (array_key, array) in batch.arrays.items():
if array_key in [ArrayKeys.RAW, ArrayKeys.GT_LABELS]:
roi = array.spec.roi/4
meshgrids = np.meshgrid(
range(roi.get_begin()[0], roi.get_end()[0]),
range(roi.get_begin()[1], roi.get_end()[1]),
range(roi.get_begin()[2], roi.get_end()[2]), indexing='ij')
data = meshgrids[0] + meshgrids[1] + meshgrids[2]
self.assertTrue(np.array_equal(array.data, data), str(array_key))
elif array_key == ArrayKeys.RAW_DOWNSAMPLED:
self.assertTrue(array.data[0,0,0] == 30)
self.assertTrue(array.data[1,0,0] == 32)
elif array_key == ArrayKeys.GT_LABELS_DOWNSAMPLED:
self.assertTrue(array.data[0,0,0] == 0)
self.assertTrue(array.data[1,0,0] == 2)
else:
self.assertTrue(False, "unexpected array type")
| true | true |
1c36dc6f1bea1ed7517e344c7d1f193ad3132998 | 7,535 | py | Python | yatube/posts/tests/test_forms.py | nekron2323/yatube_project | f2e802e816b32db4626962861f6883ba9e18ef4e | [
"MIT"
] | null | null | null | yatube/posts/tests/test_forms.py | nekron2323/yatube_project | f2e802e816b32db4626962861f6883ba9e18ef4e | [
"MIT"
] | null | null | null | yatube/posts/tests/test_forms.py | nekron2323/yatube_project | f2e802e816b32db4626962861f6883ba9e18ef4e | [
"MIT"
] | null | null | null | import shutil
import tempfile
from django import forms
from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import Client, TestCase
from django.urls import reverse
from ..forms import PostForm
from ..models import Comment, Group, Post, User
TEMP_MEDIA_ROOT = tempfile.mkdtemp(dir=settings.BASE_DIR)
USERNAME = 'MrNobody'
POST_CREATE_URL = reverse('posts:post_create')
PROFILE_URL = reverse('posts:profile', kwargs={'username': USERNAME})
LOGIN_URL = reverse('users:login')
SMALL_GIF = (
b'\x47\x49\x46\x38\x39\x61\x02\x00'
b'\x01\x00\x80\x00\x00\x00\x00\x00'
b'\xFF\xFF\xFF\x21\xF9\x04\x00\x00'
b'\x00\x00\x00\x2C\x00\x00\x00\x00'
b'\x02\x00\x01\x00\x00\x02\x02\x0C'
b'\x0A\x00\x3B'
)
class PostFormsTest(TestCase):
"""Тестируем формы."""
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.user = User.objects.create_user(username=USERNAME)
cls.another_user = User.objects.create_user(
username='AnotherMrNobody'
)
cls.form = PostForm()
cls.group = Group.objects.create(
title='Тестовый заголовок',
slug='test_slug',
description='Тестовое описание'
)
cls.another_group = Group.objects.create(
title='Другой тестовый заголовок',
slug='another_test_slug',
description='Другое тестовое описание'
)
cls.post = Post.objects.create(
text='Тестовый текст',
author=cls.user,
group=cls.group
)
cls.EDIT_URL = reverse(
'posts:post_edit',
kwargs={'post_id': cls.post.pk}
)
cls.DETAIL_URL = reverse(
'posts:post_detail',
kwargs={'post_id': cls.post.pk}
)
cls.authorized_user = Client()
cls.another_client = Client()
cls.guest = Client()
cls.authorized_user.force_login(cls.user)
cls.another_client.force_login(cls.another_user)
cls.ADD_COMMENT_URL = reverse(
'posts:add_comment',
kwargs={'post_id': cls.post.pk}
)
@classmethod
def tearDownClass(cls):
super().tearDownClass()
shutil.rmtree(TEMP_MEDIA_ROOT, ignore_errors=True)
def setUp(self):
super().setUp()
def test_post_create(self):
"""Проверяем, что создается новый пост и после создания переходит
на страницу профиля автора."""
posts = set(Post.objects.all())
form_data = {
'text': 'Новый тестовый текст',
'group': self.group.pk,
'image': SimpleUploadedFile(
name='small.gif',
content=SMALL_GIF,
content_type='image/gif'
)
}
response = self.authorized_user.post(
POST_CREATE_URL,
form_data,
follow=True
)
posts = set(response.context['page_obj']) - posts
self.assertEqual(len(posts), 1)
post = posts.pop()
self.assertEqual(post.text, form_data['text'])
self.assertEqual(post.group.pk, form_data['group'])
self.assertTrue(post.image)
self.assertEqual(post.author, self.user)
self.assertRedirects(
response,
PROFILE_URL
)
def test_post_edit(self):
"""Проверяем что изменяется пост и не создается новый. После создания
перенаправляет на страницу этого поста."""
posts_count = Post.objects.count()
form_data = {
'text': 'Измененный тестовый текст',
'group': self.another_group.pk,
'image': SimpleUploadedFile(
name='small.gif',
content=SMALL_GIF,
content_type='image/gif'
)
}
response = self.authorized_user.post(
self.EDIT_URL,
data=form_data,
follow=True
)
post = response.context['post']
self.assertEqual(Post.objects.count(), posts_count)
self.assertEqual(post.text, form_data['text'])
self.assertEqual(post.group.pk, form_data['group'])
self.assertEqual(post.author, self.post.author)
self.assertEqual(post.pk, self.post.pk)
self.assertTrue(post.image)
self.assertRedirects(response, self.DETAIL_URL)
def test_post_context_correct_form(self):
"""Проверяем, что шаблоны создания и редактирования постов
сформированы с правильным контекстом."""
view_names = (
POST_CREATE_URL,
self.EDIT_URL
)
form_fields = {
'text': forms.fields.CharField,
'group': forms.models.ModelChoiceField
}
for url in view_names:
context = self.authorized_user.get(url).context
for value, expected in form_fields.items():
with self.subTest(value=value):
form_field = context.get('form').fields.get(value)
self.assertIsInstance(form_field, expected)
def test_comment_guest_create(self):
"""Проверяем, что гость не может создать комментарий."""
comments = Comment.objects.all()
comments_count = comments.count()
form_data = {
'text': 'Тестовый текст комментария',
}
self.guest.post(
self.ADD_COMMENT_URL,
form_data,
follow=True
)
self.assertEqual(comments_count, Comment.objects.count())
self.assertQuerysetEqual(comments, Comment.objects.all())
def test_post_cant_be_edited_by_guest(self):
"""Проверяем, что гость не может отредактировать пост."""
form_data = {
'text': 'Текст поста',
'group': self.group.pk,
'image': SimpleUploadedFile(
name='small.gif',
content=SMALL_GIF,
content_type='image/gif'
)
}
clients = (
self.guest,
self.another_client
)
for client in clients:
with self.subTest(client=client):
response = self.client.post(
self.EDIT_URL,
form_data,
follow=True
)
post = response.context['post']
self.assertEqual(self.post.text, post.text)
self.assertEqual(self.group, post.group)
self.assertEqual(self.post.author, post.author)
self.assertEqual(self.post.image, post.image)
self.assertEqual(self.post.pk, post.pk)
self.assertRedirects(response, self.DETAIL_URL)
def test_add_new_comment(self):
"""Проверяем, что после успешной отправки комментарий появляется на
странице поста."""
comments = set(Comment.objects.all())
form_data = {
'text': 'Тестовый текст комментария',
}
response = self.authorized_user.post(
self.ADD_COMMENT_URL,
form_data,
follow=True
)
comments_count = response.context['post'].comments.count()
self.assertEqual(comments_count, 1)
comment = (
set(response.context['post'].comments.all()) - comments
).pop()
self.assertEqual(comment.author, self.user)
self.assertEqual(comment.post, self.post)
self.assertEqual(comment.text, form_data['text'])
| 34.406393 | 77 | 0.582216 | import shutil
import tempfile
from django import forms
from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import Client, TestCase
from django.urls import reverse
from ..forms import PostForm
from ..models import Comment, Group, Post, User
TEMP_MEDIA_ROOT = tempfile.mkdtemp(dir=settings.BASE_DIR)
USERNAME = 'MrNobody'
POST_CREATE_URL = reverse('posts:post_create')
PROFILE_URL = reverse('posts:profile', kwargs={'username': USERNAME})
LOGIN_URL = reverse('users:login')
SMALL_GIF = (
b'\x47\x49\x46\x38\x39\x61\x02\x00'
b'\x01\x00\x80\x00\x00\x00\x00\x00'
b'\xFF\xFF\xFF\x21\xF9\x04\x00\x00'
b'\x00\x00\x00\x2C\x00\x00\x00\x00'
b'\x02\x00\x01\x00\x00\x02\x02\x0C'
b'\x0A\x00\x3B'
)
class PostFormsTest(TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.user = User.objects.create_user(username=USERNAME)
cls.another_user = User.objects.create_user(
username='AnotherMrNobody'
)
cls.form = PostForm()
cls.group = Group.objects.create(
title='Тестовый заголовок',
slug='test_slug',
description='Тестовое описание'
)
cls.another_group = Group.objects.create(
title='Другой тестовый заголовок',
slug='another_test_slug',
description='Другое тестовое описание'
)
cls.post = Post.objects.create(
text='Тестовый текст',
author=cls.user,
group=cls.group
)
cls.EDIT_URL = reverse(
'posts:post_edit',
kwargs={'post_id': cls.post.pk}
)
cls.DETAIL_URL = reverse(
'posts:post_detail',
kwargs={'post_id': cls.post.pk}
)
cls.authorized_user = Client()
cls.another_client = Client()
cls.guest = Client()
cls.authorized_user.force_login(cls.user)
cls.another_client.force_login(cls.another_user)
cls.ADD_COMMENT_URL = reverse(
'posts:add_comment',
kwargs={'post_id': cls.post.pk}
)
@classmethod
def tearDownClass(cls):
super().tearDownClass()
shutil.rmtree(TEMP_MEDIA_ROOT, ignore_errors=True)
def setUp(self):
super().setUp()
def test_post_create(self):
posts = set(Post.objects.all())
form_data = {
'text': 'Новый тестовый текст',
'group': self.group.pk,
'image': SimpleUploadedFile(
name='small.gif',
content=SMALL_GIF,
content_type='image/gif'
)
}
response = self.authorized_user.post(
POST_CREATE_URL,
form_data,
follow=True
)
posts = set(response.context['page_obj']) - posts
self.assertEqual(len(posts), 1)
post = posts.pop()
self.assertEqual(post.text, form_data['text'])
self.assertEqual(post.group.pk, form_data['group'])
self.assertTrue(post.image)
self.assertEqual(post.author, self.user)
self.assertRedirects(
response,
PROFILE_URL
)
def test_post_edit(self):
posts_count = Post.objects.count()
form_data = {
'text': 'Измененный тестовый текст',
'group': self.another_group.pk,
'image': SimpleUploadedFile(
name='small.gif',
content=SMALL_GIF,
content_type='image/gif'
)
}
response = self.authorized_user.post(
self.EDIT_URL,
data=form_data,
follow=True
)
post = response.context['post']
self.assertEqual(Post.objects.count(), posts_count)
self.assertEqual(post.text, form_data['text'])
self.assertEqual(post.group.pk, form_data['group'])
self.assertEqual(post.author, self.post.author)
self.assertEqual(post.pk, self.post.pk)
self.assertTrue(post.image)
self.assertRedirects(response, self.DETAIL_URL)
def test_post_context_correct_form(self):
view_names = (
POST_CREATE_URL,
self.EDIT_URL
)
form_fields = {
'text': forms.fields.CharField,
'group': forms.models.ModelChoiceField
}
for url in view_names:
context = self.authorized_user.get(url).context
for value, expected in form_fields.items():
with self.subTest(value=value):
form_field = context.get('form').fields.get(value)
self.assertIsInstance(form_field, expected)
def test_comment_guest_create(self):
comments = Comment.objects.all()
comments_count = comments.count()
form_data = {
'text': 'Тестовый текст комментария',
}
self.guest.post(
self.ADD_COMMENT_URL,
form_data,
follow=True
)
self.assertEqual(comments_count, Comment.objects.count())
self.assertQuerysetEqual(comments, Comment.objects.all())
def test_post_cant_be_edited_by_guest(self):
form_data = {
'text': 'Текст поста',
'group': self.group.pk,
'image': SimpleUploadedFile(
name='small.gif',
content=SMALL_GIF,
content_type='image/gif'
)
}
clients = (
self.guest,
self.another_client
)
for client in clients:
with self.subTest(client=client):
response = self.client.post(
self.EDIT_URL,
form_data,
follow=True
)
post = response.context['post']
self.assertEqual(self.post.text, post.text)
self.assertEqual(self.group, post.group)
self.assertEqual(self.post.author, post.author)
self.assertEqual(self.post.image, post.image)
self.assertEqual(self.post.pk, post.pk)
self.assertRedirects(response, self.DETAIL_URL)
def test_add_new_comment(self):
comments = set(Comment.objects.all())
form_data = {
'text': 'Тестовый текст комментария',
}
response = self.authorized_user.post(
self.ADD_COMMENT_URL,
form_data,
follow=True
)
comments_count = response.context['post'].comments.count()
self.assertEqual(comments_count, 1)
comment = (
set(response.context['post'].comments.all()) - comments
).pop()
self.assertEqual(comment.author, self.user)
self.assertEqual(comment.post, self.post)
self.assertEqual(comment.text, form_data['text'])
| true | true |
1c36dc8f619c81a72054a9c56a5a2c9b120ef598 | 4,637 | py | Python | qa/rpc-tests/signrawtransactions.py | mirzaei-ce/core-alisinabit | 9929923df19fc9f03eb02fa056f325c9a284cfcf | [
"MIT"
] | null | null | null | qa/rpc-tests/signrawtransactions.py | mirzaei-ce/core-alisinabit | 9929923df19fc9f03eb02fa056f325c9a284cfcf | [
"MIT"
] | null | null | null | qa/rpc-tests/signrawtransactions.py | mirzaei-ce/core-alisinabit | 9929923df19fc9f03eb02fa056f325c9a284cfcf | [
"MIT"
] | null | null | null | #!/usr/bin/env python2
# Copyright (c) 2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import AlisinabitTestFramework
from test_framework.util import *
class SignRawTransactionsTest(AlisinabitTestFramework):
"""Tests transaction signing via RPC command "signrawtransaction"."""
def setup_chain(self):
print('Initializing test directory ' + self.options.tmpdir)
initialize_chain_clean(self.options.tmpdir, 1)
def setup_network(self, split=False):
self.nodes = start_nodes(1, self.options.tmpdir)
self.is_network_split = False
def successful_signing_test(self):
"""Creates and signs a valid raw transaction with one input.
Expected results:
1) The transaction has a complete set of signatures
2) No script verification error occurred"""
privKeys = ['cUeKHd5orzT3mz8P9pxyREHfsWtVfgsfDjiZZBcjUBAaGk1BTj7N']
inputs = [
# Valid pay-to-pubkey script
{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 0,
'scriptPubKey': '76a91460baa0f494b38ce3c940dea67f3804dc52d1fb9488ac'}
]
outputs = {'mpLQjfK79b7CCV4VMJWEWAj5Mpx8Up5zxB': 0.1}
rawTx = self.nodes[0].createrawtransaction(inputs, outputs)
rawTxSigned = self.nodes[0].signrawtransaction(rawTx, inputs, privKeys)
# 1) The transaction has a complete set of signatures
assert 'complete' in rawTxSigned
assert_equal(rawTxSigned['complete'], True)
# 2) No script verification error occurred
assert 'errors' not in rawTxSigned
def script_verification_error_test(self):
"""Creates and signs a raw transaction with valid (vin 0), invalid (vin 1) and one missing (vin 2) input script.
Expected results:
3) The transaction has no complete set of signatures
4) Two script verification errors occurred
5) Script verification errors have certain properties ("txid", "vout", "scriptSig", "sequence", "error")
6) The verification errors refer to the invalid (vin 1) and missing input (vin 2)"""
privKeys = ['cUeKHd5orzT3mz8P9pxyREHfsWtVfgsfDjiZZBcjUBAaGk1BTj7N']
inputs = [
# Valid pay-to-pubkey script
{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 0},
# Invalid script
{'txid': '5b8673686910442c644b1f4993d8f7753c7c8fcb5c87ee40d56eaeef25204547', 'vout': 7},
# Missing scriptPubKey
{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 1},
]
scripts = [
# Valid pay-to-pubkey script
{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 0,
'scriptPubKey': '76a91460baa0f494b38ce3c940dea67f3804dc52d1fb9488ac'},
# Invalid script
{'txid': '5b8673686910442c644b1f4993d8f7753c7c8fcb5c87ee40d56eaeef25204547', 'vout': 7,
'scriptPubKey': 'badbadbadbad'}
]
outputs = {'mpLQjfK79b7CCV4VMJWEWAj5Mpx8Up5zxB': 0.1}
rawTx = self.nodes[0].createrawtransaction(inputs, outputs)
rawTxSigned = self.nodes[0].signrawtransaction(rawTx, scripts, privKeys)
# 3) The transaction has no complete set of signatures
assert 'complete' in rawTxSigned
assert_equal(rawTxSigned['complete'], False)
# 4) Two script verification errors occurred
assert 'errors' in rawTxSigned
assert_equal(len(rawTxSigned['errors']), 2)
# 5) Script verification errors have certain properties
assert 'txid' in rawTxSigned['errors'][0]
assert 'vout' in rawTxSigned['errors'][0]
assert 'scriptSig' in rawTxSigned['errors'][0]
assert 'sequence' in rawTxSigned['errors'][0]
assert 'error' in rawTxSigned['errors'][0]
# 6) The verification errors refer to the invalid (vin 1) and missing input (vin 2)
assert_equal(rawTxSigned['errors'][0]['txid'], inputs[1]['txid'])
assert_equal(rawTxSigned['errors'][0]['vout'], inputs[1]['vout'])
assert_equal(rawTxSigned['errors'][1]['txid'], inputs[2]['txid'])
assert_equal(rawTxSigned['errors'][1]['vout'], inputs[2]['vout'])
def run_test(self):
self.successful_signing_test()
self.script_verification_error_test()
if __name__ == '__main__':
SignRawTransactionsTest().main()
| 42.154545 | 120 | 0.678025 |
from test_framework.test_framework import AlisinabitTestFramework
from test_framework.util import *
class SignRawTransactionsTest(AlisinabitTestFramework):
def setup_chain(self):
print('Initializing test directory ' + self.options.tmpdir)
initialize_chain_clean(self.options.tmpdir, 1)
def setup_network(self, split=False):
self.nodes = start_nodes(1, self.options.tmpdir)
self.is_network_split = False
def successful_signing_test(self):
privKeys = ['cUeKHd5orzT3mz8P9pxyREHfsWtVfgsfDjiZZBcjUBAaGk1BTj7N']
inputs = [
{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 0,
'scriptPubKey': '76a91460baa0f494b38ce3c940dea67f3804dc52d1fb9488ac'}
]
outputs = {'mpLQjfK79b7CCV4VMJWEWAj5Mpx8Up5zxB': 0.1}
rawTx = self.nodes[0].createrawtransaction(inputs, outputs)
rawTxSigned = self.nodes[0].signrawtransaction(rawTx, inputs, privKeys)
assert 'complete' in rawTxSigned
assert_equal(rawTxSigned['complete'], True)
assert 'errors' not in rawTxSigned
def script_verification_error_test(self):
privKeys = ['cUeKHd5orzT3mz8P9pxyREHfsWtVfgsfDjiZZBcjUBAaGk1BTj7N']
inputs = [
{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 0},
{'txid': '5b8673686910442c644b1f4993d8f7753c7c8fcb5c87ee40d56eaeef25204547', 'vout': 7},
{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 1},
]
scripts = [
{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 0,
'scriptPubKey': '76a91460baa0f494b38ce3c940dea67f3804dc52d1fb9488ac'},
{'txid': '5b8673686910442c644b1f4993d8f7753c7c8fcb5c87ee40d56eaeef25204547', 'vout': 7,
'scriptPubKey': 'badbadbadbad'}
]
outputs = {'mpLQjfK79b7CCV4VMJWEWAj5Mpx8Up5zxB': 0.1}
rawTx = self.nodes[0].createrawtransaction(inputs, outputs)
rawTxSigned = self.nodes[0].signrawtransaction(rawTx, scripts, privKeys)
assert 'complete' in rawTxSigned
assert_equal(rawTxSigned['complete'], False)
assert 'errors' in rawTxSigned
assert_equal(len(rawTxSigned['errors']), 2)
assert 'txid' in rawTxSigned['errors'][0]
assert 'vout' in rawTxSigned['errors'][0]
assert 'scriptSig' in rawTxSigned['errors'][0]
assert 'sequence' in rawTxSigned['errors'][0]
assert 'error' in rawTxSigned['errors'][0]
assert_equal(rawTxSigned['errors'][0]['txid'], inputs[1]['txid'])
assert_equal(rawTxSigned['errors'][0]['vout'], inputs[1]['vout'])
assert_equal(rawTxSigned['errors'][1]['txid'], inputs[2]['txid'])
assert_equal(rawTxSigned['errors'][1]['vout'], inputs[2]['vout'])
def run_test(self):
self.successful_signing_test()
self.script_verification_error_test()
if __name__ == '__main__':
SignRawTransactionsTest().main()
| true | true |
1c36ddc982c1cec56fd50fabe0b853dca852188c | 108 | py | Python | World 1.0 - Fundamentos/01 - Ola mundo.py | melissa-mfs/Exercicios-de-Python | 91c3b7bca601df4c211803805e20e4f0bea73642 | [
"MIT"
] | null | null | null | World 1.0 - Fundamentos/01 - Ola mundo.py | melissa-mfs/Exercicios-de-Python | 91c3b7bca601df4c211803805e20e4f0bea73642 | [
"MIT"
] | null | null | null | World 1.0 - Fundamentos/01 - Ola mundo.py | melissa-mfs/Exercicios-de-Python | 91c3b7bca601df4c211803805e20e4f0bea73642 | [
"MIT"
] | null | null | null | # Forma 1
print('\033[33mOlá, Mundo!\033[m')
# Forma 2
mensagem = 'Olá, Mundo!'
print('\033[32m'+mensagem)
| 15.428571 | 34 | 0.648148 |
print('\033[33mOlá, Mundo!\033[m')
mensagem = 'Olá, Mundo!'
print('\033[32m'+mensagem)
| true | true |
1c36ddcac68bb49b761b70f52d88d2cb06e3b2ef | 891 | py | Python | site_with_foldmenu/roles.py | shahab-qazavi/django_project | 346cc60132155ae1d20ec44a419cecbe495cc360 | [
"Apache-2.0"
] | 2 | 2020-04-30T18:50:24.000Z | 2020-05-20T08:10:18.000Z | site_with_foldmenu/roles.py | shahabgeek/django_project | 346cc60132155ae1d20ec44a419cecbe495cc360 | [
"Apache-2.0"
] | 1 | 2022-02-10T21:01:40.000Z | 2022-02-10T21:01:40.000Z | site_with_foldmenu/roles.py | shahabgeek/django_project | 346cc60132155ae1d20ec44a419cecbe495cc360 | [
"Apache-2.0"
] | null | null | null | from rolepermissions.roles import AbstractUserRole
class DeleteImg(AbstractUserRole):
available_permissions = {
'can_delete_image': True,
}
class AddImg(AbstractUserRole):
available_permissions = {
'can_add_image': True,
}
class AddUser(AbstractUserRole):
available_permissions = {
'can_add_users': True,
}
class EditUsers(AbstractUserRole):
available_permissions = {
'can_edit_users': True,
}
class DeleteUsers(AbstractUserRole):
available_permissions = {
'can_delete_users': True,
}
class SeeUsers(AbstractUserRole):
available_permissions = {
'can_see_users': True,
}
class Doctor(AbstractUserRole):
available_permissions = {
'create_medical_record': True,
}
class Nurse(AbstractUserRole):
available_permissions = {
'edit_patient_file': True,
}
| 16.811321 | 50 | 0.671156 | from rolepermissions.roles import AbstractUserRole
class DeleteImg(AbstractUserRole):
available_permissions = {
'can_delete_image': True,
}
class AddImg(AbstractUserRole):
available_permissions = {
'can_add_image': True,
}
class AddUser(AbstractUserRole):
available_permissions = {
'can_add_users': True,
}
class EditUsers(AbstractUserRole):
available_permissions = {
'can_edit_users': True,
}
class DeleteUsers(AbstractUserRole):
available_permissions = {
'can_delete_users': True,
}
class SeeUsers(AbstractUserRole):
available_permissions = {
'can_see_users': True,
}
class Doctor(AbstractUserRole):
available_permissions = {
'create_medical_record': True,
}
class Nurse(AbstractUserRole):
available_permissions = {
'edit_patient_file': True,
}
| true | true |
1c36e188f8bd18b7814ce3816d41afc29f0bd0fd | 15,200 | py | Python | tensorflow_probability/python/internal/special_math_test.py | nbro/probability | 07a6378155f0ed720b5aaccf5387e3f9a432bd10 | [
"Apache-2.0"
] | 1 | 2020-11-08T17:03:46.000Z | 2020-11-08T17:03:46.000Z | tensorflow_probability/python/internal/special_math_test.py | etarakci-hvl/probability | 7a0ce5e5beff91051028258dfbc7bc6cf0c4998d | [
"Apache-2.0"
] | null | null | null | tensorflow_probability/python/internal/special_math_test.py | etarakci-hvl/probability | 7a0ce5e5beff91051028258dfbc7bc6cf0c4998d | [
"Apache-2.0"
] | 1 | 2020-05-27T19:42:06.000Z | 2020-05-27T19:42:06.000Z | # Copyright 2018 The TensorFlow Probability Authors.
#
# 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.
# ============================================================================
"""Tests for Special Math Ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
# Dependency imports
import numpy as np
from scipy import special as sp_special
from scipy import stats as sp_stats
import tensorflow.compat.v1 as tf1
import tensorflow.compat.v2 as tf
from tensorflow_probability.python.internal import special_math
from tensorflow_probability.python.internal import test_util
from tensorflow_probability.python.math.gradient import value_and_gradient
def _check_strictly_increasing(array_1d):
diff = np.diff(array_1d)
np.testing.assert_array_less(0, diff)
def _make_grid(dtype, grid_spec):
"""Returns a uniform grid + noise, reshaped to shape argument."""
rng = np.random.RandomState(0)
num_points = np.prod(grid_spec.shape)
grid = np.linspace(grid_spec.min, grid_spec.max, num=num_points).astype(dtype)
grid_spacing = (grid_spec.max - grid_spec.min) / num_points
grid += 0.1 * grid_spacing * rng.randn(*grid.shape)
# More useful if it's sorted (e.g. for testing monotonicity, or debugging).
grid = np.sort(grid)
return np.reshape(grid, grid_spec.shape)
GridSpec = collections.namedtuple("GridSpec", ["min", "max", "shape"])
ErrorSpec = collections.namedtuple("ErrorSpec", ["rtol", "atol"])
@test_util.test_all_tf_execution_regimes
class NdtriTest(test_util.TestCase):
def assertAllFinite(self, x):
is_finite = np.isfinite(x)
all_true = np.ones_like(is_finite, dtype=np.bool)
self.assertAllEqual(all_true, is_finite)
def testNdtri(self):
"""Verifies that ndtri computation is correct."""
p = np.linspace(0., 1., 50).astype(np.float64)
# Quantile performs piecewise rational approximation so adding some
# sp_special input values to make sure we hit all the pieces.
p = np.hstack((p, np.exp(-32), 1. - np.exp(-32), np.exp(-2),
1. - np.exp(-2)))
expected_x = sp_special.ndtri(p)
x = special_math.ndtri(p)
self.assertAllClose(expected_x, self.evaluate(x), atol=0.)
def testNdtriDynamicShape(self):
"""Verifies that ndtri computation is correct."""
p_ = np.linspace(0., 1., 50).astype(np.float32)
p = tf1.placeholder_with_default(p_, shape=None)
self.assertAllClose(sp_special.ndtri(p_),
self.evaluate(special_math.ndtri(p)),
atol=0.)
def _baseNdtriFiniteGradientTest(self, dtype):
"""Verifies that ndtri has finite gradients at interesting points."""
# Tests gradients at 0, 1, and piece-wise boundaries.
p = tf.constant(
np.array([
0.,
np.exp(-32.),
np.exp(-2.),
1. - np.exp(-2.),
1. - np.exp(-32.),
1.,
]).astype(dtype))
# Not having the lambda sanitzer means we'd get an `IndexError` whenever
# the user supplied function has default args.
_, grads = value_and_gradient(special_math.ndtri, p)
self.assertAllFinite(self.evaluate(grads[0]))
def testNdtriFiniteGradientFloat32(self):
self._baseNdtriFiniteGradientTest(np.float32)
def testNdtriFiniteGradientFloat64(self):
self._baseNdtriFiniteGradientTest(np.float64)
@test_util.test_all_tf_execution_regimes
class NdtrTest(test_util.TestCase):
_use_log = False
# Grid min/max chosen to ensure 0 < cdf(x) < 1.
_grid32 = GridSpec(min=-12.9, max=5., shape=[100])
_grid64 = GridSpec(min=-37.5, max=8., shape=[100])
_error32 = ErrorSpec(rtol=1e-4, atol=0.)
_error64 = ErrorSpec(rtol=1e-6, atol=0.)
def _test_grid(self, dtype, grid_spec, error_spec):
if self._use_log:
self._test_grid_log(dtype, grid_spec, error_spec)
else:
self._test_grid_no_log(dtype, grid_spec, error_spec)
def _test_grid_log(self, dtype, grid_spec, error_spec):
grid = _make_grid(dtype, grid_spec)
actual = self.evaluate(special_math.log_ndtr(grid))
# Basic tests.
# isfinite checks for NaN and Inf.
self.assertTrue(np.isfinite(actual).all())
# On the grid, -inf < log_cdf(x) < 0. In this case, we should be able
# to use a huge grid because we have used tricks to escape numerical
# difficulties.
self.assertTrue((actual < 0).all())
_check_strictly_increasing(actual)
# Versus scipy.
expected = sp_special.log_ndtr(grid)
# Scipy prematurely goes to zero at some places that we don't. So don't
# include these in the comparison.
self.assertAllClose(
expected.astype(np.float64)[expected < 0],
actual.astype(np.float64)[expected < 0],
rtol=error_spec.rtol,
atol=error_spec.atol)
def _test_grid_no_log(self, dtype, grid_spec, error_spec):
grid = _make_grid(dtype, grid_spec)
actual = self.evaluate(special_math.ndtr(grid))
# Basic tests.
# isfinite checks for NaN and Inf.
self.assertTrue(np.isfinite(actual).all())
# On the grid, 0 < cdf(x) < 1. The grid cannot contain everything due
# to numerical limitations of cdf.
self.assertTrue((actual > 0).all())
self.assertTrue((actual < 1).all())
_check_strictly_increasing(actual)
# Versus scipy.
expected = sp_special.ndtr(grid)
# Scipy prematurely goes to zero at some places that we don't. So don't
# include these in the comparison.
self.assertAllClose(
expected.astype(np.float64)[expected < 0],
actual.astype(np.float64)[expected < 0],
rtol=error_spec.rtol,
atol=error_spec.atol)
def test_float32(self):
self._test_grid(np.float32, self._grid32, self._error32)
def test_float64(self):
self._test_grid(np.float64, self._grid64, self._error64)
@test_util.test_all_tf_execution_regimes
class LogNdtrTestLower(NdtrTest):
_use_log = True
_grid32 = GridSpec(
min=-100.,
max=special_math.LOGNDTR_FLOAT32_LOWER, shape=[100])
_grid64 = GridSpec(
min=-100.,
max=special_math.LOGNDTR_FLOAT64_LOWER, shape=[100])
_error32 = ErrorSpec(rtol=1e-4, atol=0.)
_error64 = ErrorSpec(rtol=1e-4, atol=0.)
# The errors are quite large when the input is > 6 or so. Also,
# scipy.sp_special.log_ndtr becomes zero very early, before 10,
# (due to ndtr becoming 1). We approximate Log[1 + epsilon] as epsilon, and
# avoid this issue.
@test_util.test_all_tf_execution_regimes
class LogNdtrTestMid(NdtrTest):
_use_log = True
_grid32 = GridSpec(
min=special_math.LOGNDTR_FLOAT32_LOWER,
max=special_math.LOGNDTR_FLOAT32_UPPER, shape=[100])
_grid64 = GridSpec(
min=special_math.LOGNDTR_FLOAT64_LOWER,
max=special_math.LOGNDTR_FLOAT64_UPPER, shape=[100])
# Differences show up as soon as we're in the tail, so add some atol.
_error32 = ErrorSpec(rtol=0.1, atol=1e-7)
_error64 = ErrorSpec(rtol=0.1, atol=1e-7)
@test_util.test_all_tf_execution_regimes
class LogNdtrTestUpper(NdtrTest):
_use_log = True
_grid32 = GridSpec(
min=special_math.LOGNDTR_FLOAT32_UPPER,
max=12., # Beyond this, log_cdf(x) may be zero.
shape=[100])
_grid64 = GridSpec(
min=special_math.LOGNDTR_FLOAT64_UPPER,
max=35., # Beyond this, log_cdf(x) may be zero.
shape=[100])
_error32 = ErrorSpec(rtol=1e-6, atol=1e-14)
_error64 = ErrorSpec(rtol=1e-6, atol=1e-14)
@test_util.test_all_tf_execution_regimes
class NdtrGradientTest(test_util.TestCase):
_use_log = False
_grid = GridSpec(min=-100., max=100., shape=[1, 2, 3, 8])
_error32 = ErrorSpec(rtol=1e-4, atol=0)
_error64 = ErrorSpec(rtol=1e-7, atol=0)
def assert_all_true(self, v):
self.assertAllEqual(np.ones_like(v, dtype=np.bool), v)
def assert_all_false(self, v):
self.assertAllEqual(np.zeros_like(v, dtype=np.bool), v)
def _test_grad_finite(self, dtype):
x = tf.constant([-100., 0., 100.], dtype=dtype)
output = (special_math.log_ndtr(x) if self._use_log
else special_math.ndtr(x))
fn = special_math.log_ndtr if self._use_log else special_math.ndtr
# Not having the lambda sanitzer means we'd get an `IndexError` whenever
# the user supplied function has default args.
output, grad_output = value_and_gradient(fn, x)
# isfinite checks for NaN and Inf.
output_, grad_output_ = self.evaluate([output, grad_output])
self.assert_all_true(np.isfinite(output_))
self.assert_all_true(np.isfinite(grad_output_[0]))
def _test_grad_accuracy(self, dtype, grid_spec, error_spec):
grid = _make_grid(dtype, grid_spec)
_, actual_grad = self.evaluate(value_and_gradient(
special_math.log_ndtr if self._use_log else special_math.ndtr, grid))
# Check for NaN separately in order to get informative failures.
self.assert_all_false(np.isnan(actual_grad))
if self._use_log:
g = np.reshape(actual_grad, [-1])
half = np.ceil(len(g) / 2)
self.assert_all_true(g[:int(half)] > 0.)
self.assert_all_true(g[int(half):] >= 0.)
else:
# The ndtr gradient will only be non-zero in the range [-14, 14] for
# float32 and [-38, 38] for float64.
self.assert_all_true(actual_grad >= 0.)
# isfinite checks for NaN and Inf.
self.assert_all_true(np.isfinite(actual_grad))
# Versus scipy.
if not (sp_special and sp_stats):
return
expected_grad = sp_stats.norm.pdf(grid)
if self._use_log:
expected_grad /= sp_special.ndtr(grid)
expected_grad[np.isnan(expected_grad)] = 0.
# Scipy prematurely goes to zero at some places that we don't. So don't
# include these in the comparison.
self.assertAllClose(
expected_grad.astype(np.float64)[expected_grad < 0],
actual_grad.astype(np.float64)[expected_grad < 0],
rtol=error_spec.rtol,
atol=error_spec.atol)
def test_float32(self):
self._test_grad_accuracy(np.float32, self._grid, self._error32)
self._test_grad_finite(np.float32)
def test_float64(self):
self._test_grad_accuracy(np.float64, self._grid, self._error64)
self._test_grad_finite(np.float64)
@test_util.test_all_tf_execution_regimes
class LogNdtrGradientTest(NdtrGradientTest):
_use_log = True
@test_util.test_all_tf_execution_regimes
class ErfInvTest(test_util.TestCase):
def testErfInvValues(self):
x = np.linspace(0., 1., 50).astype(np.float64)
self.assertAllClose(sp_special.erfinv(x),
self.evaluate(special_math.erfinv(x)),
atol=0)
def testErfInvIntegerInput(self):
with self.assertRaises(TypeError):
x = np.array([1, 2, 3]).astype(np.int32)
special_math.erfinv(x)
with self.assertRaises(TypeError):
x = np.array([1, 2, 3]).astype(np.int64)
special_math.erfinv(x)
@test_util.test_all_tf_execution_regimes
class LogCDFLaplaceTest(test_util.TestCase):
# Note that scipy.stats.laplace does not have a stable Log CDF, so we cannot
# rely on scipy to cross check the extreme values.
# Test will be done differently over different ranges. These are the values
# such that when exceeded by x, produce output that causes the naive (scipy)
# implementation to have numerical issues.
#
# If x = log(1 / (2 * eps)), then 0.5 * exp{-x} = eps.
# With inserting eps = np.finfo(dtype).eps, we see that log(1 / (2 * eps)) is
# the value of x such that any larger value will result in
# 1 - 0.5 * exp{-x} = 0, which will cause the log_cdf_laplace code to take a
# log # of zero. We therefore choose these as our cutoffs for testing.
CUTOFF_FLOAT64_UPPER = np.log(1. / (2. * np.finfo(np.float64).eps)) - 1.
CUTOFF_FLOAT32_UPPER = np.log(1. / (2. * np.finfo(np.float32).eps)) - 1.
def assertAllTrue(self, x):
self.assertAllEqual(np.ones_like(x, dtype=np.bool), x)
def _test_grid_log(self, dtype, scipy_dtype, grid_spec, error_spec):
grid = _make_grid(dtype, grid_spec)
actual = self.evaluate(special_math.log_cdf_laplace(grid))
# Basic tests.
# isfinite checks for NaN and Inf.
self.assertAllTrue(np.isfinite(actual))
self.assertAllTrue((actual < 0))
_check_strictly_increasing(actual)
# Versus scipy.
scipy_dist = sp_stats.laplace(loc=0., scale=1.)
expected = scipy_dist.logcdf(grid.astype(scipy_dtype))
self.assertAllClose(
expected.astype(np.float64),
actual.astype(np.float64),
rtol=error_spec.rtol,
atol=error_spec.atol)
def test_float32_lower_and_mid_segment_scipy_float32_ok(self):
# Choose values mild enough that we can use scipy in float32, which will
# allow for a high accuracy match to scipy (since we both use float32).
self._test_grid_log(
np.float32, # dtype
np.float32, # scipy_dtype
GridSpec(min=-10, max=self.CUTOFF_FLOAT32_UPPER - 5, shape=[100]),
ErrorSpec(rtol=5e-4, atol=0))
def test_float32_all_segments_with_scipy_float64_ok(self):
# Choose values outside the range where scipy float32 works.
# Let scipy use float64. This means we
# won't be exactly the same since we are in float32.
self._test_grid_log(
np.float32, # dtype
np.float64, # scipy_dtype
GridSpec(min=-50, max=self.CUTOFF_FLOAT32_UPPER + 5, shape=[100]),
ErrorSpec(rtol=0.05, atol=0))
def test_float32_extreme_values_result_and_gradient_finite_and_nonzero(self):
# On the lower branch, log_cdf_laplace(x) = x, so we know this will be
# fine, but test to -200 anyways.
grid = _make_grid(
np.float32, GridSpec(min=-200, max=80, shape=[20, 100]))
grid = tf.convert_to_tensor(value=grid)
actual, grad = value_and_gradient(special_math.log_cdf_laplace, grid)
actual_, grad_ = self.evaluate([actual, grad])
# isfinite checks for NaN and Inf.
self.assertAllTrue(np.isfinite(actual_))
self.assertAllTrue(np.isfinite(grad_))
self.assertFalse(np.any(actual_ == 0))
self.assertFalse(np.any(grad_ == 0))
def test_float64_extreme_values_result_and_gradient_finite_and_nonzero(self):
# On the lower branch, log_cdf_laplace(x) = x, so we know this will be
# fine, but test to -200 anyways.
grid = _make_grid(
np.float64, GridSpec(min=-200, max=700, shape=[20, 100]))
grid = tf.convert_to_tensor(value=grid)
actual, grad = value_and_gradient(special_math.log_cdf_laplace, grid)
actual_, grad_ = self.evaluate([actual, grad])
# isfinite checks for NaN and Inf.
self.assertAllTrue(np.isfinite(actual_))
self.assertAllTrue(np.isfinite(grad_))
self.assertFalse(np.any(actual_ == 0))
self.assertFalse(np.any(grad_ == 0))
if __name__ == "__main__":
tf.test.main()
| 36.714976 | 80 | 0.696316 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import numpy as np
from scipy import special as sp_special
from scipy import stats as sp_stats
import tensorflow.compat.v1 as tf1
import tensorflow.compat.v2 as tf
from tensorflow_probability.python.internal import special_math
from tensorflow_probability.python.internal import test_util
from tensorflow_probability.python.math.gradient import value_and_gradient
def _check_strictly_increasing(array_1d):
diff = np.diff(array_1d)
np.testing.assert_array_less(0, diff)
def _make_grid(dtype, grid_spec):
rng = np.random.RandomState(0)
num_points = np.prod(grid_spec.shape)
grid = np.linspace(grid_spec.min, grid_spec.max, num=num_points).astype(dtype)
grid_spacing = (grid_spec.max - grid_spec.min) / num_points
grid += 0.1 * grid_spacing * rng.randn(*grid.shape)
grid = np.sort(grid)
return np.reshape(grid, grid_spec.shape)
GridSpec = collections.namedtuple("GridSpec", ["min", "max", "shape"])
ErrorSpec = collections.namedtuple("ErrorSpec", ["rtol", "atol"])
@test_util.test_all_tf_execution_regimes
class NdtriTest(test_util.TestCase):
def assertAllFinite(self, x):
is_finite = np.isfinite(x)
all_true = np.ones_like(is_finite, dtype=np.bool)
self.assertAllEqual(all_true, is_finite)
def testNdtri(self):
p = np.linspace(0., 1., 50).astype(np.float64)
# Quantile performs piecewise rational approximation so adding some
# sp_special input values to make sure we hit all the pieces.
p = np.hstack((p, np.exp(-32), 1. - np.exp(-32), np.exp(-2),
1. - np.exp(-2)))
expected_x = sp_special.ndtri(p)
x = special_math.ndtri(p)
self.assertAllClose(expected_x, self.evaluate(x), atol=0.)
def testNdtriDynamicShape(self):
p_ = np.linspace(0., 1., 50).astype(np.float32)
p = tf1.placeholder_with_default(p_, shape=None)
self.assertAllClose(sp_special.ndtri(p_),
self.evaluate(special_math.ndtri(p)),
atol=0.)
def _baseNdtriFiniteGradientTest(self, dtype):
# Tests gradients at 0, 1, and piece-wise boundaries.
p = tf.constant(
np.array([
0.,
np.exp(-32.),
np.exp(-2.),
1. - np.exp(-2.),
1. - np.exp(-32.),
1.,
]).astype(dtype))
# Not having the lambda sanitzer means we'd get an `IndexError` whenever
_, grads = value_and_gradient(special_math.ndtri, p)
self.assertAllFinite(self.evaluate(grads[0]))
def testNdtriFiniteGradientFloat32(self):
self._baseNdtriFiniteGradientTest(np.float32)
def testNdtriFiniteGradientFloat64(self):
self._baseNdtriFiniteGradientTest(np.float64)
@test_util.test_all_tf_execution_regimes
class NdtrTest(test_util.TestCase):
_use_log = False
_grid32 = GridSpec(min=-12.9, max=5., shape=[100])
_grid64 = GridSpec(min=-37.5, max=8., shape=[100])
_error32 = ErrorSpec(rtol=1e-4, atol=0.)
_error64 = ErrorSpec(rtol=1e-6, atol=0.)
def _test_grid(self, dtype, grid_spec, error_spec):
if self._use_log:
self._test_grid_log(dtype, grid_spec, error_spec)
else:
self._test_grid_no_log(dtype, grid_spec, error_spec)
def _test_grid_log(self, dtype, grid_spec, error_spec):
grid = _make_grid(dtype, grid_spec)
actual = self.evaluate(special_math.log_ndtr(grid))
self.assertTrue(np.isfinite(actual).all())
self.assertTrue((actual < 0).all())
_check_strictly_increasing(actual)
expected = sp_special.log_ndtr(grid)
self.assertAllClose(
expected.astype(np.float64)[expected < 0],
actual.astype(np.float64)[expected < 0],
rtol=error_spec.rtol,
atol=error_spec.atol)
def _test_grid_no_log(self, dtype, grid_spec, error_spec):
grid = _make_grid(dtype, grid_spec)
actual = self.evaluate(special_math.ndtr(grid))
self.assertTrue(np.isfinite(actual).all())
self.assertTrue((actual > 0).all())
self.assertTrue((actual < 1).all())
_check_strictly_increasing(actual)
expected = sp_special.ndtr(grid)
self.assertAllClose(
expected.astype(np.float64)[expected < 0],
actual.astype(np.float64)[expected < 0],
rtol=error_spec.rtol,
atol=error_spec.atol)
def test_float32(self):
self._test_grid(np.float32, self._grid32, self._error32)
def test_float64(self):
self._test_grid(np.float64, self._grid64, self._error64)
@test_util.test_all_tf_execution_regimes
class LogNdtrTestLower(NdtrTest):
_use_log = True
_grid32 = GridSpec(
min=-100.,
max=special_math.LOGNDTR_FLOAT32_LOWER, shape=[100])
_grid64 = GridSpec(
min=-100.,
max=special_math.LOGNDTR_FLOAT64_LOWER, shape=[100])
_error32 = ErrorSpec(rtol=1e-4, atol=0.)
_error64 = ErrorSpec(rtol=1e-4, atol=0.)
@test_util.test_all_tf_execution_regimes
class LogNdtrTestMid(NdtrTest):
_use_log = True
_grid32 = GridSpec(
min=special_math.LOGNDTR_FLOAT32_LOWER,
max=special_math.LOGNDTR_FLOAT32_UPPER, shape=[100])
_grid64 = GridSpec(
min=special_math.LOGNDTR_FLOAT64_LOWER,
max=special_math.LOGNDTR_FLOAT64_UPPER, shape=[100])
_error32 = ErrorSpec(rtol=0.1, atol=1e-7)
_error64 = ErrorSpec(rtol=0.1, atol=1e-7)
@test_util.test_all_tf_execution_regimes
class LogNdtrTestUpper(NdtrTest):
_use_log = True
_grid32 = GridSpec(
min=special_math.LOGNDTR_FLOAT32_UPPER,
max=12., # Beyond this, log_cdf(x) may be zero.
shape=[100])
_grid64 = GridSpec(
min=special_math.LOGNDTR_FLOAT64_UPPER,
max=35., # Beyond this, log_cdf(x) may be zero.
shape=[100])
_error32 = ErrorSpec(rtol=1e-6, atol=1e-14)
_error64 = ErrorSpec(rtol=1e-6, atol=1e-14)
@test_util.test_all_tf_execution_regimes
class NdtrGradientTest(test_util.TestCase):
_use_log = False
_grid = GridSpec(min=-100., max=100., shape=[1, 2, 3, 8])
_error32 = ErrorSpec(rtol=1e-4, atol=0)
_error64 = ErrorSpec(rtol=1e-7, atol=0)
def assert_all_true(self, v):
self.assertAllEqual(np.ones_like(v, dtype=np.bool), v)
def assert_all_false(self, v):
self.assertAllEqual(np.zeros_like(v, dtype=np.bool), v)
def _test_grad_finite(self, dtype):
x = tf.constant([-100., 0., 100.], dtype=dtype)
output = (special_math.log_ndtr(x) if self._use_log
else special_math.ndtr(x))
fn = special_math.log_ndtr if self._use_log else special_math.ndtr
# Not having the lambda sanitzer means we'd get an `IndexError` whenever
output, grad_output = value_and_gradient(fn, x)
output_, grad_output_ = self.evaluate([output, grad_output])
self.assert_all_true(np.isfinite(output_))
self.assert_all_true(np.isfinite(grad_output_[0]))
def _test_grad_accuracy(self, dtype, grid_spec, error_spec):
grid = _make_grid(dtype, grid_spec)
_, actual_grad = self.evaluate(value_and_gradient(
special_math.log_ndtr if self._use_log else special_math.ndtr, grid))
self.assert_all_false(np.isnan(actual_grad))
if self._use_log:
g = np.reshape(actual_grad, [-1])
half = np.ceil(len(g) / 2)
self.assert_all_true(g[:int(half)] > 0.)
self.assert_all_true(g[int(half):] >= 0.)
else:
self.assert_all_true(actual_grad >= 0.)
self.assert_all_true(np.isfinite(actual_grad))
if not (sp_special and sp_stats):
return
expected_grad = sp_stats.norm.pdf(grid)
if self._use_log:
expected_grad /= sp_special.ndtr(grid)
expected_grad[np.isnan(expected_grad)] = 0.
self.assertAllClose(
expected_grad.astype(np.float64)[expected_grad < 0],
actual_grad.astype(np.float64)[expected_grad < 0],
rtol=error_spec.rtol,
atol=error_spec.atol)
def test_float32(self):
self._test_grad_accuracy(np.float32, self._grid, self._error32)
self._test_grad_finite(np.float32)
def test_float64(self):
self._test_grad_accuracy(np.float64, self._grid, self._error64)
self._test_grad_finite(np.float64)
@test_util.test_all_tf_execution_regimes
class LogNdtrGradientTest(NdtrGradientTest):
_use_log = True
@test_util.test_all_tf_execution_regimes
class ErfInvTest(test_util.TestCase):
def testErfInvValues(self):
x = np.linspace(0., 1., 50).astype(np.float64)
self.assertAllClose(sp_special.erfinv(x),
self.evaluate(special_math.erfinv(x)),
atol=0)
def testErfInvIntegerInput(self):
with self.assertRaises(TypeError):
x = np.array([1, 2, 3]).astype(np.int32)
special_math.erfinv(x)
with self.assertRaises(TypeError):
x = np.array([1, 2, 3]).astype(np.int64)
special_math.erfinv(x)
@test_util.test_all_tf_execution_regimes
class LogCDFLaplaceTest(test_util.TestCase):
eps)) - 1.
CUTOFF_FLOAT32_UPPER = np.log(1. / (2. * np.finfo(np.float32).eps)) - 1.
def assertAllTrue(self, x):
self.assertAllEqual(np.ones_like(x, dtype=np.bool), x)
def _test_grid_log(self, dtype, scipy_dtype, grid_spec, error_spec):
grid = _make_grid(dtype, grid_spec)
actual = self.evaluate(special_math.log_cdf_laplace(grid))
self.assertAllTrue(np.isfinite(actual))
self.assertAllTrue((actual < 0))
_check_strictly_increasing(actual)
scipy_dist = sp_stats.laplace(loc=0., scale=1.)
expected = scipy_dist.logcdf(grid.astype(scipy_dtype))
self.assertAllClose(
expected.astype(np.float64),
actual.astype(np.float64),
rtol=error_spec.rtol,
atol=error_spec.atol)
def test_float32_lower_and_mid_segment_scipy_float32_ok(self):
self._test_grid_log(
np.float32,
np.float32,
GridSpec(min=-10, max=self.CUTOFF_FLOAT32_UPPER - 5, shape=[100]),
ErrorSpec(rtol=5e-4, atol=0))
def test_float32_all_segments_with_scipy_float64_ok(self):
self._test_grid_log(
np.float32, # dtype
np.float64, # scipy_dtype
GridSpec(min=-50, max=self.CUTOFF_FLOAT32_UPPER + 5, shape=[100]),
ErrorSpec(rtol=0.05, atol=0))
def test_float32_extreme_values_result_and_gradient_finite_and_nonzero(self):
# On the lower branch, log_cdf_laplace(x) = x, so we know this will be
# fine, but test to -200 anyways.
grid = _make_grid(
np.float32, GridSpec(min=-200, max=80, shape=[20, 100]))
grid = tf.convert_to_tensor(value=grid)
actual, grad = value_and_gradient(special_math.log_cdf_laplace, grid)
actual_, grad_ = self.evaluate([actual, grad])
# isfinite checks for NaN and Inf.
self.assertAllTrue(np.isfinite(actual_))
self.assertAllTrue(np.isfinite(grad_))
self.assertFalse(np.any(actual_ == 0))
self.assertFalse(np.any(grad_ == 0))
def test_float64_extreme_values_result_and_gradient_finite_and_nonzero(self):
# On the lower branch, log_cdf_laplace(x) = x, so we know this will be
# fine, but test to -200 anyways.
grid = _make_grid(
np.float64, GridSpec(min=-200, max=700, shape=[20, 100]))
grid = tf.convert_to_tensor(value=grid)
actual, grad = value_and_gradient(special_math.log_cdf_laplace, grid)
actual_, grad_ = self.evaluate([actual, grad])
# isfinite checks for NaN and Inf.
self.assertAllTrue(np.isfinite(actual_))
self.assertAllTrue(np.isfinite(grad_))
self.assertFalse(np.any(actual_ == 0))
self.assertFalse(np.any(grad_ == 0))
if __name__ == "__main__":
tf.test.main()
| true | true |
1c36e36c670a6d183b34f3128565369bb69ed9ce | 622 | py | Python | stdplugins/Exit.py | kaalhoonme/PepeBot | d1678f3c5e57adb8c9d2e1bc5a54568ad2938258 | [
"Apache-2.0"
] | 1 | 2020-08-12T21:36:58.000Z | 2020-08-12T21:36:58.000Z | stdplugins/Exit.py | shn999/PepeBot | 912b97dc89c4c7581cbaee337d4fcc05c98d79c0 | [
"Apache-2.0"
] | null | null | null | stdplugins/Exit.py | shn999/PepeBot | 912b97dc89c4c7581cbaee337d4fcc05c98d79c0 | [
"Apache-2.0"
] | null | null | null | # For @UniBorg
"""fake exit
.fexit"""
from telethon import events
from datetime import datetime
from uniborg.util import admin_cmd
import importlib.util
import asyncio
import random
import importlib.util
@borg.on(events.NewMessage(outgoing=True, pattern='^\.(f?f)exit'))
async def timer_blankx(e):
txt=e.text[7:] + '\n\n`Processing....` '
j=1
k=j
for j in range(j):
await e.edit(txt + str(k))
k=k-1
await asyncio.sleep(1)
if e.pattern_match.group(1) == 'f':
await e.edit("`Legend is leaving this chat.....!` @admin `Goodbye aren't forever. It was a pleasant time with you guys..` ")
| 12.958333 | 126 | 0.672026 |
from telethon import events
from datetime import datetime
from uniborg.util import admin_cmd
import importlib.util
import asyncio
import random
import importlib.util
@borg.on(events.NewMessage(outgoing=True, pattern='^\.(f?f)exit'))
async def timer_blankx(e):
txt=e.text[7:] + '\n\n`Processing....` '
j=1
k=j
for j in range(j):
await e.edit(txt + str(k))
k=k-1
await asyncio.sleep(1)
if e.pattern_match.group(1) == 'f':
await e.edit("`Legend is leaving this chat.....!` @admin `Goodbye aren't forever. It was a pleasant time with you guys..` ")
| true | true |
1c36e3f17e8c45ae7b60a60a39cc07d960f5ccb8 | 391 | py | Python | wechat/celery.py | awesome-archive/Wechat-Admin | 6970ff4793bb57a864818011c3187370127fd0f9 | [
"MIT"
] | null | null | null | wechat/celery.py | awesome-archive/Wechat-Admin | 6970ff4793bb57a864818011c3187370127fd0f9 | [
"MIT"
] | null | null | null | wechat/celery.py | awesome-archive/Wechat-Admin | 6970ff4793bb57a864818011c3187370127fd0f9 | [
"MIT"
] | null | null | null | from celery import Celery
from celery.signals import worker_ready
from celery.schedules import crontab
app = Celery('wechat', include=['wechat.tasks'])
app.config_from_object('wechat.celeryconfig')
@worker_ready.connect
def at_start(sender, **k):
with sender.app.connection() as conn:
sender.app.send_task('wechat.tasks.listener')
if __name__ == '__main__':
app.start()
| 23 | 53 | 0.741688 | from celery import Celery
from celery.signals import worker_ready
from celery.schedules import crontab
app = Celery('wechat', include=['wechat.tasks'])
app.config_from_object('wechat.celeryconfig')
@worker_ready.connect
def at_start(sender, **k):
with sender.app.connection() as conn:
sender.app.send_task('wechat.tasks.listener')
if __name__ == '__main__':
app.start()
| true | true |
1c36e47985d557c495af697a7782d43e312f7a8b | 2,067 | py | Python | setup.py | thehardikv/python-aiplatform | efc00ed6bb838dceaee7ad9469cc51d1500a365d | [
"Apache-2.0"
] | null | null | null | setup.py | thehardikv/python-aiplatform | efc00ed6bb838dceaee7ad9469cc51d1500a365d | [
"Apache-2.0"
] | 1 | 2021-02-12T23:56:38.000Z | 2021-02-12T23:56:38.000Z | setup.py | thehardikv/python-aiplatform | efc00ed6bb838dceaee7ad9469cc51d1500a365d | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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 io
import os
import setuptools # type: ignore
name = "google-cloud-aiplatform"
version = "0.4.0"
description = "Cloud AI Platform API client library"
package_root = os.path.abspath(os.path.dirname(__file__))
readme_filename = os.path.join(package_root, "README.rst")
with io.open(readme_filename, encoding="utf-8") as readme_file:
readme = readme_file.read()
setuptools.setup(
name=name,
version=version,
description=description,
long_description=readme,
packages=setuptools.PEP420PackageFinder.find(),
namespace_packages=("google", "google.cloud"),
author="Google LLC",
author_email="googleapis-packages@google.com",
license="Apache 2.0",
url="https://github.com/googleapis/python-aiplatform",
platforms="Posix; MacOS X; Windows",
include_package_data=True,
install_requires=(
"google-api-core[grpc] >= 1.22.2, < 2.0.0dev",
"proto-plus >= 1.10.1",
"google-cloud-storage >= 1.26.0, < 2.0.0dev",
),
python_requires=">=3.6",
scripts=[],
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Topic :: Internet",
"Topic :: Software Development :: Libraries :: Python Modules",
],
zip_safe=False,
)
| 32.296875 | 74 | 0.676343 |
import io
import os
import setuptools
name = "google-cloud-aiplatform"
version = "0.4.0"
description = "Cloud AI Platform API client library"
package_root = os.path.abspath(os.path.dirname(__file__))
readme_filename = os.path.join(package_root, "README.rst")
with io.open(readme_filename, encoding="utf-8") as readme_file:
readme = readme_file.read()
setuptools.setup(
name=name,
version=version,
description=description,
long_description=readme,
packages=setuptools.PEP420PackageFinder.find(),
namespace_packages=("google", "google.cloud"),
author="Google LLC",
author_email="googleapis-packages@google.com",
license="Apache 2.0",
url="https://github.com/googleapis/python-aiplatform",
platforms="Posix; MacOS X; Windows",
include_package_data=True,
install_requires=(
"google-api-core[grpc] >= 1.22.2, < 2.0.0dev",
"proto-plus >= 1.10.1",
"google-cloud-storage >= 1.26.0, < 2.0.0dev",
),
python_requires=">=3.6",
scripts=[],
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Topic :: Internet",
"Topic :: Software Development :: Libraries :: Python Modules",
],
zip_safe=False,
)
| true | true |
1c36e61af0e8b36f9f1f33d651f1128ce683465e | 2,650 | py | Python | main.py | lmc212006/Cheap-Clothing-Finder | 1806a2ae841cf66ac5ea27d39e7e2434c4f40488 | [
"MIT"
] | 1 | 2021-08-30T11:14:35.000Z | 2021-08-30T11:14:35.000Z | main.py | lmc212006/Cheap-Clothing-Finder | 1806a2ae841cf66ac5ea27d39e7e2434c4f40488 | [
"MIT"
] | null | null | null | main.py | lmc212006/Cheap-Clothing-Finder | 1806a2ae841cf66ac5ea27d39e7e2434c4f40488 | [
"MIT"
] | null | null | null | from selenium import webdriver
from time import sleep
def getCheapestMyntra(drvr, link, elToSearch):
drvr.get(link)
out = {}
sleep(2)
for i in range(elToSearch):
out[drvr.find_element_by_xpath(f"//*[@id='desktopSearchResults']/div[2]/section/ul/li[{i + 1}]/a/div[2]/div/span").text] = drvr.find_element_by_xpath("//*[@id='desktopSearchResults']/div[2]/section/ul/li[1]/a/div[2]/h4[1]").text
return out
def getCheapestAjio(drvr, link, elToSearch):
drvr.get(link)
out = {}
sleep(2)
for i in range(elToSearch):
out[drvr.find_element_by_xpath(f"//*[@id='products']/div[3]/div[1]/div/div[{i + 1}]/a/div/div[2]/div[3]/span").text] = drvr.find_element_by_xpath(f"//*[@id='products']/div[3]/div[1]/div/div[{i + 1}]/a/div/div[2]/div[2]").text
return out
PATH = "chromedriver.exe"
rsearchQuery = input("Enter the item you want to buy:")
searchQuery = rsearchQuery.replace(" ", "-")
searchNum = int(input("Enter the amount of elements you want to search"))
driver = webdriver.Chrome(PATH, 1)
linkMyntra = f"https://www.myntra.com/{searchQuery}"
searchQuery = searchQuery.replace("-", "%20")
linkAjio = f"https://www.ajio.com/search/?text={searchQuery}"
myntraVals = getCheapestMyntra(driver, linkMyntra, searchNum)
ajioVals = getCheapestAjio(driver, linkAjio, searchNum)
myntraPrices = list(myntraVals.keys())
ajioPrices = list(ajioVals.keys())
currentCheapest = 10000000
cheapShop = ""
cheapIndex = 0
for i in range(len(myntraPrices)):
if int(myntraPrices[i].strip("Rs. ").split("R")[0]) < currentCheapest:
currentCheapest = int(myntraPrices[i].strip("Rs .").split("R")[0])
cheapShop = "Myntra"
cheapIndex = i
if int(ajioPrices[i].strip("Rs .").split("R")[0]) < currentCheapest:
currentCheapest = int(ajioPrices[i].strip("Rs .").split("R")[0])
cheapShop = "Ajio"
cheapIndex = i
if cheapShop == "Ajio":
print("The cheapest", rsearchQuery, "was at the price", currentCheapest, "from", cheapShop, ", and is called", list(myntraVals.values())[cheapIndex])
else:
print("The cheapest", rsearchQuery, "was at the price", currentCheapest, "from", cheapShop, ", and is called", list(myntraVals.values())[cheapIndex])
driver.close()
sleep(30) | 37.857143 | 389 | 0.573208 | from selenium import webdriver
from time import sleep
def getCheapestMyntra(drvr, link, elToSearch):
drvr.get(link)
out = {}
sleep(2)
for i in range(elToSearch):
out[drvr.find_element_by_xpath(f"//*[@id='desktopSearchResults']/div[2]/section/ul/li[{i + 1}]/a/div[2]/div/span").text] = drvr.find_element_by_xpath("//*[@id='desktopSearchResults']/div[2]/section/ul/li[1]/a/div[2]/h4[1]").text
return out
def getCheapestAjio(drvr, link, elToSearch):
drvr.get(link)
out = {}
sleep(2)
for i in range(elToSearch):
out[drvr.find_element_by_xpath(f"//*[@id='products']/div[3]/div[1]/div/div[{i + 1}]/a/div/div[2]/div[3]/span").text] = drvr.find_element_by_xpath(f"//*[@id='products']/div[3]/div[1]/div/div[{i + 1}]/a/div/div[2]/div[2]").text
return out
PATH = "chromedriver.exe"
rsearchQuery = input("Enter the item you want to buy:")
searchQuery = rsearchQuery.replace(" ", "-")
searchNum = int(input("Enter the amount of elements you want to search"))
driver = webdriver.Chrome(PATH, 1)
linkMyntra = f"https://www.myntra.com/{searchQuery}"
searchQuery = searchQuery.replace("-", "%20")
linkAjio = f"https://www.ajio.com/search/?text={searchQuery}"
myntraVals = getCheapestMyntra(driver, linkMyntra, searchNum)
ajioVals = getCheapestAjio(driver, linkAjio, searchNum)
myntraPrices = list(myntraVals.keys())
ajioPrices = list(ajioVals.keys())
currentCheapest = 10000000
cheapShop = ""
cheapIndex = 0
for i in range(len(myntraPrices)):
if int(myntraPrices[i].strip("Rs. ").split("R")[0]) < currentCheapest:
currentCheapest = int(myntraPrices[i].strip("Rs .").split("R")[0])
cheapShop = "Myntra"
cheapIndex = i
if int(ajioPrices[i].strip("Rs .").split("R")[0]) < currentCheapest:
currentCheapest = int(ajioPrices[i].strip("Rs .").split("R")[0])
cheapShop = "Ajio"
cheapIndex = i
if cheapShop == "Ajio":
print("The cheapest", rsearchQuery, "was at the price", currentCheapest, "from", cheapShop, ", and is called", list(myntraVals.values())[cheapIndex])
else:
print("The cheapest", rsearchQuery, "was at the price", currentCheapest, "from", cheapShop, ", and is called", list(myntraVals.values())[cheapIndex])
driver.close()
sleep(30) | true | true |
1c36e69feb35e0bf0b925f104610862cfd135d71 | 3,452 | py | Python | tests/app/test_delegating.py | hello0827/keripy | db41d612357acb231354ba3f353995635d91a02e | [
"Apache-2.0"
] | 10 | 2021-06-09T16:15:32.000Z | 2022-03-28T22:14:11.000Z | tests/app/test_delegating.py | hello0827/keripy | db41d612357acb231354ba3f353995635d91a02e | [
"Apache-2.0"
] | 47 | 2021-06-17T20:00:02.000Z | 2022-03-31T20:20:44.000Z | tests/app/test_delegating.py | hello0827/keripy | db41d612357acb231354ba3f353995635d91a02e | [
"Apache-2.0"
] | 6 | 2021-06-10T11:24:25.000Z | 2022-01-28T08:07:43.000Z | from keri.app import habbing, delegating, keeping
from keri.core import eventing, parsing, coring
from keri.db import basing
def test_delegating():
# Dan is the delegator
# Deb is the delegatee, or the entity "requesting" delegation of an identifier
with habbing.openHab(name="dan", salt=b'0123456789abcdef', transferable=True, temp=True) as danHab:
# delegatee
ks = keeping.Keeper(name="deb", temp=True)
ks.reopen()
db = basing.Baser(name="deb", temp=True)
db.reopen()
# start delegation
delegatey = delegating.Delegatey(name="deb", db=db, ks=ks)
msg = dict(
delpre=danHab.pre,
salt="0123456789abcdef",
transferable=True,
icount=1,
ncount=1,
isith=1,
nsith=1,
)
# results in processing of delcept
delegatey.processMessage(msg)
debHab = delegatey.hab
assert delegatey.hab.name == "deb"
danpre = danHab.pre
debpre = debHab.pre
assert danpre == "EqiimbkL1F-G8WkXXhsptPI555JJB81mXBEQZxayqm4U"
assert debpre == "EJlZWmnwtLyHCsZiKEk0GTfBhVbdfIq0ThyHbchWRL84"
delsrdr = delegatey.posts[0]["srdr"]
delsigers = delegatey.posts[0]["sigers"]
assert delsrdr.ked["t"] == "dip"
assert delsrdr.ked["i"] == debpre
assert delsrdr.ked["di"] == danpre
assert debHab.kvy.cues[0]["kin"] == "delegatage"
assert debHab.kvy.cues[0]["delpre"] == danpre
# delegator
dankvy = eventing.Kevery(db=danHab.db, lax=False, local=False)
evt = eventing.messagize(serder=delsrdr, sigers=delsigers)
# process an incoming delcept
parsing.Parser().parse(ims=evt, kvy=dankvy)
srdr = dankvy.cues[0]["serder"]
assert dankvy.cues[0]["kin"] == "delegating"
assert srdr.ked["t"] == "dip"
assert srdr.ked["i"] == debpre
assert srdr.ked["di"] == danpre
# business logic outstanding, approve delegation automagically with interact
msg = danHab.interact(data=[
dict(i=srdr.pre, s=srdr.ked["s"], d=srdr.said)
])
isrdr = coring.Serder(raw=msg)
assert isrdr.ked["i"] == danpre
assert isrdr.ked["t"] == "ixn"
assert isrdr.ked["a"][0]["i"] == debpre
assert isrdr.ked["a"][0]["s"] == "0"
assert isrdr.ked["a"][0]["d"] == "EJlZWmnwtLyHCsZiKEk0GTfBhVbdfIq0ThyHbchWRL84"
danHab.kvy.processEscrows()
# after process interact and escrow, ensure we have the out of escrow event
assert danHab.kvy.cues[2]["kin"] == "psUnescrow"
assert danHab.kvy.cues[2]["serder"].ked["i"] == debpre
assert danHab.kvy.cues[2]["serder"].ked["di"] == danpre
# process dan's (delegator) events with kvy for deb (delegatee)
debkvy = eventing.Kevery(db=debHab.db, lax=False, local=False)
parsing.Parser().parse(ims=danHab.makeOwnEvent(sn=0), kvy=debkvy)
parsing.Parser().parse(ims=msg, kvy=debkvy)
debHab.kvy.processEscrows()
# after process interact and escrow, ensure we have the out of escrow event
assert debHab.kvy.cues[2]["kin"] == "psUnescrow"
assert danHab.kvy.cues[2]["serder"].ked["i"] == debpre
# finally ensure we can accept the delegation
debHab.delegationAccepted()
assert debHab.accepted is True
# happy delegation
| 37.11828 | 103 | 0.609212 | from keri.app import habbing, delegating, keeping
from keri.core import eventing, parsing, coring
from keri.db import basing
def test_delegating():
with habbing.openHab(name="dan", salt=b'0123456789abcdef', transferable=True, temp=True) as danHab:
ks = keeping.Keeper(name="deb", temp=True)
ks.reopen()
db = basing.Baser(name="deb", temp=True)
db.reopen()
delegatey = delegating.Delegatey(name="deb", db=db, ks=ks)
msg = dict(
delpre=danHab.pre,
salt="0123456789abcdef",
transferable=True,
icount=1,
ncount=1,
isith=1,
nsith=1,
)
delegatey.processMessage(msg)
debHab = delegatey.hab
assert delegatey.hab.name == "deb"
danpre = danHab.pre
debpre = debHab.pre
assert danpre == "EqiimbkL1F-G8WkXXhsptPI555JJB81mXBEQZxayqm4U"
assert debpre == "EJlZWmnwtLyHCsZiKEk0GTfBhVbdfIq0ThyHbchWRL84"
delsrdr = delegatey.posts[0]["srdr"]
delsigers = delegatey.posts[0]["sigers"]
assert delsrdr.ked["t"] == "dip"
assert delsrdr.ked["i"] == debpre
assert delsrdr.ked["di"] == danpre
assert debHab.kvy.cues[0]["kin"] == "delegatage"
assert debHab.kvy.cues[0]["delpre"] == danpre
dankvy = eventing.Kevery(db=danHab.db, lax=False, local=False)
evt = eventing.messagize(serder=delsrdr, sigers=delsigers)
parsing.Parser().parse(ims=evt, kvy=dankvy)
srdr = dankvy.cues[0]["serder"]
assert dankvy.cues[0]["kin"] == "delegating"
assert srdr.ked["t"] == "dip"
assert srdr.ked["i"] == debpre
assert srdr.ked["di"] == danpre
msg = danHab.interact(data=[
dict(i=srdr.pre, s=srdr.ked["s"], d=srdr.said)
])
isrdr = coring.Serder(raw=msg)
assert isrdr.ked["i"] == danpre
assert isrdr.ked["t"] == "ixn"
assert isrdr.ked["a"][0]["i"] == debpre
assert isrdr.ked["a"][0]["s"] == "0"
assert isrdr.ked["a"][0]["d"] == "EJlZWmnwtLyHCsZiKEk0GTfBhVbdfIq0ThyHbchWRL84"
danHab.kvy.processEscrows()
assert danHab.kvy.cues[2]["kin"] == "psUnescrow"
assert danHab.kvy.cues[2]["serder"].ked["i"] == debpre
assert danHab.kvy.cues[2]["serder"].ked["di"] == danpre
debkvy = eventing.Kevery(db=debHab.db, lax=False, local=False)
parsing.Parser().parse(ims=danHab.makeOwnEvent(sn=0), kvy=debkvy)
parsing.Parser().parse(ims=msg, kvy=debkvy)
debHab.kvy.processEscrows()
# after process interact and escrow, ensure we have the out of escrow event
assert debHab.kvy.cues[2]["kin"] == "psUnescrow"
assert danHab.kvy.cues[2]["serder"].ked["i"] == debpre
# finally ensure we can accept the delegation
debHab.delegationAccepted()
assert debHab.accepted is True
# happy delegation
| true | true |
1c36e8b34b252a6af1224c80d2bea2ccb59c9297 | 16,364 | py | Python | glue/core/data_factories.py | bsipocz/glue | 7b7e4879b4c746b2419a0eca2a17c2d07a3fded3 | [
"BSD-3-Clause"
] | null | null | null | glue/core/data_factories.py | bsipocz/glue | 7b7e4879b4c746b2419a0eca2a17c2d07a3fded3 | [
"BSD-3-Clause"
] | null | null | null | glue/core/data_factories.py | bsipocz/glue | 7b7e4879b4c746b2419a0eca2a17c2d07a3fded3 | [
"BSD-3-Clause"
] | null | null | null | """ Factory methods to build Data objects from files"""
"""
Implementation notes:
Each factory method conforms to the folowing structure, which
helps the GUI Frontend easily load data:
1) The first argument is a file name to open
2) The return value is a Data object
3) The function has a .label attribute that describes (in human
language) what kinds of files it understands
4) The function has a callable .identifier attribute that returns
whether it can handle a requested filename and keyword set
5) The function is added to the __factories__ list
6) Optionally, the function is registered to open a given extension by
default by calling set_default_factory
Putting this together, the simplest data factory code looks like this::
def dummy_factory(file_name):
return glue.core.Data()
dummy_factory.label = "Foo file"
dummy_factory.identifier = has_extension('foo FOO')
__factories__.append(dummy_factory)
set_default_factory("foo", dummy_factory)
"""
import os
import numpy as np
from .data import Component, Data, CategoricalComponent
from .io import extract_data_fits, extract_data_hdf5
from .util import file_format, as_list
from .coordinates import coordinates_from_header, coordinates_from_wcs
from ..external.astro import fits
__all__ = ['load_data', 'gridded_data', 'casalike_cube',
'tabular_data', 'img_data', 'auto_data']
__factories__ = []
_default_factory = {}
def _extension(path):
# extract the extension type from a path
# test.fits -> fits
# test.fits.gz -> fits.gz (special case)
# a.b.c.fits -> fits
_, path = os.path.split(path)
if '.' not in path:
return ''
stems = path.split('.')[1:]
# special case: test.fits.gz -> fits.gz
if len(stems) > 1 and any(x == stems[-1]
for x in ['gz', 'gzip', 'bz', 'bz2']):
return '.'.join(stems[-2:])
return stems[-1]
def has_extension(exts):
"""
A simple default filetype identifier function
It returns a function that tests whether its input
filename contains a particular extension
Inputs
------
exts : str
A space-delimited string listing the extensions
(e.g., 'txt', or 'txt csv fits')
Returns
-------
A function suitable as a factory identifier function
"""
def tester(x, **kwargs):
return _extension(x) in set(exts.split())
return tester
def is_hdf5(filename):
# All hdf5 files begin with the same sequence
with open(filename) as infile:
return infile.read(8) == '\x89HDF\r\n\x1a\n'
def is_fits(filename):
try:
with fits.open(filename):
return True
except IOError:
return False
class LoadLog(object):
"""
This class attaches some metadata to data created
from load_data, so that the data can be re-constructed
when loading saved state. It's only meant to be used
within load_data
"""
def __init__(self, path, factory, kwargs):
self.path = os.path.abspath(path)
self.factory = factory
self.kwargs = kwargs
self.components = []
self.data = []
def _log_component(self, component):
self.components.append(component)
def _log_data(self, data):
self.data.append(data)
def log(self, obj):
if isinstance(obj, Component):
self._log_component(obj)
elif isinstance(obj, Data):
self._log_data(obj)
obj._load_log = self
def id(self, component):
return self.components.index(component)
def component(self, index):
return self.components[index]
def __gluestate__(self, context):
return dict(path=self.path,
factory=context.do(self.factory),
kwargs=[list(self.kwargs.items())])
@classmethod
def __setgluestate__(cls, rec, context):
fac = context.object(rec['factory'])
kwargs = dict(*rec['kwargs'])
d = load_data(rec['path'], factory=fac, **kwargs)
return as_list(d)[0]._load_log
def load_data(path, factory=None, **kwargs):
"""Use a factory to load a file and assign a label.
This is the preferred interface for loading data into Glue,
as it logs metadata about how data objects relate to files
on disk.
:param path: Path to a file
:param factory: factory function to use. Defaults to :func:`auto_data`
Extra keywords are passed through to factory functions
"""
factory = factory or auto_data
d = factory(path, **kwargs)
lbl = data_label(path)
log = LoadLog(path, factory, kwargs)
for item in as_list(d):
item.label = lbl
log.log(item)
for cid in item.primary_components:
log.log(item.get_component(cid))
return d
def data_label(path):
"""Convert a file path into a data label, by stripping out
slashes, file extensions, etc."""
_, fname = os.path.split(path)
name, _ = os.path.splitext(fname)
return name
def set_default_factory(extension, factory):
"""Register an extension that should be handled by a factory by default
:param extension: File extension (do not include the '.')
:param factory: The factory function to dispatch to
"""
for ex in extension.split():
_default_factory[ex] = factory
def get_default_factory(extension):
"""Return the default factory function to read a given file extension.
:param extension: The extension to lookup
:rtype: A factory function, or None if the extension has no default
"""
try:
return _default_factory[extension]
except KeyError:
return None
def find_factory(filename, **kwargs):
from ..config import data_factory
# on first pass, only try the default factory
default = _default_factory.get(_extension(filename))
for func, _, identifier in data_factory:
if func is auto_data:
continue
if (func is default) and identifier(filename, **kwargs):
return func
# if that fails, try everything
for func, _, identifier in data_factory:
if func is auto_data:
continue
if identifier(filename, **kwargs):
return func
def auto_data(filename, *args, **kwargs):
"""Attempt to automatically construct a data object"""
fac = find_factory(filename, **kwargs)
if fac is None:
raise KeyError("Don't know how to open file: %s" % filename)
return fac(filename, *args, **kwargs)
auto_data.label = 'Auto'
auto_data.identifier = lambda x: True
__factories__.append(auto_data)
def gridded_data(filename, format='auto', **kwargs):
"""
Construct an n - dimensional data object from ``filename``. If the
format cannot be determined from the extension, it can be
specified using the ``format`` option. Valid formats are 'fits' and
'hdf5'.
"""
result = Data()
# Try and automatically find the format if not specified
if format == 'auto':
format = file_format(filename)
# Read in the data
if is_fits(filename):
arrays = extract_data_fits(filename, **kwargs)
header = fits.getheader(filename)
result.coords = coordinates_from_header(header)
elif is_hdf5(filename):
arrays = extract_data_hdf5(filename, **kwargs)
else:
raise Exception("Unkonwn format: %s" % format)
for component_name in arrays:
comp = Component.autotyped(arrays[component_name])
result.add_component(comp, component_name)
return result
def is_gridded_data(filename, **kwargs):
if is_hdf5(filename):
return True
if is_fits(filename):
with fits.open(filename) as hdulist:
for hdu in hdulist:
if not isinstance(hdu, (fits.PrimaryHDU, fits.ImageHDU)):
return False
return True
return False
gridded_data.label = "FITS/HDF5 Image"
gridded_data.identifier = is_gridded_data
__factories__.append(gridded_data)
set_default_factory('fits', gridded_data)
set_default_factory('hd5', gridded_data)
set_default_factory('hdf5', gridded_data)
def casalike_cube(filename, **kwargs):
"""
This provides special support for 4D CASA - like cubes,
which have 2 spatial axes, a spectral axis, and a stokes axis
in that order.
Each stokes cube is split out as a separate component
"""
result = Data()
with fits.open(filename, **kwargs) as hdulist:
array = hdulist[0].data
header = hdulist[0].header
result.coords = coordinates_from_header(header)
for i in range(array.shape[0]):
result.add_component(array[[i]], label='STOKES %i' % i)
return result
def is_casalike(filename, **kwargs):
"""
Check if a file is a CASA like cube,
with (P, P, V, Stokes) layout
"""
if not is_fits(filename):
return False
with fits.open(filename) as hdulist:
if len(hdulist) != 1:
return False
if hdulist[0].header['NAXIS'] != 4:
return False
from astropy.wcs import WCS
w = WCS(hdulist[0].header)
ax = [a.get('coordinate_type') for a in w.get_axis_types()]
return ax == ['celestial', 'celestial', 'spectral', 'stokes']
casalike_cube.label = 'CASA PPV Cube'
casalike_cube.identifier = is_casalike
def _ascii_identifier_v02(origin, args, kwargs):
# this works for astropy v0.2
if isinstance(args[0], basestring):
return args[0].endswith(('csv', 'tsv', 'txt', 'tbl', 'dat',
'csv.gz', 'tsv.gz', 'txt.gz', 'tbl.gz',
'dat.gz'))
else:
return False
def _ascii_identifier_v03(origin, *args, **kwargs):
# this works for astropy v0.3
return _ascii_identifier_v02(origin, args, kwargs)
def tabular_data(*args, **kwargs):
"""
Build a data set from a table. We restrict ourselves to tables
with 1D columns.
All arguments are passed to
astropy.table.Table.read(...).
"""
from distutils.version import LooseVersion
from astropy import __version__
if LooseVersion(__version__) < LooseVersion("0.2"):
raise RuntimeError("Glue requires astropy >= v0.2. Please update")
result = Data()
# Read the table
from astropy.table import Table
# Add identifiers for ASCII data
from astropy.io import registry
if LooseVersion(__version__) < LooseVersion("0.3"):
registry.register_identifier('ascii', Table, _ascii_identifier_v02,
force=True)
else:
registry.register_identifier('ascii', Table, _ascii_identifier_v03,
force=True)
# Clobber the identifier
# added in astropy/astropy/pull/1935
registry.register_identifier('ascii.csv', Table, lambda *a, **k: False,
force=True)
# Import FITS compatibility (for Astropy 0.2.x)
from ..external import fits_io
table = Table.read(*args, **kwargs)
# Loop through columns and make component list
for column_name in table.columns:
c = table[column_name]
u = c.units
if table.masked:
# fill array for now
try:
c = c.filled(fill_value=np.nan)
except ValueError: # assigning nan to integer dtype
c = c.filled(fill_value=-1)
nc = Component.autotyped(c, units=u)
result.add_component(nc, column_name)
return result
tabular_data.label = "Catalog"
tabular_data.identifier = has_extension('xml vot csv txt tsv tbl dat fits '
'xml.gz vot.gz csv.gz txt.gz tbl.bz '
'dat.gz fits.gz')
__factories__.append(tabular_data)
set_default_factory('xml', tabular_data)
set_default_factory('vot', tabular_data)
set_default_factory('csv', tabular_data)
set_default_factory('txt', tabular_data)
set_default_factory('tsv', tabular_data)
set_default_factory('tbl', tabular_data)
set_default_factory('dat', tabular_data)
def panda_process(indf):
"""
Build a data set from a table using pandas. This attempts to respect
categorical data input by letting pandas.read_csv infer the type
"""
result = Data()
for name, column in indf.iteritems():
if (column.dtype == np.object) | (column.dtype == np.bool):
# pandas has a 'special' nan implementation and this doesn't
# play well with np.unique
c = CategoricalComponent(column.fillna(np.nan))
else:
c = Component(column.values)
result.add_component(c, name)
return result
def panda_read_excel(path, sheet='Sheet1', **kwargs):
""" A factory for reading excel data using pandas.
:param path: path/to/file
:param sheet: The sheet to read
:param kwargs: All other kwargs are passed to pandas.read_excel
:return: core.data.Data object.
"""
try:
import pandas as pd
except ImportError:
raise ImportError('Pandas is required for Excel input.')
indf = pd.read_excel(path, sheet, **kwargs)
return panda_process(indf)
panda_read_excel.label = "Excel"
panda_read_excel.identifier = has_extension('xls xlsx')
__factories__.append(panda_read_excel)
set_default_factory('xls', panda_read_excel)
set_default_factory('xlsx', panda_read_excel)
def pandas_read_table(path, **kwargs):
""" A factory for reading tabular data using pandas
:param path: path/to/file
:param kwargs: All kwargs are passed to pandas.read_csv
:returns: :class:`glue.core.data.Data` object
"""
import pandas as pd
# iterate over common delimiters to search for best option
delimiters = kwargs.pop('delimiter', [None] + list(',|\t '))
fallback = None
for d in delimiters:
try:
indf = pd.read_csv(path, delimiter=d, **kwargs)
# ignore files parsed to empty dataframes
if len(indf) == 0:
continue
# only use files parsed to single-column dataframes
# if we don't find a better strategy
if len(indf.columns) < 2:
fallback = indf
continue
return panda_process(indf)
except pd._parser.CParserError:
continue
if fallback is not None:
return panda_process(fallback)
raise IOError("Could not parse %s using pandas" % path)
pandas_read_table.label = "Pandas Table"
pandas_read_table.identifier = has_extension('csv csv txt tsv tbl dat')
__factories__.append(pandas_read_table)
img_fmt = ['jpg', 'jpeg', 'bmp', 'png', 'tiff', 'tif']
def img_loader(file_name):
"""Load an image to a numpy array, using either PIL or skimage
:param file_name: Path of file to load
:rtype: Numpy array
"""
try:
from skimage.io import imread
return np.asarray(imread(file_name))
except ImportError:
pass
try:
from PIL import Image
return np.asarray(Image.open(file_name))
except ImportError:
raise ImportError("Reading %s requires PIL or scikit-image" %
file_name)
def img_data(file_name):
"""Load common image files into a Glue data object"""
result = Data()
data = img_loader(file_name)
data = np.flipud(data)
shp = data.shape
comps = []
labels = []
# split 3 color images into each color plane
if len(shp) == 3 and shp[2] in [3, 4]:
comps.extend([data[:, :, 0], data[:, :, 1], data[:, :, 2]])
labels.extend(['red', 'green', 'blue'])
if shp[2] == 4:
comps.append(data[:, :, 3])
labels.append('alpha')
else:
comps = [data]
labels = ['PRIMARY']
# look for AVM coordinate metadata
try:
from pyavm import AVM
avm = AVM(str(file_name)) # avoid unicode
wcs = avm.to_wcs()
except:
pass
else:
result.coords = coordinates_from_wcs(wcs)
for c, l in zip(comps, labels):
result.add_component(c, l)
return result
img_data.label = "Image"
img_data.identifier = has_extension(' '.join(img_fmt))
for i in img_fmt:
set_default_factory(i, img_data)
__factories__.append(img_data)
__factories__.append(casalike_cube)
| 29.014184 | 79 | 0.64208 |
import os
import numpy as np
from .data import Component, Data, CategoricalComponent
from .io import extract_data_fits, extract_data_hdf5
from .util import file_format, as_list
from .coordinates import coordinates_from_header, coordinates_from_wcs
from ..external.astro import fits
__all__ = ['load_data', 'gridded_data', 'casalike_cube',
'tabular_data', 'img_data', 'auto_data']
__factories__ = []
_default_factory = {}
def _extension(path):
_, path = os.path.split(path)
if '.' not in path:
return ''
stems = path.split('.')[1:]
if len(stems) > 1 and any(x == stems[-1]
for x in ['gz', 'gzip', 'bz', 'bz2']):
return '.'.join(stems[-2:])
return stems[-1]
def has_extension(exts):
def tester(x, **kwargs):
return _extension(x) in set(exts.split())
return tester
def is_hdf5(filename):
with open(filename) as infile:
return infile.read(8) == '\x89HDF\r\n\x1a\n'
def is_fits(filename):
try:
with fits.open(filename):
return True
except IOError:
return False
class LoadLog(object):
def __init__(self, path, factory, kwargs):
self.path = os.path.abspath(path)
self.factory = factory
self.kwargs = kwargs
self.components = []
self.data = []
def _log_component(self, component):
self.components.append(component)
def _log_data(self, data):
self.data.append(data)
def log(self, obj):
if isinstance(obj, Component):
self._log_component(obj)
elif isinstance(obj, Data):
self._log_data(obj)
obj._load_log = self
def id(self, component):
return self.components.index(component)
def component(self, index):
return self.components[index]
def __gluestate__(self, context):
return dict(path=self.path,
factory=context.do(self.factory),
kwargs=[list(self.kwargs.items())])
@classmethod
def __setgluestate__(cls, rec, context):
fac = context.object(rec['factory'])
kwargs = dict(*rec['kwargs'])
d = load_data(rec['path'], factory=fac, **kwargs)
return as_list(d)[0]._load_log
def load_data(path, factory=None, **kwargs):
factory = factory or auto_data
d = factory(path, **kwargs)
lbl = data_label(path)
log = LoadLog(path, factory, kwargs)
for item in as_list(d):
item.label = lbl
log.log(item)
for cid in item.primary_components:
log.log(item.get_component(cid))
return d
def data_label(path):
_, fname = os.path.split(path)
name, _ = os.path.splitext(fname)
return name
def set_default_factory(extension, factory):
for ex in extension.split():
_default_factory[ex] = factory
def get_default_factory(extension):
try:
return _default_factory[extension]
except KeyError:
return None
def find_factory(filename, **kwargs):
from ..config import data_factory
default = _default_factory.get(_extension(filename))
for func, _, identifier in data_factory:
if func is auto_data:
continue
if (func is default) and identifier(filename, **kwargs):
return func
for func, _, identifier in data_factory:
if func is auto_data:
continue
if identifier(filename, **kwargs):
return func
def auto_data(filename, *args, **kwargs):
fac = find_factory(filename, **kwargs)
if fac is None:
raise KeyError("Don't know how to open file: %s" % filename)
return fac(filename, *args, **kwargs)
auto_data.label = 'Auto'
auto_data.identifier = lambda x: True
__factories__.append(auto_data)
def gridded_data(filename, format='auto', **kwargs):
result = Data()
# Try and automatically find the format if not specified
if format == 'auto':
format = file_format(filename)
# Read in the data
if is_fits(filename):
arrays = extract_data_fits(filename, **kwargs)
header = fits.getheader(filename)
result.coords = coordinates_from_header(header)
elif is_hdf5(filename):
arrays = extract_data_hdf5(filename, **kwargs)
else:
raise Exception("Unkonwn format: %s" % format)
for component_name in arrays:
comp = Component.autotyped(arrays[component_name])
result.add_component(comp, component_name)
return result
def is_gridded_data(filename, **kwargs):
if is_hdf5(filename):
return True
if is_fits(filename):
with fits.open(filename) as hdulist:
for hdu in hdulist:
if not isinstance(hdu, (fits.PrimaryHDU, fits.ImageHDU)):
return False
return True
return False
gridded_data.label = "FITS/HDF5 Image"
gridded_data.identifier = is_gridded_data
__factories__.append(gridded_data)
set_default_factory('fits', gridded_data)
set_default_factory('hd5', gridded_data)
set_default_factory('hdf5', gridded_data)
def casalike_cube(filename, **kwargs):
result = Data()
with fits.open(filename, **kwargs) as hdulist:
array = hdulist[0].data
header = hdulist[0].header
result.coords = coordinates_from_header(header)
for i in range(array.shape[0]):
result.add_component(array[[i]], label='STOKES %i' % i)
return result
def is_casalike(filename, **kwargs):
if not is_fits(filename):
return False
with fits.open(filename) as hdulist:
if len(hdulist) != 1:
return False
if hdulist[0].header['NAXIS'] != 4:
return False
from astropy.wcs import WCS
w = WCS(hdulist[0].header)
ax = [a.get('coordinate_type') for a in w.get_axis_types()]
return ax == ['celestial', 'celestial', 'spectral', 'stokes']
casalike_cube.label = 'CASA PPV Cube'
casalike_cube.identifier = is_casalike
def _ascii_identifier_v02(origin, args, kwargs):
# this works for astropy v0.2
if isinstance(args[0], basestring):
return args[0].endswith(('csv', 'tsv', 'txt', 'tbl', 'dat',
'csv.gz', 'tsv.gz', 'txt.gz', 'tbl.gz',
'dat.gz'))
else:
return False
def _ascii_identifier_v03(origin, *args, **kwargs):
# this works for astropy v0.3
return _ascii_identifier_v02(origin, args, kwargs)
def tabular_data(*args, **kwargs):
from distutils.version import LooseVersion
from astropy import __version__
if LooseVersion(__version__) < LooseVersion("0.2"):
raise RuntimeError("Glue requires astropy >= v0.2. Please update")
result = Data()
# Read the table
from astropy.table import Table
# Add identifiers for ASCII data
from astropy.io import registry
if LooseVersion(__version__) < LooseVersion("0.3"):
registry.register_identifier('ascii', Table, _ascii_identifier_v02,
force=True)
else:
registry.register_identifier('ascii', Table, _ascii_identifier_v03,
force=True)
# Clobber the identifier
# added in astropy/astropy/pull/1935
registry.register_identifier('ascii.csv', Table, lambda *a, **k: False,
force=True)
# Import FITS compatibility (for Astropy 0.2.x)
from ..external import fits_io
table = Table.read(*args, **kwargs)
# Loop through columns and make component list
for column_name in table.columns:
c = table[column_name]
u = c.units
if table.masked:
# fill array for now
try:
c = c.filled(fill_value=np.nan)
except ValueError: # assigning nan to integer dtype
c = c.filled(fill_value=-1)
nc = Component.autotyped(c, units=u)
result.add_component(nc, column_name)
return result
tabular_data.label = "Catalog"
tabular_data.identifier = has_extension('xml vot csv txt tsv tbl dat fits '
'xml.gz vot.gz csv.gz txt.gz tbl.bz '
'dat.gz fits.gz')
__factories__.append(tabular_data)
set_default_factory('xml', tabular_data)
set_default_factory('vot', tabular_data)
set_default_factory('csv', tabular_data)
set_default_factory('txt', tabular_data)
set_default_factory('tsv', tabular_data)
set_default_factory('tbl', tabular_data)
set_default_factory('dat', tabular_data)
def panda_process(indf):
result = Data()
for name, column in indf.iteritems():
if (column.dtype == np.object) | (column.dtype == np.bool):
# pandas has a 'special' nan implementation and this doesn't
c = CategoricalComponent(column.fillna(np.nan))
else:
c = Component(column.values)
result.add_component(c, name)
return result
def panda_read_excel(path, sheet='Sheet1', **kwargs):
try:
import pandas as pd
except ImportError:
raise ImportError('Pandas is required for Excel input.')
indf = pd.read_excel(path, sheet, **kwargs)
return panda_process(indf)
panda_read_excel.label = "Excel"
panda_read_excel.identifier = has_extension('xls xlsx')
__factories__.append(panda_read_excel)
set_default_factory('xls', panda_read_excel)
set_default_factory('xlsx', panda_read_excel)
def pandas_read_table(path, **kwargs):
import pandas as pd
delimiters = kwargs.pop('delimiter', [None] + list(',|\t '))
fallback = None
for d in delimiters:
try:
indf = pd.read_csv(path, delimiter=d, **kwargs)
if len(indf) == 0:
continue
if len(indf.columns) < 2:
fallback = indf
continue
return panda_process(indf)
except pd._parser.CParserError:
continue
if fallback is not None:
return panda_process(fallback)
raise IOError("Could not parse %s using pandas" % path)
pandas_read_table.label = "Pandas Table"
pandas_read_table.identifier = has_extension('csv csv txt tsv tbl dat')
__factories__.append(pandas_read_table)
img_fmt = ['jpg', 'jpeg', 'bmp', 'png', 'tiff', 'tif']
def img_loader(file_name):
try:
from skimage.io import imread
return np.asarray(imread(file_name))
except ImportError:
pass
try:
from PIL import Image
return np.asarray(Image.open(file_name))
except ImportError:
raise ImportError("Reading %s requires PIL or scikit-image" %
file_name)
def img_data(file_name):
result = Data()
data = img_loader(file_name)
data = np.flipud(data)
shp = data.shape
comps = []
labels = []
# split 3 color images into each color plane
if len(shp) == 3 and shp[2] in [3, 4]:
comps.extend([data[:, :, 0], data[:, :, 1], data[:, :, 2]])
labels.extend(['red', 'green', 'blue'])
if shp[2] == 4:
comps.append(data[:, :, 3])
labels.append('alpha')
else:
comps = [data]
labels = ['PRIMARY']
# look for AVM coordinate metadata
try:
from pyavm import AVM
avm = AVM(str(file_name)) # avoid unicode
wcs = avm.to_wcs()
except:
pass
else:
result.coords = coordinates_from_wcs(wcs)
for c, l in zip(comps, labels):
result.add_component(c, l)
return result
img_data.label = "Image"
img_data.identifier = has_extension(' '.join(img_fmt))
for i in img_fmt:
set_default_factory(i, img_data)
__factories__.append(img_data)
__factories__.append(casalike_cube)
| true | true |
1c36e9fd3666e12b3eadb3fbf7b629db8e79ecb0 | 10,742 | py | Python | nova/tests/unit/virt/test_virt.py | tbreeds/nova | 3f8c69b2ef3eef886e36c0b7f397b83a36a7beb8 | [
"Apache-2.0"
] | null | null | null | nova/tests/unit/virt/test_virt.py | tbreeds/nova | 3f8c69b2ef3eef886e36c0b7f397b83a36a7beb8 | [
"Apache-2.0"
] | null | null | null | nova/tests/unit/virt/test_virt.py | tbreeds/nova | 3f8c69b2ef3eef886e36c0b7f397b83a36a7beb8 | [
"Apache-2.0"
] | null | null | null | # Copyright 2011 Isaku Yamahata
# 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.
import io
import os
import mock
import six
from nova import test
from nova import utils
from nova.virt.disk import api as disk_api
from nova.virt.disk.mount import api as mount
from nova.virt import driver
PROC_MOUNTS_CONTENTS = """rootfs / rootfs rw 0 0
sysfs /sys sysfs rw,nosuid,nodev,noexec,relatime 0 0
proc /proc proc rw,nosuid,nodev,noexec,relatime 0 0
udev /dev devtmpfs rw,relatime,size=1013160k,nr_inodes=253290,mode=755 0 0
devpts /dev/pts devpts rw,nosuid,noexec,relatime,gid=5,mode=620 0 0
tmpfs /run tmpfs rw,nosuid,relatime,size=408904k,mode=755 0 0"""
class TestVirtDriver(test.NoDBTestCase):
def test_block_device(self):
swap = {'device_name': '/dev/sdb',
'swap_size': 1}
ephemerals = [{'num': 0,
'virtual_name': 'ephemeral0',
'device_name': '/dev/sdc1',
'size': 1}]
block_device_mapping = [{'mount_device': '/dev/sde',
'device_path': 'fake_device'}]
block_device_info = {
'root_device_name': '/dev/sda',
'swap': swap,
'ephemerals': ephemerals,
'block_device_mapping': block_device_mapping}
empty_block_device_info = {}
self.assertEqual(
driver.block_device_info_get_root(block_device_info), '/dev/sda')
self.assertIsNone(
driver.block_device_info_get_root(empty_block_device_info))
self.assertIsNone(driver.block_device_info_get_root(None))
self.assertEqual(
driver.block_device_info_get_swap(block_device_info), swap)
self.assertIsNone(driver.block_device_info_get_swap(
empty_block_device_info)['device_name'])
self.assertEqual(driver.block_device_info_get_swap(
empty_block_device_info)['swap_size'], 0)
self.assertIsNone(
driver.block_device_info_get_swap({'swap': None})['device_name'])
self.assertEqual(
driver.block_device_info_get_swap({'swap': None})['swap_size'],
0)
self.assertIsNone(
driver.block_device_info_get_swap(None)['device_name'])
self.assertEqual(
driver.block_device_info_get_swap(None)['swap_size'], 0)
self.assertEqual(
driver.block_device_info_get_ephemerals(block_device_info),
ephemerals)
self.assertEqual(
driver.block_device_info_get_ephemerals(empty_block_device_info),
[])
self.assertEqual(
driver.block_device_info_get_ephemerals(None),
[])
def test_swap_is_usable(self):
self.assertFalse(driver.swap_is_usable(None))
self.assertFalse(driver.swap_is_usable({'device_name': None}))
self.assertFalse(driver.swap_is_usable({'device_name': '/dev/sdb',
'swap_size': 0}))
self.assertTrue(driver.swap_is_usable({'device_name': '/dev/sdb',
'swap_size': 1}))
class FakeMount(object):
def __init__(self, image, mount_dir, partition=None, device=None):
self.image = image
self.partition = partition
self.mount_dir = mount_dir
self.linked = self.mapped = self.mounted = False
self.device = device
def do_mount(self):
self.linked = True
self.mapped = True
self.mounted = True
self.device = '/dev/fake'
return True
def do_umount(self):
self.linked = True
self.mounted = False
def do_teardown(self):
self.linked = False
self.mapped = False
self.mounted = False
self.device = None
class TestDiskImage(test.NoDBTestCase):
def mock_proc_mounts(self, mock_open):
response = io.StringIO(six.text_type(PROC_MOUNTS_CONTENTS))
mock_open.return_value = response
@mock.patch.object(six.moves.builtins, 'open')
def test_mount(self, mock_open):
self.mock_proc_mounts(mock_open)
image = '/tmp/fake-image'
mountdir = '/mnt/fake_rootfs'
fakemount = FakeMount(image, mountdir, None)
def fake_instance_for_format(image, mountdir, partition):
return fakemount
self.stubs.Set(mount.Mount, 'instance_for_format',
staticmethod(fake_instance_for_format))
diskimage = disk_api._DiskImage(image=image, mount_dir=mountdir)
dev = diskimage.mount()
self.assertEqual(diskimage._mounter, fakemount)
self.assertEqual(dev, '/dev/fake')
@mock.patch.object(six.moves.builtins, 'open')
def test_umount(self, mock_open):
self.mock_proc_mounts(mock_open)
image = '/tmp/fake-image'
mountdir = '/mnt/fake_rootfs'
fakemount = FakeMount(image, mountdir, None)
def fake_instance_for_format(image, mountdir, partition):
return fakemount
self.stubs.Set(mount.Mount, 'instance_for_format',
staticmethod(fake_instance_for_format))
diskimage = disk_api._DiskImage(image=image, mount_dir=mountdir)
dev = diskimage.mount()
self.assertEqual(diskimage._mounter, fakemount)
self.assertEqual(dev, '/dev/fake')
diskimage.umount()
self.assertIsNone(diskimage._mounter)
@mock.patch.object(six.moves.builtins, 'open')
def test_teardown(self, mock_open):
self.mock_proc_mounts(mock_open)
image = '/tmp/fake-image'
mountdir = '/mnt/fake_rootfs'
fakemount = FakeMount(image, mountdir, None)
def fake_instance_for_format(image, mountdir, partition):
return fakemount
self.stubs.Set(mount.Mount, 'instance_for_format',
staticmethod(fake_instance_for_format))
diskimage = disk_api._DiskImage(image=image, mount_dir=mountdir)
dev = diskimage.mount()
self.assertEqual(diskimage._mounter, fakemount)
self.assertEqual(dev, '/dev/fake')
diskimage.teardown()
self.assertIsNone(diskimage._mounter)
class TestVirtDisk(test.NoDBTestCase):
def setUp(self):
super(TestVirtDisk, self).setUp()
self.executes = []
def fake_execute(*cmd, **kwargs):
self.executes.append(cmd)
return None, None
self.stubs.Set(utils, 'execute', fake_execute)
def test_lxc_setup_container(self):
image = '/tmp/fake-image'
container_dir = '/mnt/fake_rootfs/'
def proc_mounts(self, mount_point):
return None
def fake_instance_for_format(image, mountdir, partition):
return FakeMount(image, mountdir, partition)
self.stubs.Set(os.path, 'exists', lambda _: True)
self.stubs.Set(disk_api._DiskImage, '_device_for_path', proc_mounts)
self.stubs.Set(mount.Mount, 'instance_for_format',
staticmethod(fake_instance_for_format))
self.assertEqual(disk_api.setup_container(image, container_dir),
'/dev/fake')
def test_lxc_teardown_container(self):
def proc_mounts(self, mount_point):
mount_points = {
'/mnt/loop/nopart': '/dev/loop0',
'/mnt/loop/part': '/dev/mapper/loop0p1',
'/mnt/nbd/nopart': '/dev/nbd15',
'/mnt/nbd/part': '/dev/mapper/nbd15p1',
}
return mount_points[mount_point]
self.stubs.Set(os.path, 'exists', lambda _: True)
self.stubs.Set(disk_api._DiskImage, '_device_for_path', proc_mounts)
expected_commands = []
disk_api.teardown_container('/mnt/loop/nopart')
expected_commands += [
('umount', '/dev/loop0'),
('losetup', '--detach', '/dev/loop0'),
]
disk_api.teardown_container('/mnt/loop/part')
expected_commands += [
('umount', '/dev/mapper/loop0p1'),
('kpartx', '-d', '/dev/loop0'),
('losetup', '--detach', '/dev/loop0'),
]
disk_api.teardown_container('/mnt/nbd/nopart')
expected_commands += [
('blockdev', '--flushbufs', '/dev/nbd15'),
('umount', '/dev/nbd15'),
('qemu-nbd', '-d', '/dev/nbd15'),
]
disk_api.teardown_container('/mnt/nbd/part')
expected_commands += [
('blockdev', '--flushbufs', '/dev/nbd15'),
('umount', '/dev/mapper/nbd15p1'),
('kpartx', '-d', '/dev/nbd15'),
('qemu-nbd', '-d', '/dev/nbd15'),
]
self.assertEqual(self.executes, expected_commands)
def test_lxc_teardown_container_with_namespace_cleaned(self):
def proc_mounts(self, mount_point):
return None
self.stubs.Set(os.path, 'exists', lambda _: True)
self.stubs.Set(disk_api._DiskImage, '_device_for_path', proc_mounts)
expected_commands = []
disk_api.teardown_container('/mnt/loop/nopart', '/dev/loop0')
expected_commands += [
('losetup', '--detach', '/dev/loop0'),
]
disk_api.teardown_container('/mnt/loop/part', '/dev/loop0')
expected_commands += [
('losetup', '--detach', '/dev/loop0'),
]
disk_api.teardown_container('/mnt/nbd/nopart', '/dev/nbd15')
expected_commands += [
('qemu-nbd', '-d', '/dev/nbd15'),
]
disk_api.teardown_container('/mnt/nbd/part', '/dev/nbd15')
expected_commands += [
('qemu-nbd', '-d', '/dev/nbd15'),
]
self.assertEqual(self.executes, expected_commands)
| 37.16955 | 78 | 0.588345 |
import io
import os
import mock
import six
from nova import test
from nova import utils
from nova.virt.disk import api as disk_api
from nova.virt.disk.mount import api as mount
from nova.virt import driver
PROC_MOUNTS_CONTENTS = """rootfs / rootfs rw 0 0
sysfs /sys sysfs rw,nosuid,nodev,noexec,relatime 0 0
proc /proc proc rw,nosuid,nodev,noexec,relatime 0 0
udev /dev devtmpfs rw,relatime,size=1013160k,nr_inodes=253290,mode=755 0 0
devpts /dev/pts devpts rw,nosuid,noexec,relatime,gid=5,mode=620 0 0
tmpfs /run tmpfs rw,nosuid,relatime,size=408904k,mode=755 0 0"""
class TestVirtDriver(test.NoDBTestCase):
def test_block_device(self):
swap = {'device_name': '/dev/sdb',
'swap_size': 1}
ephemerals = [{'num': 0,
'virtual_name': 'ephemeral0',
'device_name': '/dev/sdc1',
'size': 1}]
block_device_mapping = [{'mount_device': '/dev/sde',
'device_path': 'fake_device'}]
block_device_info = {
'root_device_name': '/dev/sda',
'swap': swap,
'ephemerals': ephemerals,
'block_device_mapping': block_device_mapping}
empty_block_device_info = {}
self.assertEqual(
driver.block_device_info_get_root(block_device_info), '/dev/sda')
self.assertIsNone(
driver.block_device_info_get_root(empty_block_device_info))
self.assertIsNone(driver.block_device_info_get_root(None))
self.assertEqual(
driver.block_device_info_get_swap(block_device_info), swap)
self.assertIsNone(driver.block_device_info_get_swap(
empty_block_device_info)['device_name'])
self.assertEqual(driver.block_device_info_get_swap(
empty_block_device_info)['swap_size'], 0)
self.assertIsNone(
driver.block_device_info_get_swap({'swap': None})['device_name'])
self.assertEqual(
driver.block_device_info_get_swap({'swap': None})['swap_size'],
0)
self.assertIsNone(
driver.block_device_info_get_swap(None)['device_name'])
self.assertEqual(
driver.block_device_info_get_swap(None)['swap_size'], 0)
self.assertEqual(
driver.block_device_info_get_ephemerals(block_device_info),
ephemerals)
self.assertEqual(
driver.block_device_info_get_ephemerals(empty_block_device_info),
[])
self.assertEqual(
driver.block_device_info_get_ephemerals(None),
[])
def test_swap_is_usable(self):
self.assertFalse(driver.swap_is_usable(None))
self.assertFalse(driver.swap_is_usable({'device_name': None}))
self.assertFalse(driver.swap_is_usable({'device_name': '/dev/sdb',
'swap_size': 0}))
self.assertTrue(driver.swap_is_usable({'device_name': '/dev/sdb',
'swap_size': 1}))
class FakeMount(object):
def __init__(self, image, mount_dir, partition=None, device=None):
self.image = image
self.partition = partition
self.mount_dir = mount_dir
self.linked = self.mapped = self.mounted = False
self.device = device
def do_mount(self):
self.linked = True
self.mapped = True
self.mounted = True
self.device = '/dev/fake'
return True
def do_umount(self):
self.linked = True
self.mounted = False
def do_teardown(self):
self.linked = False
self.mapped = False
self.mounted = False
self.device = None
class TestDiskImage(test.NoDBTestCase):
def mock_proc_mounts(self, mock_open):
response = io.StringIO(six.text_type(PROC_MOUNTS_CONTENTS))
mock_open.return_value = response
@mock.patch.object(six.moves.builtins, 'open')
def test_mount(self, mock_open):
self.mock_proc_mounts(mock_open)
image = '/tmp/fake-image'
mountdir = '/mnt/fake_rootfs'
fakemount = FakeMount(image, mountdir, None)
def fake_instance_for_format(image, mountdir, partition):
return fakemount
self.stubs.Set(mount.Mount, 'instance_for_format',
staticmethod(fake_instance_for_format))
diskimage = disk_api._DiskImage(image=image, mount_dir=mountdir)
dev = diskimage.mount()
self.assertEqual(diskimage._mounter, fakemount)
self.assertEqual(dev, '/dev/fake')
@mock.patch.object(six.moves.builtins, 'open')
def test_umount(self, mock_open):
self.mock_proc_mounts(mock_open)
image = '/tmp/fake-image'
mountdir = '/mnt/fake_rootfs'
fakemount = FakeMount(image, mountdir, None)
def fake_instance_for_format(image, mountdir, partition):
return fakemount
self.stubs.Set(mount.Mount, 'instance_for_format',
staticmethod(fake_instance_for_format))
diskimage = disk_api._DiskImage(image=image, mount_dir=mountdir)
dev = diskimage.mount()
self.assertEqual(diskimage._mounter, fakemount)
self.assertEqual(dev, '/dev/fake')
diskimage.umount()
self.assertIsNone(diskimage._mounter)
@mock.patch.object(six.moves.builtins, 'open')
def test_teardown(self, mock_open):
self.mock_proc_mounts(mock_open)
image = '/tmp/fake-image'
mountdir = '/mnt/fake_rootfs'
fakemount = FakeMount(image, mountdir, None)
def fake_instance_for_format(image, mountdir, partition):
return fakemount
self.stubs.Set(mount.Mount, 'instance_for_format',
staticmethod(fake_instance_for_format))
diskimage = disk_api._DiskImage(image=image, mount_dir=mountdir)
dev = diskimage.mount()
self.assertEqual(diskimage._mounter, fakemount)
self.assertEqual(dev, '/dev/fake')
diskimage.teardown()
self.assertIsNone(diskimage._mounter)
class TestVirtDisk(test.NoDBTestCase):
def setUp(self):
super(TestVirtDisk, self).setUp()
self.executes = []
def fake_execute(*cmd, **kwargs):
self.executes.append(cmd)
return None, None
self.stubs.Set(utils, 'execute', fake_execute)
def test_lxc_setup_container(self):
image = '/tmp/fake-image'
container_dir = '/mnt/fake_rootfs/'
def proc_mounts(self, mount_point):
return None
def fake_instance_for_format(image, mountdir, partition):
return FakeMount(image, mountdir, partition)
self.stubs.Set(os.path, 'exists', lambda _: True)
self.stubs.Set(disk_api._DiskImage, '_device_for_path', proc_mounts)
self.stubs.Set(mount.Mount, 'instance_for_format',
staticmethod(fake_instance_for_format))
self.assertEqual(disk_api.setup_container(image, container_dir),
'/dev/fake')
def test_lxc_teardown_container(self):
def proc_mounts(self, mount_point):
mount_points = {
'/mnt/loop/nopart': '/dev/loop0',
'/mnt/loop/part': '/dev/mapper/loop0p1',
'/mnt/nbd/nopart': '/dev/nbd15',
'/mnt/nbd/part': '/dev/mapper/nbd15p1',
}
return mount_points[mount_point]
self.stubs.Set(os.path, 'exists', lambda _: True)
self.stubs.Set(disk_api._DiskImage, '_device_for_path', proc_mounts)
expected_commands = []
disk_api.teardown_container('/mnt/loop/nopart')
expected_commands += [
('umount', '/dev/loop0'),
('losetup', '--detach', '/dev/loop0'),
]
disk_api.teardown_container('/mnt/loop/part')
expected_commands += [
('umount', '/dev/mapper/loop0p1'),
('kpartx', '-d', '/dev/loop0'),
('losetup', '--detach', '/dev/loop0'),
]
disk_api.teardown_container('/mnt/nbd/nopart')
expected_commands += [
('blockdev', '--flushbufs', '/dev/nbd15'),
('umount', '/dev/nbd15'),
('qemu-nbd', '-d', '/dev/nbd15'),
]
disk_api.teardown_container('/mnt/nbd/part')
expected_commands += [
('blockdev', '--flushbufs', '/dev/nbd15'),
('umount', '/dev/mapper/nbd15p1'),
('kpartx', '-d', '/dev/nbd15'),
('qemu-nbd', '-d', '/dev/nbd15'),
]
self.assertEqual(self.executes, expected_commands)
def test_lxc_teardown_container_with_namespace_cleaned(self):
def proc_mounts(self, mount_point):
return None
self.stubs.Set(os.path, 'exists', lambda _: True)
self.stubs.Set(disk_api._DiskImage, '_device_for_path', proc_mounts)
expected_commands = []
disk_api.teardown_container('/mnt/loop/nopart', '/dev/loop0')
expected_commands += [
('losetup', '--detach', '/dev/loop0'),
]
disk_api.teardown_container('/mnt/loop/part', '/dev/loop0')
expected_commands += [
('losetup', '--detach', '/dev/loop0'),
]
disk_api.teardown_container('/mnt/nbd/nopart', '/dev/nbd15')
expected_commands += [
('qemu-nbd', '-d', '/dev/nbd15'),
]
disk_api.teardown_container('/mnt/nbd/part', '/dev/nbd15')
expected_commands += [
('qemu-nbd', '-d', '/dev/nbd15'),
]
self.assertEqual(self.executes, expected_commands)
| true | true |
1c36ec208d4e62cb07ff717e7f701420ea7a2ba1 | 9,542 | py | Python | manila/tests/volume/test_cinder.py | redhat-openstack/manila | bef43561b303a36d99849952ba8c408b19bafd02 | [
"Apache-2.0"
] | null | null | null | manila/tests/volume/test_cinder.py | redhat-openstack/manila | bef43561b303a36d99849952ba8c408b19bafd02 | [
"Apache-2.0"
] | null | null | null | manila/tests/volume/test_cinder.py | redhat-openstack/manila | bef43561b303a36d99849952ba8c408b19bafd02 | [
"Apache-2.0"
] | null | null | null | # Copyright 2014 Mirantis, 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 cinderclient import exceptions as cinder_exception
import ddt
import mock
from manila import context
from manila import exception
from manila import test
from manila.volume import cinder
class FakeCinderClient(object):
class Volumes(object):
def get(self, volume_id):
return {'id': volume_id}
def list(self, detailed, search_opts={}):
return [{'id': 'id1'}, {'id': 'id2'}]
def create(self, *args, **kwargs):
return {'id': 'created_id'}
def __getattr__(self, item):
return None
def __init__(self):
self.volumes = self.Volumes()
self.volume_snapshots = self.volumes
@ddt.ddt
class CinderApiTestCase(test.TestCase):
def setUp(self):
super(CinderApiTestCase, self).setUp()
self.api = cinder.API()
self.cinderclient = FakeCinderClient()
self.ctx = context.get_admin_context()
self.mock_object(cinder, 'cinderclient',
mock.Mock(return_value=self.cinderclient))
self.mock_object(cinder, '_untranslate_volume_summary_view',
lambda ctx, vol: vol)
self.mock_object(cinder, '_untranslate_snapshot_summary_view',
lambda ctx, snap: snap)
def test_get(self):
volume_id = 'volume_id1'
result = self.api.get(self.ctx, volume_id)
self.assertEqual(result['id'], volume_id)
@ddt.data(
{'cinder_e': cinder_exception.NotFound(404),
'manila_e': exception.VolumeNotFound},
{'cinder_e': cinder_exception.BadRequest(400),
'manila_e': exception.InvalidInput},
)
@ddt.unpack
def test_get_failed(self, cinder_e, manila_e):
cinder.cinderclient.side_effect = cinder_e
volume_id = 'volume_id'
self.assertRaises(manila_e, self.api.get, self.ctx, volume_id)
def test_create(self):
result = self.api.create(self.ctx, 1, '', '')
self.assertEqual(result['id'], 'created_id')
def test_create_failed(self):
cinder.cinderclient.side_effect = cinder_exception.BadRequest(400)
self.assertRaises(exception.InvalidInput,
self.api.create, self.ctx, 1, '', '')
def test_create_not_found_error(self):
cinder.cinderclient.side_effect = cinder_exception.NotFound(404)
self.assertRaises(exception.NotFound,
self.api.create, self.ctx, 1, '', '')
def test_create_failed_exception(self):
cinder.cinderclient.side_effect = Exception("error msg")
self.assertRaises(exception.ManilaException,
self.api.create, self.ctx, 1, '', '')
def test_get_all(self):
cinder._untranslate_volume_summary_view.return_value = ['id1', 'id2']
self.assertEqual([{'id': 'id1'}, {'id': 'id2'}],
self.api.get_all(self.ctx))
def test_check_attach_volume_status_error(self):
volume = {'status': 'error'}
self.assertRaises(exception.InvalidVolume,
self.api.check_attach, self.ctx, volume)
def test_check_attach_volume_already_attached(self):
volume = {'status': 'available'}
volume['attach_status'] = "attached"
self.assertRaises(exception.InvalidVolume,
self.api.check_attach, self.ctx, volume)
def test_check_attach_availability_zone_differs(self):
volume = {'status': 'available'}
volume['attach_status'] = "detached"
instance = {'availability_zone': 'zone1'}
volume['availability_zone'] = 'zone2'
cinder.CONF.set_override('cinder_cross_az_attach', False)
self.assertRaises(exception.InvalidVolume,
self.api.check_attach, self.ctx, volume, instance)
volume['availability_zone'] = 'zone1'
self.assertIsNone(self.api.check_attach(self.ctx, volume, instance))
cinder.CONF.reset()
def test_check_attach(self):
volume = {'status': 'available'}
volume['attach_status'] = "detached"
volume['availability_zone'] = 'zone1'
instance = {'availability_zone': 'zone1'}
cinder.CONF.set_override('cinder_cross_az_attach', False)
self.assertIsNone(self.api.check_attach(self.ctx, volume, instance))
cinder.CONF.reset()
def test_check_detach(self):
volume = {'status': 'available'}
self.assertRaises(exception.InvalidVolume,
self.api.check_detach, self.ctx, volume)
volume['status'] = 'non-available'
self.assertIsNone(self.api.check_detach(self.ctx, volume))
def test_update(self):
fake_volume = {'fake': 'fake'}
self.mock_object(self.cinderclient.volumes, 'get',
mock.Mock(return_value=fake_volume))
self.mock_object(self.cinderclient.volumes, 'update')
fake_volume_id = 'fake_volume'
fake_data = {'test': 'test'}
self.api.update(self.ctx, fake_volume_id, fake_data)
self.cinderclient.volumes.get.assert_called_once_with(fake_volume_id)
self.cinderclient.volumes.update.assert_called_once_with(fake_volume,
**fake_data)
def test_reserve_volume(self):
self.mock_object(self.cinderclient.volumes, 'reserve')
self.api.reserve_volume(self.ctx, 'id1')
self.cinderclient.volumes.reserve.assert_called_once_with('id1')
def test_unreserve_volume(self):
self.mock_object(self.cinderclient.volumes, 'unreserve')
self.api.unreserve_volume(self.ctx, 'id1')
self.cinderclient.volumes.unreserve.assert_called_once_with('id1')
def test_begin_detaching(self):
self.mock_object(self.cinderclient.volumes, 'begin_detaching')
self.api.begin_detaching(self.ctx, 'id1')
self.cinderclient.volumes.begin_detaching.assert_called_once_with(
'id1')
def test_roll_detaching(self):
self.mock_object(self.cinderclient.volumes, 'roll_detaching')
self.api.roll_detaching(self.ctx, 'id1')
self.cinderclient.volumes.roll_detaching.assert_called_once_with('id1')
def test_attach(self):
self.mock_object(self.cinderclient.volumes, 'attach')
self.api.attach(self.ctx, 'id1', 'uuid', 'point')
self.cinderclient.volumes.attach.assert_called_once_with('id1',
'uuid',
'point')
def test_detach(self):
self.mock_object(self.cinderclient.volumes, 'detach')
self.api.detach(self.ctx, 'id1')
self.cinderclient.volumes.detach.assert_called_once_with('id1')
def test_initialize_connection(self):
self.mock_object(self.cinderclient.volumes, 'initialize_connection')
self.api.initialize_connection(self.ctx, 'id1', 'connector')
self.cinderclient.volumes.initialize_connection.\
assert_called_once_with('id1', 'connector')
def test_terminate_connection(self):
self.mock_object(self.cinderclient.volumes, 'terminate_connection')
self.api.terminate_connection(self.ctx, 'id1', 'connector')
self.cinderclient.volumes.terminate_connection.\
assert_called_once_with('id1', 'connector')
def test_delete(self):
self.mock_object(self.cinderclient.volumes, 'delete')
self.api.delete(self.ctx, 'id1')
self.cinderclient.volumes.delete.assert_called_once_with('id1')
def test_get_snapshot(self):
snapshot_id = 'snapshot_id1'
result = self.api.get_snapshot(self.ctx, snapshot_id)
self.assertEqual(result['id'], snapshot_id)
def test_get_snapshot_failed(self):
cinder.cinderclient.side_effect = cinder_exception.NotFound(404)
snapshot_id = 'snapshot_id'
self.assertRaises(exception.VolumeSnapshotNotFound,
self.api.get_snapshot, self.ctx, snapshot_id)
def test_get_all_snapshots(self):
cinder._untranslate_snapshot_summary_view.return_value = ['id1', 'id2']
self.assertEqual([{'id': 'id1'}, {'id': 'id2'}],
self.api.get_all_snapshots(self.ctx))
def test_create_snapshot(self):
result = self.api.create_snapshot(self.ctx, {'id': 'id1'}, '', '')
self.assertEqual(result['id'], 'created_id')
def test_create_force(self):
result = self.api.create_snapshot_force(self.ctx,
{'id': 'id1'}, '', '')
self.assertEqual(result['id'], 'created_id')
def test_delete_snapshot(self):
self.mock_object(self.cinderclient.volume_snapshots, 'delete')
self.api.delete_snapshot(self.ctx, 'id1')
self.cinderclient.volume_snapshots.delete.assert_called_once_with(
'id1')
| 40.95279 | 79 | 0.642318 |
from cinderclient import exceptions as cinder_exception
import ddt
import mock
from manila import context
from manila import exception
from manila import test
from manila.volume import cinder
class FakeCinderClient(object):
class Volumes(object):
def get(self, volume_id):
return {'id': volume_id}
def list(self, detailed, search_opts={}):
return [{'id': 'id1'}, {'id': 'id2'}]
def create(self, *args, **kwargs):
return {'id': 'created_id'}
def __getattr__(self, item):
return None
def __init__(self):
self.volumes = self.Volumes()
self.volume_snapshots = self.volumes
@ddt.ddt
class CinderApiTestCase(test.TestCase):
def setUp(self):
super(CinderApiTestCase, self).setUp()
self.api = cinder.API()
self.cinderclient = FakeCinderClient()
self.ctx = context.get_admin_context()
self.mock_object(cinder, 'cinderclient',
mock.Mock(return_value=self.cinderclient))
self.mock_object(cinder, '_untranslate_volume_summary_view',
lambda ctx, vol: vol)
self.mock_object(cinder, '_untranslate_snapshot_summary_view',
lambda ctx, snap: snap)
def test_get(self):
volume_id = 'volume_id1'
result = self.api.get(self.ctx, volume_id)
self.assertEqual(result['id'], volume_id)
@ddt.data(
{'cinder_e': cinder_exception.NotFound(404),
'manila_e': exception.VolumeNotFound},
{'cinder_e': cinder_exception.BadRequest(400),
'manila_e': exception.InvalidInput},
)
@ddt.unpack
def test_get_failed(self, cinder_e, manila_e):
cinder.cinderclient.side_effect = cinder_e
volume_id = 'volume_id'
self.assertRaises(manila_e, self.api.get, self.ctx, volume_id)
def test_create(self):
result = self.api.create(self.ctx, 1, '', '')
self.assertEqual(result['id'], 'created_id')
def test_create_failed(self):
cinder.cinderclient.side_effect = cinder_exception.BadRequest(400)
self.assertRaises(exception.InvalidInput,
self.api.create, self.ctx, 1, '', '')
def test_create_not_found_error(self):
cinder.cinderclient.side_effect = cinder_exception.NotFound(404)
self.assertRaises(exception.NotFound,
self.api.create, self.ctx, 1, '', '')
def test_create_failed_exception(self):
cinder.cinderclient.side_effect = Exception("error msg")
self.assertRaises(exception.ManilaException,
self.api.create, self.ctx, 1, '', '')
def test_get_all(self):
cinder._untranslate_volume_summary_view.return_value = ['id1', 'id2']
self.assertEqual([{'id': 'id1'}, {'id': 'id2'}],
self.api.get_all(self.ctx))
def test_check_attach_volume_status_error(self):
volume = {'status': 'error'}
self.assertRaises(exception.InvalidVolume,
self.api.check_attach, self.ctx, volume)
def test_check_attach_volume_already_attached(self):
volume = {'status': 'available'}
volume['attach_status'] = "attached"
self.assertRaises(exception.InvalidVolume,
self.api.check_attach, self.ctx, volume)
def test_check_attach_availability_zone_differs(self):
volume = {'status': 'available'}
volume['attach_status'] = "detached"
instance = {'availability_zone': 'zone1'}
volume['availability_zone'] = 'zone2'
cinder.CONF.set_override('cinder_cross_az_attach', False)
self.assertRaises(exception.InvalidVolume,
self.api.check_attach, self.ctx, volume, instance)
volume['availability_zone'] = 'zone1'
self.assertIsNone(self.api.check_attach(self.ctx, volume, instance))
cinder.CONF.reset()
def test_check_attach(self):
volume = {'status': 'available'}
volume['attach_status'] = "detached"
volume['availability_zone'] = 'zone1'
instance = {'availability_zone': 'zone1'}
cinder.CONF.set_override('cinder_cross_az_attach', False)
self.assertIsNone(self.api.check_attach(self.ctx, volume, instance))
cinder.CONF.reset()
def test_check_detach(self):
volume = {'status': 'available'}
self.assertRaises(exception.InvalidVolume,
self.api.check_detach, self.ctx, volume)
volume['status'] = 'non-available'
self.assertIsNone(self.api.check_detach(self.ctx, volume))
def test_update(self):
fake_volume = {'fake': 'fake'}
self.mock_object(self.cinderclient.volumes, 'get',
mock.Mock(return_value=fake_volume))
self.mock_object(self.cinderclient.volumes, 'update')
fake_volume_id = 'fake_volume'
fake_data = {'test': 'test'}
self.api.update(self.ctx, fake_volume_id, fake_data)
self.cinderclient.volumes.get.assert_called_once_with(fake_volume_id)
self.cinderclient.volumes.update.assert_called_once_with(fake_volume,
**fake_data)
def test_reserve_volume(self):
self.mock_object(self.cinderclient.volumes, 'reserve')
self.api.reserve_volume(self.ctx, 'id1')
self.cinderclient.volumes.reserve.assert_called_once_with('id1')
def test_unreserve_volume(self):
self.mock_object(self.cinderclient.volumes, 'unreserve')
self.api.unreserve_volume(self.ctx, 'id1')
self.cinderclient.volumes.unreserve.assert_called_once_with('id1')
def test_begin_detaching(self):
self.mock_object(self.cinderclient.volumes, 'begin_detaching')
self.api.begin_detaching(self.ctx, 'id1')
self.cinderclient.volumes.begin_detaching.assert_called_once_with(
'id1')
def test_roll_detaching(self):
self.mock_object(self.cinderclient.volumes, 'roll_detaching')
self.api.roll_detaching(self.ctx, 'id1')
self.cinderclient.volumes.roll_detaching.assert_called_once_with('id1')
def test_attach(self):
self.mock_object(self.cinderclient.volumes, 'attach')
self.api.attach(self.ctx, 'id1', 'uuid', 'point')
self.cinderclient.volumes.attach.assert_called_once_with('id1',
'uuid',
'point')
def test_detach(self):
self.mock_object(self.cinderclient.volumes, 'detach')
self.api.detach(self.ctx, 'id1')
self.cinderclient.volumes.detach.assert_called_once_with('id1')
def test_initialize_connection(self):
self.mock_object(self.cinderclient.volumes, 'initialize_connection')
self.api.initialize_connection(self.ctx, 'id1', 'connector')
self.cinderclient.volumes.initialize_connection.\
assert_called_once_with('id1', 'connector')
def test_terminate_connection(self):
self.mock_object(self.cinderclient.volumes, 'terminate_connection')
self.api.terminate_connection(self.ctx, 'id1', 'connector')
self.cinderclient.volumes.terminate_connection.\
assert_called_once_with('id1', 'connector')
def test_delete(self):
self.mock_object(self.cinderclient.volumes, 'delete')
self.api.delete(self.ctx, 'id1')
self.cinderclient.volumes.delete.assert_called_once_with('id1')
def test_get_snapshot(self):
snapshot_id = 'snapshot_id1'
result = self.api.get_snapshot(self.ctx, snapshot_id)
self.assertEqual(result['id'], snapshot_id)
def test_get_snapshot_failed(self):
cinder.cinderclient.side_effect = cinder_exception.NotFound(404)
snapshot_id = 'snapshot_id'
self.assertRaises(exception.VolumeSnapshotNotFound,
self.api.get_snapshot, self.ctx, snapshot_id)
def test_get_all_snapshots(self):
cinder._untranslate_snapshot_summary_view.return_value = ['id1', 'id2']
self.assertEqual([{'id': 'id1'}, {'id': 'id2'}],
self.api.get_all_snapshots(self.ctx))
def test_create_snapshot(self):
result = self.api.create_snapshot(self.ctx, {'id': 'id1'}, '', '')
self.assertEqual(result['id'], 'created_id')
def test_create_force(self):
result = self.api.create_snapshot_force(self.ctx,
{'id': 'id1'}, '', '')
self.assertEqual(result['id'], 'created_id')
def test_delete_snapshot(self):
self.mock_object(self.cinderclient.volume_snapshots, 'delete')
self.api.delete_snapshot(self.ctx, 'id1')
self.cinderclient.volume_snapshots.delete.assert_called_once_with(
'id1')
| true | true |
1c36ed9b5c4760c2faa95b824943b60701dc5701 | 2,189 | py | Python | babybuddy/models.py | HorizonXP/babybuddy | 88999233e8c3f02c5e8a514164a0fdc45e3ebe70 | [
"BSD-2-Clause"
] | 1 | 2019-01-27T03:50:29.000Z | 2019-01-27T03:50:29.000Z | babybuddy/models.py | HorizonXP/babybuddy | 88999233e8c3f02c5e8a514164a0fdc45e3ebe70 | [
"BSD-2-Clause"
] | 8 | 2020-02-11T23:36:13.000Z | 2022-03-11T23:37:17.000Z | babybuddy/models.py | HorizonXP/babybuddy | 88999233e8c3f02c5e8a514164a0fdc45e3ebe70 | [
"BSD-2-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils.timezone import timedelta
from rest_framework.authtoken.models import Token
class Settings(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
dashboard_refresh_rate = models.DurationField(
verbose_name='Refresh rate',
help_text='This setting will only be used when a browser does not '
'support refresh on focus.',
blank=True,
null=True,
default=timedelta(minutes=1),
choices=[
(None, 'disabled'),
(timedelta(minutes=1), '1 min.'),
(timedelta(minutes=2), '2 min.'),
(timedelta(minutes=3), '3 min.'),
(timedelta(minutes=4), '4 min.'),
(timedelta(minutes=5), '5 min.'),
(timedelta(minutes=10), '10 min.'),
(timedelta(minutes=15), '15 min.'),
(timedelta(minutes=30), '30 min.'),
])
def __str__(self):
return '{}\'s Settings'.format(self.user)
def api_key(self, reset=False):
"""
Get or create an API key for the associated user.
:param reset: If True, delete the existing key and create a new one.
:return: The user's API key.
"""
if reset:
Token.objects.get(user=self.user).delete()
return Token.objects.get_or_create(user=self.user)[0]
@property
def dashboard_refresh_rate_milliseconds(self):
"""
Convert seconds to milliseconds to be used in a Javascript setInterval
function call.
:return: the refresh rate in milliseconds or None.
"""
if self.dashboard_refresh_rate:
return self.dashboard_refresh_rate.seconds * 1000
return None
@receiver(post_save, sender=User)
def create_user_settings(sender, instance, created, **kwargs):
if created:
Settings.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_settings(sender, instance, **kwargs):
instance.settings.save()
| 33.166667 | 78 | 0.631339 |
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils.timezone import timedelta
from rest_framework.authtoken.models import Token
class Settings(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
dashboard_refresh_rate = models.DurationField(
verbose_name='Refresh rate',
help_text='This setting will only be used when a browser does not '
'support refresh on focus.',
blank=True,
null=True,
default=timedelta(minutes=1),
choices=[
(None, 'disabled'),
(timedelta(minutes=1), '1 min.'),
(timedelta(minutes=2), '2 min.'),
(timedelta(minutes=3), '3 min.'),
(timedelta(minutes=4), '4 min.'),
(timedelta(minutes=5), '5 min.'),
(timedelta(minutes=10), '10 min.'),
(timedelta(minutes=15), '15 min.'),
(timedelta(minutes=30), '30 min.'),
])
def __str__(self):
return '{}\'s Settings'.format(self.user)
def api_key(self, reset=False):
if reset:
Token.objects.get(user=self.user).delete()
return Token.objects.get_or_create(user=self.user)[0]
@property
def dashboard_refresh_rate_milliseconds(self):
if self.dashboard_refresh_rate:
return self.dashboard_refresh_rate.seconds * 1000
return None
@receiver(post_save, sender=User)
def create_user_settings(sender, instance, created, **kwargs):
if created:
Settings.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_settings(sender, instance, **kwargs):
instance.settings.save()
| true | true |
1c36ee08eadc4e8a79ddf1a224aa04fcbd9fd04e | 1,682 | py | Python | applicationDriverForRobot/thermalImagingDataCollect/server/tidc_pb2_grpc.py | dkzhang/Robot2019 | f85610832a513bd232633a028433512b85c08eae | [
"MIT"
] | null | null | null | applicationDriverForRobot/thermalImagingDataCollect/server/tidc_pb2_grpc.py | dkzhang/Robot2019 | f85610832a513bd232633a028433512b85c08eae | [
"MIT"
] | null | null | null | applicationDriverForRobot/thermalImagingDataCollect/server/tidc_pb2_grpc.py | dkzhang/Robot2019 | f85610832a513bd232633a028433512b85c08eae | [
"MIT"
] | null | null | null | # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
import tidc_pb2 as tidc__pb2
class ThermalImagingDataCollectServiceStub(object):
"""The ThermalImagingDataCollect service definition.
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.CollectThermalImagingData = channel.unary_unary(
'/thermalImagingDataCollect.ThermalImagingDataCollectService/CollectThermalImagingData',
request_serializer=tidc__pb2.ThermalImagingDataCollectRequest.SerializeToString,
response_deserializer=tidc__pb2.ThermalImagingDataCollectReply.FromString,
)
class ThermalImagingDataCollectServiceServicer(object):
"""The ThermalImagingDataCollect service definition.
"""
def CollectThermalImagingData(self, request, context):
"""Using a dataArray to render a ThermalImaging file
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_ThermalImagingDataCollectServiceServicer_to_server(servicer, server):
rpc_method_handlers = {
'CollectThermalImagingData': grpc.unary_unary_rpc_method_handler(
servicer.CollectThermalImagingData,
request_deserializer=tidc__pb2.ThermalImagingDataCollectRequest.FromString,
response_serializer=tidc__pb2.ThermalImagingDataCollectReply.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'thermalImagingDataCollect.ThermalImagingDataCollectService', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
| 35.787234 | 96 | 0.78478 |
import grpc
import tidc_pb2 as tidc__pb2
class ThermalImagingDataCollectServiceStub(object):
def __init__(self, channel):
self.CollectThermalImagingData = channel.unary_unary(
'/thermalImagingDataCollect.ThermalImagingDataCollectService/CollectThermalImagingData',
request_serializer=tidc__pb2.ThermalImagingDataCollectRequest.SerializeToString,
response_deserializer=tidc__pb2.ThermalImagingDataCollectReply.FromString,
)
class ThermalImagingDataCollectServiceServicer(object):
def CollectThermalImagingData(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_ThermalImagingDataCollectServiceServicer_to_server(servicer, server):
rpc_method_handlers = {
'CollectThermalImagingData': grpc.unary_unary_rpc_method_handler(
servicer.CollectThermalImagingData,
request_deserializer=tidc__pb2.ThermalImagingDataCollectRequest.FromString,
response_serializer=tidc__pb2.ThermalImagingDataCollectReply.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'thermalImagingDataCollect.ThermalImagingDataCollectService', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
| true | true |
1c36ef60af9973dfa95f8a932a2a3e29b3034b63 | 6,077 | py | Python | src/oci/core/models/tunnel_route_summary.py | LaudateCorpus1/oci-python-sdk | b0d3ce629d5113df4d8b83b7a6502b2c5bfa3015 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | src/oci/core/models/tunnel_route_summary.py | LaudateCorpus1/oci-python-sdk | b0d3ce629d5113df4d8b83b7a6502b2c5bfa3015 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | src/oci/core/models/tunnel_route_summary.py | LaudateCorpus1/oci-python-sdk | b0d3ce629d5113df4d8b83b7a6502b2c5bfa3015 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | # coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class TunnelRouteSummary(object):
"""
The routes advertised to the Customer and the routes received from the Customer
"""
#: A constant which can be used with the advertiser property of a TunnelRouteSummary.
#: This constant has a value of "CUSTOMER"
ADVERTISER_CUSTOMER = "CUSTOMER"
#: A constant which can be used with the advertiser property of a TunnelRouteSummary.
#: This constant has a value of "ORACLE"
ADVERTISER_ORACLE = "ORACLE"
def __init__(self, **kwargs):
"""
Initializes a new TunnelRouteSummary object with values from keyword arguments.
The following keyword arguments are supported (corresponding to the getters/setters of this class):
:param prefix:
The value to assign to the prefix property of this TunnelRouteSummary.
:type prefix: str
:param age:
The value to assign to the age property of this TunnelRouteSummary.
:type age: int
:param is_best_path:
The value to assign to the is_best_path property of this TunnelRouteSummary.
:type is_best_path: bool
:param as_path:
The value to assign to the as_path property of this TunnelRouteSummary.
:type as_path: list[int]
:param advertiser:
The value to assign to the advertiser property of this TunnelRouteSummary.
Allowed values for this property are: "CUSTOMER", "ORACLE", 'UNKNOWN_ENUM_VALUE'.
Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'.
:type advertiser: str
"""
self.swagger_types = {
'prefix': 'str',
'age': 'int',
'is_best_path': 'bool',
'as_path': 'list[int]',
'advertiser': 'str'
}
self.attribute_map = {
'prefix': 'prefix',
'age': 'age',
'is_best_path': 'isBestPath',
'as_path': 'asPath',
'advertiser': 'advertiser'
}
self._prefix = None
self._age = None
self._is_best_path = None
self._as_path = None
self._advertiser = None
@property
def prefix(self):
"""
Gets the prefix of this TunnelRouteSummary.
BGP Network Layer Reachability Information
:return: The prefix of this TunnelRouteSummary.
:rtype: str
"""
return self._prefix
@prefix.setter
def prefix(self, prefix):
"""
Sets the prefix of this TunnelRouteSummary.
BGP Network Layer Reachability Information
:param prefix: The prefix of this TunnelRouteSummary.
:type: str
"""
self._prefix = prefix
@property
def age(self):
"""
Gets the age of this TunnelRouteSummary.
The age of the route
:return: The age of this TunnelRouteSummary.
:rtype: int
"""
return self._age
@age.setter
def age(self, age):
"""
Sets the age of this TunnelRouteSummary.
The age of the route
:param age: The age of this TunnelRouteSummary.
:type: int
"""
self._age = age
@property
def is_best_path(self):
"""
Gets the is_best_path of this TunnelRouteSummary.
Is this the best route
:return: The is_best_path of this TunnelRouteSummary.
:rtype: bool
"""
return self._is_best_path
@is_best_path.setter
def is_best_path(self, is_best_path):
"""
Sets the is_best_path of this TunnelRouteSummary.
Is this the best route
:param is_best_path: The is_best_path of this TunnelRouteSummary.
:type: bool
"""
self._is_best_path = is_best_path
@property
def as_path(self):
"""
Gets the as_path of this TunnelRouteSummary.
List of ASNs in AS Path
:return: The as_path of this TunnelRouteSummary.
:rtype: list[int]
"""
return self._as_path
@as_path.setter
def as_path(self, as_path):
"""
Sets the as_path of this TunnelRouteSummary.
List of ASNs in AS Path
:param as_path: The as_path of this TunnelRouteSummary.
:type: list[int]
"""
self._as_path = as_path
@property
def advertiser(self):
"""
Gets the advertiser of this TunnelRouteSummary.
Route advertiser
Allowed values for this property are: "CUSTOMER", "ORACLE", 'UNKNOWN_ENUM_VALUE'.
Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'.
:return: The advertiser of this TunnelRouteSummary.
:rtype: str
"""
return self._advertiser
@advertiser.setter
def advertiser(self, advertiser):
"""
Sets the advertiser of this TunnelRouteSummary.
Route advertiser
:param advertiser: The advertiser of this TunnelRouteSummary.
:type: str
"""
allowed_values = ["CUSTOMER", "ORACLE"]
if not value_allowed_none_or_none_sentinel(advertiser, allowed_values):
advertiser = 'UNKNOWN_ENUM_VALUE'
self._advertiser = advertiser
def __repr__(self):
return formatted_flat_dict(self)
def __eq__(self, other):
if other is None:
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| 28.800948 | 245 | 0.623169 |
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class TunnelRouteSummary(object):
ADVERTISER_CUSTOMER = "CUSTOMER"
ADVERTISER_ORACLE = "ORACLE"
def __init__(self, **kwargs):
self.swagger_types = {
'prefix': 'str',
'age': 'int',
'is_best_path': 'bool',
'as_path': 'list[int]',
'advertiser': 'str'
}
self.attribute_map = {
'prefix': 'prefix',
'age': 'age',
'is_best_path': 'isBestPath',
'as_path': 'asPath',
'advertiser': 'advertiser'
}
self._prefix = None
self._age = None
self._is_best_path = None
self._as_path = None
self._advertiser = None
@property
def prefix(self):
return self._prefix
@prefix.setter
def prefix(self, prefix):
self._prefix = prefix
@property
def age(self):
return self._age
@age.setter
def age(self, age):
self._age = age
@property
def is_best_path(self):
return self._is_best_path
@is_best_path.setter
def is_best_path(self, is_best_path):
self._is_best_path = is_best_path
@property
def as_path(self):
return self._as_path
@as_path.setter
def as_path(self, as_path):
self._as_path = as_path
@property
def advertiser(self):
return self._advertiser
@advertiser.setter
def advertiser(self, advertiser):
allowed_values = ["CUSTOMER", "ORACLE"]
if not value_allowed_none_or_none_sentinel(advertiser, allowed_values):
advertiser = 'UNKNOWN_ENUM_VALUE'
self._advertiser = advertiser
def __repr__(self):
return formatted_flat_dict(self)
def __eq__(self, other):
if other is None:
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| true | true |
1c36ef6f98fb05e3e891633e540655d100080f7a | 2,129 | py | Python | json/basic.py | keys4words/oop | ddb80de06fcba8075632b6fdd620bb64056634d3 | [
"Apache-2.0"
] | null | null | null | json/basic.py | keys4words/oop | ddb80de06fcba8075632b6fdd620bb64056634d3 | [
"Apache-2.0"
] | 2 | 2021-06-09T07:03:54.000Z | 2022-03-12T00:55:18.000Z | json/basic.py | keys4words/oop | ddb80de06fcba8075632b6fdd620bb64056634d3 | [
"Apache-2.0"
] | null | null | null | import json, datetime
data = {
'first_name': 'Eugene',
'last_name': 'Petrov',
'age': 35,
'hobbies': [
'guitar',
'cars',
'mountains',
'adventures'
]
}
# convert dict to json string
json_data = json.dumps(data)
# print(json_data)
# write dict to json file
# with open('data/output.json', 'w') as f:
# json.dump(data, f, indent=4)
# read data from json string
json_data = '{"first_name": "Eugene"}'
data = json.loads(json_data)
# print(data['first_name'])
# read data from json file
with open('data/output.json', 'r') as f:
data = json.load(f)
# print(data['hobbies'][2])
# problems with json
data = {
'current_date': datetime.datetime.now()
}
# json_data = json.dumps(data)
# print(json_data)
# solving problem with hooks
class ComplexEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return {
'value': obj.strftime('%d/%m/%Y %H:%M:%S'),
'__datetime__': True
}
elif isinstance(obj, datetime.date):
return {
'value': obj.strftime('%d/%m/%Y'),
'__date__': True
}
return json.JSONEncoder.default(self, obj)
data = {
'first_name': 'Eugene',
'last_name': 'Petrov',
'birthday': datetime.date(1986, 9, 29),
'hired_at': datetime.datetime(2006, 9, 29, 12, 30, 5),
'hobbies': [
'guitar',
'cars',
'mountains',
'adventures'
]
}
# to string
json_data = json.dumps(data, cls=ComplexEncoder)
# print(json_data)
# to file
# with open('data/output2.json', 'w') as f:
# json.dump(data, f, cls=ComplexEncoder, indent=4)
# get from file
def as_date_datetime(dct):
# print(dct)
if '__datetime__' in dct:
return datetime.datetime.strptime(dct['value'], '%d/%m/%Y %H:%M:%S')
if '__date__' in dct:
return datetime.datetime.strptime(dct['value'], '%d/%m/%Y').date()
return dct
with open('data/output2.json', 'r') as f:
data = json.load(f, object_hook=as_date_datetime)
print(data['hired_at'])
| 23.395604 | 76 | 0.582903 | import json, datetime
data = {
'first_name': 'Eugene',
'last_name': 'Petrov',
'age': 35,
'hobbies': [
'guitar',
'cars',
'mountains',
'adventures'
]
}
json_data = json.dumps(data)
json_data = '{"first_name": "Eugene"}'
data = json.loads(json_data)
with open('data/output.json', 'r') as f:
data = json.load(f)
data = {
'current_date': datetime.datetime.now()
}
class ComplexEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return {
'value': obj.strftime('%d/%m/%Y %H:%M:%S'),
'__datetime__': True
}
elif isinstance(obj, datetime.date):
return {
'value': obj.strftime('%d/%m/%Y'),
'__date__': True
}
return json.JSONEncoder.default(self, obj)
data = {
'first_name': 'Eugene',
'last_name': 'Petrov',
'birthday': datetime.date(1986, 9, 29),
'hired_at': datetime.datetime(2006, 9, 29, 12, 30, 5),
'hobbies': [
'guitar',
'cars',
'mountains',
'adventures'
]
}
json_data = json.dumps(data, cls=ComplexEncoder)
def as_date_datetime(dct):
if '__datetime__' in dct:
return datetime.datetime.strptime(dct['value'], '%d/%m/%Y %H:%M:%S')
if '__date__' in dct:
return datetime.datetime.strptime(dct['value'], '%d/%m/%Y').date()
return dct
with open('data/output2.json', 'r') as f:
data = json.load(f, object_hook=as_date_datetime)
print(data['hired_at'])
| true | true |
1c36ef7fa7aeb5daefd24ab4335d932525bf8267 | 20,992 | py | Python | use_cases/TensorRT_object_detection/uff_ssd/voc_evaluation.py | itselavia/edge-computing-platform-for-deep-learning-apps | 43f0737d5635296b83be0eeba52d1a5d430df08f | [
"MIT"
] | 1 | 2021-05-19T19:39:59.000Z | 2021-05-19T19:39:59.000Z | use_cases/TensorRT_object_detection/uff_ssd/voc_evaluation.py | itselavia/edge-computing-platform-for-deep-learning-apps | 43f0737d5635296b83be0eeba52d1a5d430df08f | [
"MIT"
] | null | null | null | use_cases/TensorRT_object_detection/uff_ssd/voc_evaluation.py | itselavia/edge-computing-platform-for-deep-learning-apps | 43f0737d5635296b83be0eeba52d1a5d430df08f | [
"MIT"
] | 1 | 2021-08-08T06:49:42.000Z | 2021-08-08T06:49:42.000Z | #!/usr/bin/env python3
#
# Copyright (c) 2021, NVIDIA CORPORATION. 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.
#
import sys
import os
import ctypes
import time
import argparse
import glob
if sys.version_info[0] == 2:
import xml.etree.cElementTree as ET
else:
import xml.etree.ElementTree as ET
import numpy as np
import tensorrt as trt
from PIL import Image
# Utility functions
import utils.inference as inference_utils # TRT/TF inference wrappers
import utils.model as model_utils # UFF conversion
import utils.mAP as voc_mAP_utils # mAP computation
import utils.voc as voc_utils # VOC dataset descriptors
import utils.coco as coco_utils # COCO dataset descriptors
from utils.paths import PATHS # Path management
# VOC and COCO label lists
VOC_CLASSES = voc_utils.VOC_CLASSES_LIST
COCO_LABELS = coco_utils.COCO_CLASSES_LIST
# Model used for inference
MODEL_NAME = 'ssd_inception_v2_coco_2017_11_17'
# Precision command line argument -> TRT Engine datatype
TRT_PRECISION_TO_DATATYPE = {
16: trt.DataType.HALF,
32: trt.DataType.FLOAT
}
# Layout of TensorRT network output metadata
TRT_PREDICTION_LAYOUT = {
"image_id": 0,
"label": 1,
"confidence": 2,
"xmin": 3,
"ymin": 4,
"xmax": 5,
"ymax": 6
}
class Detection(object):
"""Describes detection for VOC detection file.
During evaluation of model on VOC, we save objects detected to result
files, with one file per each class. One line in such file corresponds
to one object that is detected in an image. The Detection class describes
one such detection.
Attributes:
image_number (str): number of image from VOC dataset
confidence (float): confidence score for detection
xmin (float): bounding box min x coordinate
ymin (float): bounding box min y coordinate
xmax (float): bounding box max x coordinate
ymax (float): bounding box max y coordinate
"""
def __init__(self, image_number, confidence, xmin, ymin, xmax, ymax):
self.image_number = image_number
self.confidence = confidence
self.xmin = xmin
self.ymin = ymin
self.xmax = xmax
self.ymax = ymax
def __repr__(self):
return "{} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\n".format(
self.image_number, self.confidence,
self.xmin, self.ymin, self.xmax, self.ymax
)
def write_to_file(self, f):
"""Adds detection corresponding to Detection object to file f.
Args:
f (file): detection results file
"""
f.write(self.__repr__())
def fetch_prediction_field(field_name, detection_out, pred_start_idx):
"""Fetches prediction field from prediction byte array.
After TensorRT inference, prediction data is saved in
byte array and returned by object detection network.
This byte array contains several pieces of data about
prediction - we call one such piece a prediction field.
This function, given prediction byte array returned by network,
staring index of given prediction and field name of interest,
returns prediction field data corresponding to given arguments.
Args:
field_name (str): field of interest, one of keys of TRT_PREDICTION_LAYOUT
detection_out (array): object detection network output
pred_start_idx (int): start index of prediction of interest in detection_out
Returns:
Prediction field corresponding to given data.
"""
return detection_out[pred_start_idx + TRT_PREDICTION_LAYOUT[field_name]]
def analyze_tensorrt_prediction(detection_out, pred_start_idx):
image_id = int(fetch_prediction_field("image_id", detection_out, pred_start_idx))
label = int(fetch_prediction_field("label", detection_out, pred_start_idx))
confidence = fetch_prediction_field("confidence", detection_out, pred_start_idx)
xmin = fetch_prediction_field("xmin", detection_out, pred_start_idx)
ymin = fetch_prediction_field("ymin", detection_out, pred_start_idx)
xmax = fetch_prediction_field("xmax", detection_out, pred_start_idx)
ymax = fetch_prediction_field("ymax", detection_out, pred_start_idx)
xmin = float(xmin) * model_utils.ModelData.get_input_width()
ymin = float(ymin) * model_utils.ModelData.get_input_height()
xmax = float(xmax) * model_utils.ModelData.get_input_width()
ymax = float(ymax) * model_utils.ModelData.get_input_height()
return image_id, label, confidence, xmin, ymin, xmax, ymax
def produce_tensorrt_detections(detection_files, trt_inference_wrapper, max_batch_size,
image_numbers, image_path):
"""Fetches output from TensorRT model, and saves it to results file.
The output of TensorRT model is a pair of:
* location byte array that contains detection metadata,
which is layout according to TRT_PREDICTION_LAYOUT
* number of detections returned by NMS
TRT_PREDICTION_LAYOUT fields correspond to Tensorflow ones as follows:
label -> detection_classes
confidence -> detection_scores
xmin, ymin, xmax, ymax -> detection_boxes
The number of detections correspond to num_detection Tensorflow output.
Tensorflow output semantics is more throughly explained in
produce_tensorflow_detections().
This function iterates over all VOC images, feeding each one
into TensotRT model, fetching object detections
from each output, converting them to Detection object,
and saving to detection result file.
Args:
detection_files (dict): dictionary that maps class labels to
class result files
trt_inference_wrapper (inference_utils.TRTInference):
internal Python class wrapping TensorRT inferece
setup/run code
batch_size (int): batch size used for inference
image_numbers [str]: VOC image numbers to use for inference
image_path (str): Python string, which stores path to VOC image file,
when you do image_path.format(voc_mage_number)
"""
total_imgs = len(image_numbers)
for idx in range(0, len(image_numbers), max_batch_size):
imgs = image_numbers[idx:idx+max_batch_size]
batch_size = len(imgs)
print("Infering image {}/{}".format(idx+1, total_imgs))
image_paths = [image_path.format(img) for img in imgs]
detections, keep_count = trt_inference_wrapper.infer_batch(image_paths)
prediction_fields = len(TRT_PREDICTION_LAYOUT)
for img_idx, img_number in enumerate(imgs):
img_predictions_start_idx = prediction_fields * keep_count[img_idx] * img_idx
for det in range(int(keep_count[img_idx])):
_, label, confidence, xmin, ymin, xmax, ymax = \
analyze_tensorrt_prediction(detections, img_predictions_start_idx + det * prediction_fields)
if confidence > 0.0:
label_name = voc_utils.coco_label_to_voc_label(COCO_LABELS[label])
if label_name:
det_file = detection_files[label_name]
detection = Detection(
img_number,
confidence,
xmin,
ymin,
xmax,
ymax,
)
detection.write_to_file(det_file)
def produce_tensorflow_detections(detection_files, tf_inference_wrapper, batch_size,
image_numbers, image_path):
"""Fetches output from Tensorflow model, and saves it to results file.
The format of output from Tensorflow is output_dict Python
dictionary containing following fields:
num_detections: maximum number of detections keeped per image
detection_classes: label of classes detected
detection_scores: confidences for detections
detection_boxes: bounding box coordinates for detections,
in format (ymin, xmin, ymax, xmax)
This function iterates over all VOC images, feeding each one
into Tensorflow model, fetching object detections
from each output, converting them to Detection object,
and saving to detection result file.
Args:
detection_files (dict): dictionary that maps class labels to
class result files
tf_inference_wrapper (inference_utils.TensorflowInference):
internal Python class wrapping Tensorflow inferece
setup/run code
batch_size (int): batch size used for inference
image_numbers [str]: VOC image numbers to use for inference
image_path (str): Python string, which stores path to VOC image file,
when you do image_path.format(voc_mage_number)
"""
total_imgs = len(image_numbers)
for idx in range(0, len(image_numbers), batch_size):
print("Infering image {}/{}".format(idx+1, total_imgs))
imgs = image_numbers[idx:idx+batch_size]
image_paths = [image_path.format(img) for img in imgs]
output_dict = tf_inference_wrapper.infer_batch(image_paths)
keep_count = output_dict['num_detections']
for img_idx, img_number in enumerate(imgs):
for det in range(int(keep_count[img_idx])):
label = output_dict['detection_classes'][img_idx][det]
confidence = output_dict['detection_scores'][img_idx][det]
bbox = output_dict['detection_boxes'][img_idx][det]
# Output bounding boxes are in [0, 1] format,
# here we rescale them to pixel [0, 255] format
ymin, xmin, ymax, xmax = bbox
xmin = float(xmin) * model_utils.ModelData.get_input_width()
ymin = float(ymin) * model_utils.ModelData.get_input_height()
xmax = float(xmax) * model_utils.ModelData.get_input_width()
ymax = float(ymax) * model_utils.ModelData.get_input_height()
# Detection is saved only if confidence is bigger than zero
if confidence > 0.0:
# Model was trained on COCO, so we need to convert label to VOC one
label_name = voc_utils.coco_label_to_voc_label(COCO_LABELS[label])
if label_name: # Checks for label_name correctness
det_file = detection_files[label_name]
detection = Detection(
img_number,
confidence,
xmin,
ymin,
xmax,
ymax,
)
detection.write_to_file(det_file)
def should_skip_inference(parsed_args):
"""Checks if inference should be skipped.
When evaluating on VOC, if results from some earlier run
of the script exist, we can reuse them to evaluate VOC mAP.
The user can overwrite this behavior by supplying -f flag to the script.
Args:
parsed_args (dict): commandline arguments parsed by
parse_commandline_arguments()
Returns:
bool: if True, script skips inference
"""
skip_inference = True
for voc_class in VOC_CLASSES:
voc_class_detection_file = \
os.path.join(parsed_args['results_dir'], 'det_test_{}.txt'.format(voc_class))
if os.path.exists(voc_class_detection_file) and not parsed_args['force_inference']:
continue
else:
skip_inference = False
if skip_inference:
print("Model detections present - skipping inference. To avoid this, use -f flag.")
return skip_inference
def preprocess_voc():
"""Resizes all VOC images to 300x300 and saves them into .ppm files.
This script assumes all images fetched to network in batches have size 300x300,
so in this function we preproceess all VOC images to fit that format.
"""
voc_root = PATHS.get_voc_dir_path()
voc_jpegs = glob.glob(
os.path.join(voc_root, 'JPEGImages', '*.jpg'))
voc_ppms = glob.glob(
os.path.join(voc_root, 'PPMImages', '*.ppm'))
# Check if preprocessing is needed by comparing
# image names between JPEGImages and PPMImages
voc_jpegs_basenames = \
[os.path.splitext(os.path.basename(p))[0] for p in voc_jpegs]
voc_ppms_basenames = \
[os.path.splitext(os.path.basename(p))[0] for p in voc_ppms]
# If lists are not the same, preprocessing is needed
if sorted(voc_jpegs_basenames) != sorted(voc_ppms_basenames):
print("Preprocessing VOC dataset. It may take few minutes.")
# Make PPMImages directory if it doesn't exist
voc_ppms_path = PATHS.get_voc_ppm_img_path()
if not os.path.exists(os.path.dirname(voc_ppms_path)):
os.makedirs(os.path.dirname(voc_ppms_path))
# For each .jpg file, make a resized
# .ppm copy to fit model input expectations
for voc_jpeg_path in voc_jpegs:
voc_jpeg_basename = os.path.basename(voc_jpeg_path)
voc_ppm_path = voc_ppms_path.format(
os.path.splitext(voc_jpeg_basename)[0])
if not os.path.exists(voc_ppm_path):
img_pil = Image.open(voc_jpeg_path)
img_pil = img_pil.resize(
size=(
model_utils.ModelData.get_input_width(),
model_utils.ModelData.get_input_height()),
resample=Image.BILINEAR
)
img_pil.save(voc_ppm_path)
def adjust_paths(args):
"""Adjust all file/directory paths, arguments passed by user.
During script launch, user can pass several arguments to the script
(e.g. --workspace_dir, --voc_dir), that define where script will look
for the files needed for execution. This function adjusts internal
Paths Python datastructure to accomodate for changes from defaults
requested by user through appropriate command line arguments.
Args:
args (argparse.Namespace): parsed user arguments
"""
if args.voc_dir:
PATHS.set_voc_dir_path(args.voc_dir)
if args.workspace_dir:
PATHS.set_workspace_dir_path(args.workspace_dir)
if not os.path.exists(PATHS.get_workspace_dir_path()):
os.makedirs(PATHS.get_workspace_dir_path())
def parse_commandline_arguments():
"""Parses command line arguments and adjusts internal data structures."""
# Define script command line arguments
parser = argparse.ArgumentParser(description='Run object detection evaluation on VOC2007 dataset.')
parser.add_argument('inference_backend', metavar='INFERENCE_BACKEND',
type=str, choices=['tensorrt', 'tensorflow'], default='tensorrt', nargs='?',
help='inference backend to run evaluation with')
parser.add_argument('-p', '--precision', type=int, choices=[32, 16], default=32,
help='desired TensorRT float precision to build an engine with')
parser.add_argument('-b', '--max_batch_size', type=int, default=64,
help='max TensorRT engine batch size')
parser.add_argument('-f', '--force_inference', action='store_true',
help='force model inference even if detections exist')
parser.add_argument('-w', '--workspace_dir',
help='sample workspace directory')
parser.add_argument('-voc', '--voc_dir',
help='VOC2007 root directory')
# Parse arguments passed
args = parser.parse_args()
# Adjust global Paths data structure
adjust_paths(args)
# Verify Paths after adjustments. This also exits script if verification fails
PATHS.verify_all_paths(should_verify_voc=True)
# Fetch directory to save inference results to, create it if it doesn't exist
trt_engine_datatype = None
trt_engine_path = None
if args.inference_backend == 'tensorrt':
# In case of TensorRT we also fetch engine data type and engine path
trt_engine_datatype = TRT_PRECISION_TO_DATATYPE[args.precision]
trt_engine_path = PATHS.get_engine_path(trt_engine_datatype,
args.max_batch_size)
if not os.path.exists(os.path.dirname(trt_engine_path)):
os.makedirs(os.path.dirname(trt_engine_path))
results_dir = PATHS.get_voc_model_detections_path('tensorrt',
trt_engine_datatype)
elif args.inference_backend == 'tensorflow':
results_dir = PATHS.get_voc_model_detections_path('tensorflow')
if not os.path.exists(results_dir):
os.makedirs(results_dir)
# Return parsed arguments for further functions to use
parsed = {
'inference_backend': args.inference_backend,
'max_batch_size': args.max_batch_size,
'force_inference': args.force_inference,
'results_dir': results_dir,
'trt_engine_path': trt_engine_path,
'trt_engine_datatype': trt_engine_datatype
}
return parsed
if __name__ == '__main__':
# Parse command line arguments
start_time = time.time()
parsed = parse_commandline_arguments()
# Check if inference should be skipped (if model inference
# results are already computed, we don't need to recompute
# them for VOC mAP computation)
skip_inference = should_skip_inference(parsed)
# And if inference will not be skipped, then we
# create files to store its results in
detection_files = {}
if not skip_inference:
for voc_class in VOC_CLASSES:
detection_files[voc_class] = open(
os.path.join(
parsed['results_dir'], 'det_test_{}.txt'.format(voc_class)
), 'w'
)
# Fetch frozen model .pb path...
ssd_model_pb_path = PATHS.get_model_pb_path(MODEL_NAME)
# ...and .uff path, if needed (converting .pb to .uff if not already done)
if parsed['inference_backend'] == 'tensorrt':
ssd_model_uff_path = PATHS.get_model_uff_path(MODEL_NAME)
if not os.path.exists(ssd_model_uff_path):
model_utils.prepare_ssd_model(MODEL_NAME)
# This block of code sets up and performs inference, if needed
if not skip_inference:
# Preprocess VOC dataset if necessary by resizing images
preprocess_voc()
# Fetch image list and input .ppm files path
with open(PATHS.get_voc_image_set_path(), 'r') as f:
voc_image_numbers = f.readlines()
voc_image_numbers = [line.strip() for line in voc_image_numbers]
voc_image_path = PATHS.get_voc_ppm_img_path()
# Tensorflow and TensorRT paths are a little bit different,
# so we must treat each one individually
if parsed['inference_backend'] == 'tensorrt':
# TRTInference initialization initializes
# all TensorRT structures, creates engine if it doesn't
# already exist and finally saves it to file for future uses
trt_inference_wrapper = inference_utils.TRTInference(
parsed['trt_engine_path'], ssd_model_uff_path,
parsed['trt_engine_datatype'], parsed['max_batch_size'])
# Outputs from TensorRT are handled differently than
# outputs from Tensorflow, that's why we use another
# function to produce the detections from them
produce_tensorrt_detections(detection_files,
trt_inference_wrapper, parsed['max_batch_size'],
voc_image_numbers, voc_image_path)
elif parsed['inference_backend'] == 'tensorflow':
# In case of Tensorflow all we need to
# initialize inference is frozen model...
tf_inference_wrapper = \
inference_utils.TensorflowInference(ssd_model_pb_path)
# ...and after initializing it, we can
# proceed to producing detections
produce_tensorflow_detections(detection_files,
tf_inference_wrapper, parsed['max_batch_size'],
voc_image_numbers, voc_image_path)
# Flush detection to files to make sure evaluation is correct
for key in detection_files:
detection_files[key].flush()
# Do mAP computation based on saved detections
voc_mAP_utils.do_python_eval(parsed['results_dir'])
# Close detection files, they are not needed anymore
for key in detection_files:
detection_files[key].close()
print("--- Total time taken for inference is %s seconds ---" % (time.time() - start_time))
| 42.493927 | 112 | 0.672875 |
import sys
import os
import ctypes
import time
import argparse
import glob
if sys.version_info[0] == 2:
import xml.etree.cElementTree as ET
else:
import xml.etree.ElementTree as ET
import numpy as np
import tensorrt as trt
from PIL import Image
import utils.inference as inference_utils
import utils.model as model_utils
import utils.mAP as voc_mAP_utils
import utils.voc as voc_utils
import utils.coco as coco_utils
from utils.paths import PATHS
VOC_CLASSES = voc_utils.VOC_CLASSES_LIST
COCO_LABELS = coco_utils.COCO_CLASSES_LIST
MODEL_NAME = 'ssd_inception_v2_coco_2017_11_17'
TRT_PRECISION_TO_DATATYPE = {
16: trt.DataType.HALF,
32: trt.DataType.FLOAT
}
TRT_PREDICTION_LAYOUT = {
"image_id": 0,
"label": 1,
"confidence": 2,
"xmin": 3,
"ymin": 4,
"xmax": 5,
"ymax": 6
}
class Detection(object):
def __init__(self, image_number, confidence, xmin, ymin, xmax, ymax):
self.image_number = image_number
self.confidence = confidence
self.xmin = xmin
self.ymin = ymin
self.xmax = xmax
self.ymax = ymax
def __repr__(self):
return "{} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\n".format(
self.image_number, self.confidence,
self.xmin, self.ymin, self.xmax, self.ymax
)
def write_to_file(self, f):
f.write(self.__repr__())
def fetch_prediction_field(field_name, detection_out, pred_start_idx):
return detection_out[pred_start_idx + TRT_PREDICTION_LAYOUT[field_name]]
def analyze_tensorrt_prediction(detection_out, pred_start_idx):
image_id = int(fetch_prediction_field("image_id", detection_out, pred_start_idx))
label = int(fetch_prediction_field("label", detection_out, pred_start_idx))
confidence = fetch_prediction_field("confidence", detection_out, pred_start_idx)
xmin = fetch_prediction_field("xmin", detection_out, pred_start_idx)
ymin = fetch_prediction_field("ymin", detection_out, pred_start_idx)
xmax = fetch_prediction_field("xmax", detection_out, pred_start_idx)
ymax = fetch_prediction_field("ymax", detection_out, pred_start_idx)
xmin = float(xmin) * model_utils.ModelData.get_input_width()
ymin = float(ymin) * model_utils.ModelData.get_input_height()
xmax = float(xmax) * model_utils.ModelData.get_input_width()
ymax = float(ymax) * model_utils.ModelData.get_input_height()
return image_id, label, confidence, xmin, ymin, xmax, ymax
def produce_tensorrt_detections(detection_files, trt_inference_wrapper, max_batch_size,
image_numbers, image_path):
total_imgs = len(image_numbers)
for idx in range(0, len(image_numbers), max_batch_size):
imgs = image_numbers[idx:idx+max_batch_size]
batch_size = len(imgs)
print("Infering image {}/{}".format(idx+1, total_imgs))
image_paths = [image_path.format(img) for img in imgs]
detections, keep_count = trt_inference_wrapper.infer_batch(image_paths)
prediction_fields = len(TRT_PREDICTION_LAYOUT)
for img_idx, img_number in enumerate(imgs):
img_predictions_start_idx = prediction_fields * keep_count[img_idx] * img_idx
for det in range(int(keep_count[img_idx])):
_, label, confidence, xmin, ymin, xmax, ymax = \
analyze_tensorrt_prediction(detections, img_predictions_start_idx + det * prediction_fields)
if confidence > 0.0:
label_name = voc_utils.coco_label_to_voc_label(COCO_LABELS[label])
if label_name:
det_file = detection_files[label_name]
detection = Detection(
img_number,
confidence,
xmin,
ymin,
xmax,
ymax,
)
detection.write_to_file(det_file)
def produce_tensorflow_detections(detection_files, tf_inference_wrapper, batch_size,
image_numbers, image_path):
total_imgs = len(image_numbers)
for idx in range(0, len(image_numbers), batch_size):
print("Infering image {}/{}".format(idx+1, total_imgs))
imgs = image_numbers[idx:idx+batch_size]
image_paths = [image_path.format(img) for img in imgs]
output_dict = tf_inference_wrapper.infer_batch(image_paths)
keep_count = output_dict['num_detections']
for img_idx, img_number in enumerate(imgs):
for det in range(int(keep_count[img_idx])):
label = output_dict['detection_classes'][img_idx][det]
confidence = output_dict['detection_scores'][img_idx][det]
bbox = output_dict['detection_boxes'][img_idx][det]
ymin, xmin, ymax, xmax = bbox
xmin = float(xmin) * model_utils.ModelData.get_input_width()
ymin = float(ymin) * model_utils.ModelData.get_input_height()
xmax = float(xmax) * model_utils.ModelData.get_input_width()
ymax = float(ymax) * model_utils.ModelData.get_input_height()
if confidence > 0.0:
label_name = voc_utils.coco_label_to_voc_label(COCO_LABELS[label])
if label_name:
det_file = detection_files[label_name]
detection = Detection(
img_number,
confidence,
xmin,
ymin,
xmax,
ymax,
)
detection.write_to_file(det_file)
def should_skip_inference(parsed_args):
skip_inference = True
for voc_class in VOC_CLASSES:
voc_class_detection_file = \
os.path.join(parsed_args['results_dir'], 'det_test_{}.txt'.format(voc_class))
if os.path.exists(voc_class_detection_file) and not parsed_args['force_inference']:
continue
else:
skip_inference = False
if skip_inference:
print("Model detections present - skipping inference. To avoid this, use -f flag.")
return skip_inference
def preprocess_voc():
voc_root = PATHS.get_voc_dir_path()
voc_jpegs = glob.glob(
os.path.join(voc_root, 'JPEGImages', '*.jpg'))
voc_ppms = glob.glob(
os.path.join(voc_root, 'PPMImages', '*.ppm'))
voc_jpegs_basenames = \
[os.path.splitext(os.path.basename(p))[0] for p in voc_jpegs]
voc_ppms_basenames = \
[os.path.splitext(os.path.basename(p))[0] for p in voc_ppms]
if sorted(voc_jpegs_basenames) != sorted(voc_ppms_basenames):
print("Preprocessing VOC dataset. It may take few minutes.")
voc_ppms_path = PATHS.get_voc_ppm_img_path()
if not os.path.exists(os.path.dirname(voc_ppms_path)):
os.makedirs(os.path.dirname(voc_ppms_path))
# For each .jpg file, make a resized
# .ppm copy to fit model input expectations
for voc_jpeg_path in voc_jpegs:
voc_jpeg_basename = os.path.basename(voc_jpeg_path)
voc_ppm_path = voc_ppms_path.format(
os.path.splitext(voc_jpeg_basename)[0])
if not os.path.exists(voc_ppm_path):
img_pil = Image.open(voc_jpeg_path)
img_pil = img_pil.resize(
size=(
model_utils.ModelData.get_input_width(),
model_utils.ModelData.get_input_height()),
resample=Image.BILINEAR
)
img_pil.save(voc_ppm_path)
def adjust_paths(args):
if args.voc_dir:
PATHS.set_voc_dir_path(args.voc_dir)
if args.workspace_dir:
PATHS.set_workspace_dir_path(args.workspace_dir)
if not os.path.exists(PATHS.get_workspace_dir_path()):
os.makedirs(PATHS.get_workspace_dir_path())
def parse_commandline_arguments():
# Define script command line arguments
parser = argparse.ArgumentParser(description='Run object detection evaluation on VOC2007 dataset.')
parser.add_argument('inference_backend', metavar='INFERENCE_BACKEND',
type=str, choices=['tensorrt', 'tensorflow'], default='tensorrt', nargs='?',
help='inference backend to run evaluation with')
parser.add_argument('-p', '--precision', type=int, choices=[32, 16], default=32,
help='desired TensorRT float precision to build an engine with')
parser.add_argument('-b', '--max_batch_size', type=int, default=64,
help='max TensorRT engine batch size')
parser.add_argument('-f', '--force_inference', action='store_true',
help='force model inference even if detections exist')
parser.add_argument('-w', '--workspace_dir',
help='sample workspace directory')
parser.add_argument('-voc', '--voc_dir',
help='VOC2007 root directory')
# Parse arguments passed
args = parser.parse_args()
# Adjust global Paths data structure
adjust_paths(args)
# Verify Paths after adjustments. This also exits script if verification fails
PATHS.verify_all_paths(should_verify_voc=True)
# Fetch directory to save inference results to, create it if it doesn't exist
trt_engine_datatype = None
trt_engine_path = None
if args.inference_backend == 'tensorrt':
trt_engine_datatype = TRT_PRECISION_TO_DATATYPE[args.precision]
trt_engine_path = PATHS.get_engine_path(trt_engine_datatype,
args.max_batch_size)
if not os.path.exists(os.path.dirname(trt_engine_path)):
os.makedirs(os.path.dirname(trt_engine_path))
results_dir = PATHS.get_voc_model_detections_path('tensorrt',
trt_engine_datatype)
elif args.inference_backend == 'tensorflow':
results_dir = PATHS.get_voc_model_detections_path('tensorflow')
if not os.path.exists(results_dir):
os.makedirs(results_dir)
parsed = {
'inference_backend': args.inference_backend,
'max_batch_size': args.max_batch_size,
'force_inference': args.force_inference,
'results_dir': results_dir,
'trt_engine_path': trt_engine_path,
'trt_engine_datatype': trt_engine_datatype
}
return parsed
if __name__ == '__main__':
start_time = time.time()
parsed = parse_commandline_arguments()
# them for VOC mAP computation)
skip_inference = should_skip_inference(parsed)
# And if inference will not be skipped, then we
# create files to store its results in
detection_files = {}
if not skip_inference:
for voc_class in VOC_CLASSES:
detection_files[voc_class] = open(
os.path.join(
parsed['results_dir'], 'det_test_{}.txt'.format(voc_class)
), 'w'
)
# Fetch frozen model .pb path...
ssd_model_pb_path = PATHS.get_model_pb_path(MODEL_NAME)
# ...and .uff path, if needed (converting .pb to .uff if not already done)
if parsed['inference_backend'] == 'tensorrt':
ssd_model_uff_path = PATHS.get_model_uff_path(MODEL_NAME)
if not os.path.exists(ssd_model_uff_path):
model_utils.prepare_ssd_model(MODEL_NAME)
# This block of code sets up and performs inference, if needed
if not skip_inference:
# Preprocess VOC dataset if necessary by resizing images
preprocess_voc()
# Fetch image list and input .ppm files path
with open(PATHS.get_voc_image_set_path(), 'r') as f:
voc_image_numbers = f.readlines()
voc_image_numbers = [line.strip() for line in voc_image_numbers]
voc_image_path = PATHS.get_voc_ppm_img_path()
# Tensorflow and TensorRT paths are a little bit different,
# so we must treat each one individually
if parsed['inference_backend'] == 'tensorrt':
# TRTInference initialization initializes
# all TensorRT structures, creates engine if it doesn't
trt_inference_wrapper = inference_utils.TRTInference(
parsed['trt_engine_path'], ssd_model_uff_path,
parsed['trt_engine_datatype'], parsed['max_batch_size'])
# function to produce the detections from them
produce_tensorrt_detections(detection_files,
trt_inference_wrapper, parsed['max_batch_size'],
voc_image_numbers, voc_image_path)
elif parsed['inference_backend'] == 'tensorflow':
# In case of Tensorflow all we need to
# initialize inference is frozen model...
tf_inference_wrapper = \
inference_utils.TensorflowInference(ssd_model_pb_path)
# ...and after initializing it, we can
# proceed to producing detections
produce_tensorflow_detections(detection_files,
tf_inference_wrapper, parsed['max_batch_size'],
voc_image_numbers, voc_image_path)
# Flush detection to files to make sure evaluation is correct
for key in detection_files:
detection_files[key].flush()
# Do mAP computation based on saved detections
voc_mAP_utils.do_python_eval(parsed['results_dir'])
# Close detection files, they are not needed anymore
for key in detection_files:
detection_files[key].close()
print("--- Total time taken for inference is %s seconds ---" % (time.time() - start_time))
| true | true |
1c36f0a2e49e20d854c8f83d1daf80698cc45545 | 4,588 | py | Python | news/announce.py | Goom11/vscode-python | 2070c68fb35cfe5f2f62870b796fd120e367bd7d | [
"MIT"
] | 1 | 2022-02-17T12:35:37.000Z | 2022-02-17T12:35:37.000Z | news/announce.py | chrisjsewell/vscode-python | 293b117b96b214546f8f2ca43a20c1f91411207a | [
"MIT"
] | null | null | null | news/announce.py | chrisjsewell/vscode-python | 293b117b96b214546f8f2ca43a20c1f91411207a | [
"MIT"
] | 1 | 2022-02-17T12:35:45.000Z | 2022-02-17T12:35:45.000Z | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Generate the changelog.
Usage: announce [--dry_run | --interim | --final] [<directory>]
"""
import dataclasses
import enum
import operator
import os
import pathlib
import re
import subprocess
import sys
import docopt
FILENAME_RE = re.compile(r"(?P<issue>\d+)(?P<nonce>-\S+)?\.md")
@dataclasses.dataclass
class NewsEntry:
"""Representation of a news entry."""
issue_number: int
description: str
path: pathlib.Path
def news_entries(directory):
"""Yield news entries in the directory.
Entries are sorted by issue number.
"""
entries = []
for path in directory.iterdir():
if path.name == "README.md":
continue
match = FILENAME_RE.match(path.name)
if match is None:
raise ValueError(f"{path} has a bad file name")
issue = int(match.group("issue"))
try:
entry = path.read_text("utf-8")
except UnicodeDecodeError as exc:
raise ValueError(f"'{path}' is not encoded as UTF-8") from exc
if "\ufeff" in entry:
raise ValueError(f"'{path}' contains the BOM")
entries.append(NewsEntry(issue, entry, path))
entries.sort(key=operator.attrgetter("issue_number"))
yield from entries
@dataclasses.dataclass
class SectionTitle:
"""Create a data object for a section of the changelog."""
index: int
title: str
path: pathlib.Path
def sections(directory):
"""Yield the sections in their appropriate order."""
found = []
for path in directory.iterdir():
if not path.is_dir() or path.name.startswith("."):
continue
position, sep, title = path.name.partition(" ")
if not sep:
print(
f"directory {path.name!r} is missing a ranking; skipping",
file=sys.stderr,
)
continue
found.append(SectionTitle(int(position), title, path))
return sorted(found, key=operator.attrgetter("index"))
def gather(directory):
"""Gather all the entries together."""
data = []
for section in sections(directory):
data.append((section, list(news_entries(section.path))))
return data
def entry_markdown(entry):
"""Generate the Markdown for the specified entry."""
enumerated_item = "1. "
indent = " " * len(enumerated_item)
issue_url = (
f"https://github.com/Microsoft/vscode-python/issues/{entry.issue_number}"
)
issue_md = f"([#{entry.issue_number}]({issue_url}))"
entry_lines = entry.description.strip().splitlines()
formatted_lines = [f"{enumerated_item}{entry_lines[0]}"]
formatted_lines.extend(f"{indent}{line}" for line in entry_lines[1:])
formatted_lines.append(f"{indent}{issue_md}")
return "\n".join(formatted_lines)
return ENTRY_TEMPLATE.format(
entry=entry.description.strip(), issue=entry.issue_number, issue_url=issue_url
)
def changelog_markdown(data):
"""Generate the Markdown for the release."""
changelog = []
for section, entries in data:
changelog.append(f"### {section.title}")
changelog.append("")
changelog.extend(map(entry_markdown, entries))
changelog.append("")
return "\n".join(changelog)
def git_rm(path):
"""Run git-rm on the path."""
status = subprocess.run(
["git", "rm", os.fspath(path.resolve())],
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
try:
status.check_returncode()
except Exception:
print(status.stdout, file=sys.stderr)
raise
def cleanup(data):
"""Remove news entries from git and disk."""
for section, entries in data:
for entry in entries:
git_rm(entry.path)
class RunType(enum.Enum):
"""Possible run-time options."""
dry_run = 0
interim = 1
final = 2
def main(run_type, directory):
directory = pathlib.Path(directory)
data = gather(directory)
markdown = changelog_markdown(data)
if run_type != RunType.dry_run:
print(markdown)
if run_type == RunType.final:
cleanup(data)
if __name__ == "__main__":
arguments = docopt.docopt(__doc__)
for possible_run_type in RunType:
if arguments[f"--{possible_run_type.name}"]:
run_type = possible_run_type
break
else:
run_type = RunType.interim
directory = arguments["<directory>"] or pathlib.Path(__file__).parent
main(run_type, directory)
| 26.830409 | 86 | 0.634917 |
import dataclasses
import enum
import operator
import os
import pathlib
import re
import subprocess
import sys
import docopt
FILENAME_RE = re.compile(r"(?P<issue>\d+)(?P<nonce>-\S+)?\.md")
@dataclasses.dataclass
class NewsEntry:
issue_number: int
description: str
path: pathlib.Path
def news_entries(directory):
entries = []
for path in directory.iterdir():
if path.name == "README.md":
continue
match = FILENAME_RE.match(path.name)
if match is None:
raise ValueError(f"{path} has a bad file name")
issue = int(match.group("issue"))
try:
entry = path.read_text("utf-8")
except UnicodeDecodeError as exc:
raise ValueError(f"'{path}' is not encoded as UTF-8") from exc
if "\ufeff" in entry:
raise ValueError(f"'{path}' contains the BOM")
entries.append(NewsEntry(issue, entry, path))
entries.sort(key=operator.attrgetter("issue_number"))
yield from entries
@dataclasses.dataclass
class SectionTitle:
index: int
title: str
path: pathlib.Path
def sections(directory):
found = []
for path in directory.iterdir():
if not path.is_dir() or path.name.startswith("."):
continue
position, sep, title = path.name.partition(" ")
if not sep:
print(
f"directory {path.name!r} is missing a ranking; skipping",
file=sys.stderr,
)
continue
found.append(SectionTitle(int(position), title, path))
return sorted(found, key=operator.attrgetter("index"))
def gather(directory):
data = []
for section in sections(directory):
data.append((section, list(news_entries(section.path))))
return data
def entry_markdown(entry):
enumerated_item = "1. "
indent = " " * len(enumerated_item)
issue_url = (
f"https://github.com/Microsoft/vscode-python/issues/{entry.issue_number}"
)
issue_md = f"([#{entry.issue_number}]({issue_url}))"
entry_lines = entry.description.strip().splitlines()
formatted_lines = [f"{enumerated_item}{entry_lines[0]}"]
formatted_lines.extend(f"{indent}{line}" for line in entry_lines[1:])
formatted_lines.append(f"{indent}{issue_md}")
return "\n".join(formatted_lines)
return ENTRY_TEMPLATE.format(
entry=entry.description.strip(), issue=entry.issue_number, issue_url=issue_url
)
def changelog_markdown(data):
changelog = []
for section, entries in data:
changelog.append(f"### {section.title}")
changelog.append("")
changelog.extend(map(entry_markdown, entries))
changelog.append("")
return "\n".join(changelog)
def git_rm(path):
status = subprocess.run(
["git", "rm", os.fspath(path.resolve())],
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
try:
status.check_returncode()
except Exception:
print(status.stdout, file=sys.stderr)
raise
def cleanup(data):
for section, entries in data:
for entry in entries:
git_rm(entry.path)
class RunType(enum.Enum):
dry_run = 0
interim = 1
final = 2
def main(run_type, directory):
directory = pathlib.Path(directory)
data = gather(directory)
markdown = changelog_markdown(data)
if run_type != RunType.dry_run:
print(markdown)
if run_type == RunType.final:
cleanup(data)
if __name__ == "__main__":
arguments = docopt.docopt(__doc__)
for possible_run_type in RunType:
if arguments[f"--{possible_run_type.name}"]:
run_type = possible_run_type
break
else:
run_type = RunType.interim
directory = arguments["<directory>"] or pathlib.Path(__file__).parent
main(run_type, directory)
| true | true |
1c36f0b9738235174619666944ab690ac69c8ec7 | 1,709 | py | Python | app/core/migrations/0001_initial.py | netolenildo/recipe-app-api | 6fa1620e9b47e515a36be94ffdab6b1a2c178d78 | [
"MIT"
] | null | null | null | app/core/migrations/0001_initial.py | netolenildo/recipe-app-api | 6fa1620e9b47e515a36be94ffdab6b1a2c178d78 | [
"MIT"
] | null | null | null | app/core/migrations/0001_initial.py | netolenildo/recipe-app-api | 6fa1620e9b47e515a36be94ffdab6b1a2c178d78 | [
"MIT"
] | null | null | null | # Generated by Django 3.1.7 on 2021-03-04 00:26
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('email', models.EmailField(max_length=255, unique=True)),
('name', models.CharField(max_length=255)),
('is_active', models.BooleanField(default=True)),
('is_staff', models.BooleanField(default=False)),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'abstract': False,
},
),
]
| 50.264706 | 266 | 0.63897 |
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('email', models.EmailField(max_length=255, unique=True)),
('name', models.CharField(max_length=255)),
('is_active', models.BooleanField(default=True)),
('is_staff', models.BooleanField(default=False)),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'abstract': False,
},
),
]
| true | true |
1c36f23539322a7f2ccaf1b58e6caf95efe0a405 | 2,122 | py | Python | ICD11OWLConverter/namespaces.py | hsolbrig/ICD11OWLConverter | 45ec2bce559b04ae6a190ef2467eb225319c9bb2 | [
"MIT"
] | null | null | null | ICD11OWLConverter/namespaces.py | hsolbrig/ICD11OWLConverter | 45ec2bce559b04ae6a190ef2467eb225319c9bb2 | [
"MIT"
] | null | null | null | ICD11OWLConverter/namespaces.py | hsolbrig/ICD11OWLConverter | 45ec2bce559b04ae6a190ef2467eb225319c9bb2 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright (c) 2014, Mayo Clinic
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted 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 the <ORGANIZATION> nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# 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 HOLDER 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 rdflib.namespace import Namespace, OWL, NamespaceManager
from rdflib import Graph
WHO = Namespace("http://id.who.int/icd/entity/")
SCT = Namespace("http://snomed.info/id/")
ICDF = Namespace("http://who.int/field/")
ICDM = Namespace("http://id.who.int/icd/map/")
ICDCG = Namespace("http://who.int/icd/cg/")
SCTCG = Namespace("http://snomed.info/cg/")
namespaces = {'who': WHO,
'sctid': SCT,
'icdf': ICDF,
'icdm': ICDM,
'icdcg': ICDCG,
'sctcg': SCTCG,
'owl': OWL} | 46.130435 | 84 | 0.722903 |
from rdflib.namespace import Namespace, OWL, NamespaceManager
from rdflib import Graph
WHO = Namespace("http://id.who.int/icd/entity/")
SCT = Namespace("http://snomed.info/id/")
ICDF = Namespace("http://who.int/field/")
ICDM = Namespace("http://id.who.int/icd/map/")
ICDCG = Namespace("http://who.int/icd/cg/")
SCTCG = Namespace("http://snomed.info/cg/")
namespaces = {'who': WHO,
'sctid': SCT,
'icdf': ICDF,
'icdm': ICDM,
'icdcg': ICDCG,
'sctcg': SCTCG,
'owl': OWL} | true | true |
1c36f2f8385ed7a5a63eaa544502c065aaab6fa5 | 666 | py | Python | game_seq_embedder/app/cp_py_file.py | Anonymous9999999/Pretrain-via-MTC | bc47c162aecb68708b68d8ff7c9bfd54b0fc485e | [
"Artistic-1.0-Perl"
] | null | null | null | game_seq_embedder/app/cp_py_file.py | Anonymous9999999/Pretrain-via-MTC | bc47c162aecb68708b68d8ff7c9bfd54b0fc485e | [
"Artistic-1.0-Perl"
] | null | null | null | game_seq_embedder/app/cp_py_file.py | Anonymous9999999/Pretrain-via-MTC | bc47c162aecb68708b68d8ff7c9bfd54b0fc485e | [
"Artistic-1.0-Perl"
] | null | null | null | def main():
file_path = '/Users/jiashupu/netease_projects/game_bert/app/pjs_bert_model/bert_model.py'
save_path = '/Users/jiashupu/netease_projects/game_seq_embedder/game_seq_embedder/custom_models/bert_model.py'
with open(file_path, 'r') as f_r:
with open(save_path, 'w') as f_w:
for line in f_r:
if line.startswith("from transformers"):
new_line = line.replace('from transformers', 'from ..transformers')
else:
new_line = line
f_w.write(new_line)
print(f"Copy file from {file_path} to {save_path}")
if __name__ == '__main__':
main()
| 37 | 114 | 0.62012 | def main():
file_path = '/Users/jiashupu/netease_projects/game_bert/app/pjs_bert_model/bert_model.py'
save_path = '/Users/jiashupu/netease_projects/game_seq_embedder/game_seq_embedder/custom_models/bert_model.py'
with open(file_path, 'r') as f_r:
with open(save_path, 'w') as f_w:
for line in f_r:
if line.startswith("from transformers"):
new_line = line.replace('from transformers', 'from ..transformers')
else:
new_line = line
f_w.write(new_line)
print(f"Copy file from {file_path} to {save_path}")
if __name__ == '__main__':
main()
| true | true |
1c36f3346ca0de9e9624c94547d2f642de91dff1 | 2,858 | py | Python | analysis_scripts/reference.py | gautelinga/-BERNAISE | aa45ae5ccc323d9c61c93542cc327889cae4d0b2 | [
"MIT"
] | 15 | 2017-07-19T18:33:26.000Z | 2021-03-25T18:36:47.000Z | analysis_scripts/reference.py | gautelinga/-BERNAISE | aa45ae5ccc323d9c61c93542cc327889cae4d0b2 | [
"MIT"
] | 9 | 2017-05-30T16:13:08.000Z | 2017-08-25T09:09:05.000Z | analysis_scripts/reference.py | gautelinga/-BERNAISE | aa45ae5ccc323d9c61c93542cc327889cae4d0b2 | [
"MIT"
] | 7 | 2018-05-08T22:50:15.000Z | 2020-06-25T13:50:37.000Z | """ reference script """
from common import info, info_split, info_on_red, info_cyan
from utilities.TimeSeries import TimeSeries
import os
from postprocess import rank, compute_norms
import dolfin as df
from utilities.plot import plot_any_field
def description(ts, **kwargs):
info("""Compare to numerical reference at given timestep.
The reference solution is assumed to be on a finer mesh, so the reference
solution is interpolated to the coarser mesh, where the comparison is made.""")
def method(ts, ref=None, time=1., show=False, save_fig=False, **kwargs):
"""Compare to numerical reference at given timestep.
The reference solution is assumed to be on a finer mesh, so the
reference solution is interpolated to the coarser mesh, where the
comparison is made.
"""
info_cyan("Comparing to numerical reference.")
if not isinstance(ref, str):
info_on_red("No reference specified. Use ref=(path).")
exit()
ts_ref = TimeSeries(ref, sought_fields=ts.fields)
info_split("Reference fields:", ", ".join(ts_ref.fields))
# Compute a 'reference ID' for storage purposes
ref_id = os.path.relpath(ts_ref.folder,
os.path.join(ts.folder, "../")).replace(
"../", "-").replace("/", "+")
step, time_0 = ts.get_nearest_step_and_time(time)
step_ref, time_ref = ts_ref.get_nearest_step_and_time(
time, dataset_str="reference")
info("Dataset: Time = {}, timestep = {}.".format(time_0, step))
info("Reference: Time = {}, timestep = {}.".format(time_ref, step_ref))
# from fenicstools import interpolate_nonmatching_mesh
f = ts.functions()
f_ref = ts_ref.functions()
err = ts_ref.functions()
ts.update_all(f, step=step)
ts_ref.update_all(f_ref, step=step_ref)
for field in ts_ref.fields:
# Interpolate solution to the reference mesh.
f_int = df.interpolate(
f[field], err[field].function_space())
err[field].vector().set_local(
f_int.vector().get_local() - f_ref[field].vector().get_local())
if show or save_fig:
err_arr = ts_ref.nodal_values(err[field])
label = "Error in " + field
if rank == 0:
save_fig_file = None
if save_fig:
save_fig_file = os.path.join(
ts.plots_folder, "error_{}_time{}_ref{}.png".format(
field, time, ref_id))
plot_any_field(ts_ref.nodes, ts_ref.elems, err_arr,
save=save_fig_file, show=show, label=label)
save_file = os.path.join(ts.analysis_folder,
"errornorms_time{}_ref{}.dat".format(
time, ref_id))
compute_norms(err, save=save_file)
| 35.283951 | 79 | 0.620014 | from common import info, info_split, info_on_red, info_cyan
from utilities.TimeSeries import TimeSeries
import os
from postprocess import rank, compute_norms
import dolfin as df
from utilities.plot import plot_any_field
def description(ts, **kwargs):
info("""Compare to numerical reference at given timestep.
The reference solution is assumed to be on a finer mesh, so the reference
solution is interpolated to the coarser mesh, where the comparison is made.""")
def method(ts, ref=None, time=1., show=False, save_fig=False, **kwargs):
info_cyan("Comparing to numerical reference.")
if not isinstance(ref, str):
info_on_red("No reference specified. Use ref=(path).")
exit()
ts_ref = TimeSeries(ref, sought_fields=ts.fields)
info_split("Reference fields:", ", ".join(ts_ref.fields))
ref_id = os.path.relpath(ts_ref.folder,
os.path.join(ts.folder, "../")).replace(
"../", "-").replace("/", "+")
step, time_0 = ts.get_nearest_step_and_time(time)
step_ref, time_ref = ts_ref.get_nearest_step_and_time(
time, dataset_str="reference")
info("Dataset: Time = {}, timestep = {}.".format(time_0, step))
info("Reference: Time = {}, timestep = {}.".format(time_ref, step_ref))
f = ts.functions()
f_ref = ts_ref.functions()
err = ts_ref.functions()
ts.update_all(f, step=step)
ts_ref.update_all(f_ref, step=step_ref)
for field in ts_ref.fields:
f_int = df.interpolate(
f[field], err[field].function_space())
err[field].vector().set_local(
f_int.vector().get_local() - f_ref[field].vector().get_local())
if show or save_fig:
err_arr = ts_ref.nodal_values(err[field])
label = "Error in " + field
if rank == 0:
save_fig_file = None
if save_fig:
save_fig_file = os.path.join(
ts.plots_folder, "error_{}_time{}_ref{}.png".format(
field, time, ref_id))
plot_any_field(ts_ref.nodes, ts_ref.elems, err_arr,
save=save_fig_file, show=show, label=label)
save_file = os.path.join(ts.analysis_folder,
"errornorms_time{}_ref{}.dat".format(
time, ref_id))
compute_norms(err, save=save_file)
| true | true |
1c36f35a446d49c3031b2b4e597087cdccf2c803 | 241 | py | Python | python/python/collections/sets.py | othonreyes/code_problems | 6e65b26120b0b9d6e5ac7342a4d964696b7bd5bf | [
"MIT"
] | null | null | null | python/python/collections/sets.py | othonreyes/code_problems | 6e65b26120b0b9d6e5ac7342a4d964696b7bd5bf | [
"MIT"
] | null | null | null | python/python/collections/sets.py | othonreyes/code_problems | 6e65b26120b0b9d6e5ac7342a4d964696b7bd5bf | [
"MIT"
] | null | null | null | my_set = set()
print('Empty set', my_set)
if my_set:
print('Unexpected')
else:
print('set is empty')
my_set.add(2)
print(my_set)
if 2 in my_set:
print('set has a 2')
# not possible -> gives error
#print('set has a ', my_set.get(2))
| 15.0625 | 35 | 0.655602 | my_set = set()
print('Empty set', my_set)
if my_set:
print('Unexpected')
else:
print('set is empty')
my_set.add(2)
print(my_set)
if 2 in my_set:
print('set has a 2')
| true | true |
1c36f4ad6150ac7841dbf0d6aba3c06c73bed03b | 1,089 | py | Python | tests/conftest.py | the-scouts/incognita | f0634f3d812b816ad3d46f55e88d7524ebf81d32 | [
"MIT"
] | 2 | 2019-06-14T08:05:24.000Z | 2021-01-03T00:18:07.000Z | tests/conftest.py | the-scouts/geo_mapping | f0634f3d812b816ad3d46f55e88d7524ebf81d32 | [
"MIT"
] | 47 | 2019-06-17T21:27:57.000Z | 2021-03-11T00:27:47.000Z | tests/conftest.py | the-scouts/incognita | f0634f3d812b816ad3d46f55e88d7524ebf81d32 | [
"MIT"
] | null | null | null | from pathlib import Path
import sys
import geopandas as gpd
from hypothesis.extra.pandas import column
from hypothesis.extra.pandas import data_frames
from hypothesis.extra.pandas import range_indexes
import hypothesis.strategies as st
import pytest
# https://github.com/pytest-dev/pytest/issues/2421#issuecomment-403724503
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
from incognita.utility import constants # NoQA: E402
COLUMN_NAME = "ctry"
@pytest.fixture(scope="module")
def blank_geo_data_frame() -> gpd.GeoDataFrame:
return gpd.GeoDataFrame(columns=("id",), geometry=gpd.points_from_xy(x=(0,), y=(0,)), crs=constants.WGS_84)
CountryDataFrame = data_frames(
columns=[
column(name=COLUMN_NAME, elements=st.from_regex(r"^[A-Za-z]{2}[0-9]{8}\Z")),
],
index=range_indexes(min_size=2),
)
LocationDataFrame = data_frames(
columns=[
column(name="lat", elements=st.floats(min_value=-85, max_value=85)),
column(name="long", elements=st.floats(min_value=-180, max_value=180)),
],
index=range_indexes(min_size=2),
)
| 28.657895 | 111 | 0.730028 | from pathlib import Path
import sys
import geopandas as gpd
from hypothesis.extra.pandas import column
from hypothesis.extra.pandas import data_frames
from hypothesis.extra.pandas import range_indexes
import hypothesis.strategies as st
import pytest
(Path(__file__).parent.parent / "src"))
from incognita.utility import constants
COLUMN_NAME = "ctry"
@pytest.fixture(scope="module")
def blank_geo_data_frame() -> gpd.GeoDataFrame:
return gpd.GeoDataFrame(columns=("id",), geometry=gpd.points_from_xy(x=(0,), y=(0,)), crs=constants.WGS_84)
CountryDataFrame = data_frames(
columns=[
column(name=COLUMN_NAME, elements=st.from_regex(r"^[A-Za-z]{2}[0-9]{8}\Z")),
],
index=range_indexes(min_size=2),
)
LocationDataFrame = data_frames(
columns=[
column(name="lat", elements=st.floats(min_value=-85, max_value=85)),
column(name="long", elements=st.floats(min_value=-180, max_value=180)),
],
index=range_indexes(min_size=2),
)
| true | true |
1c36f4c7a53b26194cae5792d84114cb9c6f00fe | 5,491 | py | Python | play_midi.py | curtissimo41/Player-Piano-19363 | 41123ec1e62cfee0ab7b4b511407f141e5f0e169 | [
"Apache-2.0"
] | null | null | null | play_midi.py | curtissimo41/Player-Piano-19363 | 41123ec1e62cfee0ab7b4b511407f141e5f0e169 | [
"Apache-2.0"
] | null | null | null | play_midi.py | curtissimo41/Player-Piano-19363 | 41123ec1e62cfee0ab7b4b511407f141e5f0e169 | [
"Apache-2.0"
] | null | null | null | import mido
import json
import time
from math import floor
import board
import busio
import digitalio
import adafruit_tlc5947
def reset_key():
SCK = board.SCK
MOSI = board.MOSI
LATCH = digitalio.DigitalInOut(board.D5)
# Initialize SPI bus.
spi = busio.SPI(clock=SCK, MOSI=MOSI)
# Initialize TLC5947
tlc5947 = adafruit_tlc5947.TLC5947(spi, LATCH, auto_write=False,
num_drivers=4)
for x in range(88):
tlc5947[x] = 0
tlc5947.write()
def playMidi(song_name):
mid = mido.MidiFile('midifiles/' + song_name)
notesDict = {'songName': 'testname', 'bpm': 999, 'notes': []}
tempo = 0
length = 0
notesArray = [[]]
tickLength = 0
VOLUME = 4
MIN = 800
SCK = board.SCK
MOSI = board.MOSI
LATCH = digitalio.DigitalInOut(board.D5)
# Initialize SPI bus.
spi = busio.SPI(clock=SCK, MOSI=MOSI)
# Initialize TLC5947
tlc5947 = adafruit_tlc5947.TLC5947(spi, LATCH, auto_write=False,
num_drivers=4)
for x in range(88):
tlc5947[x] = 0
tlc5947.write()
for msg in mid:
if msg.is_meta and msg.type == 'set_tempo':
tempo = int(msg.tempo)
length = int(floor(mido.second2tick(mid.length,
mid.ticks_per_beat,
tempo)))
tickLength = mido.tick2second(1, mid.ticks_per_beat, tempo)
break
print('Tick length: ' + str(tickLength))
currentTick = 0
notesArray[0] = [0 for x in range(89)]
lineIncrement = 0
for msg in mid:
#print(msg)
if msg.type is 'note_on' or msg.type is 'note_off':
delayAfter = int(floor(mido.second2tick(msg.time, mid.ticks_per_beat, tempo)))
if delayAfter == 0:
if msg.note < 89:
notesArray[lineIncrement][msg.note - 12] = msg.velocity
else:
notesArray[lineIncrement][88] = delayAfter
notesArray.append([0 for x in range(89)])
for y in range(88) :
notesArray[lineIncrement+1][y] = notesArray[lineIncrement][y]
#notesArray.append(notesArray[lineIncrement])
lineIncrement += 1
notesArray[lineIncrement][88] = 0
if msg.note < 89:
notesArray[lineIncrement][msg.note - 12] = msg.velocity
notesArray.append([0 for x in range(89)])
for y in range(88) :
notesArray[lineIncrement+1][y] = notesArray[lineIncrement][y]
lineIncrement += 1
""" Old code:
for x in range (newNote['delayAfter']):
if x != 0:
notesArray[x+currentTick] = notesArray[x+currentTick-1]
currentTick += newNote['delayAfter']
notesArray[currentTick][newNote['note'] - 1] = newNote['velocity']
# tlc5947.write()
notesDict['notes'].append(newNote)
"""
"""
with open('notes.json', 'w') as outfile:
json.dump(notesDict, outfile)
"""
startTime = time.time()
tlc5947.write()
time.sleep(3)
for z in range(0, len(notesArray)-1, 2):
line = notesArray[z]
"""
tlc5947[27] = 900
tlc5947[68] = 4000
tlc5947.write()
time.sleep(2)
tlc5947[27] = 0
tlc5947[68] = 0
tlc5947.write()
time.sleep(2)
"""
#print(line)
# send array to PWM IC
for x in range(len(line) - 1):
if line[x] != 0:
if x == 56:
tlc5947[x] = MIN+200
elif x== 46:
tlc5947[x] = 600
elif line[x]*VOLUME < MIN:
tlc5947[x] = MIN
else:
# tlc5947[x] = line[x] * VOLUME
tlc5947[x] = MIN
else:
tlc5947[x] = 0
tlc5947.write()
# time.sleep(tickLength)
time.sleep(mido.tick2second(line[88], mid.ticks_per_beat, tempo) * 0.7)
for x in range(88):
tlc5947[x] = notesArray[z+1][x]
tlc5947.write()
time.sleep(mido.tick2second(line[88], mid.ticks_per_beat, tempo) * 0.3)
for x in range(88):
tlc5947[x] = 0
tlc5947.write()
reset_key()
#playMidi('bumble_bee.mid')
#playMidi('for_elise_by_beethoven.mid')
# playMidi('debussy_clair_de_lune.mid')
#playMidi('Maple_Leaf_Rag_MIDI.mid')
#playMidi('jules_mad_world.mid')
#playMidi('Pinkfong-Babyshark-Anonymous-20190203093900-nonstop2k.com.mid')
#playMidi('080-Finale.mid')
#playMidi('gwyn_by_nitro.mid')
playMidi('Westworld_Theme.mid')
#playMidi('Smash_Mouth.mid')
#playMidi('vangelis_-_chariots_of_fire_ost_bryus_vsemogushchiy.mid')
#playMidi('GameofThrones.mid')
#playMidi('Welcome_to_Jurassic_World.mid')
#playMidi('Games_of_Thrones_piano_cover_by_Lisztlovers.MID')
#playMidi('Sonic.mid')
#playMidi('Moana.mid')
#playMidi('HesaPirate.mid')
#playMidi('ChamberOfSecrets-HedwigsTheme.mid')
#playMidi('DuelOfTheFates.mid')
#playMidi('Star-Wars-Imperial-March.mid')
#playMidi('PianoMan.mid')
#playMidi('the_entertainer.mid')
#playMidi('chopin_minute.mid') | 31.557471 | 90 | 0.54562 | import mido
import json
import time
from math import floor
import board
import busio
import digitalio
import adafruit_tlc5947
def reset_key():
SCK = board.SCK
MOSI = board.MOSI
LATCH = digitalio.DigitalInOut(board.D5)
spi = busio.SPI(clock=SCK, MOSI=MOSI)
tlc5947 = adafruit_tlc5947.TLC5947(spi, LATCH, auto_write=False,
num_drivers=4)
for x in range(88):
tlc5947[x] = 0
tlc5947.write()
def playMidi(song_name):
mid = mido.MidiFile('midifiles/' + song_name)
notesDict = {'songName': 'testname', 'bpm': 999, 'notes': []}
tempo = 0
length = 0
notesArray = [[]]
tickLength = 0
VOLUME = 4
MIN = 800
SCK = board.SCK
MOSI = board.MOSI
LATCH = digitalio.DigitalInOut(board.D5)
spi = busio.SPI(clock=SCK, MOSI=MOSI)
tlc5947 = adafruit_tlc5947.TLC5947(spi, LATCH, auto_write=False,
num_drivers=4)
for x in range(88):
tlc5947[x] = 0
tlc5947.write()
for msg in mid:
if msg.is_meta and msg.type == 'set_tempo':
tempo = int(msg.tempo)
length = int(floor(mido.second2tick(mid.length,
mid.ticks_per_beat,
tempo)))
tickLength = mido.tick2second(1, mid.ticks_per_beat, tempo)
break
print('Tick length: ' + str(tickLength))
currentTick = 0
notesArray[0] = [0 for x in range(89)]
lineIncrement = 0
for msg in mid:
if msg.type is 'note_on' or msg.type is 'note_off':
delayAfter = int(floor(mido.second2tick(msg.time, mid.ticks_per_beat, tempo)))
if delayAfter == 0:
if msg.note < 89:
notesArray[lineIncrement][msg.note - 12] = msg.velocity
else:
notesArray[lineIncrement][88] = delayAfter
notesArray.append([0 for x in range(89)])
for y in range(88) :
notesArray[lineIncrement+1][y] = notesArray[lineIncrement][y]
lineIncrement += 1
notesArray[lineIncrement][88] = 0
if msg.note < 89:
notesArray[lineIncrement][msg.note - 12] = msg.velocity
notesArray.append([0 for x in range(89)])
for y in range(88) :
notesArray[lineIncrement+1][y] = notesArray[lineIncrement][y]
lineIncrement += 1
startTime = time.time()
tlc5947.write()
time.sleep(3)
for z in range(0, len(notesArray)-1, 2):
line = notesArray[z]
for x in range(len(line) - 1):
if line[x] != 0:
if x == 56:
tlc5947[x] = MIN+200
elif x== 46:
tlc5947[x] = 600
elif line[x]*VOLUME < MIN:
tlc5947[x] = MIN
else:
tlc5947[x] = MIN
else:
tlc5947[x] = 0
tlc5947.write()
time.sleep(mido.tick2second(line[88], mid.ticks_per_beat, tempo) * 0.7)
for x in range(88):
tlc5947[x] = notesArray[z+1][x]
tlc5947.write()
time.sleep(mido.tick2second(line[88], mid.ticks_per_beat, tempo) * 0.3)
for x in range(88):
tlc5947[x] = 0
tlc5947.write()
reset_key()
playMidi('Westworld_Theme.mid')
| true | true |
1c36f590764cc4744af1edb5112986a53a690fe4 | 2,558 | py | Python | utils/config.py | k4r4koyun/HeadFuzz | efb3481e55e48102fd8c8329328b233ac62f2af7 | [
"MIT"
] | null | null | null | utils/config.py | k4r4koyun/HeadFuzz | efb3481e55e48102fd8c8329328b233ac62f2af7 | [
"MIT"
] | null | null | null | utils/config.py | k4r4koyun/HeadFuzz | efb3481e55e48102fd8c8329328b233ac62f2af7 | [
"MIT"
] | 1 | 2019-07-21T01:31:40.000Z | 2019-07-21T01:31:40.000Z | class Config():
TEST_LEVEL_OPTIMAL = 1
TEST_LEVEL_PARTIAL = 2
TEST_LEVEL_ALL = 3
logger = None
initial_response = None
static_cookies = []
max_workers = 20
test_level = 1
verbosity = 1
revshell_ip = "0.0.0.0"
revshell_port = 1337
exclude_code = ["400", "403", "405", "422"]
include_code = []
http_codes = {
# 1XX Informational
100:"Continue",
101:"Switching Protocols",
102:"Processing",
# 2XX Success
200:"OK",
201:"Created",
202:"Accepted",
203:"Non-authoritative Information",
204:"No Content",
205:"Reset Content",
206:"Partial Content",
207:"Multi-Status",
208:"Already Reported",
226:"IM Used",
# 3XX Redirection
300:"Multiple Choices",
301:"Moved Permanently",
302:"Found",
303:"See Other",
304:"Not Modified",
305:"Use Proxy",
307:"Temporary Redirect",
308:"Permanent Redirect",
# 4XX Client Error
400:"Bad Request",
401:"Unauthorized",
402:"Payment Required",
403:"Forbidden",
404:"Not Found",
405:"Method Not Allowed",
406:"Not Acceptable",
407:"Proxy Authentication Required",
408:"Request Timeout",
409:"Conflict",
410:"Gone",
411:"Length Required",
412:"Precondition Failed",
413:"Payload Too Large",
414:"Request-URI Too Long",
415:"Unsupported Media Type",
416:"Requested Range Not Satisfiable",
417:"Expectation Failed",
418:"I'm a teapot",
421:"Misdirected Request",
422:"Unprocessable Entity",
423:"Locked",
424:"Failed Dependency",
426:"Upgrade Required",
428:"Precondition Required",
429:"Too Many Requests",
431:"Request Header Fields Too Large",
444:"Connection Closed Without Response",
451:"Unavailable For Legal Reasons",
499:"Client Closed Request",
# 5XX Server Error
500:"Internal Server Error",
501:"Not Implemented",
502:"Bad Gateway",
503:"Service Unavailable",
504:"Gateway Timeout",
505:"HTTP Version Not Supported",
506:"Variant Also Negotiates",
507:"Insufficient Storage",
508:"Loop Detected",
510:"Not Extended",
511:"Network Authentication Required",
599:"Network Connect Timeout Error"
} | 29.068182 | 49 | 0.556294 | class Config():
TEST_LEVEL_OPTIMAL = 1
TEST_LEVEL_PARTIAL = 2
TEST_LEVEL_ALL = 3
logger = None
initial_response = None
static_cookies = []
max_workers = 20
test_level = 1
verbosity = 1
revshell_ip = "0.0.0.0"
revshell_port = 1337
exclude_code = ["400", "403", "405", "422"]
include_code = []
http_codes = {
100:"Continue",
101:"Switching Protocols",
102:"Processing",
200:"OK",
201:"Created",
202:"Accepted",
203:"Non-authoritative Information",
204:"No Content",
205:"Reset Content",
206:"Partial Content",
207:"Multi-Status",
208:"Already Reported",
226:"IM Used",
300:"Multiple Choices",
301:"Moved Permanently",
302:"Found",
303:"See Other",
304:"Not Modified",
305:"Use Proxy",
307:"Temporary Redirect",
308:"Permanent Redirect",
400:"Bad Request",
401:"Unauthorized",
402:"Payment Required",
403:"Forbidden",
404:"Not Found",
405:"Method Not Allowed",
406:"Not Acceptable",
407:"Proxy Authentication Required",
408:"Request Timeout",
409:"Conflict",
410:"Gone",
411:"Length Required",
412:"Precondition Failed",
413:"Payload Too Large",
414:"Request-URI Too Long",
415:"Unsupported Media Type",
416:"Requested Range Not Satisfiable",
417:"Expectation Failed",
418:"I'm a teapot",
421:"Misdirected Request",
422:"Unprocessable Entity",
423:"Locked",
424:"Failed Dependency",
426:"Upgrade Required",
428:"Precondition Required",
429:"Too Many Requests",
431:"Request Header Fields Too Large",
444:"Connection Closed Without Response",
451:"Unavailable For Legal Reasons",
499:"Client Closed Request",
# 5XX Server Error
500:"Internal Server Error",
501:"Not Implemented",
502:"Bad Gateway",
503:"Service Unavailable",
504:"Gateway Timeout",
505:"HTTP Version Not Supported",
506:"Variant Also Negotiates",
507:"Insufficient Storage",
508:"Loop Detected",
510:"Not Extended",
511:"Network Authentication Required",
599:"Network Connect Timeout Error"
} | true | true |
1c36f59fdc7ca39d695d84d405ea0cd961c3dbc9 | 868 | py | Python | projects/migrations/0012_auto_20210709_0511.py | dennereed/paleocore | d6da6c39cde96050ee4b9e7213ec1200530cbeee | [
"MIT"
] | 1 | 2021-02-05T19:50:13.000Z | 2021-02-05T19:50:13.000Z | projects/migrations/0012_auto_20210709_0511.py | dennereed/paleocore | d6da6c39cde96050ee4b9e7213ec1200530cbeee | [
"MIT"
] | 59 | 2020-06-17T22:21:51.000Z | 2022-02-10T05:00:01.000Z | projects/migrations/0012_auto_20210709_0511.py | dennereed/paleocore | d6da6c39cde96050ee4b9e7213ec1200530cbeee | [
"MIT"
] | 2 | 2020-07-01T14:11:09.000Z | 2020-08-10T17:27:26.000Z | # Generated by Django 2.2.24 on 2021-07-09 05:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('projects', '0011_auto_20210306_0019'),
]
operations = [
migrations.AlterField(
model_name='projectpage',
name='app_label',
field=models.CharField(blank=True, choices=[('compressor', 'compressor'), ('joyous', 'joyous'), ('mptt', 'mptt'), ('publications', 'publications'), ('projects', 'projects'), ('standard', 'standard'), ('drp', 'drp'), ('mlp', 'mlp'), ('hrp', 'hrp'), ('lgrp', 'lgrp'), ('eppe', 'eppe'), ('gdb', 'gdb'), ('omo_mursi', 'omo_mursi'), ('origins', 'origins'), ('psr', 'psr'), ('cc', 'cc'), ('fc', 'fc'), ('wtap', 'wtap'), ('arvrc', 'arvrc'), ('eval', 'eval'), ('paleosites', 'paleosites')], max_length=100, null=True),
),
]
| 45.684211 | 522 | 0.569124 |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('projects', '0011_auto_20210306_0019'),
]
operations = [
migrations.AlterField(
model_name='projectpage',
name='app_label',
field=models.CharField(blank=True, choices=[('compressor', 'compressor'), ('joyous', 'joyous'), ('mptt', 'mptt'), ('publications', 'publications'), ('projects', 'projects'), ('standard', 'standard'), ('drp', 'drp'), ('mlp', 'mlp'), ('hrp', 'hrp'), ('lgrp', 'lgrp'), ('eppe', 'eppe'), ('gdb', 'gdb'), ('omo_mursi', 'omo_mursi'), ('origins', 'origins'), ('psr', 'psr'), ('cc', 'cc'), ('fc', 'fc'), ('wtap', 'wtap'), ('arvrc', 'arvrc'), ('eval', 'eval'), ('paleosites', 'paleosites')], max_length=100, null=True),
),
]
| true | true |
1c36f5b3320823b6274a12212efadc4ad122a74a | 265 | py | Python | utils/__init__.py | hhsummerwind/few-shot | 48fdf3137271d5cc908fe0071dd0cf9da1ba574e | [
"MIT"
] | null | null | null | utils/__init__.py | hhsummerwind/few-shot | 48fdf3137271d5cc908fe0071dd0cf9da1ba574e | [
"MIT"
] | null | null | null | utils/__init__.py | hhsummerwind/few-shot | 48fdf3137271d5cc908fe0071dd0cf9da1ba574e | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Copyright 2021 HuHui, Inc. All Rights Reserved.
@author: HuHui
@software: PyCharm
@project: few-shot
@file: __init__.py
@version: v1.0
@time: 2021/10/9 下午4:05
-------------------------------------------------
Description :
工程文件说明:
"""
| 17.666667 | 49 | 0.54717 | true | true | |
1c36f73c1d6c033f462ea0470b5c45c07f6916bf | 7,879 | py | Python | clients/client/python/ory_client/model/ui_node_input_attributes.py | kolotaev/sdk | 0dda1becd70be8d7b9d678321ebe780c1ba00485 | [
"Apache-2.0"
] | null | null | null | clients/client/python/ory_client/model/ui_node_input_attributes.py | kolotaev/sdk | 0dda1becd70be8d7b9d678321ebe780c1ba00485 | [
"Apache-2.0"
] | null | null | null | clients/client/python/ory_client/model/ui_node_input_attributes.py | kolotaev/sdk | 0dda1becd70be8d7b9d678321ebe780c1ba00485 | [
"Apache-2.0"
] | null | null | null | """
Ory APIs
Documentation for all public and administrative Ory APIs. Administrative APIs can only be accessed with a valid Personal Access Token. Public APIs are mostly used in browsers. # noqa: E501
The version of the OpenAPI document: v0.0.1-alpha.17
Contact: support@ory.sh
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from ory_client.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNormal,
ModelSimple,
cached_property,
change_keys_js_to_python,
convert_js_args_to_python_args,
date,
datetime,
file_type,
none_type,
validate_get_composed_info,
)
def lazy_import():
from ory_client.model.ui_text import UiText
globals()['UiText'] = UiText
class UiNodeInputAttributes(ModelNormal):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the allowed value and an allowed
value. These dicts store the allowed enum values.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
discriminator_value_class_map (dict): A dict to go from the discriminator
variable value to the discriminator class name.
validations (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
"""
allowed_values = {
}
validations = {
}
additional_properties_type = None
_nullable = False
@cached_property
def openapi_types():
"""
This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type.
"""
lazy_import()
return {
'disabled': (bool,), # noqa: E501
'name': (str,), # noqa: E501
'type': (str,), # noqa: E501
'label': (UiText,), # noqa: E501
'pattern': (str,), # noqa: E501
'required': (bool,), # noqa: E501
'value': (bool, date, datetime, dict, float, int, list, str, none_type,), # noqa: E501
}
@cached_property
def discriminator():
return None
attribute_map = {
'disabled': 'disabled', # noqa: E501
'name': 'name', # noqa: E501
'type': 'type', # noqa: E501
'label': 'label', # noqa: E501
'pattern': 'pattern', # noqa: E501
'required': 'required', # noqa: E501
'value': 'value', # noqa: E501
}
_composed_schemas = {}
required_properties = set([
'_data_store',
'_check_type',
'_spec_property_naming',
'_path_to_item',
'_configuration',
'_visited_composed_classes',
])
@convert_js_args_to_python_args
def __init__(self, disabled, name, type, *args, **kwargs): # noqa: E501
"""UiNodeInputAttributes - a model defined in OpenAPI
Args:
disabled (bool): Sets the input's disabled field to true or false.
name (str): The input's element name.
type (str):
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
label (UiText): [optional] # noqa: E501
pattern (str): The input's pattern.. [optional] # noqa: E501
required (bool): Mark this input field as required.. [optional] # noqa: E501
value (bool, date, datetime, dict, float, int, list, str, none_type): The input's value.. [optional] # noqa: E501
"""
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
self.disabled = disabled
self.name = name
self.type = type
for var_name, var_value in kwargs.items():
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
# discard variable.
continue
setattr(self, var_name, var_value)
| 40.19898 | 194 | 0.578754 |
import re
import sys
from ory_client.model_utils import (
ApiTypeError,
ModelComposed,
ModelNormal,
ModelSimple,
cached_property,
change_keys_js_to_python,
convert_js_args_to_python_args,
date,
datetime,
file_type,
none_type,
validate_get_composed_info,
)
def lazy_import():
from ory_client.model.ui_text import UiText
globals()['UiText'] = UiText
class UiNodeInputAttributes(ModelNormal):
allowed_values = {
}
validations = {
}
additional_properties_type = None
_nullable = False
@cached_property
def openapi_types():
lazy_import()
return {
'disabled': (bool,),
'name': (str,),
'type': (str,),
'label': (UiText,),
'pattern': (str,),
'required': (bool,),
'value': (bool, date, datetime, dict, float, int, list, str, none_type,),
}
@cached_property
def discriminator():
return None
attribute_map = {
'disabled': 'disabled',
'name': 'name',
'type': 'type',
'label': 'label',
'pattern': 'pattern',
'required': 'required',
'value': 'value',
}
_composed_schemas = {}
required_properties = set([
'_data_store',
'_check_type',
'_spec_property_naming',
'_path_to_item',
'_configuration',
'_visited_composed_classes',
])
@convert_js_args_to_python_args
def __init__(self, disabled, name, type, *args, **kwargs):
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
self.disabled = disabled
self.name = name
self.type = type
for var_name, var_value in kwargs.items():
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
continue
setattr(self, var_name, var_value)
| true | true |
1c36f78972a914fd786fc8b609d09c9503057bdf | 117,517 | py | Python | libs/SmartMeshSDK/HartMgrConnector/HartMgrConnector.py | realms-team/rangetest | 19cfee769f095ea146cb2d12cc303e92a2b3e7b0 | [
"BSD-3-Clause"
] | null | null | null | libs/SmartMeshSDK/HartMgrConnector/HartMgrConnector.py | realms-team/rangetest | 19cfee769f095ea146cb2d12cc303e92a2b3e7b0 | [
"BSD-3-Clause"
] | null | null | null | libs/SmartMeshSDK/HartMgrConnector/HartMgrConnector.py | realms-team/rangetest | 19cfee769f095ea146cb2d12cc303e92a2b3e7b0 | [
"BSD-3-Clause"
] | null | null | null | '''
This module was generated automatically. Do not edit directly.
'''
import collections
from SmartMeshSDK import ApiException
from HartMgrConnectorInternal import HartMgrConnectorInternal
##
# \addtogroup HartMgrConnector
# \{
#
class HartMgrConnector(HartMgrConnectorInternal):
'''
\brief Public class for the HART Manager connector using the XML API.
'''
#======================== commands ========================================
##
# The named tuple returned by the dn_activateAdvertising() function.
#
# - <tt>result</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_activateAdvertising = collections.namedtuple("Tuple_dn_activateAdvertising", ['result'])
##
# Activate advertisement frame
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param timeout 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_activateAdvertising named tuple.
#
def dn_activateAdvertising(self, macAddr, timeout) :
res = HartMgrConnectorInternal.send(self, ['activateAdvertising'], {"macAddr" : macAddr, "timeout" : timeout})
return HartMgrConnector.Tuple_dn_activateAdvertising(**res)
##
# The named tuple returned by the dn_activateFastPipe() function.
#
# - <tt>result</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_activateFastPipe = collections.namedtuple("Tuple_dn_activateFastPipe", ['result'])
##
# Activate the fast network pipe to the specified mote.
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param pipeDirection 25-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - UniUp: upstream
# - UniDown: downstream
# - Bi: bidirectional
#
# \returns The response to the command, formatted as a #Tuple_dn_activateFastPipe named tuple.
#
def dn_activateFastPipe(self, macAddr, pipeDirection) :
res = HartMgrConnectorInternal.send(self, ['activateFastPipe'], {"macAddr" : macAddr, "pipeDirection" : pipeDirection})
return HartMgrConnector.Tuple_dn_activateFastPipe(**res)
##
# The named tuple returned by the dn_cancelOtap() function.
#
# - <tt>result</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_cancelOtap = collections.namedtuple("Tuple_dn_cancelOtap", ['result'])
##
# This command cancels the OTAP (Over-The-Air-Programming) process to upgrade software on motes and the access point.
#
#
#
# \returns The response to the command, formatted as a #Tuple_dn_cancelOtap named tuple.
#
def dn_cancelOtap(self, ) :
res = HartMgrConnectorInternal.send(self, ['cancelOtap'], {})
return HartMgrConnector.Tuple_dn_cancelOtap(**res)
##
# The named tuple returned by the dn_cli() function.
#
# - <tt>result</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_cli = collections.namedtuple("Tuple_dn_cli", ['result'])
##
# This command tunnels a given command through to the manager's Command Line Interface (CLI). The CLI command can be called by only one XML API client at a time. The response to the given CLI command is tunneled back to the client via the notifications channel. To receive the CLI notification, the client must be subscribed to CLI notifications (see Notification Channel)
#
# \param command 128-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_cli named tuple.
#
def dn_cli(self, command) :
res = HartMgrConnectorInternal.send(self, ['cli'], {"command" : command})
return HartMgrConnector.Tuple_dn_cli(**res)
##
# The named tuple returned by the dn_deactivateFastPipe() function.
#
# - <tt>result</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_deactivateFastPipe = collections.namedtuple("Tuple_dn_deactivateFastPipe", ['result'])
##
# Deactivate the fast network pipe to the specified mote.
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_deactivateFastPipe named tuple.
#
def dn_deactivateFastPipe(self, macAddr) :
res = HartMgrConnectorInternal.send(self, ['deactivateFastPipe'], {"macAddr" : macAddr})
return HartMgrConnector.Tuple_dn_deactivateFastPipe(**res)
##
# Remove a device from the ACL
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command.
#
def dn_deleteAcl(self, macAddr) :
res = HartMgrConnectorInternal.send(self, ['deleteAcl'], {"macAddr" : macAddr})
return res
##
# Remove a mote from the manager configuration
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command.
#
def dn_deleteMote(self, macAddr) :
res = HartMgrConnectorInternal.send(self, ['deleteMote'], {"macAddr" : macAddr})
return res
##
# Remove a user
#
# \param userName 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command.
#
def dn_deleteUser(self, userName) :
res = HartMgrConnectorInternal.send(self, ['deleteUser'], {"userName" : userName})
return res
##
# The named tuple returned by the dn_exchangeJoinKey() function.
#
# - <tt>callbackId</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_exchangeJoinKey = collections.namedtuple("Tuple_dn_exchangeJoinKey", ['callbackId'])
##
# Exchange the common join key
#
# \param newKey 16-byte field formatted as a hex.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_exchangeJoinKey named tuple.
#
def dn_exchangeJoinKey(self, newKey) :
res = HartMgrConnectorInternal.send(self, ['exchangeJoinKey'], {"newKey" : newKey})
return HartMgrConnector.Tuple_dn_exchangeJoinKey(**res)
##
# The named tuple returned by the dn_exchangeMoteJoinKey() function.
#
# - <tt>callbackId</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_exchangeMoteJoinKey = collections.namedtuple("Tuple_dn_exchangeMoteJoinKey", ['callbackId'])
##
# Exchange a mote's join key
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param newKey 16-byte field formatted as a hex.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_exchangeMoteJoinKey named tuple.
#
def dn_exchangeMoteJoinKey(self, macAddr, newKey) :
res = HartMgrConnectorInternal.send(self, ['exchangeMoteJoinKey'], {"macAddr" : macAddr, "newKey" : newKey})
return HartMgrConnector.Tuple_dn_exchangeMoteJoinKey(**res)
##
# The named tuple returned by the dn_exchangeMoteNetworkId() function.
#
# - <tt>callbackId</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_exchangeMoteNetworkId = collections.namedtuple("Tuple_dn_exchangeMoteNetworkId", ['callbackId'])
##
# Exchange the network ID for a mote
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param newId 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_exchangeMoteNetworkId named tuple.
#
def dn_exchangeMoteNetworkId(self, macAddr, newId) :
res = HartMgrConnectorInternal.send(self, ['exchangeMoteNetworkId'], {"macAddr" : macAddr, "newId" : newId})
return HartMgrConnector.Tuple_dn_exchangeMoteNetworkId(**res)
##
# The named tuple returned by the dn_exchangeNetworkKey() function.
#
# - <tt>callbackId</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_exchangeNetworkKey = collections.namedtuple("Tuple_dn_exchangeNetworkKey", ['callbackId'])
##
# Exchange the network key
#
#
#
# \returns The response to the command, formatted as a #Tuple_dn_exchangeNetworkKey named tuple.
#
def dn_exchangeNetworkKey(self, ) :
res = HartMgrConnectorInternal.send(self, ['exchangeNetworkKey'], {})
return HartMgrConnector.Tuple_dn_exchangeNetworkKey(**res)
##
# The named tuple returned by the dn_exchangeNetworkId() function.
#
# - <tt>callbackId</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_exchangeNetworkId = collections.namedtuple("Tuple_dn_exchangeNetworkId", ['callbackId'])
##
# Exchange the network ID
#
# \param newId 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_exchangeNetworkId named tuple.
#
def dn_exchangeNetworkId(self, newId) :
res = HartMgrConnectorInternal.send(self, ['exchangeNetworkId'], {"newId" : newId})
return HartMgrConnector.Tuple_dn_exchangeNetworkId(**res)
##
# The named tuple returned by the dn_exchangeSessionKey() function.
#
# - <tt>callbackId</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_exchangeSessionKey = collections.namedtuple("Tuple_dn_exchangeSessionKey", ['callbackId'])
##
# Exchange a mote's session key
#
# \param macAddrA 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param macAddrB 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_exchangeSessionKey named tuple.
#
def dn_exchangeSessionKey(self, macAddrA, macAddrB) :
res = HartMgrConnectorInternal.send(self, ['exchangeSessionKey'], {"macAddrA" : macAddrA, "macAddrB" : macAddrB})
return HartMgrConnector.Tuple_dn_exchangeSessionKey(**res)
##
# The named tuple returned by the dn_decommissionDevice() function.
#
# - <tt>result</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_decommissionDevice = collections.namedtuple("Tuple_dn_decommissionDevice", ['result'])
##
# Decommission a device in the network
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_decommissionDevice named tuple.
#
def dn_decommissionDevice(self, macAddr) :
res = HartMgrConnectorInternal.send(self, ['decommissionDevice'], {"macAddr" : macAddr})
return HartMgrConnector.Tuple_dn_decommissionDevice(**res)
##
# The named tuple returned by the dn_getAcl() function.
#
# - <tt>macAddr</tt>: 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_getAcl = collections.namedtuple("Tuple_dn_getAcl", ['macAddr'])
##
# Check whether a device is part of the ACL
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_getAcl named tuple.
#
def dn_getAcl(self, macAddr) :
res = HartMgrConnectorInternal.send(self, ['getAcl'], {"macAddr" : macAddr})
return HartMgrConnector.Tuple_dn_getAcl(**res)
##
# The named tuple returned by the dn_getAcls() function.
#
# - <tt>macAddr</tt>: 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_getAcls = collections.namedtuple("Tuple_dn_getAcls", ['macAddr'])
##
# Get the list of devices on the ACL
#
#
#
# \returns The response to the command, formatted as a list of #Tuple_dn_getAcls named tuple.
#
def dn_getAcls(self, ) :
res = HartMgrConnectorInternal.send(self, ['getAcls'], {})
tupleList = []
for r in res :
tupleList.append(HartMgrConnector.Tuple_dn_getAcls(**r))
return tupleList
##
# The named tuple returned by the dn_getBlacklist() function.
#
# - <tt>frequency</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_getBlacklist = collections.namedtuple("Tuple_dn_getBlacklist", ['frequency'])
##
# Get the channel blacklist
#
#
#
# \returns The response to the command, formatted as a list of #Tuple_dn_getBlacklist named tuple.
#
def dn_getBlacklist(self, ) :
res = HartMgrConnectorInternal.send(self, ['getBlacklist'], {})
tupleList = []
for r in res :
tupleList.append(HartMgrConnector.Tuple_dn_getBlacklist(**r))
return tupleList
##
# The named tuple returned by the dn_getMote() function.
#
# - <tt>moteId</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt>: 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>name</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>state</tt>: 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - Idle: idle
# - Lost: lost
# - Joining: joining
# - Operational: operational
# - Disconnecting: disconnecting
# - <tt>numJoins</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>joinTime</tt>: 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>reason</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>isAccessPoint</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>powerSource</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>dischargeCurrent</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>dischargeTime</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>recoveryTime</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>enableRouting</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>productName</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>hwModel</tt>: 1-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>hwRev</tt>: 1-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>swRev</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>voltage</tt>: 8-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# - <tt>numNeighbors</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>needNeighbor</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>goodNeighbors</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>allocatedPkPeriod</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>allocatedPipePkPeriod</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>pipeStatus</tt>: 4-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - off: off
# - pending: Pipe activation pending
# - on_bi: Bidirection pipe on
# - on_up: Upstream pipe on
# - on_down: Downstream pipe on
# - <tt>advertisingStatus</tt>: 4-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - on: on
# - off: off
# - pending: pending
# - <tt>locationTag</tt>: 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - supported: supported
# - not supported: not supported
#
Tuple_dn_getMote = collections.namedtuple("Tuple_dn_getMote", ['moteId', 'macAddr', 'name', 'state', 'numJoins', 'joinTime', 'reason', 'isAccessPoint', 'powerSource', 'dischargeCurrent', 'dischargeTime', 'recoveryTime', 'enableRouting', 'productName', 'hwModel', 'hwRev', 'swRev', 'voltage', 'numNeighbors', 'needNeighbor', 'goodNeighbors', 'allocatedPkPeriod', 'allocatedPipePkPeriod', 'pipeStatus', 'advertisingStatus', 'locationTag'])
##
#
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_getMote named tuple.
#
def dn_getMote(self, macAddr) :
res = HartMgrConnectorInternal.send(self, ['getMote'], {"macAddr" : macAddr})
return HartMgrConnector.Tuple_dn_getMote(**res)
##
# The named tuple returned by the dn_setMote() function.
#
# - <tt>moteId</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt>: 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>name</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>state</tt>: 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - Idle: idle
# - Lost: lost
# - Joining: joining
# - Operational: operational
# - Disconnecting: disconnecting
# - <tt>numJoins</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>joinTime</tt>: 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>reason</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>isAccessPoint</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>powerSource</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>dischargeCurrent</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>dischargeTime</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>recoveryTime</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>enableRouting</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>productName</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>hwModel</tt>: 1-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>hwRev</tt>: 1-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>swRev</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>voltage</tt>: 8-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# - <tt>numNeighbors</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>needNeighbor</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>goodNeighbors</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>allocatedPkPeriod</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>allocatedPipePkPeriod</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>pipeStatus</tt>: 4-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - off: off
# - pending: Pipe activation pending
# - on_bi: Bidirection pipe on
# - on_up: Upstream pipe on
# - on_down: Downstream pipe on
# - <tt>advertisingStatus</tt>: 4-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - on: on
# - off: off
# - pending: pending
# - <tt>locationTag</tt>: 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - supported: supported
# - not supported: not supported
#
Tuple_dn_setMote = collections.namedtuple("Tuple_dn_setMote", ['moteId', 'macAddr', 'name', 'state', 'numJoins', 'joinTime', 'reason', 'isAccessPoint', 'powerSource', 'dischargeCurrent', 'dischargeTime', 'recoveryTime', 'enableRouting', 'productName', 'hwModel', 'hwRev', 'swRev', 'voltage', 'numNeighbors', 'needNeighbor', 'goodNeighbors', 'allocatedPkPeriod', 'allocatedPipePkPeriod', 'pipeStatus', 'advertisingStatus', 'locationTag'])
##
# Set mote configuration
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param name 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param enableRouting 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_setMote named tuple.
#
def dn_setMote(self, macAddr, name, enableRouting) :
res = HartMgrConnectorInternal.send(self, ['setMote'], {"macAddr" : macAddr, "name" : name, "enableRouting" : enableRouting})
return HartMgrConnector.Tuple_dn_setMote(**res)
##
# The named tuple returned by the dn_getMotes() function.
#
# - <tt>moteId</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt>: 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>name</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>state</tt>: 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - Idle: idle
# - Lost: lost
# - Joining: joining
# - Operational: operational
# - Disconnecting: disconnecting
# - <tt>numJoins</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>joinTime</tt>: 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>reason</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>isAccessPoint</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>powerSource</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>dischargeCurrent</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>dischargeTime</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>recoveryTime</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>enableRouting</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>productName</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>hwModel</tt>: 1-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>hwRev</tt>: 1-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>swRev</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>voltage</tt>: 8-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# - <tt>numNeighbors</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>needNeighbor</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>goodNeighbors</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>allocatedPkPeriod</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>allocatedPipePkPeriod</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>pipeStatus</tt>: 4-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - off: off
# - pending: Pipe activation pending
# - on_bi: Bidirection pipe on
# - on_up: Upstream pipe on
# - on_down: Downstream pipe on
# - <tt>advertisingStatus</tt>: 4-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - on: on
# - off: off
# - pending: pending
# - <tt>locationTag</tt>: 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - supported: supported
# - not supported: not supported
#
Tuple_dn_getMotes = collections.namedtuple("Tuple_dn_getMotes", ['moteId', 'macAddr', 'name', 'state', 'numJoins', 'joinTime', 'reason', 'isAccessPoint', 'powerSource', 'dischargeCurrent', 'dischargeTime', 'recoveryTime', 'enableRouting', 'productName', 'hwModel', 'hwRev', 'swRev', 'voltage', 'numNeighbors', 'needNeighbor', 'goodNeighbors', 'allocatedPkPeriod', 'allocatedPipePkPeriod', 'pipeStatus', 'advertisingStatus', 'locationTag'])
##
# Get the list of Motes
#
#
#
# \returns The response to the command, formatted as a list of #Tuple_dn_getMotes named tuple.
#
def dn_getMotes(self, ) :
res = HartMgrConnectorInternal.send(self, ['getMotes'], {})
tupleList = []
for r in res :
tupleList.append(HartMgrConnector.Tuple_dn_getMotes(**r))
return tupleList
##
# The named tuple returned by the dn_getMoteStatistics() function.
#
# - <tt>index</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>startTime</tt>: 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>avgLatency</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>reliability</tt>: 0-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# - <tt>numJoins</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>voltage</tt>: 4-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# - <tt>chargeConsumption</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>temperature</tt>: 4-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# - <tt>numLostPackets</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>latencyToMote</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_getMoteStatistics = collections.namedtuple("Tuple_dn_getMoteStatistics", ['index', 'startTime', 'avgLatency', 'reliability', 'numJoins', 'voltage', 'chargeConsumption', 'temperature', 'numLostPackets', 'latencyToMote'])
##
# Get the Mote Statistics
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param period 32-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - current: current
# - lifetime: lifetime
# - short: short
# - long: long
# \param index 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_getMoteStatistics named tuple.
#
def dn_getMoteStatistics(self, macAddr, period, index) :
res = HartMgrConnectorInternal.send(self, ['getMoteStatistics'], {"macAddr" : macAddr, "period" : period, "index" : index})
return HartMgrConnector.Tuple_dn_getMoteStatistics(**res)
##
# The named tuple returned by the dn_getNetwork() function.
#
# - <tt>netName</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>networkId</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>maxMotes</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>numMotes</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>optimizationEnable</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>accessPointPA</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>ccaEnabled</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>requestedBasePkPeriod</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>minServicesPkPeriod</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>minPipePkPeriod</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>bandwidthProfile</tt>: 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - Manual: manual profile
# - P1: normal profile
# - P2: low-power profile
# - <tt>manualUSFrameSize</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>manualDSFrameSize</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>manualAdvFrameSize</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>netQueueSize</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>userQueueSize</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>locationMode</tt>: 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - on: on
# - off: off
# - <tt>backboneEnabled</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>backboneSize</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_getNetwork = collections.namedtuple("Tuple_dn_getNetwork", ['netName', 'networkId', 'maxMotes', 'numMotes', 'optimizationEnable', 'accessPointPA', 'ccaEnabled', 'requestedBasePkPeriod', 'minServicesPkPeriod', 'minPipePkPeriod', 'bandwidthProfile', 'manualUSFrameSize', 'manualDSFrameSize', 'manualAdvFrameSize', 'netQueueSize', 'userQueueSize', 'locationMode', 'backboneEnabled', 'backboneSize'])
##
# Retrieves network configuration parameters
#
#
#
# \returns The response to the command, formatted as a #Tuple_dn_getNetwork named tuple.
#
def dn_getNetwork(self, ) :
res = HartMgrConnectorInternal.send(self, ['getNetwork'], {})
return HartMgrConnector.Tuple_dn_getNetwork(**res)
##
# The named tuple returned by the dn_getNetworkStatistics() function.
#
# - <tt>index</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>startTime</tt>: 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>netLatency</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>netReliability</tt>: 0-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# - <tt>netPathStability</tt>: 0-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# - <tt>lostUpstreamPackets</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_getNetworkStatistics = collections.namedtuple("Tuple_dn_getNetworkStatistics", ['index', 'startTime', 'netLatency', 'netReliability', 'netPathStability', 'lostUpstreamPackets'])
##
# Get the Network Statistics
#
# \param period 32-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - current: current
# - lifetime: lifetime
# - short: short
# - long: long
# \param index 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_getNetworkStatistics named tuple.
#
def dn_getNetworkStatistics(self, period, index) :
res = HartMgrConnectorInternal.send(self, ['getNetworkStatistics'], {"period" : period, "index" : index})
return HartMgrConnector.Tuple_dn_getNetworkStatistics(**res)
##
# The named tuple returned by the dn_getOpenAlarms() function.
#
# - <tt>timeStamp</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>alarmType</tt>: 32-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - moteDown: Mote down alarm
# - slaReliability: SLA Reliability
# - slaLatency: SLA Latency
# - slaStability: SLA Stability
# - maxMotesReached: Maximum number of motes reached
# - bbLatencyWarn: Backbone latency warning
# - <tt>macAddr</tt>: 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_getOpenAlarms = collections.namedtuple("Tuple_dn_getOpenAlarms", ['timeStamp', 'eventId', 'alarmType', 'macAddr'])
##
# Retrieves a list of the open alarms on the Manager
#
#
#
# \returns The response to the command, formatted as a list of #Tuple_dn_getOpenAlarms named tuple.
#
def dn_getOpenAlarms(self, ) :
res = HartMgrConnectorInternal.send(self, ['getOpenAlarms'], {})
tupleList = []
for r in res :
tupleList.append(HartMgrConnector.Tuple_dn_getOpenAlarms(**r))
return tupleList
##
# The named tuple returned by the dn_getPaths() function.
#
# - <tt>pathId</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>moteAMac</tt>: 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>moteBMac</tt>: 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>numLinks</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>pathDirection</tt>: 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - all: all
# - upstream: upstream
# - downstream: downstream
# - unused: unused
# - <tt>pathQuality</tt>: 0-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_getPaths = collections.namedtuple("Tuple_dn_getPaths", ['pathId', 'moteAMac', 'moteBMac', 'numLinks', 'pathDirection', 'pathQuality'])
##
# Get the list of Paths to the mote's neighbors
#
# \param moteMac 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a list of #Tuple_dn_getPaths named tuple.
#
def dn_getPaths(self, moteMac) :
res = HartMgrConnectorInternal.send(self, ['getPaths'], {"moteMac" : moteMac})
tupleList = []
for r in res :
tupleList.append(HartMgrConnector.Tuple_dn_getPaths(**r))
return tupleList
##
# The named tuple returned by the dn_getPathStatistics() function.
#
# - <tt>index</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>startTime</tt>: 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>baPwr</tt>: 1-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>abPwr</tt>: 1-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>stability</tt>: 8-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_getPathStatistics = collections.namedtuple("Tuple_dn_getPathStatistics", ['index', 'startTime', 'baPwr', 'abPwr', 'stability'])
##
# Get Statistics for a specific Path
#
# \param pathId 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# \param period 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - current: current
# - lifetime: lifetime
# - short: short
# - long: long
# \param index 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_getPathStatistics named tuple.
#
def dn_getPathStatistics(self, pathId, period, index) :
res = HartMgrConnectorInternal.send(self, ['getPathStatistics'], {"pathId" : pathId, "period" : period, "index" : index})
return HartMgrConnector.Tuple_dn_getPathStatistics(**res)
##
# The named tuple returned by the dn_getRedundancy() function.
#
# - <tt>localMode</tt>: 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - standalone: standalone
# - transToMaster: Transitioning to master
# - transToSlave: Transitioning to slave
# - master: master
# - slave: slave
# - failed: Manager failed
# - <tt>peerStatus</tt>: 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - unknown: unknown
# - connected: connected
# - synchronized: synchronized
# - <tt>peerControllerSwRev</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_getRedundancy = collections.namedtuple("Tuple_dn_getRedundancy", ['localMode', 'peerStatus', 'peerControllerSwRev'])
##
# Get the redundancy state
#
#
#
# \returns The response to the command, formatted as a #Tuple_dn_getRedundancy named tuple.
#
def dn_getRedundancy(self, ) :
res = HartMgrConnectorInternal.send(self, ['getRedundancy'], {})
return HartMgrConnector.Tuple_dn_getRedundancy(**res)
##
# The named tuple returned by the dn_getSecurity() function.
#
# - <tt>securityMode</tt>: 20-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - acceptACL: Accept ACL
# - acceptCommonJoinKey: Accept common join key
# - <tt>acceptHARTDevicesOnly</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_getSecurity = collections.namedtuple("Tuple_dn_getSecurity", ['securityMode', 'acceptHARTDevicesOnly'])
##
# Get the Security configuration
#
#
#
# \returns The response to the command, formatted as a #Tuple_dn_getSecurity named tuple.
#
def dn_getSecurity(self, ) :
res = HartMgrConnectorInternal.send(self, ['getSecurity'], {})
return HartMgrConnector.Tuple_dn_getSecurity(**res)
##
# The named tuple returned by the dn_getSla() function.
#
# - <tt>minNetReliability</tt>: 8-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# - <tt>maxNetLatency</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>minNetPathStability</tt>: 8-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# - <tt>apRdntCoverageThreshold</tt>: 8-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_getSla = collections.namedtuple("Tuple_dn_getSla", ['minNetReliability', 'maxNetLatency', 'minNetPathStability', 'apRdntCoverageThreshold'])
##
# Get the Service Level Agreement (SLA) configuration
#
#
#
# \returns The response to the command, formatted as a #Tuple_dn_getSla named tuple.
#
def dn_getSla(self, ) :
res = HartMgrConnectorInternal.send(self, ['getSla'], {})
return HartMgrConnector.Tuple_dn_getSla(**res)
##
# The named tuple returned by the dn_getSystem() function.
#
# - <tt>systemName</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>location</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>swRev</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>hwModel</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>hwRev</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>serialNumber</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>time</tt>: 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>startTime</tt>: 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>cliTimeout</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>controllerSwRev</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_getSystem = collections.namedtuple("Tuple_dn_getSystem", ['systemName', 'location', 'swRev', 'hwModel', 'hwRev', 'serialNumber', 'time', 'startTime', 'cliTimeout', 'controllerSwRev'])
##
# Retrieves system-level information
#
#
#
# \returns The response to the command, formatted as a #Tuple_dn_getSystem named tuple.
#
def dn_getSystem(self, ) :
res = HartMgrConnectorInternal.send(self, ['getSystem'], {})
return HartMgrConnector.Tuple_dn_getSystem(**res)
##
# The named tuple returned by the dn_getUser() function.
#
# - <tt>userName</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>privilege</tt>: 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - viewer: viewer
# - user: user
# - superuser: superuser
#
Tuple_dn_getUser = collections.namedtuple("Tuple_dn_getUser", ['userName', 'privilege'])
##
# Get the description of a user
#
# \param userName 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_getUser named tuple.
#
def dn_getUser(self, userName) :
res = HartMgrConnectorInternal.send(self, ['getUser'], {"userName" : userName})
return HartMgrConnector.Tuple_dn_getUser(**res)
##
# The named tuple returned by the dn_getUsers() function.
#
# - <tt>userName</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>privilege</tt>: 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - viewer: viewer
# - user: user
# - superuser: superuser
#
Tuple_dn_getUsers = collections.namedtuple("Tuple_dn_getUsers", ['userName', 'privilege'])
##
# Get the list of users
#
#
#
# \returns The response to the command, formatted as a list of #Tuple_dn_getUsers named tuple.
#
def dn_getUsers(self, ) :
res = HartMgrConnectorInternal.send(self, ['getUsers'], {})
tupleList = []
for r in res :
tupleList.append(HartMgrConnector.Tuple_dn_getUsers(**r))
return tupleList
##
# The named tuple returned by the dn_getSourceRoute() function.
#
# - <tt>destMacAddr</tt>: 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>primaryPath</tt>: 16-byte field formatted as a list.<br/>
# There is no restriction on the value of this field.
# - <tt>secondaryPath</tt>: 16-byte field formatted as a list.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_getSourceRoute = collections.namedtuple("Tuple_dn_getSourceRoute", ['destMacAddr', 'primaryPath', 'secondaryPath'])
##
# Get the Source Route for a specific Mote
#
# \param destMacAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_getSourceRoute named tuple.
#
def dn_getSourceRoute(self, destMacAddr) :
res = HartMgrConnectorInternal.send(self, ['getSourceRoute'], {"destMacAddr" : destMacAddr})
return HartMgrConnector.Tuple_dn_getSourceRoute(**res)
##
# The named tuple returned by the dn_getLatency() function.
#
# - <tt>downstream</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>upstream</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_getLatency = collections.namedtuple("Tuple_dn_getLatency", ['downstream', 'upstream'])
##
# Get estimated latency for a mote.
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_getLatency named tuple.
#
def dn_getLatency(self, macAddr) :
res = HartMgrConnectorInternal.send(self, ['getLatency'], {"macAddr" : macAddr})
return HartMgrConnector.Tuple_dn_getLatency(**res)
##
# The named tuple returned by the dn_getLicense() function.
#
# - <tt>license</tt>: 40-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_getLicense = collections.namedtuple("Tuple_dn_getLicense", ['license'])
##
# Get the software license key.
#
#
#
# \returns The response to the command, formatted as a #Tuple_dn_getLicense named tuple.
#
def dn_getLicense(self, ) :
res = HartMgrConnectorInternal.send(self, ['getLicense'], {})
return HartMgrConnector.Tuple_dn_getLicense(**res)
##
# The named tuple returned by the dn_getTime() function.
#
# - <tt>utc_time</tt>: 0-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# - <tt>asn_time</tt>: 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_getTime = collections.namedtuple("Tuple_dn_getTime", ['utc_time', 'asn_time'])
##
# Get the current time.
#
#
#
# \returns The response to the command, formatted as a #Tuple_dn_getTime named tuple.
#
def dn_getTime(self, ) :
res = HartMgrConnectorInternal.send(self, ['getTime'], {})
return HartMgrConnector.Tuple_dn_getTime(**res)
##
# The named tuple returned by the dn_pingMote() function.
#
# - <tt>callbackId</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_pingMote = collections.namedtuple("Tuple_dn_pingMote", ['callbackId'])
##
# Ping the specified mote. A Net Ping Reply event notification will contain the mote's response.
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_pingMote named tuple.
#
def dn_pingMote(self, macAddr) :
res = HartMgrConnectorInternal.send(self, ['pingMote'], {"macAddr" : macAddr})
return HartMgrConnector.Tuple_dn_pingMote(**res)
##
# The named tuple returned by the dn_promoteToOperational() function.
#
# - <tt>result</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_promoteToOperational = collections.namedtuple("Tuple_dn_promoteToOperational", ['result'])
##
# Promote a quarantined device to operational
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_promoteToOperational named tuple.
#
def dn_promoteToOperational(self, macAddr) :
res = HartMgrConnectorInternal.send(self, ['promoteToOperational'], {"macAddr" : macAddr})
return HartMgrConnector.Tuple_dn_promoteToOperational(**res)
##
# The named tuple returned by the dn_reset() function.
#
# - <tt>result</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_reset = collections.namedtuple("Tuple_dn_reset", ['result'])
##
# Reset the system or network
#
# \param object 25-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - network: network
# - system: system
# - stat: statistics
# - eventLog: eventLog
#
# \returns The response to the command, formatted as a #Tuple_dn_reset named tuple.
#
def dn_reset(self, object) :
res = HartMgrConnectorInternal.send(self, ['reset'], {"object" : object})
return HartMgrConnector.Tuple_dn_reset(**res)
##
# The named tuple returned by the dn_resetWithId() function.
#
# - <tt>result</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_resetWithId = collections.namedtuple("Tuple_dn_resetWithId", ['result'])
##
# Reset mote by ID
#
# \param object 25-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - mote: mote
# \param moteId 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_resetWithId named tuple.
#
def dn_resetWithId(self, object, moteId) :
res = HartMgrConnectorInternal.send(self, ['resetWithId'], {"object" : object, "moteId" : moteId})
return HartMgrConnector.Tuple_dn_resetWithId(**res)
##
# The named tuple returned by the dn_resetWithMac() function.
#
# - <tt>result</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_resetWithMac = collections.namedtuple("Tuple_dn_resetWithMac", ['result'])
##
# Reset mote by MAC address
#
# \param object 25-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - mote: mote
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_resetWithMac named tuple.
#
def dn_resetWithMac(self, object, macAddr) :
res = HartMgrConnectorInternal.send(self, ['resetWithMac'], {"object" : object, "macAddr" : macAddr})
return HartMgrConnector.Tuple_dn_resetWithMac(**res)
##
# The named tuple returned by the dn_sendRequest() function.
#
# - <tt>callbackId</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_sendRequest = collections.namedtuple("Tuple_dn_sendRequest", ['callbackId'])
##
# Send downstream (request) data
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param domain 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - maintenance: maintenance
# \param priority 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - low: low
# - high: high
# \param reliable 0-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# \param data None-byte field formatted as a hex.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_sendRequest named tuple.
#
def dn_sendRequest(self, macAddr, domain, priority, reliable, data) :
res = HartMgrConnectorInternal.send(self, ['sendRequest'], {"macAddr" : macAddr, "domain" : domain, "priority" : priority, "reliable" : reliable, "data" : data})
return HartMgrConnector.Tuple_dn_sendRequest(**res)
##
# The named tuple returned by the dn_sendResponse() function.
#
# - <tt>callbackId</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_sendResponse = collections.namedtuple("Tuple_dn_sendResponse", ['callbackId'])
##
# Send downstream data as a response. sendResponse should only be used in special cases.
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param domain 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - maintenance: maintenance
# \param priority 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - low: low
# - high: high
# \param reliable 0-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# \param callbackId 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# \param data None-byte field formatted as a hex.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_sendResponse named tuple.
#
def dn_sendResponse(self, macAddr, domain, priority, reliable, callbackId, data) :
res = HartMgrConnectorInternal.send(self, ['sendResponse'], {"macAddr" : macAddr, "domain" : domain, "priority" : priority, "reliable" : reliable, "callbackId" : callbackId, "data" : data})
return HartMgrConnector.Tuple_dn_sendResponse(**res)
##
# The named tuple returned by the dn_setAcl() function.
#
# - <tt>macAddr</tt>: 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_setAcl = collections.namedtuple("Tuple_dn_setAcl", ['macAddr'])
##
# Add or update a device in the ACL
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param joinKey 16-byte field formatted as a hex.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_setAcl named tuple.
#
def dn_setAcl(self, macAddr, joinKey) :
res = HartMgrConnectorInternal.send(self, ['setAcl'], {"macAddr" : macAddr, "joinKey" : joinKey})
return HartMgrConnector.Tuple_dn_setAcl(**res)
##
# The named tuple returned by the dn_setBlacklist() function.
#
# - <tt>frequency</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_setBlacklist = collections.namedtuple("Tuple_dn_setBlacklist", ['frequency'])
##
# Update the channel blacklist
#
# \param frequency 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_setBlacklist named tuple.
#
def dn_setBlacklist(self, frequency) :
res = HartMgrConnectorInternal.send(self, ['setBlacklist'], {"frequency" : frequency})
return HartMgrConnector.Tuple_dn_setBlacklist(**res)
##
# The named tuple returned by the dn_setNetwork() function.
#
# - <tt>netName</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>networkId</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>maxMotes</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>optimizationEnable</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>accessPointPA</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>ccaEnabled</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>requestedBasePkPeriod</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>minServicesPkPeriod</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>minPipePkPeriod</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>bandwidthProfile</tt>: 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - Manual: manual profile
# - P1: normal profile
# - P2: low-power profile
# - <tt>manualUSFrameSize</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>manualDSFrameSize</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>manualAdvFrameSize</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>locationMode</tt>: 8-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - on: on
# - off: off
# - <tt>backboneEnabled</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>backboneSize</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_setNetwork = collections.namedtuple("Tuple_dn_setNetwork", ['netName', 'networkId', 'maxMotes', 'optimizationEnable', 'accessPointPA', 'ccaEnabled', 'requestedBasePkPeriod', 'minServicesPkPeriod', 'minPipePkPeriod', 'bandwidthProfile', 'manualUSFrameSize', 'manualDSFrameSize', 'manualAdvFrameSize', 'locationMode', 'backboneEnabled', 'backboneSize'])
##
# Set network configuration
#
# \param netName 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param networkId 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# \param maxMotes 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# \param optimizationEnable 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# \param accessPointPA 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# \param ccaEnabled 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# \param requestedBasePkPeriod 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# \param minServicesPkPeriod 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# \param minPipePkPeriod 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# \param bandwidthProfile 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - Manual: manual profile
# - P1: normal profile
# - P2: low-power profile
# \param manualUSFrameSize 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# \param manualDSFrameSize 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# \param manualAdvFrameSize 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# \param locationMode 8-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - on: on
# - off: off
#
# \returns The response to the command, formatted as a #Tuple_dn_setNetwork named tuple.
#
def dn_setNetwork(self, netName, networkId, maxMotes, optimizationEnable, accessPointPA, ccaEnabled, requestedBasePkPeriod, minServicesPkPeriod, minPipePkPeriod, bandwidthProfile, manualUSFrameSize, manualDSFrameSize, manualAdvFrameSize, locationMode) :
res = HartMgrConnectorInternal.send(self, ['setNetwork'], {"netName" : netName, "networkId" : networkId, "maxMotes" : maxMotes, "optimizationEnable" : optimizationEnable, "accessPointPA" : accessPointPA, "ccaEnabled" : ccaEnabled, "requestedBasePkPeriod" : requestedBasePkPeriod, "minServicesPkPeriod" : minServicesPkPeriod, "minPipePkPeriod" : minPipePkPeriod, "bandwidthProfile" : bandwidthProfile, "manualUSFrameSize" : manualUSFrameSize, "manualDSFrameSize" : manualDSFrameSize, "manualAdvFrameSize" : manualAdvFrameSize, "locationMode" : locationMode})
return HartMgrConnector.Tuple_dn_setNetwork(**res)
##
# The named tuple returned by the dn_setSecurity() function.
#
# - <tt>securityMode</tt>: 20-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - acceptACL: Accept ACL
# - acceptCommonJoinKey: Accept common join key
# - <tt>acceptHARTDevicesOnly</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_setSecurity = collections.namedtuple("Tuple_dn_setSecurity", ['securityMode', 'acceptHARTDevicesOnly'])
##
# Set security configuration
#
# \param securityMode 20-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - acceptACL: Accept ACL
# - acceptCommonJoinKey: Accept common join key
# \param commonJoinKey 16-byte field formatted as a hex.<br/>
# There is no restriction on the value of this field.
# \param acceptHARTDevicesOnly 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_setSecurity named tuple.
#
def dn_setSecurity(self, securityMode, commonJoinKey, acceptHARTDevicesOnly) :
res = HartMgrConnectorInternal.send(self, ['setSecurity'], {"securityMode" : securityMode, "commonJoinKey" : commonJoinKey, "acceptHARTDevicesOnly" : acceptHARTDevicesOnly})
return HartMgrConnector.Tuple_dn_setSecurity(**res)
##
# The named tuple returned by the dn_setSla() function.
#
# - <tt>minNetReliability</tt>: 8-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# - <tt>maxNetLatency</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>minNetPathStability</tt>: 8-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# - <tt>apRdntCoverageThreshold</tt>: 8-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_setSla = collections.namedtuple("Tuple_dn_setSla", ['minNetReliability', 'maxNetLatency', 'minNetPathStability', 'apRdntCoverageThreshold'])
##
# Set SLA configuration
#
# \param minNetReliability 8-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# \param maxNetLatency 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# \param minNetPathStability 8-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# \param apRdntCoverageThreshold 8-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_setSla named tuple.
#
def dn_setSla(self, minNetReliability, maxNetLatency, minNetPathStability, apRdntCoverageThreshold) :
res = HartMgrConnectorInternal.send(self, ['setSla'], {"minNetReliability" : minNetReliability, "maxNetLatency" : maxNetLatency, "minNetPathStability" : minNetPathStability, "apRdntCoverageThreshold" : apRdntCoverageThreshold})
return HartMgrConnector.Tuple_dn_setSla(**res)
##
# The named tuple returned by the dn_setSystem() function.
#
# - <tt>systemName</tt>: 50-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>location</tt>: 50-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>cliTimeout</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_setSystem = collections.namedtuple("Tuple_dn_setSystem", ['systemName', 'location', 'cliTimeout'])
##
# Set system-level configuration
#
# \param systemName 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param location 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param cliTimeout 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_setSystem named tuple.
#
def dn_setSystem(self, systemName, location, cliTimeout) :
res = HartMgrConnectorInternal.send(self, ['setSystem'], {"systemName" : systemName, "location" : location, "cliTimeout" : cliTimeout})
return HartMgrConnector.Tuple_dn_setSystem(**res)
##
# The named tuple returned by the dn_setUser() function.
#
# - <tt>userName</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>privilege</tt>: 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - viewer: viewer
# - user: user
# - superuser: superuser
#
Tuple_dn_setUser = collections.namedtuple("Tuple_dn_setUser", ['userName', 'privilege'])
##
# Add or update user configuration
#
# \param userName 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param password 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param privilege 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - viewer: viewer
# - user: user
# - superuser: superuser
#
# \returns The response to the command, formatted as a #Tuple_dn_setUser named tuple.
#
def dn_setUser(self, userName, password, privilege) :
res = HartMgrConnectorInternal.send(self, ['setUser'], {"userName" : userName, "password" : password, "privilege" : privilege})
return HartMgrConnector.Tuple_dn_setUser(**res)
##
# The named tuple returned by the dn_setLicense() function.
#
# - <tt>result</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_setLicense = collections.namedtuple("Tuple_dn_setLicense", ['result'])
##
# Set the software license key.
#
# \param license 40-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_setLicense named tuple.
#
def dn_setLicense(self, license) :
res = HartMgrConnectorInternal.send(self, ['setLicense'], {"license" : license})
return HartMgrConnector.Tuple_dn_setLicense(**res)
##
# The named tuple returned by the dn_startOtap() function.
#
# - <tt>result</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_startOtap = collections.namedtuple("Tuple_dn_startOtap", ['result'])
##
# This command initiates the OTAP (Over-The-Air-Programming) process to upgrade software on motes and the Access Point. By default, the process will retry the OTAP file transmission 100 times.
#
#
#
# \returns The response to the command, formatted as a #Tuple_dn_startOtap named tuple.
#
def dn_startOtap(self, ) :
res = HartMgrConnectorInternal.send(self, ['startOtap'], {})
return HartMgrConnector.Tuple_dn_startOtap(**res)
##
# The named tuple returned by the dn_startOtapWithRetries() function.
#
# - <tt>result</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_startOtapWithRetries = collections.namedtuple("Tuple_dn_startOtapWithRetries", ['result'])
##
# This command initiates the OTAP (Over-The-Air-Programming) process to upgrade software for motes and the Access Point, using the specified number of retries.
#
# \param retries 1-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_startOtapWithRetries named tuple.
#
def dn_startOtapWithRetries(self, retries) :
res = HartMgrConnectorInternal.send(self, ['startOtapWithRetries'], {"retries" : retries})
return HartMgrConnector.Tuple_dn_startOtapWithRetries(**res)
##
# The named tuple returned by the dn_subscribe() function.
#
# - <tt>notif_token</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_subscribe = collections.namedtuple("Tuple_dn_subscribe", ['notif_token'])
##
# Subscribe to notifications. This function adds or updates the subscribed notifications to match 'filter'. The filter is a space-separated list of notification types. Valid types include 'data' and 'events'.
#
# \param filter 128-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_subscribe named tuple.
#
def dn_subscribe(self, filter) :
res = HartMgrConnectorInternal.send(self, ['subscribe'], {"filter" : filter})
return HartMgrConnector.Tuple_dn_subscribe(**res)
##
# The named tuple returned by the dn_unsubscribe() function.
#
# - <tt>result</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_unsubscribe = collections.namedtuple("Tuple_dn_unsubscribe", ['result'])
##
# Unsubscribe from notifications. This function clears the existing notification subscription of the client and stops the notification thread.
#
#
#
# \returns The response to the command, formatted as a #Tuple_dn_unsubscribe named tuple.
#
def dn_unsubscribe(self, ) :
res = HartMgrConnectorInternal.send(self, ['unsubscribe'], {})
return HartMgrConnector.Tuple_dn_unsubscribe(**res)
#======================== notifications ===================================
##
# Dictionary of all notification tuples.
#
notifTupleTable = {}
##
# \brief USERCONNECT notification.
#
#
#
# Formatted as a Tuple_UserConnect named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>channel</tt> 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - cli: Manager CLI
# - config: API control
# - notif: API notifications
# - <tt>ipAddr</tt> 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>userName</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
USERCONNECT = "UserConnect"
notifTupleTable[USERCONNECT] = Tuple_UserConnect = collections.namedtuple("Tuple_UserConnect", ['timeStamp', 'eventId', 'channel', 'ipAddr', 'userName'])
##
# \brief USERDISCONNECT notification.
#
#
#
# Formatted as a Tuple_UserDisconnect named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>channel</tt> 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - cli: Manager CLI
# - config: API control
# - notif: API notifications
# - <tt>ipAddr</tt> 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>userName</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
USERDISCONNECT = "UserDisconnect"
notifTupleTable[USERDISCONNECT] = Tuple_UserDisconnect = collections.namedtuple("Tuple_UserDisconnect", ['timeStamp', 'eventId', 'channel', 'ipAddr', 'userName'])
##
# \brief MANUALMOTERESET notification.
#
#
#
# Formatted as a Tuple_ManualMoteReset named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>userName</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>moteId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
MANUALMOTERESET = "ManualMoteReset"
notifTupleTable[MANUALMOTERESET] = Tuple_ManualMoteReset = collections.namedtuple("Tuple_ManualMoteReset", ['timeStamp', 'eventId', 'userName', 'moteId', 'macAddr'])
##
# \brief MANUALMOTEDELETE notification.
#
#
#
# Formatted as a Tuple_ManualMoteDelete named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>userName</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>moteId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
MANUALMOTEDELETE = "ManualMoteDelete"
notifTupleTable[MANUALMOTEDELETE] = Tuple_ManualMoteDelete = collections.namedtuple("Tuple_ManualMoteDelete", ['timeStamp', 'eventId', 'userName', 'moteId', 'macAddr'])
##
# \brief MANUALMOTEDECOMMISSION notification.
#
#
#
# Formatted as a Tuple_ManualMoteDecommission named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>userName</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>moteId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
MANUALMOTEDECOMMISSION = "ManualMoteDecommission"
notifTupleTable[MANUALMOTEDECOMMISSION] = Tuple_ManualMoteDecommission = collections.namedtuple("Tuple_ManualMoteDecommission", ['timeStamp', 'eventId', 'userName', 'moteId', 'macAddr'])
##
# \brief MANUALNETRESET notification.
#
#
#
# Formatted as a Tuple_ManualNetReset named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>userName</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
MANUALNETRESET = "ManualNetReset"
notifTupleTable[MANUALNETRESET] = Tuple_ManualNetReset = collections.namedtuple("Tuple_ManualNetReset", ['timeStamp', 'eventId', 'userName'])
##
# \brief MANUALDCCRESET notification.
#
#
#
# Formatted as a Tuple_ManualDccReset named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>userName</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
MANUALDCCRESET = "ManualDccReset"
notifTupleTable[MANUALDCCRESET] = Tuple_ManualDccReset = collections.namedtuple("Tuple_ManualDccReset", ['timeStamp', 'eventId', 'userName'])
##
# \brief MANUALSTATRESET notification.
#
#
#
# Formatted as a Tuple_ManualStatReset named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>userName</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
MANUALSTATRESET = "ManualStatReset"
notifTupleTable[MANUALSTATRESET] = Tuple_ManualStatReset = collections.namedtuple("Tuple_ManualStatReset", ['timeStamp', 'eventId', 'userName'])
##
# \brief CONFIGCHANGE notification.
#
#
#
# Formatted as a Tuple_ConfigChange named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>userName</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>objectType</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>objectId</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
CONFIGCHANGE = "ConfigChange"
notifTupleTable[CONFIGCHANGE] = Tuple_ConfigChange = collections.namedtuple("Tuple_ConfigChange", ['timeStamp', 'eventId', 'userName', 'objectType', 'objectId'])
##
# \brief BOOTUP notification.
#
#
#
# Formatted as a Tuple_BootUp named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
BOOTUP = "BootUp"
notifTupleTable[BOOTUP] = Tuple_BootUp = collections.namedtuple("Tuple_BootUp", ['timeStamp', 'eventId'])
##
# \brief NETWORKRESET notification.
#
#
#
# Formatted as a Tuple_NetworkReset named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
NETWORKRESET = "NetworkReset"
notifTupleTable[NETWORKRESET] = Tuple_NetworkReset = collections.namedtuple("Tuple_NetworkReset", ['timeStamp', 'eventId'])
##
# \brief COMMANDFINISHED notification.
#
#
#
# Formatted as a Tuple_CommandFinished named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>callbackId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>objectType</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>resultCode</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
COMMANDFINISHED = "CommandFinished"
notifTupleTable[COMMANDFINISHED] = Tuple_CommandFinished = collections.namedtuple("Tuple_CommandFinished", ['timeStamp', 'eventId', 'callbackId', 'objectType', 'macAddr', 'resultCode'])
##
# \brief PACKETSENT notification.
#
#
#
# Formatted as a Tuple_PacketSent named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>callbackId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
PACKETSENT = "PacketSent"
notifTupleTable[PACKETSENT] = Tuple_PacketSent = collections.namedtuple("Tuple_PacketSent", ['timeStamp', 'eventId', 'callbackId', 'macAddr'])
##
# \brief MOTEJOIN notification.
#
#
#
# Formatted as a Tuple_MoteJoin named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>moteId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>reason</tt> 64-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>userData</tt> 64-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
MOTEJOIN = "MoteJoin"
notifTupleTable[MOTEJOIN] = Tuple_MoteJoin = collections.namedtuple("Tuple_MoteJoin", ['timeStamp', 'eventId', 'moteId', 'macAddr', 'reason', 'userData'])
##
# \brief MOTELIVE notification.
#
#
#
# Formatted as a Tuple_MoteLive named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>moteId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>reason</tt> 64-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
MOTELIVE = "MoteLive"
notifTupleTable[MOTELIVE] = Tuple_MoteLive = collections.namedtuple("Tuple_MoteLive", ['timeStamp', 'eventId', 'moteId', 'macAddr', 'reason'])
##
# \brief MOTEQUARANTINE notification.
#
#
#
# Formatted as a Tuple_MoteQuarantine named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>moteId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>reason</tt> 64-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
MOTEQUARANTINE = "MoteQuarantine"
notifTupleTable[MOTEQUARANTINE] = Tuple_MoteQuarantine = collections.namedtuple("Tuple_MoteQuarantine", ['timeStamp', 'eventId', 'moteId', 'macAddr', 'reason'])
##
# \brief MOTEJOINQUARANTINE notification.
#
#
#
# Formatted as a Tuple_MoteJoinQuarantine named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>moteId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>reason</tt> 64-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>userData</tt> 64-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
MOTEJOINQUARANTINE = "MoteJoinQuarantine"
notifTupleTable[MOTEJOINQUARANTINE] = Tuple_MoteJoinQuarantine = collections.namedtuple("Tuple_MoteJoinQuarantine", ['timeStamp', 'eventId', 'moteId', 'macAddr', 'reason', 'userData'])
##
# \brief MOTEUNKNOWN notification.
#
#
#
# Formatted as a Tuple_MoteUnknown named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>moteId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>reason</tt> 64-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
MOTEUNKNOWN = "MoteUnknown"
notifTupleTable[MOTEUNKNOWN] = Tuple_MoteUnknown = collections.namedtuple("Tuple_MoteUnknown", ['timeStamp', 'eventId', 'moteId', 'macAddr', 'reason'])
##
# \brief MOTEDISCONNECT notification.
#
#
#
# Formatted as a Tuple_MoteDisconnect named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>moteId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>reason</tt> 64-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
MOTEDISCONNECT = "MoteDisconnect"
notifTupleTable[MOTEDISCONNECT] = Tuple_MoteDisconnect = collections.namedtuple("Tuple_MoteDisconnect", ['timeStamp', 'eventId', 'moteId', 'macAddr', 'reason'])
##
# \brief MOTEJOINFAILURE notification.
#
#
#
# Formatted as a Tuple_MoteJoinFailure named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>reason</tt> 64-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
MOTEJOINFAILURE = "MoteJoinFailure"
notifTupleTable[MOTEJOINFAILURE] = Tuple_MoteJoinFailure = collections.namedtuple("Tuple_MoteJoinFailure", ['timeStamp', 'eventId', 'macAddr', 'reason'])
##
# \brief INVALIDMIC notification.
#
#
#
# Formatted as a Tuple_InvalidMIC named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
INVALIDMIC = "InvalidMIC"
notifTupleTable[INVALIDMIC] = Tuple_InvalidMIC = collections.namedtuple("Tuple_InvalidMIC", ['timeStamp', 'eventId', 'macAddr'])
##
# \brief PATHCREATE notification.
#
#
#
# Formatted as a Tuple_PathCreate named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>pathId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>moteAMac</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>moteBMac</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
PATHCREATE = "PathCreate"
notifTupleTable[PATHCREATE] = Tuple_PathCreate = collections.namedtuple("Tuple_PathCreate", ['timeStamp', 'eventId', 'pathId', 'moteAMac', 'moteBMac'])
##
# \brief PATHDELETE notification.
#
#
#
# Formatted as a Tuple_PathDelete named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>pathId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>moteAMac</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>moteBMac</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
PATHDELETE = "PathDelete"
notifTupleTable[PATHDELETE] = Tuple_PathDelete = collections.namedtuple("Tuple_PathDelete", ['timeStamp', 'eventId', 'pathId', 'moteAMac', 'moteBMac'])
##
# \brief PATHACTIVATE notification.
#
#
#
# Formatted as a Tuple_PathActivate named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>pathId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>moteAMac</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>moteBMac</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
PATHACTIVATE = "PathActivate"
notifTupleTable[PATHACTIVATE] = Tuple_PathActivate = collections.namedtuple("Tuple_PathActivate", ['timeStamp', 'eventId', 'pathId', 'moteAMac', 'moteBMac'])
##
# \brief PATHDEACTIVATE notification.
#
#
#
# Formatted as a Tuple_PathDeactivate named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>pathId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>moteAMac</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>moteBMac</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
PATHDEACTIVATE = "PathDeactivate"
notifTupleTable[PATHDEACTIVATE] = Tuple_PathDeactivate = collections.namedtuple("Tuple_PathDeactivate", ['timeStamp', 'eventId', 'pathId', 'moteAMac', 'moteBMac'])
##
# \brief PATHALERT notification.
#
#
#
# Formatted as a Tuple_PathAlert named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>pathId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>moteAMac</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>moteBMac</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
PATHALERT = "PathAlert"
notifTupleTable[PATHALERT] = Tuple_PathAlert = collections.namedtuple("Tuple_PathAlert", ['timeStamp', 'eventId', 'pathId', 'moteAMac', 'moteBMac'])
##
# \brief PIPEON notification.
#
#
#
# Formatted as a Tuple_PipeOn named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>allocatedPipePkPeriod</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
PIPEON = "PipeOn"
notifTupleTable[PIPEON] = Tuple_PipeOn = collections.namedtuple("Tuple_PipeOn", ['timeStamp', 'eventId', 'macAddr', 'allocatedPipePkPeriod'])
##
# \brief PIPEOFF notification.
#
#
#
# Formatted as a Tuple_PipeOff named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
PIPEOFF = "PipeOff"
notifTupleTable[PIPEOFF] = Tuple_PipeOff = collections.namedtuple("Tuple_PipeOff", ['timeStamp', 'eventId', 'macAddr'])
##
# \brief SERVICEDENIED notification.
#
#
#
# Formatted as a Tuple_ServiceDenied named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>serviceId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>requestingMacAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>peerMacAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>appDomain</tt> 32-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - maintenance: maintenance
# - <tt>isSource</tt> 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>isSink</tt> 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>isIntermittent</tt> 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>period</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
SERVICEDENIED = "ServiceDenied"
notifTupleTable[SERVICEDENIED] = Tuple_ServiceDenied = collections.namedtuple("Tuple_ServiceDenied", ['timeStamp', 'eventId', 'serviceId', 'requestingMacAddr', 'peerMacAddr', 'appDomain', 'isSource', 'isSink', 'isIntermittent', 'period'])
##
# \brief PINGREPLY notification.
#
#
#
# Formatted as a Tuple_PingReply named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>callbackId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>latency</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>temperature</tt> 8-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# - <tt>voltage</tt> 8-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# - <tt>hopCount</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
PINGREPLY = "PingReply"
notifTupleTable[PINGREPLY] = Tuple_PingReply = collections.namedtuple("Tuple_PingReply", ['timeStamp', 'eventId', 'macAddr', 'callbackId', 'latency', 'temperature', 'voltage', 'hopCount'])
##
# \brief TRANSPORTTIMEOUT notification.
#
#
#
# Formatted as a Tuple_TransportTimeout named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>srcMacAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>destMacAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>timeoutType</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>callbackId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
TRANSPORTTIMEOUT = "TransportTimeout"
notifTupleTable[TRANSPORTTIMEOUT] = Tuple_TransportTimeout = collections.namedtuple("Tuple_TransportTimeout", ['timeStamp', 'eventId', 'srcMacAddr', 'destMacAddr', 'timeoutType', 'callbackId'])
##
# \brief DATA notification.
#
#
#
# Formatted as a Tuple_data named tuple. It contains the following fields:
# - <tt>moteId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>time</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>payload</tt> None-byte field formatted as a hex.<br/>
# There is no restriction on the value of this field.
# - <tt>payloadType</tt> 1-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>isReliable</tt> 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>isRequest</tt> 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>isBroadcast</tt> 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>callbackId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>counter</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
DATA = "data"
notifTupleTable[DATA] = Tuple_data = collections.namedtuple("Tuple_data", ['moteId', 'macAddr', 'time', 'payload', 'payloadType', 'isReliable', 'isRequest', 'isBroadcast', 'callbackId', 'counter'])
##
# \brief LOCATION notification.
#
#
#
# Formatted as a Tuple_Location named tuple. It contains the following fields:
# - <tt>ver</tt> 1-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>asn</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>src</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>dest</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>payload</tt> None-byte field formatted as a hex.<br/>
# There is no restriction on the value of this field.
#
LOCATION = "Location"
notifTupleTable[LOCATION] = Tuple_Location = collections.namedtuple("Tuple_Location", ['ver', 'asn', 'src', 'dest', 'payload'])
##
# \brief CLI notification.
#
#
#
# Formatted as a Tuple_cli named tuple. It contains the following fields:
# - <tt>time</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>message</tt> 128-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
CLI = "cli"
notifTupleTable[CLI] = Tuple_cli = collections.namedtuple("Tuple_cli", ['time', 'message'])
##
# \brief LOG notification.
#
#
#
# Formatted as a Tuple_log named tuple. It contains the following fields:
# - <tt>time</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>severity</tt> 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>message</tt> 128-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
LOG = "log"
notifTupleTable[LOG] = Tuple_log = collections.namedtuple("Tuple_log", ['time', 'severity', 'message'])
##
# \brief STDMOTEREPORT notification.
#
#
#
# Formatted as a Tuple_stdMoteReport named tuple. It contains the following fields:
# - <tt>time</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>payload</tt> None-byte field formatted as a hex.<br/>
# There is no restriction on the value of this field.
#
STDMOTEREPORT = "stdMoteReport"
notifTupleTable[STDMOTEREPORT] = Tuple_stdMoteReport = collections.namedtuple("Tuple_stdMoteReport", ['time', 'macAddr', 'payload'])
##
# \brief VENDORMOTEREPORT notification.
#
#
#
# Formatted as a Tuple_vendorMoteReport named tuple. It contains the following fields:
# - <tt>time</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>payload</tt> None-byte field formatted as a hex.<br/>
# There is no restriction on the value of this field.
#
VENDORMOTEREPORT = "vendorMoteReport"
notifTupleTable[VENDORMOTEREPORT] = Tuple_vendorMoteReport = collections.namedtuple("Tuple_vendorMoteReport", ['time', 'macAddr', 'payload'])
##
# \brief Get a notification from the notification queue, and returns
# it properly formatted.
#
# \exception NotificationError if unknown notification.
#
def getNotification(self, timeoutSec=-1) :
temp = self.getNotificationInternal(timeoutSec)
if not temp:
return temp
(ids, param) = temp
try :
if HartMgrConnector.notifTupleTable[ids[-1]] :
return (ids[-1], HartMgrConnector.notifTupleTable[ids[-1]](**param))
else :
return (ids[-1], None)
except KeyError :
raise ApiException.NotificationError(ids, param)
##
# end of HartMgrConnector
# \}
#
| 48.681442 | 566 | 0.635729 |
import collections
from SmartMeshSDK import ApiException
from HartMgrConnectorInternal import HartMgrConnectorInternal
class HartMgrConnector(HartMgrConnectorInternal):
Tuple_dn_activateAdvertising = collections.namedtuple("Tuple_dn_activateAdvertising", ['result'])
macAddr, timeout) :
res = HartMgrConnectorInternal.send(self, ['activateAdvertising'], {"macAddr" : macAddr, "timeout" : timeout})
return HartMgrConnector.Tuple_dn_activateAdvertising(**res)
Tuple_dn_activateFastPipe = collections.namedtuple("Tuple_dn_activateFastPipe", ['result'])
macAddr, pipeDirection) :
res = HartMgrConnectorInternal.send(self, ['activateFastPipe'], {"macAddr" : macAddr, "pipeDirection" : pipeDirection})
return HartMgrConnector.Tuple_dn_activateFastPipe(**res)
Tuple_dn_cancelOtap = collections.namedtuple("Tuple_dn_cancelOtap", ['result'])
) :
res = HartMgrConnectorInternal.send(self, ['cancelOtap'], {})
return HartMgrConnector.Tuple_dn_cancelOtap(**res)
Tuple_dn_cli = collections.namedtuple("Tuple_dn_cli", ['result'])
#
# \param command 128-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_cli named tuple.
#
def dn_cli(self, command) :
res = HartMgrConnectorInternal.send(self, ['cli'], {"command" : command})
return HartMgrConnector.Tuple_dn_cli(**res)
##
# The named tuple returned by the dn_deactivateFastPipe() function.
#
# - <tt>result</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_deactivateFastPipe = collections.namedtuple("Tuple_dn_deactivateFastPipe", ['result'])
##
# Deactivate the fast network pipe to the specified mote.
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_deactivateFastPipe named tuple.
#
def dn_deactivateFastPipe(self, macAddr) :
res = HartMgrConnectorInternal.send(self, ['deactivateFastPipe'], {"macAddr" : macAddr})
return HartMgrConnector.Tuple_dn_deactivateFastPipe(**res)
##
# Remove a device from the ACL
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command.
#
def dn_deleteAcl(self, macAddr) :
res = HartMgrConnectorInternal.send(self, ['deleteAcl'], {"macAddr" : macAddr})
return res
##
# Remove a mote from the manager configuration
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command.
#
def dn_deleteMote(self, macAddr) :
res = HartMgrConnectorInternal.send(self, ['deleteMote'], {"macAddr" : macAddr})
return res
##
# Remove a user
#
# \param userName 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command.
#
def dn_deleteUser(self, userName) :
res = HartMgrConnectorInternal.send(self, ['deleteUser'], {"userName" : userName})
return res
##
# The named tuple returned by the dn_exchangeJoinKey() function.
#
# - <tt>callbackId</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_exchangeJoinKey = collections.namedtuple("Tuple_dn_exchangeJoinKey", ['callbackId'])
##
# Exchange the common join key
#
# \param newKey 16-byte field formatted as a hex.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_exchangeJoinKey named tuple.
#
def dn_exchangeJoinKey(self, newKey) :
res = HartMgrConnectorInternal.send(self, ['exchangeJoinKey'], {"newKey" : newKey})
return HartMgrConnector.Tuple_dn_exchangeJoinKey(**res)
##
# The named tuple returned by the dn_exchangeMoteJoinKey() function.
#
# - <tt>callbackId</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_exchangeMoteJoinKey = collections.namedtuple("Tuple_dn_exchangeMoteJoinKey", ['callbackId'])
##
# Exchange a mote's join key
macAddr, newKey) :
res = HartMgrConnectorInternal.send(self, ['exchangeMoteJoinKey'], {"macAddr" : macAddr, "newKey" : newKey})
return HartMgrConnector.Tuple_dn_exchangeMoteJoinKey(**res)
Tuple_dn_exchangeMoteNetworkId = collections.namedtuple("Tuple_dn_exchangeMoteNetworkId", ['callbackId'])
macAddr, newId) :
res = HartMgrConnectorInternal.send(self, ['exchangeMoteNetworkId'], {"macAddr" : macAddr, "newId" : newId})
return HartMgrConnector.Tuple_dn_exchangeMoteNetworkId(**res)
Tuple_dn_exchangeNetworkKey = collections.namedtuple("Tuple_dn_exchangeNetworkKey", ['callbackId'])
) :
res = HartMgrConnectorInternal.send(self, ['exchangeNetworkKey'], {})
return HartMgrConnector.Tuple_dn_exchangeNetworkKey(**res)
Tuple_dn_exchangeNetworkId = collections.namedtuple("Tuple_dn_exchangeNetworkId", ['callbackId'])
newId) :
res = HartMgrConnectorInternal.send(self, ['exchangeNetworkId'], {"newId" : newId})
return HartMgrConnector.Tuple_dn_exchangeNetworkId(**res)
Tuple_dn_exchangeSessionKey = collections.namedtuple("Tuple_dn_exchangeSessionKey", ['callbackId'])
#
# \param macAddrA 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param macAddrB 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_exchangeSessionKey named tuple.
#
def dn_exchangeSessionKey(self, macAddrA, macAddrB) :
res = HartMgrConnectorInternal.send(self, ['exchangeSessionKey'], {"macAddrA" : macAddrA, "macAddrB" : macAddrB})
return HartMgrConnector.Tuple_dn_exchangeSessionKey(**res)
##
# The named tuple returned by the dn_decommissionDevice() function.
#
# - <tt>result</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_decommissionDevice = collections.namedtuple("Tuple_dn_decommissionDevice", ['result'])
##
# Decommission a device in the network
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_decommissionDevice named tuple.
#
def dn_decommissionDevice(self, macAddr) :
res = HartMgrConnectorInternal.send(self, ['decommissionDevice'], {"macAddr" : macAddr})
return HartMgrConnector.Tuple_dn_decommissionDevice(**res)
##
# The named tuple returned by the dn_getAcl() function.
#
# - <tt>macAddr</tt>: 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_getAcl = collections.namedtuple("Tuple_dn_getAcl", ['macAddr'])
##
# Check whether a device is part of the ACL
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_getAcl named tuple.
#
def dn_getAcl(self, macAddr) :
res = HartMgrConnectorInternal.send(self, ['getAcl'], {"macAddr" : macAddr})
return HartMgrConnector.Tuple_dn_getAcl(**res)
##
# The named tuple returned by the dn_getAcls() function.
#
# - <tt>macAddr</tt>: 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_getAcls = collections.namedtuple("Tuple_dn_getAcls", ['macAddr'])
##
# Get the list of devices on the ACL
#
#
#
# \returns The response to the command, formatted as a list of #Tuple_dn_getAcls named tuple.
#
def dn_getAcls(self, ) :
res = HartMgrConnectorInternal.send(self, ['getAcls'], {})
tupleList = []
for r in res :
tupleList.append(HartMgrConnector.Tuple_dn_getAcls(**r))
return tupleList
##
# The named tuple returned by the dn_getBlacklist() function.
#
# - <tt>frequency</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_getBlacklist = collections.namedtuple("Tuple_dn_getBlacklist", ['frequency'])
##
# Get the channel blacklist
#
#
#
# \returns The response to the command, formatted as a list of #Tuple_dn_getBlacklist named tuple.
#
def dn_getBlacklist(self, ) :
res = HartMgrConnectorInternal.send(self, ['getBlacklist'], {})
tupleList = []
for r in res :
tupleList.append(HartMgrConnector.Tuple_dn_getBlacklist(**r))
return tupleList
##
# The named tuple returned by the dn_getMote() function.
#
# - <tt>moteId</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt>: 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>name</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>state</tt>: 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - Idle: idle
# - Lost: lost
# - Joining: joining
# - Operational: operational
# - Disconnecting: disconnecting
# - <tt>numJoins</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>joinTime</tt>: 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>reason</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>isAccessPoint</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>powerSource</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>dischargeCurrent</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>dischargeTime</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>recoveryTime</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>enableRouting</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>productName</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>hwModel</tt>: 1-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>hwRev</tt>: 1-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>swRev</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>voltage</tt>: 8-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# - <tt>numNeighbors</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>needNeighbor</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>goodNeighbors</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>allocatedPkPeriod</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>allocatedPipePkPeriod</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>pipeStatus</tt>: 4-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - off: off
# - pending: Pipe activation pending
# - on_bi: Bidirection pipe on
# - on_up: Upstream pipe on
# - on_down: Downstream pipe on
# - <tt>advertisingStatus</tt>: 4-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - on: on
# - off: off
# - pending: pending
# - <tt>locationTag</tt>: 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - supported: supported
# - not supported: not supported
#
Tuple_dn_getMote = collections.namedtuple("Tuple_dn_getMote", ['moteId', 'macAddr', 'name', 'state', 'numJoins', 'joinTime', 'reason', 'isAccessPoint', 'powerSource', 'dischargeCurrent', 'dischargeTime', 'recoveryTime', 'enableRouting', 'productName', 'hwModel', 'hwRev', 'swRev', 'voltage', 'numNeighbors', 'needNeighbor', 'goodNeighbors', 'allocatedPkPeriod', 'allocatedPipePkPeriod', 'pipeStatus', 'advertisingStatus', 'locationTag'])
##
#
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_getMote named tuple.
#
def dn_getMote(self, macAddr) :
res = HartMgrConnectorInternal.send(self, ['getMote'], {"macAddr" : macAddr})
return HartMgrConnector.Tuple_dn_getMote(**res)
##
# The named tuple returned by the dn_setMote() function.
#
# - <tt>moteId</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt>: 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>name</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>state</tt>: 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - Idle: idle
# - Lost: lost
# - Joining: joining
# - Operational: operational
# - Disconnecting: disconnecting
# - <tt>numJoins</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>joinTime</tt>: 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>reason</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>isAccessPoint</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>powerSource</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>dischargeCurrent</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>dischargeTime</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>recoveryTime</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>enableRouting</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>productName</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>hwModel</tt>: 1-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>hwRev</tt>: 1-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>swRev</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>voltage</tt>: 8-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# - <tt>numNeighbors</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>needNeighbor</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>goodNeighbors</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>allocatedPkPeriod</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>allocatedPipePkPeriod</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>pipeStatus</tt>: 4-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - off: off
# - pending: Pipe activation pending
# - on_bi: Bidirection pipe on
# - on_up: Upstream pipe on
# - on_down: Downstream pipe on
# - <tt>advertisingStatus</tt>: 4-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - on: on
# - off: off
# - pending: pending
# - <tt>locationTag</tt>: 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - supported: supported
# - not supported: not supported
#
Tuple_dn_setMote = collections.namedtuple("Tuple_dn_setMote", ['moteId', 'macAddr', 'name', 'state', 'numJoins', 'joinTime', 'reason', 'isAccessPoint', 'powerSource', 'dischargeCurrent', 'dischargeTime', 'recoveryTime', 'enableRouting', 'productName', 'hwModel', 'hwRev', 'swRev', 'voltage', 'numNeighbors', 'needNeighbor', 'goodNeighbors', 'allocatedPkPeriod', 'allocatedPipePkPeriod', 'pipeStatus', 'advertisingStatus', 'locationTag'])
##
# Set mote configuration
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param name 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param enableRouting 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_setMote named tuple.
#
def dn_setMote(self, macAddr, name, enableRouting) :
res = HartMgrConnectorInternal.send(self, ['setMote'], {"macAddr" : macAddr, "name" : name, "enableRouting" : enableRouting})
return HartMgrConnector.Tuple_dn_setMote(**res)
##
# The named tuple returned by the dn_getMotes() function.
#
# - <tt>moteId</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt>: 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>name</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>state</tt>: 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - Idle: idle
# - Lost: lost
# - Joining: joining
# - Operational: operational
# - Disconnecting: disconnecting
# - <tt>numJoins</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>joinTime</tt>: 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>reason</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>isAccessPoint</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>powerSource</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>dischargeCurrent</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>dischargeTime</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>recoveryTime</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>enableRouting</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>productName</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>hwModel</tt>: 1-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>hwRev</tt>: 1-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>swRev</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>voltage</tt>: 8-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# - <tt>numNeighbors</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>needNeighbor</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>goodNeighbors</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>allocatedPkPeriod</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>allocatedPipePkPeriod</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>pipeStatus</tt>: 4-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - off: off
# - pending: Pipe activation pending
# - on_bi: Bidirection pipe on
# - on_up: Upstream pipe on
# - on_down: Downstream pipe on
# - <tt>advertisingStatus</tt>: 4-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - on: on
# - off: off
# - pending: pending
# - <tt>locationTag</tt>: 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - supported: supported
# - not supported: not supported
#
Tuple_dn_getMotes = collections.namedtuple("Tuple_dn_getMotes", ['moteId', 'macAddr', 'name', 'state', 'numJoins', 'joinTime', 'reason', 'isAccessPoint', 'powerSource', 'dischargeCurrent', 'dischargeTime', 'recoveryTime', 'enableRouting', 'productName', 'hwModel', 'hwRev', 'swRev', 'voltage', 'numNeighbors', 'needNeighbor', 'goodNeighbors', 'allocatedPkPeriod', 'allocatedPipePkPeriod', 'pipeStatus', 'advertisingStatus', 'locationTag'])
##
# Get the list of Motes
#
#
#
# \returns The response to the command, formatted as a list of #Tuple_dn_getMotes named tuple.
#
def dn_getMotes(self, ) :
res = HartMgrConnectorInternal.send(self, ['getMotes'], {})
tupleList = []
for r in res :
tupleList.append(HartMgrConnector.Tuple_dn_getMotes(**r))
return tupleList
##
# The named tuple returned by the dn_getMoteStatistics() function.
#
# - <tt>index</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>startTime</tt>: 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>avgLatency</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>reliability</tt>: 0-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# - <tt>numJoins</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>voltage</tt>: 4-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# - <tt>chargeConsumption</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>temperature</tt>: 4-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# - <tt>numLostPackets</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>latencyToMote</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_getMoteStatistics = collections.namedtuple("Tuple_dn_getMoteStatistics", ['index', 'startTime', 'avgLatency', 'reliability', 'numJoins', 'voltage', 'chargeConsumption', 'temperature', 'numLostPackets', 'latencyToMote'])
##
# Get the Mote Statistics
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param period 32-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - current: current
# - lifetime: lifetime
# - short: short
# - long: long
# \param index 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_getMoteStatistics named tuple.
#
def dn_getMoteStatistics(self, macAddr, period, index) :
res = HartMgrConnectorInternal.send(self, ['getMoteStatistics'], {"macAddr" : macAddr, "period" : period, "index" : index})
return HartMgrConnector.Tuple_dn_getMoteStatistics(**res)
##
# The named tuple returned by the dn_getNetwork() function.
#
# - <tt>netName</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>networkId</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>maxMotes</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>numMotes</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>optimizationEnable</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>accessPointPA</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>ccaEnabled</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>requestedBasePkPeriod</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>minServicesPkPeriod</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>minPipePkPeriod</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>bandwidthProfile</tt>: 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - Manual: manual profile
# - P1: normal profile
# - P2: low-power profile
# - <tt>manualUSFrameSize</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>manualDSFrameSize</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>manualAdvFrameSize</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>netQueueSize</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>userQueueSize</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>locationMode</tt>: 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - on: on
# - off: off
# - <tt>backboneEnabled</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>backboneSize</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_getNetwork = collections.namedtuple("Tuple_dn_getNetwork", ['netName', 'networkId', 'maxMotes', 'numMotes', 'optimizationEnable', 'accessPointPA', 'ccaEnabled', 'requestedBasePkPeriod', 'minServicesPkPeriod', 'minPipePkPeriod', 'bandwidthProfile', 'manualUSFrameSize', 'manualDSFrameSize', 'manualAdvFrameSize', 'netQueueSize', 'userQueueSize', 'locationMode', 'backboneEnabled', 'backboneSize'])
##
# Retrieves network configuration parameters
#
#
#
# \returns The response to the command, formatted as a #Tuple_dn_getNetwork named tuple.
#
def dn_getNetwork(self, ) :
res = HartMgrConnectorInternal.send(self, ['getNetwork'], {})
return HartMgrConnector.Tuple_dn_getNetwork(**res)
##
# The named tuple returned by the dn_getNetworkStatistics() function.
#
# - <tt>index</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>startTime</tt>: 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>netLatency</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>netReliability</tt>: 0-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# - <tt>netPathStability</tt>: 0-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# - <tt>lostUpstreamPackets</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_getNetworkStatistics = collections.namedtuple("Tuple_dn_getNetworkStatistics", ['index', 'startTime', 'netLatency', 'netReliability', 'netPathStability', 'lostUpstreamPackets'])
##
# Get the Network Statistics
#
# \param period 32-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - current: current
# - lifetime: lifetime
# - short: short
# - long: long
# \param index 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_getNetworkStatistics named tuple.
#
def dn_getNetworkStatistics(self, period, index) :
res = HartMgrConnectorInternal.send(self, ['getNetworkStatistics'], {"period" : period, "index" : index})
return HartMgrConnector.Tuple_dn_getNetworkStatistics(**res)
##
# The named tuple returned by the dn_getOpenAlarms() function.
#
# - <tt>timeStamp</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>alarmType</tt>: 32-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - moteDown: Mote down alarm
# - slaReliability: SLA Reliability
# - slaLatency: SLA Latency
# - slaStability: SLA Stability
# - maxMotesReached: Maximum number of motes reached
# - bbLatencyWarn: Backbone latency warning
# - <tt>macAddr</tt>: 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_getOpenAlarms = collections.namedtuple("Tuple_dn_getOpenAlarms", ['timeStamp', 'eventId', 'alarmType', 'macAddr'])
##
# Retrieves a list of the open alarms on the Manager
#
#
#
# \returns The response to the command, formatted as a list of #Tuple_dn_getOpenAlarms named tuple.
#
def dn_getOpenAlarms(self, ) :
res = HartMgrConnectorInternal.send(self, ['getOpenAlarms'], {})
tupleList = []
for r in res :
tupleList.append(HartMgrConnector.Tuple_dn_getOpenAlarms(**r))
return tupleList
##
# The named tuple returned by the dn_getPaths() function.
#
# - <tt>pathId</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>moteAMac</tt>: 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>moteBMac</tt>: 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>numLinks</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>pathDirection</tt>: 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - all: all
# - upstream: upstream
# - downstream: downstream
# - unused: unused
# - <tt>pathQuality</tt>: 0-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_getPaths = collections.namedtuple("Tuple_dn_getPaths", ['pathId', 'moteAMac', 'moteBMac', 'numLinks', 'pathDirection', 'pathQuality'])
##
# Get the list of Paths to the mote's neighbors
moteMac) :
res = HartMgrConnectorInternal.send(self, ['getPaths'], {"moteMac" : moteMac})
tupleList = []
for r in res :
tupleList.append(HartMgrConnector.Tuple_dn_getPaths(**r))
return tupleList
Tuple_dn_getPathStatistics = collections.namedtuple("Tuple_dn_getPathStatistics", ['index', 'startTime', 'baPwr', 'abPwr', 'stability'])
pathId, period, index) :
res = HartMgrConnectorInternal.send(self, ['getPathStatistics'], {"pathId" : pathId, "period" : period, "index" : index})
return HartMgrConnector.Tuple_dn_getPathStatistics(**res)
Tuple_dn_getRedundancy = collections.namedtuple("Tuple_dn_getRedundancy", ['localMode', 'peerStatus', 'peerControllerSwRev'])
) :
res = HartMgrConnectorInternal.send(self, ['getRedundancy'], {})
return HartMgrConnector.Tuple_dn_getRedundancy(**res)
Tuple_dn_getSecurity = collections.namedtuple("Tuple_dn_getSecurity", ['securityMode', 'acceptHARTDevicesOnly'])
) :
res = HartMgrConnectorInternal.send(self, ['getSecurity'], {})
return HartMgrConnector.Tuple_dn_getSecurity(**res)
Tuple_dn_getSla = collections.namedtuple("Tuple_dn_getSla", ['minNetReliability', 'maxNetLatency', 'minNetPathStability', 'apRdntCoverageThreshold'])
) :
res = HartMgrConnectorInternal.send(self, ['getSla'], {})
return HartMgrConnector.Tuple_dn_getSla(**res)
Tuple_dn_getSystem = collections.namedtuple("Tuple_dn_getSystem", ['systemName', 'location', 'swRev', 'hwModel', 'hwRev', 'serialNumber', 'time', 'startTime', 'cliTimeout', 'controllerSwRev'])
) :
res = HartMgrConnectorInternal.send(self, ['getSystem'], {})
return HartMgrConnector.Tuple_dn_getSystem(**res)
Tuple_dn_getUser = collections.namedtuple("Tuple_dn_getUser", ['userName', 'privilege'])
userName) :
res = HartMgrConnectorInternal.send(self, ['getUser'], {"userName" : userName})
return HartMgrConnector.Tuple_dn_getUser(**res)
Tuple_dn_getUsers = collections.namedtuple("Tuple_dn_getUsers", ['userName', 'privilege'])
) :
res = HartMgrConnectorInternal.send(self, ['getUsers'], {})
tupleList = []
for r in res :
tupleList.append(HartMgrConnector.Tuple_dn_getUsers(**r))
return tupleList
Tuple_dn_getSourceRoute = collections.namedtuple("Tuple_dn_getSourceRoute", ['destMacAddr', 'primaryPath', 'secondaryPath'])
destMacAddr) :
res = HartMgrConnectorInternal.send(self, ['getSourceRoute'], {"destMacAddr" : destMacAddr})
return HartMgrConnector.Tuple_dn_getSourceRoute(**res)
Tuple_dn_getLatency = collections.namedtuple("Tuple_dn_getLatency", ['downstream', 'upstream'])
macAddr) :
res = HartMgrConnectorInternal.send(self, ['getLatency'], {"macAddr" : macAddr})
return HartMgrConnector.Tuple_dn_getLatency(**res)
Tuple_dn_getLicense = collections.namedtuple("Tuple_dn_getLicense", ['license'])
) :
res = HartMgrConnectorInternal.send(self, ['getLicense'], {})
return HartMgrConnector.Tuple_dn_getLicense(**res)
Tuple_dn_getTime = collections.namedtuple("Tuple_dn_getTime", ['utc_time', 'asn_time'])
) :
res = HartMgrConnectorInternal.send(self, ['getTime'], {})
return HartMgrConnector.Tuple_dn_getTime(**res)
Tuple_dn_pingMote = collections.namedtuple("Tuple_dn_pingMote", ['callbackId'])
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_pingMote named tuple.
#
def dn_pingMote(self, macAddr) :
res = HartMgrConnectorInternal.send(self, ['pingMote'], {"macAddr" : macAddr})
return HartMgrConnector.Tuple_dn_pingMote(**res)
##
# The named tuple returned by the dn_promoteToOperational() function.
#
# - <tt>result</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_promoteToOperational = collections.namedtuple("Tuple_dn_promoteToOperational", ['result'])
##
# Promote a quarantined device to operational
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_promoteToOperational named tuple.
#
def dn_promoteToOperational(self, macAddr) :
res = HartMgrConnectorInternal.send(self, ['promoteToOperational'], {"macAddr" : macAddr})
return HartMgrConnector.Tuple_dn_promoteToOperational(**res)
##
# The named tuple returned by the dn_reset() function.
#
# - <tt>result</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_reset = collections.namedtuple("Tuple_dn_reset", ['result'])
##
# Reset the system or network
#
# \param object 25-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - network: network
# - system: system
# - stat: statistics
# - eventLog: eventLog
#
# \returns The response to the command, formatted as a #Tuple_dn_reset named tuple.
#
def dn_reset(self, object) :
res = HartMgrConnectorInternal.send(self, ['reset'], {"object" : object})
return HartMgrConnector.Tuple_dn_reset(**res)
##
# The named tuple returned by the dn_resetWithId() function.
#
# - <tt>result</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_resetWithId = collections.namedtuple("Tuple_dn_resetWithId", ['result'])
##
# Reset mote by ID
#
# \param object 25-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - mote: mote
# \param moteId 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_resetWithId named tuple.
#
def dn_resetWithId(self, object, moteId) :
res = HartMgrConnectorInternal.send(self, ['resetWithId'], {"object" : object, "moteId" : moteId})
return HartMgrConnector.Tuple_dn_resetWithId(**res)
##
# The named tuple returned by the dn_resetWithMac() function.
#
# - <tt>result</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_resetWithMac = collections.namedtuple("Tuple_dn_resetWithMac", ['result'])
##
# Reset mote by MAC address
#
# \param object 25-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - mote: mote
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_resetWithMac named tuple.
#
def dn_resetWithMac(self, object, macAddr) :
res = HartMgrConnectorInternal.send(self, ['resetWithMac'], {"object" : object, "macAddr" : macAddr})
return HartMgrConnector.Tuple_dn_resetWithMac(**res)
##
# The named tuple returned by the dn_sendRequest() function.
#
# - <tt>callbackId</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_sendRequest = collections.namedtuple("Tuple_dn_sendRequest", ['callbackId'])
##
# Send downstream (request) data
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param domain 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - maintenance: maintenance
# \param priority 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - low: low
# - high: high
# \param reliable 0-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# \param data None-byte field formatted as a hex.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_sendRequest named tuple.
#
def dn_sendRequest(self, macAddr, domain, priority, reliable, data) :
res = HartMgrConnectorInternal.send(self, ['sendRequest'], {"macAddr" : macAddr, "domain" : domain, "priority" : priority, "reliable" : reliable, "data" : data})
return HartMgrConnector.Tuple_dn_sendRequest(**res)
##
# The named tuple returned by the dn_sendResponse() function.
#
# - <tt>callbackId</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_sendResponse = collections.namedtuple("Tuple_dn_sendResponse", ['callbackId'])
##
# Send downstream data as a response. sendResponse should only be used in special cases.
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param domain 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - maintenance: maintenance
# \param priority 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - low: low
# - high: high
# \param reliable 0-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# \param callbackId 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# \param data None-byte field formatted as a hex.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_sendResponse named tuple.
#
def dn_sendResponse(self, macAddr, domain, priority, reliable, callbackId, data) :
res = HartMgrConnectorInternal.send(self, ['sendResponse'], {"macAddr" : macAddr, "domain" : domain, "priority" : priority, "reliable" : reliable, "callbackId" : callbackId, "data" : data})
return HartMgrConnector.Tuple_dn_sendResponse(**res)
##
# The named tuple returned by the dn_setAcl() function.
#
# - <tt>macAddr</tt>: 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_setAcl = collections.namedtuple("Tuple_dn_setAcl", ['macAddr'])
##
# Add or update a device in the ACL
#
# \param macAddr 25-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param joinKey 16-byte field formatted as a hex.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_setAcl named tuple.
#
def dn_setAcl(self, macAddr, joinKey) :
res = HartMgrConnectorInternal.send(self, ['setAcl'], {"macAddr" : macAddr, "joinKey" : joinKey})
return HartMgrConnector.Tuple_dn_setAcl(**res)
##
# The named tuple returned by the dn_setBlacklist() function.
#
# - <tt>frequency</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_setBlacklist = collections.namedtuple("Tuple_dn_setBlacklist", ['frequency'])
##
# Update the channel blacklist
#
# \param frequency 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_setBlacklist named tuple.
#
def dn_setBlacklist(self, frequency) :
res = HartMgrConnectorInternal.send(self, ['setBlacklist'], {"frequency" : frequency})
return HartMgrConnector.Tuple_dn_setBlacklist(**res)
##
# The named tuple returned by the dn_setNetwork() function.
#
# - <tt>netName</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>networkId</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>maxMotes</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>optimizationEnable</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>accessPointPA</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>ccaEnabled</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>requestedBasePkPeriod</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>minServicesPkPeriod</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>minPipePkPeriod</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>bandwidthProfile</tt>: 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - Manual: manual profile
# - P1: normal profile
# - P2: low-power profile
# - <tt>manualUSFrameSize</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>manualDSFrameSize</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>manualAdvFrameSize</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>locationMode</tt>: 8-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - on: on
# - off: off
# - <tt>backboneEnabled</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>backboneSize</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_setNetwork = collections.namedtuple("Tuple_dn_setNetwork", ['netName', 'networkId', 'maxMotes', 'optimizationEnable', 'accessPointPA', 'ccaEnabled', 'requestedBasePkPeriod', 'minServicesPkPeriod', 'minPipePkPeriod', 'bandwidthProfile', 'manualUSFrameSize', 'manualDSFrameSize', 'manualAdvFrameSize', 'locationMode', 'backboneEnabled', 'backboneSize'])
##
# Set network configuration
#
# \param netName 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param networkId 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# \param maxMotes 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# \param optimizationEnable 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# \param accessPointPA 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# \param ccaEnabled 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# \param requestedBasePkPeriod 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# \param minServicesPkPeriod 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# \param minPipePkPeriod 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# \param bandwidthProfile 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - Manual: manual profile
# - P1: normal profile
# - P2: low-power profile
# \param manualUSFrameSize 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# \param manualDSFrameSize 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# \param manualAdvFrameSize 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# \param locationMode 8-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - on: on
# - off: off
#
# \returns The response to the command, formatted as a #Tuple_dn_setNetwork named tuple.
#
def dn_setNetwork(self, netName, networkId, maxMotes, optimizationEnable, accessPointPA, ccaEnabled, requestedBasePkPeriod, minServicesPkPeriod, minPipePkPeriod, bandwidthProfile, manualUSFrameSize, manualDSFrameSize, manualAdvFrameSize, locationMode) :
res = HartMgrConnectorInternal.send(self, ['setNetwork'], {"netName" : netName, "networkId" : networkId, "maxMotes" : maxMotes, "optimizationEnable" : optimizationEnable, "accessPointPA" : accessPointPA, "ccaEnabled" : ccaEnabled, "requestedBasePkPeriod" : requestedBasePkPeriod, "minServicesPkPeriod" : minServicesPkPeriod, "minPipePkPeriod" : minPipePkPeriod, "bandwidthProfile" : bandwidthProfile, "manualUSFrameSize" : manualUSFrameSize, "manualDSFrameSize" : manualDSFrameSize, "manualAdvFrameSize" : manualAdvFrameSize, "locationMode" : locationMode})
return HartMgrConnector.Tuple_dn_setNetwork(**res)
##
# The named tuple returned by the dn_setSecurity() function.
#
# - <tt>securityMode</tt>: 20-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - acceptACL: Accept ACL
# - acceptCommonJoinKey: Accept common join key
# - <tt>acceptHARTDevicesOnly</tt>: 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_setSecurity = collections.namedtuple("Tuple_dn_setSecurity", ['securityMode', 'acceptHARTDevicesOnly'])
##
# Set security configuration
#
# \param securityMode 20-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - acceptACL: Accept ACL
# - acceptCommonJoinKey: Accept common join key
# \param commonJoinKey 16-byte field formatted as a hex.<br/>
# There is no restriction on the value of this field.
# \param acceptHARTDevicesOnly 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_setSecurity named tuple.
#
def dn_setSecurity(self, securityMode, commonJoinKey, acceptHARTDevicesOnly) :
res = HartMgrConnectorInternal.send(self, ['setSecurity'], {"securityMode" : securityMode, "commonJoinKey" : commonJoinKey, "acceptHARTDevicesOnly" : acceptHARTDevicesOnly})
return HartMgrConnector.Tuple_dn_setSecurity(**res)
##
# The named tuple returned by the dn_setSla() function.
#
# - <tt>minNetReliability</tt>: 8-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# - <tt>maxNetLatency</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>minNetPathStability</tt>: 8-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# - <tt>apRdntCoverageThreshold</tt>: 8-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_setSla = collections.namedtuple("Tuple_dn_setSla", ['minNetReliability', 'maxNetLatency', 'minNetPathStability', 'apRdntCoverageThreshold'])
##
# Set SLA configuration
#
# \param minNetReliability 8-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# \param maxNetLatency 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# \param minNetPathStability 8-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# \param apRdntCoverageThreshold 8-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_setSla named tuple.
#
def dn_setSla(self, minNetReliability, maxNetLatency, minNetPathStability, apRdntCoverageThreshold) :
res = HartMgrConnectorInternal.send(self, ['setSla'], {"minNetReliability" : minNetReliability, "maxNetLatency" : maxNetLatency, "minNetPathStability" : minNetPathStability, "apRdntCoverageThreshold" : apRdntCoverageThreshold})
return HartMgrConnector.Tuple_dn_setSla(**res)
##
# The named tuple returned by the dn_setSystem() function.
#
# - <tt>systemName</tt>: 50-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>location</tt>: 50-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>cliTimeout</tt>: 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_setSystem = collections.namedtuple("Tuple_dn_setSystem", ['systemName', 'location', 'cliTimeout'])
##
# Set system-level configuration
#
# \param systemName 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param location 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param cliTimeout 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_setSystem named tuple.
#
def dn_setSystem(self, systemName, location, cliTimeout) :
res = HartMgrConnectorInternal.send(self, ['setSystem'], {"systemName" : systemName, "location" : location, "cliTimeout" : cliTimeout})
return HartMgrConnector.Tuple_dn_setSystem(**res)
##
# The named tuple returned by the dn_setUser() function.
#
# - <tt>userName</tt>: 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>privilege</tt>: 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - viewer: viewer
# - user: user
# - superuser: superuser
#
Tuple_dn_setUser = collections.namedtuple("Tuple_dn_setUser", ['userName', 'privilege'])
##
# Add or update user configuration
#
# \param userName 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param password 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# \param privilege 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - viewer: viewer
# - user: user
# - superuser: superuser
#
# \returns The response to the command, formatted as a #Tuple_dn_setUser named tuple.
#
def dn_setUser(self, userName, password, privilege) :
res = HartMgrConnectorInternal.send(self, ['setUser'], {"userName" : userName, "password" : password, "privilege" : privilege})
return HartMgrConnector.Tuple_dn_setUser(**res)
##
# The named tuple returned by the dn_setLicense() function.
#
# - <tt>result</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_setLicense = collections.namedtuple("Tuple_dn_setLicense", ['result'])
##
# Set the software license key.
#
# \param license 40-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_setLicense named tuple.
#
def dn_setLicense(self, license) :
res = HartMgrConnectorInternal.send(self, ['setLicense'], {"license" : license})
return HartMgrConnector.Tuple_dn_setLicense(**res)
##
# The named tuple returned by the dn_startOtap() function.
#
# - <tt>result</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_startOtap = collections.namedtuple("Tuple_dn_startOtap", ['result'])
##
# This command initiates the OTAP (Over-The-Air-Programming) process to upgrade software on motes and the Access Point. By default, the process will retry the OTAP file transmission 100 times.
#
#
#
# \returns The response to the command, formatted as a #Tuple_dn_startOtap named tuple.
#
def dn_startOtap(self, ) :
res = HartMgrConnectorInternal.send(self, ['startOtap'], {})
return HartMgrConnector.Tuple_dn_startOtap(**res)
##
# The named tuple returned by the dn_startOtapWithRetries() function.
#
# - <tt>result</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_startOtapWithRetries = collections.namedtuple("Tuple_dn_startOtapWithRetries", ['result'])
##
# This command initiates the OTAP (Over-The-Air-Programming) process to upgrade software for motes and the Access Point, using the specified number of retries.
#
# \param retries 1-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_startOtapWithRetries named tuple.
#
def dn_startOtapWithRetries(self, retries) :
res = HartMgrConnectorInternal.send(self, ['startOtapWithRetries'], {"retries" : retries})
return HartMgrConnector.Tuple_dn_startOtapWithRetries(**res)
##
# The named tuple returned by the dn_subscribe() function.
#
# - <tt>notif_token</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_subscribe = collections.namedtuple("Tuple_dn_subscribe", ['notif_token'])
##
# Subscribe to notifications. This function adds or updates the subscribed notifications to match 'filter'. The filter is a space-separated list of notification types. Valid types include 'data' and 'events'.
#
# \param filter 128-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
# \returns The response to the command, formatted as a #Tuple_dn_subscribe named tuple.
#
def dn_subscribe(self, filter) :
res = HartMgrConnectorInternal.send(self, ['subscribe'], {"filter" : filter})
return HartMgrConnector.Tuple_dn_subscribe(**res)
##
# The named tuple returned by the dn_unsubscribe() function.
#
# - <tt>result</tt>: 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
Tuple_dn_unsubscribe = collections.namedtuple("Tuple_dn_unsubscribe", ['result'])
##
# Unsubscribe from notifications. This function clears the existing notification subscription of the client and stops the notification thread.
#
#
#
# \returns The response to the command, formatted as a #Tuple_dn_unsubscribe named tuple.
#
def dn_unsubscribe(self, ) :
res = HartMgrConnectorInternal.send(self, ['unsubscribe'], {})
return HartMgrConnector.Tuple_dn_unsubscribe(**res)
#======================== notifications ===================================
##
# Dictionary of all notification tuples.
#
notifTupleTable = {}
##
# \brief USERCONNECT notification.
#
#
#
# Formatted as a Tuple_UserConnect named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>channel</tt> 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - cli: Manager CLI
# - config: API control
# - notif: API notifications
# - <tt>ipAddr</tt> 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>userName</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
USERCONNECT = "UserConnect"
notifTupleTable[USERCONNECT] = Tuple_UserConnect = collections.namedtuple("Tuple_UserConnect", ['timeStamp', 'eventId', 'channel', 'ipAddr', 'userName'])
##
# \brief USERDISCONNECT notification.
#
#
#
# Formatted as a Tuple_UserDisconnect named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>channel</tt> 16-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - cli: Manager CLI
# - config: API control
# - notif: API notifications
# - <tt>ipAddr</tt> 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>userName</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
USERDISCONNECT = "UserDisconnect"
notifTupleTable[USERDISCONNECT] = Tuple_UserDisconnect = collections.namedtuple("Tuple_UserDisconnect", ['timeStamp', 'eventId', 'channel', 'ipAddr', 'userName'])
##
# \brief MANUALMOTERESET notification.
#
#
#
# Formatted as a Tuple_ManualMoteReset named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>userName</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>moteId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
MANUALMOTERESET = "ManualMoteReset"
notifTupleTable[MANUALMOTERESET] = Tuple_ManualMoteReset = collections.namedtuple("Tuple_ManualMoteReset", ['timeStamp', 'eventId', 'userName', 'moteId', 'macAddr'])
##
# \brief MANUALMOTEDELETE notification.
#
#
#
# Formatted as a Tuple_ManualMoteDelete named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>userName</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>moteId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
MANUALMOTEDELETE = "ManualMoteDelete"
notifTupleTable[MANUALMOTEDELETE] = Tuple_ManualMoteDelete = collections.namedtuple("Tuple_ManualMoteDelete", ['timeStamp', 'eventId', 'userName', 'moteId', 'macAddr'])
##
# \brief MANUALMOTEDECOMMISSION notification.
#
#
#
# Formatted as a Tuple_ManualMoteDecommission named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>userName</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>moteId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
MANUALMOTEDECOMMISSION = "ManualMoteDecommission"
notifTupleTable[MANUALMOTEDECOMMISSION] = Tuple_ManualMoteDecommission = collections.namedtuple("Tuple_ManualMoteDecommission", ['timeStamp', 'eventId', 'userName', 'moteId', 'macAddr'])
##
# \brief MANUALNETRESET notification.
#
#
#
# Formatted as a Tuple_ManualNetReset named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>userName</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
MANUALNETRESET = "ManualNetReset"
notifTupleTable[MANUALNETRESET] = Tuple_ManualNetReset = collections.namedtuple("Tuple_ManualNetReset", ['timeStamp', 'eventId', 'userName'])
##
# \brief MANUALDCCRESET notification.
#
#
#
# Formatted as a Tuple_ManualDccReset named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>userName</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
MANUALDCCRESET = "ManualDccReset"
notifTupleTable[MANUALDCCRESET] = Tuple_ManualDccReset = collections.namedtuple("Tuple_ManualDccReset", ['timeStamp', 'eventId', 'userName'])
##
# \brief MANUALSTATRESET notification.
#
#
#
# Formatted as a Tuple_ManualStatReset named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>userName</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
MANUALSTATRESET = "ManualStatReset"
notifTupleTable[MANUALSTATRESET] = Tuple_ManualStatReset = collections.namedtuple("Tuple_ManualStatReset", ['timeStamp', 'eventId', 'userName'])
##
# \brief CONFIGCHANGE notification.
#
#
#
# Formatted as a Tuple_ConfigChange named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>userName</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>objectType</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>objectId</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
CONFIGCHANGE = "ConfigChange"
notifTupleTable[CONFIGCHANGE] = Tuple_ConfigChange = collections.namedtuple("Tuple_ConfigChange", ['timeStamp', 'eventId', 'userName', 'objectType', 'objectId'])
##
# \brief BOOTUP notification.
#
#
#
# Formatted as a Tuple_BootUp named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
BOOTUP = "BootUp"
notifTupleTable[BOOTUP] = Tuple_BootUp = collections.namedtuple("Tuple_BootUp", ['timeStamp', 'eventId'])
##
# \brief NETWORKRESET notification.
#
#
#
# Formatted as a Tuple_NetworkReset named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
NETWORKRESET = "NetworkReset"
notifTupleTable[NETWORKRESET] = Tuple_NetworkReset = collections.namedtuple("Tuple_NetworkReset", ['timeStamp', 'eventId'])
##
# \brief COMMANDFINISHED notification.
#
#
#
# Formatted as a Tuple_CommandFinished named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>callbackId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>objectType</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>resultCode</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
COMMANDFINISHED = "CommandFinished"
notifTupleTable[COMMANDFINISHED] = Tuple_CommandFinished = collections.namedtuple("Tuple_CommandFinished", ['timeStamp', 'eventId', 'callbackId', 'objectType', 'macAddr', 'resultCode'])
##
# \brief PACKETSENT notification.
#
#
#
# Formatted as a Tuple_PacketSent named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>callbackId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
PACKETSENT = "PacketSent"
notifTupleTable[PACKETSENT] = Tuple_PacketSent = collections.namedtuple("Tuple_PacketSent", ['timeStamp', 'eventId', 'callbackId', 'macAddr'])
##
# \brief MOTEJOIN notification.
#
#
#
# Formatted as a Tuple_MoteJoin named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>moteId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>reason</tt> 64-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>userData</tt> 64-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
MOTEJOIN = "MoteJoin"
notifTupleTable[MOTEJOIN] = Tuple_MoteJoin = collections.namedtuple("Tuple_MoteJoin", ['timeStamp', 'eventId', 'moteId', 'macAddr', 'reason', 'userData'])
##
# \brief MOTELIVE notification.
#
#
#
# Formatted as a Tuple_MoteLive named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>moteId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>reason</tt> 64-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
MOTELIVE = "MoteLive"
notifTupleTable[MOTELIVE] = Tuple_MoteLive = collections.namedtuple("Tuple_MoteLive", ['timeStamp', 'eventId', 'moteId', 'macAddr', 'reason'])
##
# \brief MOTEQUARANTINE notification.
#
#
#
# Formatted as a Tuple_MoteQuarantine named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>moteId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>reason</tt> 64-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
MOTEQUARANTINE = "MoteQuarantine"
notifTupleTable[MOTEQUARANTINE] = Tuple_MoteQuarantine = collections.namedtuple("Tuple_MoteQuarantine", ['timeStamp', 'eventId', 'moteId', 'macAddr', 'reason'])
##
# \brief MOTEJOINQUARANTINE notification.
#
#
#
# Formatted as a Tuple_MoteJoinQuarantine named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>moteId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>reason</tt> 64-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>userData</tt> 64-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
MOTEJOINQUARANTINE = "MoteJoinQuarantine"
notifTupleTable[MOTEJOINQUARANTINE] = Tuple_MoteJoinQuarantine = collections.namedtuple("Tuple_MoteJoinQuarantine", ['timeStamp', 'eventId', 'moteId', 'macAddr', 'reason', 'userData'])
##
# \brief MOTEUNKNOWN notification.
#
#
#
# Formatted as a Tuple_MoteUnknown named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>moteId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>reason</tt> 64-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
MOTEUNKNOWN = "MoteUnknown"
notifTupleTable[MOTEUNKNOWN] = Tuple_MoteUnknown = collections.namedtuple("Tuple_MoteUnknown", ['timeStamp', 'eventId', 'moteId', 'macAddr', 'reason'])
##
# \brief MOTEDISCONNECT notification.
#
#
#
# Formatted as a Tuple_MoteDisconnect named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>moteId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>reason</tt> 64-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
MOTEDISCONNECT = "MoteDisconnect"
notifTupleTable[MOTEDISCONNECT] = Tuple_MoteDisconnect = collections.namedtuple("Tuple_MoteDisconnect", ['timeStamp', 'eventId', 'moteId', 'macAddr', 'reason'])
##
# \brief MOTEJOINFAILURE notification.
#
#
#
# Formatted as a Tuple_MoteJoinFailure named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>reason</tt> 64-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
MOTEJOINFAILURE = "MoteJoinFailure"
notifTupleTable[MOTEJOINFAILURE] = Tuple_MoteJoinFailure = collections.namedtuple("Tuple_MoteJoinFailure", ['timeStamp', 'eventId', 'macAddr', 'reason'])
##
# \brief INVALIDMIC notification.
#
#
#
# Formatted as a Tuple_InvalidMIC named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
INVALIDMIC = "InvalidMIC"
notifTupleTable[INVALIDMIC] = Tuple_InvalidMIC = collections.namedtuple("Tuple_InvalidMIC", ['timeStamp', 'eventId', 'macAddr'])
##
# \brief PATHCREATE notification.
#
#
#
# Formatted as a Tuple_PathCreate named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>pathId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>moteAMac</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>moteBMac</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
PATHCREATE = "PathCreate"
notifTupleTable[PATHCREATE] = Tuple_PathCreate = collections.namedtuple("Tuple_PathCreate", ['timeStamp', 'eventId', 'pathId', 'moteAMac', 'moteBMac'])
##
# \brief PATHDELETE notification.
#
#
#
# Formatted as a Tuple_PathDelete named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>pathId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>moteAMac</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>moteBMac</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
PATHDELETE = "PathDelete"
notifTupleTable[PATHDELETE] = Tuple_PathDelete = collections.namedtuple("Tuple_PathDelete", ['timeStamp', 'eventId', 'pathId', 'moteAMac', 'moteBMac'])
##
# \brief PATHACTIVATE notification.
#
#
#
# Formatted as a Tuple_PathActivate named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>pathId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>moteAMac</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>moteBMac</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
PATHACTIVATE = "PathActivate"
notifTupleTable[PATHACTIVATE] = Tuple_PathActivate = collections.namedtuple("Tuple_PathActivate", ['timeStamp', 'eventId', 'pathId', 'moteAMac', 'moteBMac'])
##
# \brief PATHDEACTIVATE notification.
#
#
#
# Formatted as a Tuple_PathDeactivate named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>pathId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>moteAMac</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>moteBMac</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
PATHDEACTIVATE = "PathDeactivate"
notifTupleTable[PATHDEACTIVATE] = Tuple_PathDeactivate = collections.namedtuple("Tuple_PathDeactivate", ['timeStamp', 'eventId', 'pathId', 'moteAMac', 'moteBMac'])
##
# \brief PATHALERT notification.
#
#
#
# Formatted as a Tuple_PathAlert named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>pathId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>moteAMac</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>moteBMac</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
PATHALERT = "PathAlert"
notifTupleTable[PATHALERT] = Tuple_PathAlert = collections.namedtuple("Tuple_PathAlert", ['timeStamp', 'eventId', 'pathId', 'moteAMac', 'moteBMac'])
##
# \brief PIPEON notification.
#
#
#
# Formatted as a Tuple_PipeOn named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>allocatedPipePkPeriod</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
PIPEON = "PipeOn"
notifTupleTable[PIPEON] = Tuple_PipeOn = collections.namedtuple("Tuple_PipeOn", ['timeStamp', 'eventId', 'macAddr', 'allocatedPipePkPeriod'])
##
# \brief PIPEOFF notification.
#
#
#
# Formatted as a Tuple_PipeOff named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
PIPEOFF = "PipeOff"
notifTupleTable[PIPEOFF] = Tuple_PipeOff = collections.namedtuple("Tuple_PipeOff", ['timeStamp', 'eventId', 'macAddr'])
##
# \brief SERVICEDENIED notification.
#
#
#
# Formatted as a Tuple_ServiceDenied named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>serviceId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>requestingMacAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>peerMacAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>appDomain</tt> 32-byte field formatted as a string.<br/>
# This field can only take one of the following values:
# - maintenance: maintenance
# - <tt>isSource</tt> 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>isSink</tt> 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>isIntermittent</tt> 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>period</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
SERVICEDENIED = "ServiceDenied"
notifTupleTable[SERVICEDENIED] = Tuple_ServiceDenied = collections.namedtuple("Tuple_ServiceDenied", ['timeStamp', 'eventId', 'serviceId', 'requestingMacAddr', 'peerMacAddr', 'appDomain', 'isSource', 'isSink', 'isIntermittent', 'period'])
##
# \brief PINGREPLY notification.
#
#
#
# Formatted as a Tuple_PingReply named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>callbackId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>latency</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>temperature</tt> 8-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# - <tt>voltage</tt> 8-byte field formatted as a float.<br/>
# There is no restriction on the value of this field.
# - <tt>hopCount</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
PINGREPLY = "PingReply"
notifTupleTable[PINGREPLY] = Tuple_PingReply = collections.namedtuple("Tuple_PingReply", ['timeStamp', 'eventId', 'macAddr', 'callbackId', 'latency', 'temperature', 'voltage', 'hopCount'])
##
# \brief TRANSPORTTIMEOUT notification.
#
#
#
# Formatted as a Tuple_TransportTimeout named tuple. It contains the following fields:
# - <tt>timeStamp</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>eventId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>srcMacAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>destMacAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>timeoutType</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>callbackId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
TRANSPORTTIMEOUT = "TransportTimeout"
notifTupleTable[TRANSPORTTIMEOUT] = Tuple_TransportTimeout = collections.namedtuple("Tuple_TransportTimeout", ['timeStamp', 'eventId', 'srcMacAddr', 'destMacAddr', 'timeoutType', 'callbackId'])
##
# \brief DATA notification.
#
#
#
# Formatted as a Tuple_data named tuple. It contains the following fields:
# - <tt>moteId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>time</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>payload</tt> None-byte field formatted as a hex.<br/>
# There is no restriction on the value of this field.
# - <tt>payloadType</tt> 1-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>isReliable</tt> 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>isRequest</tt> 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>isBroadcast</tt> 1-byte field formatted as a bool.<br/>
# There is no restriction on the value of this field.
# - <tt>callbackId</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>counter</tt> 4-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
#
DATA = "data"
notifTupleTable[DATA] = Tuple_data = collections.namedtuple("Tuple_data", ['moteId', 'macAddr', 'time', 'payload', 'payloadType', 'isReliable', 'isRequest', 'isBroadcast', 'callbackId', 'counter'])
##
# \brief LOCATION notification.
#
#
#
# Formatted as a Tuple_Location named tuple. It contains the following fields:
# - <tt>ver</tt> 1-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>asn</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>src</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>dest</tt> 32-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>payload</tt> None-byte field formatted as a hex.<br/>
# There is no restriction on the value of this field.
#
LOCATION = "Location"
notifTupleTable[LOCATION] = Tuple_Location = collections.namedtuple("Tuple_Location", ['ver', 'asn', 'src', 'dest', 'payload'])
##
# \brief CLI notification.
#
#
#
# Formatted as a Tuple_cli named tuple. It contains the following fields:
# - <tt>time</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>message</tt> 128-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
CLI = "cli"
notifTupleTable[CLI] = Tuple_cli = collections.namedtuple("Tuple_cli", ['time', 'message'])
##
# \brief LOG notification.
#
#
#
# Formatted as a Tuple_log named tuple. It contains the following fields:
# - <tt>time</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>severity</tt> 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>message</tt> 128-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
#
LOG = "log"
notifTupleTable[LOG] = Tuple_log = collections.namedtuple("Tuple_log", ['time', 'severity', 'message'])
##
# \brief STDMOTEREPORT notification.
#
#
#
# Formatted as a Tuple_stdMoteReport named tuple. It contains the following fields:
# - <tt>time</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>payload</tt> None-byte field formatted as a hex.<br/>
# There is no restriction on the value of this field.
#
STDMOTEREPORT = "stdMoteReport"
notifTupleTable[STDMOTEREPORT] = Tuple_stdMoteReport = collections.namedtuple("Tuple_stdMoteReport", ['time', 'macAddr', 'payload'])
##
# \brief VENDORMOTEREPORT notification.
#
#
#
# Formatted as a Tuple_vendorMoteReport named tuple. It contains the following fields:
# - <tt>time</tt> 8-byte field formatted as a int.<br/>
# There is no restriction on the value of this field.
# - <tt>macAddr</tt> 16-byte field formatted as a string.<br/>
# There is no restriction on the value of this field.
# - <tt>payload</tt> None-byte field formatted as a hex.<br/>
# There is no restriction on the value of this field.
#
VENDORMOTEREPORT = "vendorMoteReport"
notifTupleTable[VENDORMOTEREPORT] = Tuple_vendorMoteReport = collections.namedtuple("Tuple_vendorMoteReport", ['time', 'macAddr', 'payload'])
##
# \brief Get a notification from the notification queue, and returns
# it properly formatted.
#
# \exception NotificationError if unknown notification.
#
def getNotification(self, timeoutSec=-1) :
temp = self.getNotificationInternal(timeoutSec)
if not temp:
return temp
(ids, param) = temp
try :
if HartMgrConnector.notifTupleTable[ids[-1]] :
return (ids[-1], HartMgrConnector.notifTupleTable[ids[-1]](**param))
else :
return (ids[-1], None)
except KeyError :
raise ApiException.NotificationError(ids, param)
##
# end of HartMgrConnector
# \}
#
| true | true |
1c36f7f91a7bb447c89b9a5728149beb493fa769 | 3,522 | py | Python | ib_insync/__init__.py | vishalbelsare/ib_insync | 9674fe974c07ca3afaf70673ae296f1d19f028dc | [
"BSD-2-Clause"
] | 1 | 2021-12-14T15:21:05.000Z | 2021-12-14T15:21:05.000Z | ib_insync/__init__.py | vishalbelsare/ib_insync | 9674fe974c07ca3afaf70673ae296f1d19f028dc | [
"BSD-2-Clause"
] | null | null | null | ib_insync/__init__.py | vishalbelsare/ib_insync | 9674fe974c07ca3afaf70673ae296f1d19f028dc | [
"BSD-2-Clause"
] | null | null | null | """Python sync/async framework for Interactive Brokers API"""
import dataclasses
import sys
from eventkit import Event
from . import util
from .client import Client
from .contract import (
Bag, Bond, CFD, ComboLeg, Commodity, ContFuture, Contract,
ContractDescription, ContractDetails, Crypto, DeltaNeutralContract,
Forex, Future, FuturesOption, Index, MutualFund, Option, ScanData, Stock,
TagValue, Warrant)
from .flexreport import FlexError, FlexReport
from .ib import IB
from .ibcontroller import IBC, IBController, Watchdog
from .objects import (
AccountValue, BarData, BarDataList, CommissionReport, ConnectionStats,
DOMLevel, DepthMktDataDescription, Dividends, Execution, ExecutionFilter,
FamilyCode, Fill, FundamentalRatios, HistogramData, HistoricalNews,
HistoricalTick, HistoricalTickBidAsk, HistoricalTickLast, MktDepthData,
NewsArticle, NewsBulletin, NewsProvider, NewsTick, OptionChain,
OptionComputation, PnL, PnLSingle, PortfolioItem, Position,
PriceIncrement, RealTimeBar, RealTimeBarList, ScanDataList,
ScannerSubscription, SmartComponent, SoftDollarTier, TickAttrib,
TickAttribBidAsk, TickAttribLast, TickByTickAllLast, TickByTickBidAsk,
TickByTickMidPoint, TickData, TradeLogEntry)
from .order import (
BracketOrder, ExecutionCondition, LimitOrder, MarginCondition, MarketOrder,
Order, OrderComboLeg, OrderCondition, OrderState, OrderStatus,
PercentChangeCondition, PriceCondition, StopLimitOrder, StopOrder,
TimeCondition, Trade, VolumeCondition)
from .ticker import Ticker
from .version import __version__, __version_info__
from .wrapper import RequestError, Wrapper
__all__ = [
'Event', 'util', 'Client',
'Bag', 'Bond', 'CFD', 'ComboLeg', 'Commodity', 'ContFuture', 'Contract',
'ContractDescription', 'ContractDetails', 'Crypto', 'DeltaNeutralContract',
'Forex', 'Future', 'FuturesOption', 'Index', 'MutualFund', 'Option',
'ScanData', 'Stock', 'TagValue', 'Warrant', 'FlexError', 'FlexReport',
'IB', 'IBC', 'IBController', 'Watchdog',
'AccountValue', 'BarData', 'BarDataList', 'CommissionReport',
'ConnectionStats', 'DOMLevel', 'DepthMktDataDescription', 'Dividends',
'Execution', 'ExecutionFilter', 'FamilyCode', 'Fill', 'FundamentalRatios',
'HistogramData', 'HistoricalNews', 'HistoricalTick',
'HistoricalTickBidAsk', 'HistoricalTickLast', 'MktDepthData',
'NewsArticle', 'NewsBulletin', 'NewsProvider', 'NewsTick', 'OptionChain',
'OptionComputation', 'PnL', 'PnLSingle', 'PortfolioItem', 'Position',
'PriceIncrement', 'RealTimeBar', 'RealTimeBarList', 'ScanDataList',
'ScannerSubscription', 'SmartComponent', 'SoftDollarTier', 'TickAttrib',
'TickAttribBidAsk', 'TickAttribLast', 'TickByTickAllLast',
'TickByTickBidAsk', 'TickByTickMidPoint', 'TickData', 'TradeLogEntry',
'BracketOrder', 'ExecutionCondition', 'LimitOrder', 'MarginCondition',
'MarketOrder', 'Order', 'OrderComboLeg', 'OrderCondition', 'OrderState',
'OrderStatus', 'PercentChangeCondition', 'PriceCondition',
'StopLimitOrder', 'StopOrder', 'TimeCondition', 'Trade', 'VolumeCondition',
'Ticker', '__version__', '__version_info__', 'RequestError', 'Wrapper'
]
# compatibility with old Object
for obj in locals().copy().values():
if dataclasses.is_dataclass(obj):
obj.dict = util.dataclassAsDict
obj.tuple = util.dataclassAsTuple
obj.update = util.dataclassUpdate
obj.nonDefaults = util.dataclassNonDefaults
del sys
del dataclasses
| 46.96 | 79 | 0.744179 |
import dataclasses
import sys
from eventkit import Event
from . import util
from .client import Client
from .contract import (
Bag, Bond, CFD, ComboLeg, Commodity, ContFuture, Contract,
ContractDescription, ContractDetails, Crypto, DeltaNeutralContract,
Forex, Future, FuturesOption, Index, MutualFund, Option, ScanData, Stock,
TagValue, Warrant)
from .flexreport import FlexError, FlexReport
from .ib import IB
from .ibcontroller import IBC, IBController, Watchdog
from .objects import (
AccountValue, BarData, BarDataList, CommissionReport, ConnectionStats,
DOMLevel, DepthMktDataDescription, Dividends, Execution, ExecutionFilter,
FamilyCode, Fill, FundamentalRatios, HistogramData, HistoricalNews,
HistoricalTick, HistoricalTickBidAsk, HistoricalTickLast, MktDepthData,
NewsArticle, NewsBulletin, NewsProvider, NewsTick, OptionChain,
OptionComputation, PnL, PnLSingle, PortfolioItem, Position,
PriceIncrement, RealTimeBar, RealTimeBarList, ScanDataList,
ScannerSubscription, SmartComponent, SoftDollarTier, TickAttrib,
TickAttribBidAsk, TickAttribLast, TickByTickAllLast, TickByTickBidAsk,
TickByTickMidPoint, TickData, TradeLogEntry)
from .order import (
BracketOrder, ExecutionCondition, LimitOrder, MarginCondition, MarketOrder,
Order, OrderComboLeg, OrderCondition, OrderState, OrderStatus,
PercentChangeCondition, PriceCondition, StopLimitOrder, StopOrder,
TimeCondition, Trade, VolumeCondition)
from .ticker import Ticker
from .version import __version__, __version_info__
from .wrapper import RequestError, Wrapper
__all__ = [
'Event', 'util', 'Client',
'Bag', 'Bond', 'CFD', 'ComboLeg', 'Commodity', 'ContFuture', 'Contract',
'ContractDescription', 'ContractDetails', 'Crypto', 'DeltaNeutralContract',
'Forex', 'Future', 'FuturesOption', 'Index', 'MutualFund', 'Option',
'ScanData', 'Stock', 'TagValue', 'Warrant', 'FlexError', 'FlexReport',
'IB', 'IBC', 'IBController', 'Watchdog',
'AccountValue', 'BarData', 'BarDataList', 'CommissionReport',
'ConnectionStats', 'DOMLevel', 'DepthMktDataDescription', 'Dividends',
'Execution', 'ExecutionFilter', 'FamilyCode', 'Fill', 'FundamentalRatios',
'HistogramData', 'HistoricalNews', 'HistoricalTick',
'HistoricalTickBidAsk', 'HistoricalTickLast', 'MktDepthData',
'NewsArticle', 'NewsBulletin', 'NewsProvider', 'NewsTick', 'OptionChain',
'OptionComputation', 'PnL', 'PnLSingle', 'PortfolioItem', 'Position',
'PriceIncrement', 'RealTimeBar', 'RealTimeBarList', 'ScanDataList',
'ScannerSubscription', 'SmartComponent', 'SoftDollarTier', 'TickAttrib',
'TickAttribBidAsk', 'TickAttribLast', 'TickByTickAllLast',
'TickByTickBidAsk', 'TickByTickMidPoint', 'TickData', 'TradeLogEntry',
'BracketOrder', 'ExecutionCondition', 'LimitOrder', 'MarginCondition',
'MarketOrder', 'Order', 'OrderComboLeg', 'OrderCondition', 'OrderState',
'OrderStatus', 'PercentChangeCondition', 'PriceCondition',
'StopLimitOrder', 'StopOrder', 'TimeCondition', 'Trade', 'VolumeCondition',
'Ticker', '__version__', '__version_info__', 'RequestError', 'Wrapper'
]
for obj in locals().copy().values():
if dataclasses.is_dataclass(obj):
obj.dict = util.dataclassAsDict
obj.tuple = util.dataclassAsTuple
obj.update = util.dataclassUpdate
obj.nonDefaults = util.dataclassNonDefaults
del sys
del dataclasses
| true | true |
1c36f82445ad62b20ee06449ad4f4e886162ec91 | 77,986 | py | Python | examples/python/bus_driver_scheduling_flow_sat.py | sreesubbash/or-tools | 701496e45d54fa9938afeedec43089314d93ec11 | [
"Apache-2.0"
] | 1 | 2021-03-30T21:10:27.000Z | 2021-03-30T21:10:27.000Z | examples/python/bus_driver_scheduling_flow_sat.py | sreesubbash/or-tools | 701496e45d54fa9938afeedec43089314d93ec11 | [
"Apache-2.0"
] | null | null | null | examples/python/bus_driver_scheduling_flow_sat.py | sreesubbash/or-tools | 701496e45d54fa9938afeedec43089314d93ec11 | [
"Apache-2.0"
] | null | null | null | # Copyright 2010-2018 Google LLC
# 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.
"""This model implements a bus driver scheduling problem.
Constraints:
- max driving time per driver <= 9h
- max working time per driver <= 12h
- min working time per driver >= 6.5h (soft)
- 30 min break after each 4h of driving time per driver
- 10 min preparation time before the first shift
- 15 min cleaning time after the last shift
- 2 min waiting time after each shift for passenger boarding and alighting
"""
import argparse
import collections
import math
from ortools.sat.python import cp_model
PARSER = argparse.ArgumentParser()
PARSER.add_argument(
'--instance', default=1, type=int, help='Instance number (1..3).')
PARSER.add_argument(
'--output_proto',
default="",
help='Output file to write the cp_model'
'proto to.')
PARSER.add_argument('--params', default="", help='Sat solver parameters.')
SAMPLE_SHIFTS_SMALL = [
#
# column description:
# - shift id
# - shift start time as hh:mm string (for logging and readability purposes)
# - shift end time as hh:mm string (for logging and readability purposes)
# - shift start minute
# - shift end minute
# - shift duration in minutes
#
[0, '05:18', '06:00', 318, 360, 42],
[1, '05:26', '06:08', 326, 368, 42],
[2, '05:40', '05:56', 340, 356, 16],
[3, '06:06', '06:51', 366, 411, 45],
[4, '06:40', '07:52', 400, 472, 72],
[5, '06:42', '07:13', 402, 433, 31],
[6, '06:48', '08:15', 408, 495, 87],
[7, '06:59', '08:07', 419, 487, 68],
[8, '07:20', '07:36', 440, 456, 16],
[9, '07:35', '08:22', 455, 502, 47],
[10, '07:50', '08:55', 470, 535, 65],
[11, '08:00', '09:05', 480, 545, 65],
[12, '08:00', '08:35', 480, 515, 35],
[13, '08:11', '09:41', 491, 581, 90],
[14, '08:28', '08:50', 508, 530, 22],
[15, '08:35', '08:45', 515, 525, 10],
[16, '08:40', '08:50', 520, 530, 10],
[17, '09:03', '10:28', 543, 628, 85],
[18, '09:23', '09:49', 563, 589, 26],
[19, '09:30', '09:40', 570, 580, 10],
[20, '09:57', '10:20', 597, 620, 23],
[21, '10:09', '11:03', 609, 663, 54],
[22, '10:20', '10:30', 620, 630, 10],
[23, '11:00', '11:10', 660, 670, 10],
[24, '11:45', '12:24', 705, 744, 39],
[25, '12:18', '13:00', 738, 780, 42],
[26, '13:18', '14:44', 798, 884, 86],
[27, '13:53', '14:49', 833, 889, 56],
[28, '14:03', '14:50', 843, 890, 47],
[29, '14:28', '15:15', 868, 915, 47],
[30, '14:30', '15:41', 870, 941, 71],
[31, '14:48', '15:35', 888, 935, 47],
[32, '15:03', '15:50', 903, 950, 47],
[33, '15:28', '16:54', 928, 1014, 86],
[34, '15:38', '16:25', 938, 985, 47],
[35, '15:40', '15:56', 940, 956, 16],
[36, '15:58', '16:45', 958, 1005, 47],
[37, '16:04', '17:30', 964, 1050, 86],
[38, '16:28', '17:15', 988, 1035, 47],
[39, '16:36', '17:21', 996, 1041, 45],
[40, '16:50', '17:00', 1010, 1020, 10],
[41, '16:54', '18:20', 1014, 1100, 86],
[42, '17:01', '17:13', 1021, 1033, 12],
[43, '17:19', '18:31', 1039, 1111, 72],
[44, '17:23', '18:10', 1043, 1090, 47],
[45, '17:34', '18:15', 1054, 1095, 41],
[46, '18:04', '19:29', 1084, 1169, 85],
[47, '18:34', '19:58', 1114, 1198, 84],
[48, '19:56', '20:34', 1196, 1234, 38],
[49, '20:05', '20:48', 1205, 1248, 43]
] # yapf:disable
SAMPLE_SHIFTS_MEDIUM = [
[0, '04:30', '04:53', 270, 293, 23],
[1, '04:46', '04:56', 286, 296, 10],
[2, '04:52', '05:56', 292, 356, 64],
[3, '04:53', '05:23', 293, 323, 30],
[4, '05:07', '05:44', 307, 344, 37],
[5, '05:10', '06:06', 310, 366, 56],
[6, '05:18', '06:03', 318, 363, 45],
[7, '05:30', '05:40', 330, 340, 10],
[8, '05:30', '05:40', 330, 340, 10],
[9, '05:33', '06:15', 333, 375, 42],
[10, '05:40', '05:50', 340, 350, 10],
[11, '05:43', '06:08', 343, 368, 25],
[12, '05:54', '07:20', 354, 440, 86],
[13, '06:04', '06:37', 364, 397, 33],
[14, '06:13', '06:58', 373, 418, 45],
[15, '06:14', '07:40', 374, 460, 86],
[16, '06:15', '07:15', 375, 435, 60],
[17, '06:16', '06:26', 376, 386, 10],
[18, '06:17', '06:34', 377, 394, 17],
[19, '06:20', '06:36', 380, 396, 16],
[20, '06:22', '07:06', 382, 426, 44],
[21, '06:24', '07:50', 384, 470, 86],
[22, '06:27', '06:44', 387, 404, 17],
[23, '06:30', '06:40', 390, 400, 10],
[24, '06:31', '06:43', 391, 403, 12],
[25, '06:33', '07:53', 393, 473, 80],
[26, '06:34', '07:09', 394, 429, 35],
[27, '06:40', '06:56', 400, 416, 16],
[28, '06:44', '07:17', 404, 437, 33],
[29, '06:46', '06:58', 406, 418, 12],
[30, '06:49', '07:43', 409, 463, 54],
[31, '06:50', '07:05', 410, 425, 15],
[32, '06:52', '07:36', 412, 456, 44],
[33, '06:54', '07:27', 414, 447, 33],
[34, '06:56', '08:23', 416, 503, 87],
[35, '07:04', '07:44', 424, 464, 40],
[36, '07:11', '08:36', 431, 516, 85],
[37, '07:17', '07:35', 437, 455, 18],
[38, '07:22', '08:06', 442, 486, 44],
[39, '07:27', '08:15', 447, 495, 48],
[40, '07:35', '07:45', 455, 465, 10],
[41, '07:43', '08:08', 463, 488, 25],
[42, '07:50', '08:37', 470, 517, 47],
[43, '07:58', '08:45', 478, 525, 47],
[44, '08:00', '08:35', 480, 515, 35],
[45, '08:06', '08:51', 486, 531, 45],
[46, '08:10', '08:45', 490, 525, 35],
[47, '08:15', '08:30', 495, 510, 15],
[48, '08:16', '09:00', 496, 540, 44],
[49, '08:18', '09:16', 498, 556, 58],
[50, '08:20', '08:36', 500, 516, 16],
[51, '08:27', '09:07', 507, 547, 40],
[52, '08:30', '08:45', 510, 525, 15],
[53, '08:35', '09:15', 515, 555, 40],
[54, '08:46', '09:30', 526, 570, 44],
[55, '08:51', '09:17', 531, 557, 26],
[56, '08:55', '09:15', 535, 555, 20],
[57, '08:58', '09:38', 538, 578, 40],
[58, '09:00', '09:35', 540, 575, 35],
[59, '09:00', '09:16', 540, 556, 16],
[60, '09:20', '09:36', 560, 576, 16],
[61, '09:31', '09:43', 571, 583, 12],
[62, '09:33', '10:15', 573, 615, 42],
[63, '09:54', '10:05', 594, 605, 11],
[64, '10:11', '10:38', 611, 638, 27],
[65, '10:18', '11:00', 618, 660, 42],
[66, '10:21', '10:47', 621, 647, 26],
[67, '10:25', '11:04', 625, 664, 39],
[68, '10:26', '11:08', 626, 668, 42],
[69, '10:44', '12:11', 644, 731, 87],
[70, '11:00', '11:16', 660, 676, 16],
[71, '11:15', '11:54', 675, 714, 39],
[72, '11:16', '11:28', 676, 688, 12],
[73, '11:20', '11:30', 680, 690, 10],
[74, '11:21', '11:47', 681, 707, 26],
[75, '11:25', '12:04', 685, 724, 39],
[76, '11:34', '11:45', 694, 705, 11],
[77, '11:35', '12:14', 695, 734, 39],
[78, '11:41', '12:23', 701, 743, 42],
[79, '11:44', '12:35', 704, 755, 51],
[80, '11:46', '11:58', 706, 718, 12],
[81, '12:00', '12:10', 720, 730, 10],
[82, '12:04', '12:15', 724, 735, 11],
[83, '12:04', '13:04', 724, 784, 60],
[84, '12:11', '12:38', 731, 758, 27],
[85, '12:15', '12:54', 735, 774, 39],
[86, '12:25', '13:10', 745, 790, 45],
[87, '12:30', '12:40', 750, 760, 10],
[88, '12:34', '13:58', 754, 838, 84],
[89, '12:38', '13:25', 758, 805, 47],
[90, '12:48', '13:35', 768, 815, 47],
[91, '13:00', '13:16', 780, 796, 16],
[92, '13:05', '13:44', 785, 824, 39],
[93, '13:08', '13:55', 788, 835, 47],
[94, '13:14', '14:38', 794, 878, 84],
[95, '13:23', '13:49', 803, 829, 26],
[96, '13:25', '14:04', 805, 844, 39],
[97, '13:28', '14:54', 808, 894, 86],
[98, '13:31', '13:43', 811, 823, 12],
[99, '13:34', '14:58', 814, 898, 84],
[100, '13:38', '14:25', 818, 865, 47],
[101, '13:38', '15:04', 818, 904, 86],
[102, '13:39', '14:33', 819, 873, 54],
[103, '13:40', '13:50', 820, 830, 10],
[104, '13:43', '14:10', 823, 850, 27],
[105, '13:48', '14:35', 828, 875, 47],
[106, '13:48', '14:35', 828, 875, 47],
[107, '13:53', '14:40', 833, 880, 47],
[108, '13:58', '15:24', 838, 924, 86],
[109, '13:58', '14:25', 838, 865, 27],
[110, '14:00', '14:16', 840, 856, 16],
[111, '14:13', '15:00', 853, 900, 47],
[112, '14:20', '15:31', 860, 931, 71],
[113, '14:25', '15:02', 865, 902, 37],
[114, '14:34', '14:45', 874, 885, 11],
[115, '14:40', '15:51', 880, 951, 71],
[116, '14:40', '14:56', 880, 896, 16],
[117, '14:46', '14:58', 886, 898, 12],
[118, '14:49', '15:43', 889, 943, 54],
[119, '14:52', '15:21', 892, 921, 29],
[120, '14:58', '16:24', 898, 984, 86],
[121, '14:59', '15:53', 899, 953, 54],
[122, '15:00', '15:10', 900, 910, 10],
[123, '15:00', '15:35', 900, 935, 35],
[124, '15:08', '15:45', 908, 945, 37],
[125, '15:12', '15:36', 912, 936, 24],
[126, '15:18', '16:05', 918, 965, 47],
[127, '15:24', '16:05', 924, 965, 41],
[128, '15:31', '15:43', 931, 943, 12],
[129, '15:35', '15:54', 935, 954, 19],
[130, '15:36', '16:21', 936, 981, 45],
[131, '15:39', '16:33', 939, 993, 54],
[132, '15:48', '16:35', 948, 995, 47],
[133, '15:50', '17:01', 950, 1021, 71],
[134, '16:03', '16:50', 963, 1010, 47],
[135, '16:18', '17:44', 978, 1064, 86],
[136, '16:24', '17:05', 984, 1025, 41],
[137, '16:28', '17:15', 988, 1035, 47],
[138, '16:34', '17:15', 994, 1035, 41],
[139, '16:38', '17:25', 998, 1045, 47],
[140, '16:40', '16:56', 1000, 1016, 16],
[141, '16:45', '17:04', 1005, 1024, 19],
[142, '16:52', '17:36', 1012, 1056, 44],
[143, '16:58', '17:45', 1018, 1065, 47],
[144, '17:04', '18:30', 1024, 1110, 86],
[145, '17:04', '17:45', 1024, 1065, 41],
[146, '17:09', '18:03', 1029, 1083, 54],
[147, '17:18', '18:44', 1038, 1124, 86],
[148, '17:28', '18:15', 1048, 1095, 47],
[149, '17:29', '18:41', 1049, 1121, 72],
[150, '17:36', '18:21', 1056, 1101, 45],
[151, '17:38', '18:25', 1058, 1105, 47],
[152, '17:40', '17:56', 1060, 1076, 16],
[153, '17:45', '18:04', 1065, 1084, 19],
[154, '17:46', '17:58', 1066, 1078, 12],
[155, '17:48', '18:35', 1068, 1115, 47],
[156, '17:49', '18:43', 1069, 1123, 54],
[157, '17:55', '18:14', 1075, 1094, 19],
[158, '17:58', '18:45', 1078, 1125, 47],
[159, '18:00', '19:11', 1080, 1151, 71],
[160, '18:04', '18:45', 1084, 1125, 41],
[161, '18:09', '19:03', 1089, 1143, 54],
[162, '18:13', '19:00', 1093, 1140, 47],
[163, '18:13', '18:40', 1093, 1120, 27],
[164, '18:19', '19:13', 1099, 1153, 54],
[165, '18:28', '19:25', 1108, 1165, 57],
[166, '18:48', '19:28', 1128, 1168, 40],
[167, '19:03', '19:45', 1143, 1185, 42],
[168, '19:20', '19:36', 1160, 1176, 16],
[169, '19:21', '19:31', 1161, 1171, 10],
[170, '19:25', '20:04', 1165, 1204, 39],
[171, '19:26', '20:08', 1166, 1208, 42],
[172, '19:30', '19:40', 1170, 1180, 10],
[173, '19:44', '20:33', 1184, 1233, 49],
[174, '19:48', '21:09', 1188, 1269, 81],
[175, '19:53', '21:02', 1193, 1262, 69],
[176, '20:04', '20:29', 1204, 1229, 25],
[177, '20:17', '21:03', 1217, 1263, 46],
[178, '20:20', '20:57', 1220, 1257, 37],
[179, '20:29', '21:18', 1229, 1278, 49],
[180, '20:35', '21:54', 1235, 1314, 79],
[181, '20:40', '20:50', 1240, 1250, 10],
[182, '20:47', '21:42', 1247, 1302, 55],
[183, '21:00', '21:10', 1260, 1270, 10],
[184, '21:07', '21:44', 1267, 1304, 37],
[185, '21:14', '22:03', 1274, 1323, 49],
[186, '21:39', '21:55', 1299, 1315, 16],
[187, '21:40', '22:17', 1300, 1337, 37],
[188, '21:40', '21:50', 1300, 1310, 10],
[189, '21:48', '22:03', 1308, 1323, 15],
[190, '22:17', '23:03', 1337, 1383, 46],
[191, '22:43', '23:08', 1363, 1388, 25],
[192, '23:35', '01:05', 1415, 1505, 90],
[193, '23:46', '00:01', 1426, 1441, 15],
[194, '23:47', '00:33', 1427, 1473, 46],
[195, '23:52', '00:24', 1432, 1464, 32],
[196, '23:58', '00:38', 1438, 1478, 40],
[197, '00:02', '00:12', 1442, 1452, 10],
[198, '00:07', '00:39', 1447, 1479, 32],
[199, '00:25', '01:12', 1465, 1512, 47]
] # yapf:disable
SAMPLE_SHIFTS_LARGE = [
[0, '04:18', '05:00', 258, 300, 42],
[1, '04:27', '05:08', 267, 308, 41],
[2, '04:29', '05:26', 269, 326, 57],
[3, '04:29', '04:55', 269, 295, 26],
[4, '04:30', '04:53', 270, 293, 23],
[5, '04:30', '04:51', 270, 291, 21],
[6, '04:31', '04:53', 271, 293, 22],
[7, '04:33', '05:15', 273, 315, 42],
[8, '04:34', '04:44', 274, 284, 10],
[9, '04:34', '05:03', 274, 303, 29],
[10, '04:35', '04:50', 275, 290, 15],
[11, '04:36', '04:46', 276, 286, 10],
[12, '04:37', '05:18', 277, 318, 41],
[13, '04:41', '05:13', 281, 313, 32],
[14, '04:42', '05:23', 282, 323, 41],
[15, '04:43', '04:53', 283, 293, 10],
[16, '04:44', '05:45', 284, 345, 61],
[17, '04:45', '05:11', 285, 311, 26],
[18, '04:46', '05:01', 286, 301, 15],
[19, '04:46', '04:56', 286, 296, 10],
[20, '04:47', '05:14', 287, 314, 27],
[21, '04:48', '05:30', 288, 330, 42],
[22, '04:49', '05:41', 289, 341, 52],
[23, '04:49', '05:18', 289, 318, 29],
[24, '04:50', '05:33', 290, 333, 43],
[25, '04:52', '05:56', 292, 356, 64],
[26, '04:52', '05:07', 292, 307, 15],
[27, '04:53', '05:19', 293, 319, 26],
[28, '04:53', '05:23', 293, 323, 30],
[29, '04:55', '05:27', 295, 327, 32],
[30, '04:57', '05:38', 297, 338, 41],
[31, '05:00', '06:00', 300, 360, 60],
[32, '05:00', '05:54', 300, 354, 54],
[33, '05:01', '05:33', 301, 333, 32],
[34, '05:01', '05:26', 301, 326, 25],
[35, '05:02', '05:29', 302, 329, 27],
[36, '05:02', '05:12', 302, 312, 10],
[37, '05:03', '05:45', 303, 345, 42],
[38, '05:03', '05:18', 303, 318, 15],
[39, '05:03', '06:28', 303, 388, 85],
[40, '05:03', '05:13', 303, 313, 10],
[41, '05:04', '06:24', 304, 384, 80],
[42, '05:07', '05:44', 307, 344, 37],
[43, '05:08', '05:48', 308, 348, 40],
[44, '05:10', '06:06', 310, 366, 56],
[45, '05:11', '05:37', 311, 337, 26],
[46, '05:11', '05:53', 311, 353, 42],
[47, '05:13', '06:15', 313, 375, 62],
[48, '05:13', '05:38', 313, 338, 25],
[49, '05:16', '05:44', 316, 344, 28],
[50, '05:17', '05:27', 317, 327, 10],
[51, '05:18', '06:40', 318, 400, 82],
[52, '05:18', '06:03', 318, 363, 45],
[53, '05:18', '06:11', 318, 371, 53],
[54, '05:18', '06:00', 318, 360, 42],
[55, '05:19', '06:34', 319, 394, 75],
[56, '05:20', '06:17', 320, 377, 57],
[57, '05:22', '05:59', 322, 359, 37],
[58, '05:24', '05:48', 324, 348, 24],
[59, '05:25', '05:40', 325, 340, 15],
[60, '05:26', '06:08', 326, 368, 42],
[61, '05:27', '06:30', 327, 390, 63],
[62, '05:27', '05:54', 327, 354, 27],
[63, '05:28', '05:53', 328, 353, 25],
[64, '05:29', '05:44', 329, 344, 15],
[65, '05:30', '05:40', 330, 340, 10],
[66, '05:30', '05:40', 330, 340, 10],
[67, '05:30', '05:40', 330, 340, 10],
[68, '05:32', '06:53', 332, 413, 81],
[69, '05:33', '07:00', 333, 420, 87],
[70, '05:33', '06:15', 333, 375, 42],
[71, '05:33', '05:47', 333, 347, 14],
[72, '05:37', '06:13', 337, 373, 36],
[73, '05:37', '06:05', 337, 365, 28],
[74, '05:38', '06:33', 338, 393, 55],
[75, '05:38', '06:04', 338, 364, 26],
[76, '05:38', '06:18', 338, 378, 40],
[77, '05:39', '05:54', 339, 354, 15],
[78, '05:40', '05:56', 340, 356, 16],
[79, '05:40', '06:41', 340, 401, 61],
[80, '05:40', '05:50', 340, 350, 10],
[81, '05:41', '06:23', 341, 383, 42],
[82, '05:41', '06:01', 341, 361, 20],
[83, '05:43', '06:08', 343, 368, 25],
[84, '05:44', '07:10', 344, 430, 86],
[85, '05:44', '05:55', 344, 355, 11],
[86, '05:45', '06:44', 345, 404, 59],
[87, '05:47', '06:17', 347, 377, 30],
[88, '05:48', '07:08', 348, 428, 80],
[89, '05:48', '06:30', 348, 390, 42],
[90, '05:50', '06:50', 350, 410, 60],
[91, '05:50', '06:00', 350, 360, 10],
[92, '05:50', '06:00', 350, 360, 10],
[93, '05:50', '06:51', 350, 411, 61],
[94, '05:52', '06:33', 352, 393, 41],
[95, '05:52', '06:36', 352, 396, 44],
[96, '05:52', '06:23', 352, 383, 31],
[97, '05:54', '06:14', 354, 374, 20],
[98, '05:54', '07:20', 354, 440, 86],
[99, '05:55', '06:40', 355, 400, 45],
[100, '05:55', '06:27', 355, 387, 32],
[101, '05:56', '06:35', 356, 395, 39],
[102, '05:56', '06:06', 356, 366, 10],
[103, '05:57', '06:21', 357, 381, 24],
[104, '05:58', '07:23', 358, 443, 85],
[105, '05:58', '06:23', 358, 383, 25],
[106, '05:58', '06:08', 358, 368, 10],
[107, '05:58', '06:43', 358, 403, 45],
[108, '06:00', '06:10', 360, 370, 10],
[109, '06:00', '06:16', 360, 376, 16],
[110, '06:00', '07:01', 360, 421, 61],
[111, '06:01', '07:00', 361, 420, 59],
[112, '06:01', '06:13', 361, 373, 12],
[113, '06:01', '06:45', 361, 405, 44],
[114, '06:03', '06:50', 363, 410, 47],
[115, '06:04', '06:37', 364, 397, 33],
[116, '06:04', '07:30', 364, 450, 86],
[117, '06:05', '06:24', 365, 384, 19],
[118, '06:06', '06:51', 366, 411, 45],
[119, '06:07', '06:43', 367, 403, 36],
[120, '06:08', '07:30', 368, 450, 82],
[121, '06:10', '06:20', 370, 380, 10],
[122, '06:10', '07:17', 370, 437, 67],
[123, '06:11', '06:54', 371, 414, 43],
[124, '06:11', '06:21', 371, 381, 10],
[125, '06:13', '06:38', 373, 398, 25],
[126, '06:13', '06:58', 373, 418, 45],
[127, '06:13', '06:53', 373, 413, 40],
[128, '06:14', '07:03', 374, 423, 49],
[129, '06:14', '06:47', 374, 407, 33],
[130, '06:14', '07:40', 374, 460, 86],
[131, '06:15', '07:15', 375, 435, 60],
[132, '06:16', '06:28', 376, 388, 12],
[133, '06:16', '06:26', 376, 386, 10],
[134, '06:17', '06:34', 377, 394, 17],
[135, '06:18', '07:06', 378, 426, 48],
[136, '06:18', '07:38', 378, 458, 80],
[137, '06:18', '07:02', 378, 422, 44],
[138, '06:19', '06:53', 379, 413, 34],
[139, '06:20', '07:25', 380, 445, 65],
[140, '06:20', '06:36', 380, 396, 16],
[141, '06:20', '06:30', 380, 390, 10],
[142, '06:20', '06:30', 380, 390, 10],
[143, '06:21', '06:49', 381, 409, 28],
[144, '06:22', '07:06', 382, 426, 44],
[145, '06:24', '07:50', 384, 470, 86],
[146, '06:24', '06:57', 384, 417, 33],
[147, '06:26', '07:45', 386, 465, 79],
[148, '06:26', '07:10', 386, 430, 44],
[149, '06:27', '06:44', 387, 404, 17],
[150, '06:28', '06:53', 388, 413, 25],
[151, '06:28', '07:14', 388, 434, 46],
[152, '06:29', '07:03', 389, 423, 34],
[153, '06:30', '06:40', 390, 400, 10],
[154, '06:30', '07:37', 390, 457, 67],
[155, '06:31', '06:43', 391, 403, 12],
[156, '06:33', '07:14', 393, 434, 41],
[157, '06:33', '07:53', 393, 473, 80],
[158, '06:34', '08:16', 394, 496, 102],
[159, '06:34', '07:09', 394, 429, 35],
[160, '06:34', '07:07', 394, 427, 33],
[161, '06:36', '07:21', 396, 441, 45],
[162, '06:37', '07:22', 397, 442, 45],
[163, '06:37', '06:54', 397, 414, 17],
[164, '06:38', '07:30', 398, 450, 52],
[165, '06:38', '07:18', 398, 438, 40],
[166, '06:39', '07:33', 399, 453, 54],
[167, '06:40', '07:52', 400, 472, 72],
[168, '06:40', '06:50', 400, 410, 10],
[169, '06:40', '07:22', 400, 442, 42],
[170, '06:40', '06:56', 400, 416, 16],
[171, '06:41', '08:00', 401, 480, 79],
[172, '06:42', '07:26', 402, 446, 44],
[173, '06:42', '07:13', 402, 433, 31],
[174, '06:43', '07:08', 403, 428, 25],
[175, '06:43', '07:30', 403, 450, 47],
[176, '06:43', '07:23', 403, 443, 40],
[177, '06:44', '07:17', 404, 437, 33],
[178, '06:44', '08:13', 404, 493, 89],
[179, '06:46', '07:01', 406, 421, 15],
[180, '06:46', '06:58', 406, 418, 12],
[181, '06:47', '07:04', 407, 424, 17],
[182, '06:48', '08:15', 408, 495, 87],
[183, '06:48', '07:34', 408, 454, 46],
[184, '06:48', '07:37', 408, 457, 49],
[185, '06:49', '07:43', 409, 463, 54],
[186, '06:50', '08:00', 410, 480, 70],
[187, '06:50', '07:00', 410, 420, 10],
[188, '06:50', '07:05', 410, 425, 15],
[189, '06:51', '07:18', 411, 438, 27],
[190, '06:52', '07:36', 412, 456, 44],
[191, '06:53', '07:37', 413, 457, 44],
[192, '06:54', '08:20', 414, 500, 86],
[193, '06:54', '07:27', 414, 447, 33],
[194, '06:54', '07:20', 414, 440, 26],
[195, '06:56', '08:23', 416, 503, 87],
[196, '06:57', '07:12', 417, 432, 15],
[197, '06:57', '07:58', 417, 478, 61],
[198, '06:57', '07:45', 417, 465, 48],
[199, '06:57', '07:40', 417, 460, 43],
[200, '06:58', '07:23', 418, 443, 25],
[201, '06:59', '07:53', 419, 473, 54],
[202, '06:59', '08:07', 419, 487, 68],
[203, '07:00', '07:10', 420, 430, 10],
[204, '07:00', '07:16', 420, 436, 16],
[205, '07:01', '08:30', 421, 510, 89],
[206, '07:01', '07:13', 421, 433, 12],
[207, '07:01', '07:43', 421, 463, 42],
[208, '07:03', '08:30', 423, 510, 87],
[209, '07:04', '07:37', 424, 457, 33],
[210, '07:04', '07:44', 424, 464, 40],
[211, '07:05', '07:52', 425, 472, 47],
[212, '07:05', '08:05', 425, 485, 60],
[213, '07:05', '07:46', 425, 466, 41],
[214, '07:06', '07:51', 426, 471, 45],
[215, '07:07', '08:08', 427, 488, 61],
[216, '07:07', '07:52', 427, 472, 45],
[217, '07:07', '08:16', 427, 496, 69],
[218, '07:07', '07:27', 427, 447, 20],
[219, '07:09', '07:50', 429, 470, 41],
[220, '07:09', '08:40', 429, 520, 91],
[221, '07:09', '08:03', 429, 483, 54],
[222, '07:10', '07:20', 430, 440, 10],
[223, '07:11', '08:36', 431, 516, 85],
[224, '07:12', '08:00', 432, 480, 48],
[225, '07:12', '07:47', 432, 467, 35],
[226, '07:13', '07:54', 433, 474, 41],
[227, '07:13', '07:38', 433, 458, 25],
[228, '07:14', '07:59', 434, 479, 45],
[229, '07:16', '08:50', 436, 530, 94],
[230, '07:16', '07:28', 436, 448, 12],
[231, '07:17', '07:35', 437, 455, 18],
[232, '07:17', '07:58', 437, 478, 41],
[233, '07:18', '08:06', 438, 486, 48],
[234, '07:18', '08:44', 438, 524, 86],
[235, '07:19', '08:13', 439, 493, 54],
[236, '07:20', '08:02', 440, 482, 42],
[237, '07:20', '08:07', 440, 487, 47],
[238, '07:20', '07:30', 440, 450, 10],
[239, '07:20', '07:57', 440, 477, 37],
[240, '07:20', '07:36', 440, 456, 16],
[241, '07:21', '07:48', 441, 468, 27],
[242, '07:22', '08:06', 442, 486, 44],
[243, '07:22', '08:25', 442, 505, 63],
[244, '07:24', '08:27', 444, 507, 63],
[245, '07:24', '08:05', 444, 485, 41],
[246, '07:26', '08:23', 446, 503, 57],
[247, '07:26', '08:52', 446, 532, 86],
[248, '07:27', '08:07', 447, 487, 40],
[249, '07:27', '07:42', 447, 462, 15],
[250, '07:27', '08:15', 447, 495, 48],
[251, '07:28', '07:53', 448, 473, 25],
[252, '07:28', '08:09', 448, 489, 41],
[253, '07:28', '07:38', 448, 458, 10],
[254, '07:30', '08:35', 450, 515, 65],
[255, '07:31', '07:43', 451, 463, 12],
[256, '07:32', '08:13', 452, 493, 41],
[257, '07:34', '09:00', 454, 540, 86],
[258, '07:34', '08:33', 454, 513, 59],
[259, '07:34', '09:04', 454, 544, 90],
[260, '07:35', '08:22', 455, 502, 47],
[261, '07:35', '07:45', 455, 465, 10],
[262, '07:35', '08:16', 455, 496, 41],
[263, '07:36', '08:17', 456, 497, 41],
[264, '07:36', '08:36', 456, 516, 60],
[265, '07:37', '07:50', 457, 470, 13],
[266, '07:40', '07:56', 460, 476, 16],
[267, '07:40', '08:20', 460, 500, 40],
[268, '07:40', '08:45', 460, 525, 65],
[269, '07:41', '08:39', 461, 519, 58],
[270, '07:41', '07:51', 461, 471, 10],
[271, '07:42', '08:30', 462, 510, 48],
[272, '07:42', '08:21', 462, 501, 39],
[273, '07:43', '08:08', 463, 488, 25],
[274, '07:43', '08:24', 463, 504, 41],
[275, '07:44', '09:10', 464, 550, 86],
[276, '07:44', '08:43', 464, 523, 59],
[277, '07:46', '08:28', 466, 508, 42],
[278, '07:46', '07:58', 466, 478, 12],
[279, '07:47', '08:00', 467, 480, 13],
[280, '07:48', '09:14', 468, 554, 86],
[281, '07:49', '08:32', 469, 512, 43],
[282, '07:50', '08:55', 470, 535, 65],
[283, '07:50', '08:00', 470, 480, 10],
[284, '07:50', '08:37', 470, 517, 47],
[285, '07:50', '08:26', 470, 506, 36],
[286, '07:51', '08:18', 471, 498, 27],
[287, '07:52', '08:21', 472, 501, 29],
[288, '07:53', '08:35', 473, 515, 42],
[289, '07:54', '09:19', 474, 559, 85],
[290, '07:55', '08:53', 475, 533, 58],
[291, '07:56', '08:54', 476, 534, 58],
[292, '07:57', '08:39', 477, 519, 42],
[293, '07:57', '08:10', 477, 490, 13],
[294, '07:58', '08:45', 478, 525, 47],
[295, '07:58', '08:23', 478, 503, 25],
[296, '08:00', '08:10', 480, 490, 10],
[297, '08:00', '09:05', 480, 545, 65],
[298, '08:00', '08:16', 480, 496, 16],
[299, '08:00', '08:35', 480, 515, 35],
[300, '08:01', '08:13', 481, 493, 12],
[301, '08:01', '08:43', 481, 523, 42],
[302, '08:03', '09:26', 483, 566, 83],
[303, '08:04', '09:29', 484, 569, 85],
[304, '08:05', '08:21', 485, 501, 16],
[305, '08:05', '08:47', 485, 527, 42],
[306, '08:06', '08:51', 486, 531, 45],
[307, '08:06', '09:03', 486, 543, 57],
[308, '08:07', '08:20', 487, 500, 13],
[309, '08:08', '08:55', 488, 535, 47],
[310, '08:08', '08:50', 488, 530, 42],
[311, '08:10', '08:45', 490, 525, 35],
[312, '08:10', '09:15', 490, 555, 65],
[313, '08:10', '08:20', 490, 500, 10],
[314, '08:11', '09:41', 491, 581, 90],
[315, '08:12', '08:55', 492, 535, 43],
[316, '08:13', '08:38', 493, 518, 25],
[317, '08:14', '09:38', 494, 578, 84],
[318, '08:15', '08:30', 495, 510, 15],
[319, '08:16', '08:30', 496, 510, 14],
[320, '08:16', '08:28', 496, 508, 12],
[321, '08:16', '09:00', 496, 540, 44],
[322, '08:17', '09:13', 497, 553, 56],
[323, '08:18', '09:16', 498, 556, 58],
[324, '08:18', '09:05', 498, 545, 47],
[325, '08:20', '08:36', 500, 516, 16],
[326, '08:20', '08:55', 500, 535, 35],
[327, '08:20', '09:05', 500, 545, 45],
[328, '08:20', '08:30', 500, 510, 10],
[329, '08:20', '09:25', 500, 565, 65],
[330, '08:21', '08:38', 501, 518, 17],
[331, '08:21', '08:47', 501, 527, 26],
[332, '08:22', '08:45', 502, 525, 23],
[333, '08:23', '09:10', 503, 550, 47],
[334, '08:24', '09:48', 504, 588, 84],
[335, '08:26', '08:46', 506, 526, 20],
[336, '08:27', '09:07', 507, 547, 40],
[337, '08:28', '08:50', 508, 530, 22],
[338, '08:28', '09:56', 508, 596, 88],
[339, '08:28', '09:23', 508, 563, 55],
[340, '08:29', '09:20', 509, 560, 51],
[341, '08:30', '09:05', 510, 545, 35],
[342, '08:30', '08:45', 510, 525, 15],
[343, '08:30', '08:40', 510, 520, 10],
[344, '08:30', '09:35', 510, 575, 65],
[345, '08:31', '08:43', 511, 523, 12],
[346, '08:31', '09:13', 511, 553, 42],
[347, '08:34', '09:58', 514, 598, 84],
[348, '08:35', '08:55', 515, 535, 20],
[349, '08:35', '09:15', 515, 555, 40],
[350, '08:35', '08:45', 515, 525, 10],
[351, '08:36', '08:46', 516, 526, 10],
[352, '08:36', '09:00', 516, 540, 24],
[353, '08:38', '09:20', 518, 560, 42],
[354, '08:38', '09:35', 518, 575, 57],
[355, '08:38', '09:14', 518, 554, 36],
[356, '08:39', '09:33', 519, 573, 54],
[357, '08:40', '09:45', 520, 585, 65],
[358, '08:40', '08:50', 520, 530, 10],
[359, '08:40', '08:56', 520, 536, 16],
[360, '08:42', '09:25', 522, 565, 43],
[361, '08:43', '09:08', 523, 548, 25],
[362, '08:44', '09:35', 524, 575, 51],
[363, '08:45', '09:00', 525, 540, 15],
[364, '08:45', '09:05', 525, 545, 20],
[365, '08:46', '09:24', 526, 564, 38],
[366, '08:46', '08:58', 526, 538, 12],
[367, '08:46', '09:30', 526, 570, 44],
[368, '08:48', '10:11', 528, 611, 83],
[369, '08:48', '10:13', 528, 613, 85],
[370, '08:49', '09:43', 529, 583, 54],
[371, '08:50', '09:30', 530, 570, 40],
[372, '08:50', '10:00', 530, 600, 70],
[373, '08:50', '09:00', 530, 540, 10],
[374, '08:51', '09:17', 531, 557, 26],
[375, '08:53', '09:20', 533, 560, 27],
[376, '08:53', '09:35', 533, 575, 42],
[377, '08:55', '09:34', 535, 574, 39],
[378, '08:55', '09:15', 535, 555, 20],
[379, '08:58', '09:38', 538, 578, 40],
[380, '08:58', '10:26', 538, 626, 88],
[381, '08:59', '09:53', 539, 593, 54],
[382, '08:59', '09:50', 539, 590, 51],
[383, '09:00', '09:35', 540, 575, 35],
[384, '09:00', '09:16', 540, 556, 16],
[385, '09:00', '09:10', 540, 550, 10],
[386, '09:00', '09:16', 540, 556, 16],
[387, '09:01', '09:13', 541, 553, 12],
[388, '09:03', '09:45', 543, 585, 42],
[389, '09:03', '10:28', 543, 628, 85],
[390, '09:05', '09:44', 545, 584, 39],
[391, '09:05', '09:25', 545, 565, 20],
[392, '09:08', '09:53', 548, 593, 45],
[393, '09:08', '10:04', 548, 604, 56],
[394, '09:09', '10:03', 549, 603, 54],
[395, '09:10', '10:15', 550, 615, 65],
[396, '09:10', '09:20', 550, 560, 10],
[397, '09:11', '09:38', 551, 578, 27],
[398, '09:13', '10:00', 553, 600, 47],
[399, '09:14', '09:39', 554, 579, 25],
[400, '09:14', '10:05', 554, 605, 51],
[401, '09:15', '09:54', 555, 594, 39],
[402, '09:16', '09:28', 556, 568, 12],
[403, '09:18', '10:43', 558, 643, 85],
[404, '09:18', '10:41', 558, 641, 83],
[405, '09:18', '09:58', 558, 598, 40],
[406, '09:19', '10:13', 559, 613, 54],
[407, '09:20', '09:30', 560, 570, 10],
[408, '09:20', '09:36', 560, 576, 16],
[409, '09:21', '09:47', 561, 587, 26],
[410, '09:23', '10:30', 563, 630, 67],
[411, '09:23', '10:05', 563, 605, 42],
[412, '09:23', '09:49', 563, 589, 26],
[413, '09:24', '09:35', 564, 575, 11],
[414, '09:25', '09:35', 565, 575, 10],
[415, '09:25', '10:04', 565, 604, 39],
[416, '09:28', '10:08', 568, 608, 40],
[417, '09:29', '09:45', 569, 585, 16],
[418, '09:29', '10:20', 569, 620, 51],
[419, '09:29', '10:56', 569, 656, 87],
[420, '09:29', '10:23', 569, 623, 54],
[421, '09:30', '09:40', 570, 580, 10],
[422, '09:31', '09:43', 571, 583, 12],
[423, '09:33', '10:58', 573, 658, 85],
[424, '09:33', '10:15', 573, 615, 42],
[425, '09:34', '09:45', 574, 585, 11],
[426, '09:35', '10:14', 575, 614, 39],
[427, '09:38', '10:45', 578, 645, 67],
[428, '09:39', '10:33', 579, 633, 54],
[429, '09:40', '09:56', 580, 596, 16],
[430, '09:40', '09:50', 580, 590, 10],
[431, '09:41', '10:08', 581, 608, 27],
[432, '09:41', '10:23', 581, 623, 42],
[433, '09:44', '10:35', 584, 635, 51],
[434, '09:44', '11:11', 584, 671, 87],
[435, '09:44', '09:55', 584, 595, 11],
[436, '09:45', '10:24', 585, 624, 39],
[437, '09:46', '09:58', 586, 598, 12],
[438, '09:48', '10:30', 588, 630, 42],
[439, '09:48', '11:13', 588, 673, 85],
[440, '09:48', '10:04', 588, 604, 16],
[441, '09:49', '10:43', 589, 643, 54],
[442, '09:50', '10:00', 590, 600, 10],
[443, '09:51', '10:17', 591, 617, 26],
[444, '09:53', '10:49', 593, 649, 56],
[445, '09:53', '11:00', 593, 660, 67],
[446, '09:54', '10:05', 594, 605, 11],
[447, '09:55', '10:34', 595, 634, 39],
[448, '09:56', '10:38', 596, 638, 42],
[449, '09:57', '10:20', 597, 620, 23],
[450, '09:59', '11:26', 599, 686, 87],
[451, '09:59', '10:50', 599, 650, 51],
[452, '09:59', '10:53', 599, 653, 54],
[453, '10:00', '10:16', 600, 616, 16],
[454, '10:00', '10:10', 600, 610, 10],
[455, '10:01', '10:13', 601, 613, 12],
[456, '10:03', '11:28', 603, 688, 85],
[457, '10:03', '10:45', 603, 645, 42],
[458, '10:04', '10:15', 604, 615, 11],
[459, '10:05', '10:44', 605, 644, 39],
[460, '10:08', '11:15', 608, 675, 67],
[461, '10:09', '11:03', 609, 663, 54],
[462, '10:10', '10:20', 610, 620, 10],
[463, '10:11', '10:38', 611, 638, 27],
[464, '10:11', '10:53', 611, 653, 42],
[465, '10:14', '11:05', 614, 665, 51],
[466, '10:14', '11:41', 614, 701, 87],
[467, '10:14', '10:25', 614, 625, 11],
[468, '10:15', '10:54', 615, 654, 39],
[469, '10:16', '10:28', 616, 628, 12],
[470, '10:18', '11:43', 618, 703, 85],
[471, '10:18', '11:00', 618, 660, 42],
[472, '10:19', '11:13', 619, 673, 54],
[473, '10:20', '10:30', 620, 630, 10],
[474, '10:20', '10:36', 620, 636, 16],
[475, '10:21', '10:47', 621, 647, 26],
[476, '10:23', '11:30', 623, 690, 67],
[477, '10:23', '10:45', 623, 645, 22],
[478, '10:24', '10:35', 624, 635, 11],
[479, '10:25', '11:04', 625, 664, 39],
[480, '10:26', '11:08', 626, 668, 42],
[481, '10:29', '11:20', 629, 680, 51],
[482, '10:29', '11:23', 629, 683, 54],
[483, '10:29', '11:56', 629, 716, 87],
[484, '10:30', '10:40', 630, 640, 10],
[485, '10:31', '10:43', 631, 643, 12],
[486, '10:33', '11:15', 633, 675, 42],
[487, '10:33', '11:58', 633, 718, 85],
[488, '10:34', '10:45', 634, 645, 11],
[489, '10:35', '11:14', 635, 674, 39],
[490, '10:38', '11:45', 638, 705, 67],
[491, '10:39', '11:33', 639, 693, 54],
[492, '10:40', '10:50', 640, 650, 10],
[493, '10:40', '10:56', 640, 656, 16],
[494, '10:41', '11:23', 641, 683, 42],
[495, '10:41', '11:08', 641, 668, 27],
[496, '10:44', '12:11', 644, 731, 87],
[497, '10:44', '11:35', 644, 695, 51],
[498, '10:44', '10:55', 644, 655, 11],
[499, '10:45', '11:24', 645, 684, 39],
[500, '10:46', '10:58', 646, 658, 12],
[501, '10:48', '12:13', 648, 733, 85],
[502, '10:48', '11:30', 648, 690, 42],
[503, '10:49', '11:43', 649, 703, 54],
[504, '10:50', '11:00', 650, 660, 10],
[505, '10:51', '11:17', 651, 677, 26],
[506, '10:53', '12:00', 653, 720, 67],
[507, '10:53', '11:20', 653, 680, 27],
[508, '10:54', '11:05', 654, 665, 11],
[509, '10:55', '11:34', 655, 694, 39],
[510, '10:56', '11:38', 656, 698, 42],
[511, '10:59', '11:14', 659, 674, 15],
[512, '10:59', '12:26', 659, 746, 87],
[513, '10:59', '11:53', 659, 713, 54],
[514, '10:59', '11:50', 659, 710, 51],
[515, '11:00', '11:16', 660, 676, 16],
[516, '11:00', '11:10', 660, 670, 10],
[517, '11:01', '11:13', 661, 673, 12],
[518, '11:03', '11:45', 663, 705, 42],
[519, '11:03', '12:28', 663, 748, 85],
[520, '11:04', '11:15', 664, 675, 11],
[521, '11:05', '11:44', 665, 704, 39],
[522, '11:08', '12:15', 668, 735, 67],
[523, '11:09', '12:03', 669, 723, 54],
[524, '11:10', '11:20', 670, 680, 10],
[525, '11:11', '11:38', 671, 698, 27],
[526, '11:11', '11:53', 671, 713, 42],
[527, '11:14', '11:25', 674, 685, 11],
[528, '11:14', '12:05', 674, 725, 51],
[529, '11:14', '12:38', 674, 758, 84],
[530, '11:14', '12:41', 674, 761, 87],
[531, '11:15', '11:54', 675, 714, 39],
[532, '11:16', '11:28', 676, 688, 12],
[533, '11:18', '12:00', 678, 720, 42],
[534, '11:19', '12:13', 679, 733, 54],
[535, '11:20', '11:30', 680, 690, 10],
[536, '11:20', '11:36', 680, 696, 16],
[537, '11:21', '11:47', 681, 707, 26],
[538, '11:23', '12:30', 683, 750, 67],
[539, '11:23', '11:49', 683, 709, 26],
[540, '11:24', '12:48', 684, 768, 84],
[541, '11:24', '11:35', 684, 695, 11],
[542, '11:25', '12:04', 685, 724, 39],
[543, '11:26', '12:08', 686, 728, 42],
[544, '11:29', '11:44', 689, 704, 15],
[545, '11:29', '12:23', 689, 743, 54],
[546, '11:29', '12:20', 689, 740, 51],
[547, '11:29', '12:54', 689, 774, 85],
[548, '11:30', '11:40', 690, 700, 10],
[549, '11:31', '11:43', 691, 703, 12],
[550, '11:33', '12:15', 693, 735, 42],
[551, '11:34', '12:58', 694, 778, 84],
[552, '11:34', '11:45', 694, 705, 11],
[553, '11:35', '12:14', 695, 734, 39],
[554, '11:38', '12:45', 698, 765, 67],
[555, '11:39', '12:33', 699, 753, 54],
[556, '11:40', '11:56', 700, 716, 16],
[557, '11:40', '11:50', 700, 710, 10],
[558, '11:41', '12:08', 701, 728, 27],
[559, '11:41', '12:23', 701, 743, 42],
[560, '11:44', '11:55', 704, 715, 11],
[561, '11:44', '13:14', 704, 794, 90],
[562, '11:44', '13:08', 704, 788, 84],
[563, '11:44', '12:35', 704, 755, 51],
[564, '11:45', '12:24', 705, 744, 39],
[565, '11:46', '11:58', 706, 718, 12],
[566, '11:48', '12:30', 708, 750, 42],
[567, '11:49', '12:43', 709, 763, 54],
[568, '11:50', '12:00', 710, 720, 10],
[569, '11:51', '12:17', 711, 737, 26],
[570, '11:53', '12:49', 713, 769, 56],
[571, '11:53', '13:00', 713, 780, 67],
[572, '11:54', '13:18', 714, 798, 84],
[573, '11:54', '12:05', 714, 725, 11],
[574, '11:55', '12:40', 715, 760, 45],
[575, '11:55', '12:34', 715, 754, 39],
[576, '11:56', '12:35', 716, 755, 39],
[577, '11:57', '12:20', 717, 740, 23],
[578, '11:58', '12:29', 718, 749, 31],
[579, '11:59', '12:50', 719, 770, 51],
[580, '11:59', '12:53', 719, 773, 54],
[581, '11:59', '13:24', 719, 804, 85],
[582, '11:59', '12:14', 719, 734, 15],
[583, '12:00', '12:16', 720, 736, 16],
[584, '12:00', '12:10', 720, 730, 10],
[585, '12:01', '12:45', 721, 765, 44],
[586, '12:01', '12:13', 721, 733, 12],
[587, '12:03', '12:50', 723, 770, 47],
[588, '12:04', '12:15', 724, 735, 11],
[589, '12:04', '13:04', 724, 784, 60],
[590, '12:04', '13:28', 724, 808, 84],
[591, '12:05', '12:44', 725, 764, 39],
[592, '12:08', '13:11', 728, 791, 63],
[593, '12:08', '12:39', 728, 759, 31],
[594, '12:09', '13:03', 729, 783, 54],
[595, '12:10', '12:20', 730, 740, 10],
[596, '12:11', '12:55', 731, 775, 44],
[597, '12:11', '12:38', 731, 758, 27],
[598, '12:14', '13:05', 734, 785, 51],
[599, '12:14', '12:25', 734, 745, 11],
[600, '12:14', '13:44', 734, 824, 90],
[601, '12:14', '13:38', 734, 818, 84],
[602, '12:15', '12:54', 735, 774, 39],
[603, '12:16', '12:28', 736, 748, 12],
[604, '12:18', '13:00', 738, 780, 42],
[605, '12:19', '13:13', 739, 793, 54],
[606, '12:20', '12:30', 740, 750, 10],
[607, '12:20', '13:31', 740, 811, 71],
[608, '12:20', '12:30', 740, 750, 10],
[609, '12:20', '12:36', 740, 756, 16],
[610, '12:21', '12:47', 741, 767, 26],
[611, '12:23', '12:45', 743, 765, 22],
[612, '12:24', '12:35', 744, 755, 11],
[613, '12:24', '13:48', 744, 828, 84],
[614, '12:25', '13:10', 745, 790, 45],
[615, '12:25', '13:04', 745, 784, 39],
[616, '12:26', '13:05', 746, 785, 39],
[617, '12:28', '13:54', 748, 834, 86],
[618, '12:28', '12:38', 748, 758, 10],
[619, '12:28', '13:15', 748, 795, 47],
[620, '12:29', '13:23', 749, 803, 54],
[621, '12:30', '13:41', 750, 821, 71],
[622, '12:30', '12:40', 750, 760, 10],
[623, '12:31', '13:15', 751, 795, 44],
[624, '12:31', '12:43', 751, 763, 12],
[625, '12:33', '12:48', 753, 768, 15],
[626, '12:33', '13:20', 753, 800, 47],
[627, '12:34', '13:58', 754, 838, 84],
[628, '12:34', '13:34', 754, 814, 60],
[629, '12:34', '12:45', 754, 765, 11],
[630, '12:35', '13:14', 755, 794, 39],
[631, '12:38', '13:25', 758, 805, 47],
[632, '12:38', '13:25', 758, 805, 47],
[633, '12:38', '14:04', 758, 844, 86],
[634, '12:39', '13:33', 759, 813, 54],
[635, '12:40', '13:51', 760, 831, 71],
[636, '12:40', '12:50', 760, 770, 10],
[637, '12:40', '12:56', 760, 776, 16],
[638, '12:41', '13:08', 761, 788, 27],
[639, '12:43', '13:30', 763, 810, 47],
[640, '12:44', '12:55', 764, 775, 11],
[641, '12:44', '14:08', 764, 848, 84],
[642, '12:45', '13:24', 765, 804, 39],
[643, '12:46', '12:58', 766, 778, 12],
[644, '12:46', '13:21', 766, 801, 35],
[645, '12:48', '14:14', 768, 854, 86],
[646, '12:48', '13:35', 768, 815, 47],
[647, '12:48', '12:58', 768, 778, 10],
[648, '12:48', '13:35', 768, 815, 47],
[649, '12:49', '13:43', 769, 823, 54],
[650, '12:50', '14:01', 770, 841, 71],
[651, '12:50', '13:00', 770, 780, 10],
[652, '12:50', '13:00', 770, 780, 10],
[653, '12:51', '13:17', 771, 797, 26],
[654, '12:53', '13:20', 773, 800, 27],
[655, '12:53', '13:24', 773, 804, 31],
[656, '12:53', '13:40', 773, 820, 47],
[657, '12:54', '14:18', 774, 858, 84],
[658, '12:54', '13:05', 774, 785, 11],
[659, '12:55', '13:34', 775, 814, 39],
[660, '12:58', '14:24', 778, 864, 86],
[661, '12:58', '13:25', 778, 805, 27],
[662, '12:58', '13:45', 778, 825, 47],
[663, '12:58', '13:45', 778, 825, 47],
[664, '12:59', '13:53', 779, 833, 54],
[665, '13:00', '13:10', 780, 790, 10],
[666, '13:00', '13:16', 780, 796, 16],
[667, '13:00', '14:11', 780, 851, 71],
[668, '13:01', '13:13', 781, 793, 12],
[669, '13:03', '13:34', 783, 814, 31],
[670, '13:03', '13:50', 783, 830, 47],
[671, '13:04', '13:15', 784, 795, 11],
[672, '13:04', '14:28', 784, 868, 84],
[673, '13:05', '13:44', 785, 824, 39],
[674, '13:08', '13:55', 788, 835, 47],
[675, '13:08', '14:34', 788, 874, 86],
[676, '13:08', '13:55', 788, 835, 47],
[677, '13:09', '14:03', 789, 843, 54],
[678, '13:10', '13:20', 790, 800, 10],
[679, '13:10', '14:21', 790, 861, 71],
[680, '13:13', '14:00', 793, 840, 47],
[681, '13:13', '13:40', 793, 820, 27],
[682, '13:14', '14:38', 794, 878, 84],
[683, '13:14', '13:25', 794, 805, 11],
[684, '13:15', '13:54', 795, 834, 39],
[685, '13:16', '13:28', 796, 808, 12],
[686, '13:18', '14:05', 798, 845, 47],
[687, '13:18', '14:44', 798, 884, 86],
[688, '13:18', '14:05', 798, 845, 47],
[689, '13:19', '14:13', 799, 853, 54],
[690, '13:20', '13:36', 800, 816, 16],
[691, '13:20', '14:31', 800, 871, 71],
[692, '13:20', '13:30', 800, 810, 10],
[693, '13:21', '13:47', 801, 827, 26],
[694, '13:23', '14:10', 803, 850, 47],
[695, '13:23', '13:49', 803, 829, 26],
[696, '13:24', '14:48', 804, 888, 84],
[697, '13:24', '13:35', 804, 815, 11],
[698, '13:25', '14:04', 805, 844, 39],
[699, '13:28', '14:15', 808, 855, 47],
[700, '13:28', '14:54', 808, 894, 86],
[701, '13:28', '13:55', 808, 835, 27],
[702, '13:28', '14:15', 808, 855, 47],
[703, '13:29', '14:23', 809, 863, 54],
[704, '13:30', '13:40', 810, 820, 10],
[705, '13:30', '14:41', 810, 881, 71],
[706, '13:31', '13:43', 811, 823, 12],
[707, '13:33', '14:20', 813, 860, 47],
[708, '13:34', '14:58', 814, 898, 84],
[709, '13:34', '13:45', 814, 825, 11],
[710, '13:35', '14:14', 815, 854, 39],
[711, '13:38', '14:25', 818, 865, 47],
[712, '13:38', '14:25', 818, 865, 47],
[713, '13:38', '15:04', 818, 904, 86],
[714, '13:39', '14:33', 819, 873, 54],
[715, '13:40', '13:50', 820, 830, 10],
[716, '13:40', '13:56', 820, 836, 16],
[717, '13:40', '14:51', 820, 891, 71],
[718, '13:43', '14:30', 823, 870, 47],
[719, '13:43', '14:10', 823, 850, 27],
[720, '13:44', '15:09', 824, 909, 85],
[721, '13:44', '13:55', 824, 835, 11],
[722, '13:45', '14:24', 825, 864, 39],
[723, '13:46', '13:58', 826, 838, 12],
[724, '13:48', '14:35', 828, 875, 47],
[725, '13:48', '15:14', 828, 914, 86],
[726, '13:48', '14:35', 828, 875, 47],
[727, '13:49', '14:43', 829, 883, 54],
[728, '13:50', '14:00', 830, 840, 10],
[729, '13:50', '15:01', 830, 901, 71],
[730, '13:51', '14:17', 831, 857, 26],
[731, '13:53', '14:40', 833, 880, 47],
[732, '13:53', '14:49', 833, 889, 56],
[733, '13:54', '14:05', 834, 845, 11],
[734, '13:54', '15:19', 834, 919, 85],
[735, '13:55', '14:34', 835, 874, 39],
[736, '13:57', '14:20', 837, 860, 23],
[737, '13:58', '15:24', 838, 924, 86],
[738, '13:58', '14:45', 838, 885, 47],
[739, '13:58', '14:45', 838, 885, 47],
[740, '13:58', '14:25', 838, 865, 27],
[741, '13:59', '14:53', 839, 893, 54],
[742, '14:00', '14:16', 840, 856, 16],
[743, '14:00', '14:10', 840, 850, 10],
[744, '14:00', '15:11', 840, 911, 71],
[745, '14:01', '14:13', 841, 853, 12],
[746, '14:03', '14:50', 843, 890, 47],
[747, '14:04', '14:15', 844, 855, 11],
[748, '14:04', '15:29', 844, 929, 85],
[749, '14:05', '14:44', 845, 884, 39],
[750, '14:08', '14:55', 848, 895, 47],
[751, '14:08', '14:55', 848, 895, 47],
[752, '14:08', '15:34', 848, 934, 86],
[753, '14:09', '15:03', 849, 903, 54],
[754, '14:10', '15:21', 850, 921, 71],
[755, '14:10', '14:20', 850, 860, 10],
[756, '14:13', '15:00', 853, 900, 47],
[757, '14:13', '14:40', 853, 880, 27],
[758, '14:14', '15:40', 854, 940, 86],
[759, '14:14', '14:25', 854, 865, 11],
[760, '14:15', '14:54', 855, 894, 39],
[761, '14:16', '14:28', 856, 868, 12],
[762, '14:18', '15:05', 858, 905, 47],
[763, '14:18', '15:44', 858, 944, 86],
[764, '14:18', '15:05', 858, 905, 47],
[765, '14:19', '15:13', 859, 913, 54],
[766, '14:20', '15:31', 860, 931, 71],
[767, '14:20', '14:30', 860, 870, 10],
[768, '14:20', '14:36', 860, 876, 16],
[769, '14:21', '14:47', 861, 887, 26],
[770, '14:23', '15:10', 863, 910, 47],
[771, '14:23', '14:45', 863, 885, 22],
[772, '14:24', '15:50', 864, 950, 86],
[773, '14:24', '14:35', 864, 875, 11],
[774, '14:25', '15:02', 865, 902, 37],
[775, '14:26', '14:52', 866, 892, 26],
[776, '14:28', '15:15', 868, 915, 47],
[777, '14:28', '14:55', 868, 895, 27],
[778, '14:28', '15:54', 868, 954, 86],
[779, '14:28', '15:15', 868, 915, 47],
[780, '14:29', '15:23', 869, 923, 54],
[781, '14:30', '15:41', 870, 941, 71],
[782, '14:30', '14:40', 870, 880, 10],
[783, '14:31', '14:43', 871, 883, 12],
[784, '14:33', '15:20', 873, 920, 47],
[785, '14:34', '16:00', 874, 960, 86],
[786, '14:34', '14:45', 874, 885, 11],
[787, '14:35', '15:11', 875, 911, 36],
[788, '14:38', '15:25', 878, 925, 47],
[789, '14:38', '15:25', 878, 925, 47],
[790, '14:38', '16:04', 878, 964, 86],
[791, '14:39', '15:33', 879, 933, 54],
[792, '14:40', '14:50', 880, 890, 10],
[793, '14:40', '15:51', 880, 951, 71],
[794, '14:40', '14:56', 880, 896, 16],
[795, '14:43', '15:30', 883, 930, 47],
[796, '14:43', '15:10', 883, 910, 27],
[797, '14:44', '15:00', 884, 900, 16],
[798, '14:44', '16:10', 884, 970, 86],
[799, '14:45', '15:19', 885, 919, 34],
[800, '14:46', '14:58', 886, 898, 12],
[801, '14:48', '15:35', 888, 935, 47],
[802, '14:48', '15:35', 888, 935, 47],
[803, '14:48', '17:04', 888, 1024, 136],
[804, '14:49', '15:43', 889, 943, 54],
[805, '14:50', '16:01', 890, 961, 71],
[806, '14:50', '15:00', 890, 900, 10],
[807, '14:51', '15:17', 891, 917, 26],
[808, '14:52', '15:27', 892, 927, 35],
[809, '14:52', '15:21', 892, 921, 29],
[810, '14:53', '15:40', 893, 940, 47],
[811, '14:54', '15:08', 894, 908, 14],
[812, '14:54', '16:20', 894, 980, 86],
[813, '14:58', '16:24', 898, 984, 86],
[814, '14:58', '15:45', 898, 945, 47],
[815, '14:58', '15:25', 898, 925, 27],
[816, '14:58', '15:45', 898, 945, 47],
[817, '14:59', '15:53', 899, 953, 54],
[818, '15:00', '15:10', 900, 910, 10],
[819, '15:00', '15:35', 900, 935, 35],
[820, '15:00', '16:11', 900, 971, 71],
[821, '15:00', '15:16', 900, 916, 16],
[822, '15:01', '15:13', 901, 913, 12],
[823, '15:02', '15:16', 902, 916, 14],
[824, '15:03', '15:50', 903, 950, 47],
[825, '15:04', '16:30', 904, 990, 86],
[826, '15:08', '16:34', 908, 994, 86],
[827, '15:08', '15:55', 908, 955, 47],
[828, '15:08', '15:55', 908, 955, 47],
[829, '15:08', '15:45', 908, 945, 37],
[830, '15:09', '16:14', 909, 974, 65],
[831, '15:09', '16:03', 909, 963, 54],
[832, '15:10', '16:21', 910, 981, 71],
[833, '15:10', '15:20', 910, 920, 10],
[834, '15:11', '15:24', 911, 924, 13],
[835, '15:12', '15:36', 912, 936, 24],
[836, '15:13', '16:00', 913, 960, 47],
[837, '15:13', '15:40', 913, 940, 27],
[838, '15:14', '16:40', 914, 1000, 86],
[839, '15:16', '15:28', 916, 928, 12],
[840, '15:16', '15:55', 916, 955, 39],
[841, '15:18', '16:05', 918, 965, 47],
[842, '15:18', '16:44', 918, 1004, 86],
[843, '15:18', '16:05', 918, 965, 47],
[844, '15:19', '16:13', 919, 973, 54],
[845, '15:19', '15:34', 919, 934, 15],
[846, '15:20', '15:30', 920, 930, 10],
[847, '15:20', '16:31', 920, 991, 71],
[848, '15:20', '15:36', 920, 936, 16],
[849, '15:21', '15:47', 921, 947, 26],
[850, '15:21', '16:06', 921, 966, 45],
[851, '15:23', '16:10', 923, 970, 47],
[852, '15:24', '16:50', 924, 1010, 86],
[853, '15:24', '16:05', 924, 965, 41],
[854, '15:27', '15:51', 927, 951, 24],
[855, '15:27', '15:44', 927, 944, 17],
[856, '15:28', '16:15', 928, 975, 47],
[857, '15:28', '16:54', 928, 1014, 86],
[858, '15:28', '16:15', 928, 975, 47],
[859, '15:28', '15:55', 928, 955, 27],
[860, '15:29', '16:23', 929, 983, 54],
[861, '15:30', '16:41', 930, 1001, 71],
[862, '15:30', '15:40', 930, 940, 10],
[863, '15:31', '15:43', 931, 943, 12],
[864, '15:33', '16:20', 933, 980, 47],
[865, '15:34', '17:00', 934, 1020, 86],
[866, '15:34', '16:15', 934, 975, 41],
[867, '15:35', '15:54', 935, 954, 19],
[868, '15:36', '16:21', 936, 981, 45],
[869, '15:38', '16:25', 938, 985, 47],
[870, '15:38', '16:25', 938, 985, 47],
[871, '15:38', '16:39', 938, 999, 61],
[872, '15:39', '16:33', 939, 993, 54],
[873, '15:40', '15:50', 940, 950, 10],
[874, '15:40', '16:51', 940, 1011, 71],
[875, '15:40', '15:56', 940, 956, 16],
[876, '15:43', '16:10', 943, 970, 27],
[877, '15:43', '16:30', 943, 990, 47],
[878, '15:44', '17:10', 944, 1030, 86],
[879, '15:44', '16:25', 944, 985, 41],
[880, '15:45', '16:04', 945, 964, 19],
[881, '15:46', '15:58', 946, 958, 12],
[882, '15:48', '16:35', 948, 995, 47],
[883, '15:48', '16:35', 948, 995, 47],
[884, '15:48', '17:14', 948, 1034, 86],
[885, '15:49', '16:43', 949, 1003, 54],
[886, '15:50', '16:00', 950, 960, 10],
[887, '15:50', '17:01', 950, 1021, 71],
[888, '15:51', '16:18', 951, 978, 27],
[889, '15:52', '16:36', 952, 996, 44],
[890, '15:53', '16:40', 953, 1000, 47],
[891, '15:54', '17:20', 954, 1040, 86],
[892, '15:54', '16:35', 954, 995, 41],
[893, '15:55', '16:14', 955, 974, 19],
[894, '15:58', '16:25', 958, 985, 27],
[895, '15:58', '16:45', 958, 1005, 47],
[896, '15:58', '16:45', 958, 1005, 47],
[897, '15:58', '17:24', 958, 1044, 86],
[898, '15:59', '17:11', 959, 1031, 72],
[899, '15:59', '16:53', 959, 1013, 54],
[900, '16:00', '16:10', 960, 970, 10],
[901, '16:00', '16:16', 960, 976, 16],
[902, '16:01', '16:13', 961, 973, 12],
[903, '16:03', '16:50', 963, 1010, 47],
[904, '16:04', '17:30', 964, 1050, 86],
[905, '16:04', '16:45', 964, 1005, 41],
[906, '16:05', '16:24', 965, 984, 19],
[907, '16:06', '16:51', 966, 1011, 45],
[908, '16:08', '16:55', 968, 1015, 47],
[909, '16:08', '17:34', 968, 1054, 86],
[910, '16:08', '16:55', 968, 1015, 47],
[911, '16:09', '17:03', 969, 1023, 54],
[912, '16:09', '17:21', 969, 1041, 72],
[913, '16:10', '16:20', 970, 980, 10],
[914, '16:13', '16:40', 973, 1000, 27],
[915, '16:13', '17:00', 973, 1020, 47],
[916, '16:14', '16:55', 974, 1015, 41],
[917, '16:14', '17:40', 974, 1060, 86],
[918, '16:15', '16:34', 975, 994, 19],
[919, '16:16', '16:28', 976, 988, 12],
[920, '16:18', '17:05', 978, 1025, 47],
[921, '16:18', '17:05', 978, 1025, 47],
[922, '16:18', '17:44', 978, 1064, 86],
[923, '16:19', '17:31', 979, 1051, 72],
[924, '16:19', '17:13', 979, 1033, 54],
[925, '16:20', '16:30', 980, 990, 10],
[926, '16:20', '16:36', 980, 996, 16],
[927, '16:21', '16:48', 981, 1008, 27],
[928, '16:22', '17:06', 982, 1026, 44],
[929, '16:23', '17:10', 983, 1030, 47],
[930, '16:24', '17:05', 984, 1025, 41],
[931, '16:24', '17:50', 984, 1070, 86],
[932, '16:25', '16:44', 985, 1004, 19],
[933, '16:28', '17:15', 988, 1035, 47],
[934, '16:28', '17:15', 988, 1035, 47],
[935, '16:28', '16:55', 988, 1015, 27],
[936, '16:28', '17:54', 988, 1074, 86],
[937, '16:29', '17:23', 989, 1043, 54],
[938, '16:29', '17:41', 989, 1061, 72],
[939, '16:30', '16:40', 990, 1000, 10],
[940, '16:31', '16:43', 991, 1003, 12],
[941, '16:33', '17:20', 993, 1040, 47],
[942, '16:34', '17:15', 994, 1035, 41],
[943, '16:34', '18:00', 994, 1080, 86],
[944, '16:35', '16:54', 995, 1014, 19],
[945, '16:36', '17:21', 996, 1041, 45],
[946, '16:38', '17:25', 998, 1045, 47],
[947, '16:38', '17:25', 998, 1045, 47],
[948, '16:38', '18:04', 998, 1084, 86],
[949, '16:39', '17:33', 999, 1053, 54],
[950, '16:39', '17:51', 999, 1071, 72],
[951, '16:40', '16:56', 1000, 1016, 16],
[952, '16:40', '16:50', 1000, 1010, 10],
[953, '16:43', '17:10', 1003, 1030, 27],
[954, '16:43', '17:30', 1003, 1050, 47],
[955, '16:44', '17:25', 1004, 1045, 41],
[956, '16:44', '18:10', 1004, 1090, 86],
[957, '16:45', '17:04', 1005, 1024, 19],
[958, '16:46', '16:58', 1006, 1018, 12],
[959, '16:48', '18:14', 1008, 1094, 86],
[960, '16:48', '17:35', 1008, 1055, 47],
[961, '16:48', '17:35', 1008, 1055, 47],
[962, '16:49', '18:01', 1009, 1081, 72],
[963, '16:49', '17:43', 1009, 1063, 54],
[964, '16:50', '17:00', 1010, 1020, 10],
[965, '16:51', '17:18', 1011, 1038, 27],
[966, '16:52', '17:36', 1012, 1056, 44],
[967, '16:53', '17:40', 1013, 1060, 47],
[968, '16:54', '18:20', 1014, 1100, 86],
[969, '16:54', '17:35', 1014, 1055, 41],
[970, '16:55', '17:14', 1015, 1034, 19],
[971, '16:58', '17:25', 1018, 1045, 27],
[972, '16:58', '17:45', 1018, 1065, 47],
[973, '16:58', '17:45', 1018, 1065, 47],
[974, '16:58', '18:24', 1018, 1104, 86],
[975, '16:59', '18:11', 1019, 1091, 72],
[976, '16:59', '17:53', 1019, 1073, 54],
[977, '17:00', '17:16', 1020, 1036, 16],
[978, '17:00', '17:10', 1020, 1030, 10],
[979, '17:01', '17:13', 1021, 1033, 12],
[980, '17:03', '17:50', 1023, 1070, 47],
[981, '17:04', '18:30', 1024, 1110, 86],
[982, '17:04', '17:45', 1024, 1065, 41],
[983, '17:05', '17:24', 1025, 1044, 19],
[984, '17:06', '17:51', 1026, 1071, 45],
[985, '17:08', '17:55', 1028, 1075, 47],
[986, '17:08', '17:55', 1028, 1075, 47],
[987, '17:08', '18:34', 1028, 1114, 86],
[988, '17:09', '18:03', 1029, 1083, 54],
[989, '17:09', '18:21', 1029, 1101, 72],
[990, '17:10', '17:20', 1030, 1040, 10],
[991, '17:13', '17:40', 1033, 1060, 27],
[992, '17:13', '18:00', 1033, 1080, 47],
[993, '17:14', '17:55', 1034, 1075, 41],
[994, '17:14', '18:40', 1034, 1120, 86],
[995, '17:15', '17:34', 1035, 1054, 19],
[996, '17:16', '17:28', 1036, 1048, 12],
[997, '17:18', '18:05', 1038, 1085, 47],
[998, '17:18', '18:05', 1038, 1085, 47],
[999, '17:18', '18:44', 1038, 1124, 86],
[1000, '17:19', '18:31', 1039, 1111, 72],
[1001, '17:19', '18:13', 1039, 1093, 54],
[1002, '17:20', '17:36', 1040, 1056, 16],
[1003, '17:20', '17:30', 1040, 1050, 10],
[1004, '17:21', '17:47', 1041, 1067, 26],
[1005, '17:22', '18:06', 1042, 1086, 44],
[1006, '17:23', '18:10', 1043, 1090, 47],
[1007, '17:24', '18:50', 1044, 1130, 86],
[1008, '17:24', '18:05', 1044, 1085, 41],
[1009, '17:25', '17:44', 1045, 1064, 19],
[1010, '17:28', '17:55', 1048, 1075, 27],
[1011, '17:28', '18:15', 1048, 1095, 47],
[1012, '17:28', '18:15', 1048, 1095, 47],
[1013, '17:28', '18:54', 1048, 1134, 86],
[1014, '17:29', '18:41', 1049, 1121, 72],
[1015, '17:29', '18:23', 1049, 1103, 54],
[1016, '17:30', '17:40', 1050, 1060, 10],
[1017, '17:31', '17:43', 1051, 1063, 12],
[1018, '17:33', '18:20', 1053, 1100, 47],
[1019, '17:34', '18:15', 1054, 1095, 41],
[1020, '17:34', '19:00', 1054, 1140, 86],
[1021, '17:35', '17:54', 1055, 1074, 19],
[1022, '17:36', '18:21', 1056, 1101, 45],
[1023, '17:38', '18:25', 1058, 1105, 47],
[1024, '17:38', '19:04', 1058, 1144, 86],
[1025, '17:38', '18:25', 1058, 1105, 47],
[1026, '17:39', '18:51', 1059, 1131, 72],
[1027, '17:39', '18:33', 1059, 1113, 54],
[1028, '17:40', '17:56', 1060, 1076, 16],
[1029, '17:40', '17:50', 1060, 1070, 10],
[1030, '17:43', '18:10', 1063, 1090, 27],
[1031, '17:43', '18:30', 1063, 1110, 47],
[1032, '17:44', '18:25', 1064, 1105, 41],
[1033, '17:44', '19:14', 1064, 1154, 90],
[1034, '17:45', '18:04', 1065, 1084, 19],
[1035, '17:46', '17:58', 1066, 1078, 12],
[1036, '17:48', '18:35', 1068, 1115, 47],
[1037, '17:48', '18:35', 1068, 1115, 47],
[1038, '17:48', '19:14', 1068, 1154, 86],
[1039, '17:49', '19:01', 1069, 1141, 72],
[1040, '17:49', '18:43', 1069, 1123, 54],
[1041, '17:50', '18:00', 1070, 1080, 10],
[1042, '17:51', '18:17', 1071, 1097, 26],
[1043, '17:52', '18:36', 1072, 1116, 44],
[1044, '17:53', '18:40', 1073, 1120, 47],
[1045, '17:54', '18:35', 1074, 1115, 41],
[1046, '17:54', '18:57', 1074, 1137, 63],
[1047, '17:55', '18:14', 1075, 1094, 19],
[1048, '17:58', '18:45', 1078, 1125, 47],
[1049, '17:58', '18:45', 1078, 1125, 47],
[1050, '17:58', '18:25', 1078, 1105, 27],
[1051, '17:58', '19:26', 1078, 1166, 88],
[1052, '17:59', '18:53', 1079, 1133, 54],
[1053, '18:00', '19:11', 1080, 1151, 71],
[1054, '18:00', '18:10', 1080, 1090, 10],
[1055, '18:00', '18:16', 1080, 1096, 16],
[1056, '18:01', '18:13', 1081, 1093, 12],
[1057, '18:03', '18:50', 1083, 1130, 47],
[1058, '18:04', '18:45', 1084, 1125, 41],
[1059, '18:04', '19:29', 1084, 1169, 85],
[1060, '18:05', '18:24', 1085, 1104, 19],
[1061, '18:06', '18:51', 1086, 1131, 45],
[1062, '18:08', '18:55', 1088, 1135, 47],
[1063, '18:08', '19:06', 1088, 1146, 58],
[1064, '18:08', '18:55', 1088, 1135, 47],
[1065, '18:09', '19:03', 1089, 1143, 54],
[1066, '18:10', '18:20', 1090, 1100, 10],
[1067, '18:10', '19:21', 1090, 1161, 71],
[1068, '18:13', '19:00', 1093, 1140, 47],
[1069, '18:13', '18:40', 1093, 1120, 27],
[1070, '18:14', '19:43', 1094, 1183, 89],
[1071, '18:14', '18:55', 1094, 1135, 41],
[1072, '18:15', '18:34', 1095, 1114, 19],
[1073, '18:16', '18:28', 1096, 1108, 12],
[1074, '18:17', '18:27', 1097, 1107, 10],
[1075, '18:18', '19:41', 1098, 1181, 83],
[1076, '18:18', '18:58', 1098, 1138, 40],
[1077, '18:18', '19:05', 1098, 1145, 47],
[1078, '18:19', '19:13', 1099, 1153, 54],
[1079, '18:20', '19:31', 1100, 1171, 71],
[1080, '18:20', '18:36', 1100, 1116, 16],
[1081, '18:20', '18:30', 1100, 1110, 10],
[1082, '18:22', '19:05', 1102, 1145, 43],
[1083, '18:23', '19:05', 1103, 1145, 42],
[1084, '18:24', '19:27', 1104, 1167, 63],
[1085, '18:24', '19:05', 1104, 1145, 41],
[1086, '18:25', '18:44', 1105, 1124, 19],
[1087, '18:28', '19:25', 1108, 1165, 57],
[1088, '18:28', '18:55', 1108, 1135, 27],
[1089, '18:28', '19:08', 1108, 1148, 40],
[1090, '18:28', '19:15', 1108, 1155, 47],
[1091, '18:29', '19:23', 1109, 1163, 54],
[1092, '18:30', '19:05', 1110, 1145, 35],
[1093, '18:30', '18:40', 1110, 1120, 10],
[1094, '18:31', '18:43', 1111, 1123, 12],
[1095, '18:33', '19:15', 1113, 1155, 42],
[1096, '18:34', '19:58', 1114, 1198, 84],
[1097, '18:34', '19:14', 1114, 1154, 40],
[1098, '18:35', '18:55', 1115, 1135, 20],
[1099, '18:36', '19:20', 1116, 1160, 44],
[1100, '18:38', '19:25', 1118, 1165, 47],
[1101, '18:38', '19:23', 1118, 1163, 45],
[1102, '18:38', '19:56', 1118, 1196, 78],
[1103, '18:39', '19:33', 1119, 1173, 54],
[1104, '18:40', '18:50', 1120, 1130, 10],
[1105, '18:40', '19:45', 1120, 1185, 65],
[1106, '18:40', '18:56', 1120, 1136, 16],
[1107, '18:43', '19:10', 1123, 1150, 27],
[1108, '18:43', '19:30', 1123, 1170, 47],
[1109, '18:44', '19:24', 1124, 1164, 40],
[1110, '18:45', '19:05', 1125, 1145, 20],
[1111, '18:46', '18:58', 1126, 1138, 12],
[1112, '18:48', '19:35', 1128, 1175, 47],
[1113, '18:48', '20:12', 1128, 1212, 84],
[1114, '18:48', '20:11', 1128, 1211, 83],
[1115, '18:48', '19:28', 1128, 1168, 40],
[1116, '18:49', '19:43', 1129, 1183, 54],
[1117, '18:50', '19:00', 1130, 1140, 10],
[1118, '18:51', '19:01', 1131, 1141, 10],
[1119, '18:53', '19:35', 1133, 1175, 42],
[1120, '18:53', '19:15', 1133, 1155, 22],
[1121, '18:53', '20:00', 1133, 1200, 67],
[1122, '18:55', '19:15', 1135, 1155, 20],
[1123, '18:55', '19:34', 1135, 1174, 39],
[1124, '18:58', '19:38', 1138, 1178, 40],
[1125, '18:59', '19:53', 1139, 1193, 54],
[1126, '18:59', '19:50', 1139, 1190, 51],
[1127, '18:59', '19:53', 1139, 1193, 54],
[1128, '19:00', '19:16', 1140, 1156, 16],
[1129, '19:00', '19:10', 1140, 1150, 10],
[1130, '19:00', '19:16', 1140, 1156, 16],
[1131, '19:01', '19:13', 1141, 1153, 12],
[1132, '19:03', '20:26', 1143, 1226, 83],
[1133, '19:03', '19:45', 1143, 1185, 42],
[1134, '19:05', '19:44', 1145, 1184, 39],
[1135, '19:05', '19:25', 1145, 1165, 20],
[1136, '19:08', '20:15', 1148, 1215, 67],
[1137, '19:08', '19:35', 1148, 1175, 27],
[1138, '19:09', '19:49', 1149, 1189, 40],
[1139, '19:09', '20:03', 1149, 1203, 54],
[1140, '19:10', '19:20', 1150, 1160, 10],
[1141, '19:10', '19:20', 1150, 1160, 10],
[1142, '19:11', '19:53', 1151, 1193, 42],
[1143, '19:14', '20:26', 1154, 1226, 72],
[1144, '19:14', '19:35', 1154, 1175, 21],
[1145, '19:14', '19:24', 1154, 1164, 10],
[1146, '19:14', '20:05', 1154, 1205, 51],
[1147, '19:15', '19:30', 1155, 1170, 15],
[1148, '19:15', '19:54', 1155, 1194, 39],
[1149, '19:18', '20:39', 1158, 1239, 81],
[1150, '19:18', '20:00', 1158, 1200, 42],
[1151, '19:19', '20:14', 1159, 1214, 55],
[1152, '19:20', '19:30', 1160, 1170, 10],
[1153, '19:20', '19:36', 1160, 1176, 16],
[1154, '19:21', '19:31', 1161, 1171, 10],
[1155, '19:23', '20:30', 1163, 1230, 67],
[1156, '19:23', '19:35', 1163, 1175, 12],
[1157, '19:24', '19:45', 1164, 1185, 21],
[1158, '19:24', '19:45', 1164, 1185, 21],
[1159, '19:25', '20:04', 1165, 1204, 39],
[1160, '19:26', '20:08', 1166, 1208, 42],
[1161, '19:29', '20:02', 1169, 1202, 33],
[1162, '19:29', '20:18', 1169, 1218, 49],
[1163, '19:29', '20:41', 1169, 1241, 72],
[1164, '19:30', '19:40', 1170, 1180, 10],
[1165, '19:33', '20:54', 1173, 1254, 81],
[1166, '19:33', '20:17', 1173, 1217, 44],
[1167, '19:34', '19:55', 1174, 1195, 21],
[1168, '19:35', '20:14', 1175, 1214, 39],
[1169, '19:38', '20:05', 1178, 1205, 27],
[1170, '19:38', '20:45', 1178, 1245, 67],
[1171, '19:39', '20:12', 1179, 1212, 33],
[1172, '19:40', '19:50', 1180, 1190, 10],
[1173, '19:40', '19:56', 1180, 1196, 16],
[1174, '19:41', '20:27', 1181, 1227, 46],
[1175, '19:43', '19:55', 1183, 1195, 12],
[1176, '19:44', '20:05', 1184, 1205, 21],
[1177, '19:44', '20:33', 1184, 1233, 49],
[1178, '19:44', '21:00', 1184, 1260, 76],
[1179, '19:45', '20:24', 1185, 1224, 39],
[1180, '19:48', '20:37', 1188, 1237, 49],
[1181, '19:48', '21:09', 1188, 1269, 81],
[1182, '19:50', '20:00', 1190, 1200, 10],
[1183, '19:52', '20:29', 1192, 1229, 37],
[1184, '19:53', '20:08', 1193, 1208, 15],
[1185, '19:53', '21:02', 1193, 1262, 69],
[1186, '19:53', '20:20', 1193, 1220, 27],
[1187, '19:54', '20:19', 1194, 1219, 25],
[1188, '19:55', '20:34', 1195, 1234, 39],
[1189, '19:56', '20:34', 1196, 1234, 38],
[1190, '19:59', '20:48', 1199, 1248, 49],
[1191, '19:59', '21:20', 1199, 1280, 81],
[1192, '20:00', '20:16', 1200, 1216, 16],
[1193, '20:00', '20:10', 1200, 1210, 10],
[1194, '20:03', '20:42', 1203, 1242, 39],
[1195, '20:03', '21:24', 1203, 1284, 81],
[1196, '20:04', '20:29', 1204, 1229, 25],
[1197, '20:05', '20:48', 1205, 1248, 43],
[1198, '20:07', '20:44', 1207, 1244, 37],
[1199, '20:08', '20:40', 1208, 1240, 32],
[1200, '20:08', '20:35', 1208, 1235, 27],
[1201, '20:10', '20:20', 1210, 1220, 10],
[1202, '20:10', '20:22', 1210, 1222, 12],
[1203, '20:11', '20:47', 1211, 1247, 36],
[1204, '20:14', '21:04', 1214, 1264, 50],
[1205, '20:14', '21:03', 1214, 1263, 49],
[1206, '20:17', '21:03', 1217, 1263, 46],
[1207, '20:18', '21:39', 1218, 1299, 81],
[1208, '20:20', '20:30', 1220, 1230, 10],
[1209, '20:20', '20:57', 1220, 1257, 37],
[1210, '20:20', '20:36', 1220, 1236, 16],
[1211, '20:22', '20:59', 1222, 1259, 37],
[1212, '20:22', '20:42', 1222, 1242, 20],
[1213, '20:24', '20:49', 1224, 1249, 25],
[1214, '20:27', '21:22', 1227, 1282, 55],
[1215, '20:29', '21:18', 1229, 1278, 49],
[1216, '20:30', '21:07', 1230, 1267, 37],
[1217, '20:30', '20:40', 1230, 1240, 10],
[1218, '20:30', '20:40', 1230, 1240, 10],
[1219, '20:30', '21:40', 1230, 1300, 70],
[1220, '20:32', '21:18', 1232, 1278, 46],
[1221, '20:35', '21:54', 1235, 1314, 79],
[1222, '20:37', '21:14', 1237, 1274, 37],
[1223, '20:38', '21:08', 1238, 1268, 30],
[1224, '20:40', '20:50', 1240, 1250, 10],
[1225, '20:40', '21:17', 1240, 1277, 37],
[1226, '20:40', '20:56', 1240, 1256, 16],
[1227, '20:44', '21:33', 1244, 1293, 49],
[1228, '20:47', '21:33', 1247, 1293, 46],
[1229, '20:47', '21:42', 1247, 1302, 55],
[1230, '20:50', '21:00', 1250, 1260, 10],
[1231, '20:50', '22:00', 1250, 1320, 70],
[1232, '20:50', '22:09', 1250, 1329, 79],
[1233, '20:50', '21:27', 1250, 1287, 37],
[1234, '20:52', '21:29', 1252, 1289, 37],
[1235, '20:53', '21:20', 1253, 1280, 27],
[1236, '20:56', '21:11', 1256, 1271, 15],
[1237, '20:59', '21:48', 1259, 1308, 49],
[1238, '21:00', '21:10', 1260, 1270, 10],
[1239, '21:00', '21:37', 1260, 1297, 37],
[1240, '21:02', '21:48', 1262, 1308, 46],
[1241, '21:05', '22:24', 1265, 1344, 79],
[1242, '21:07', '21:44', 1267, 1304, 37],
[1243, '21:07', '22:02', 1267, 1322, 55],
[1244, '21:08', '21:38', 1268, 1298, 30],
[1245, '21:10', '22:25', 1270, 1345, 75],
[1246, '21:10', '21:20', 1270, 1280, 10],
[1247, '21:10', '21:47', 1270, 1307, 37],
[1248, '21:14', '22:03', 1274, 1323, 49],
[1249, '21:17', '22:03', 1277, 1323, 46],
[1250, '21:20', '22:18', 1280, 1338, 58],
[1251, '21:20', '21:57', 1280, 1317, 37],
[1252, '21:20', '21:30', 1280, 1290, 10],
[1253, '21:22', '21:59', 1282, 1319, 37],
[1254, '21:24', '21:49', 1284, 1309, 25],
[1255, '21:27', '22:21', 1287, 1341, 54],
[1256, '21:30', '22:07', 1290, 1327, 37],
[1257, '21:30', '22:20', 1290, 1340, 50],
[1258, '21:30', '21:40', 1290, 1300, 10],
[1259, '21:32', '22:18', 1292, 1338, 46],
[1260, '21:32', '22:01', 1292, 1321, 29],
[1261, '21:35', '22:54', 1295, 1374, 79],
[1262, '21:37', '22:14', 1297, 1334, 37],
[1263, '21:39', '21:55', 1299, 1315, 16],
[1264, '21:40', '22:17', 1300, 1337, 37],
[1265, '21:40', '21:50', 1300, 1310, 10],
[1266, '21:41', '22:08', 1301, 1328, 27],
[1267, '21:47', '22:16', 1307, 1336, 29],
[1268, '21:47', '22:51', 1307, 1371, 64],
[1269, '21:47', '22:33', 1307, 1353, 46],
[1270, '21:48', '22:03', 1308, 1323, 15],
[1271, '21:50', '22:55', 1310, 1375, 65],
[1272, '21:50', '22:27', 1310, 1347, 37],
[1273, '21:50', '22:00', 1310, 1320, 10],
[1274, '21:52', '22:29', 1312, 1349, 37],
[1275, '21:53', '22:19', 1313, 1339, 26],
[1276, '22:00', '22:38', 1320, 1358, 38],
[1277, '22:00', '22:10', 1320, 1330, 10],
[1278, '22:02', '22:12', 1322, 1332, 10],
[1279, '22:02', '22:48', 1322, 1368, 46],
[1280, '22:04', '22:31', 1324, 1351, 27],
[1281, '22:05', '23:24', 1325, 1404, 79],
[1282, '22:07', '22:44', 1327, 1364, 37],
[1283, '22:07', '22:39', 1327, 1359, 32],
[1284, '22:09', '22:25', 1329, 1345, 16],
[1285, '22:10', '23:25', 1330, 1405, 75],
[1286, '22:13', '22:38', 1333, 1358, 25],
[1287, '22:13', '22:53', 1333, 1373, 40],
[1288, '22:17', '22:27', 1337, 1347, 10],
[1289, '22:17', '23:03', 1337, 1383, 46],
[1290, '22:19', '22:46', 1339, 1366, 27],
[1291, '22:22', '22:59', 1342, 1379, 37],
[1292, '22:24', '22:48', 1344, 1368, 24],
[1293, '22:27', '22:52', 1347, 1372, 25],
[1294, '22:27', '23:21', 1347, 1401, 54],
[1295, '22:28', '23:08', 1348, 1388, 40],
[1296, '22:30', '23:17', 1350, 1397, 47],
[1297, '22:32', '22:42', 1352, 1362, 10],
[1298, '22:32', '23:11', 1352, 1391, 39],
[1299, '22:34', '23:01', 1354, 1381, 27],
[1300, '22:35', '23:54', 1355, 1434, 79],
[1301, '22:37', '23:14', 1357, 1394, 37],
[1302, '22:43', '23:23', 1363, 1403, 40],
[1303, '22:43', '23:08', 1363, 1388, 25],
[1304, '22:47', '23:33', 1367, 1413, 46],
[1305, '22:47', '22:57', 1367, 1377, 10],
[1306, '22:49', '23:16', 1369, 1396, 27],
[1307, '22:52', '23:29', 1372, 1409, 37],
[1308, '22:53', '23:15', 1373, 1395, 22],
[1309, '22:55', '23:55', 1375, 1435, 60],
[1310, '22:57', '23:51', 1377, 1431, 54],
[1311, '22:58', '23:38', 1378, 1418, 40],
[1312, '23:02', '23:41', 1382, 1421, 39],
[1313, '23:02', '23:12', 1382, 1392, 10],
[1314, '23:04', '23:31', 1384, 1411, 27],
[1315, '23:05', '00:24', 1385, 1464, 79],
[1316, '23:07', '23:44', 1387, 1424, 37],
[1317, '23:13', '23:53', 1393, 1433, 40],
[1318, '23:13', '23:38', 1393, 1418, 25],
[1319, '23:17', '00:03', 1397, 1443, 46],
[1320, '23:17', '23:27', 1397, 1407, 10],
[1321, '23:19', '23:46', 1399, 1426, 27],
[1322, '23:22', '23:59', 1402, 1439, 37],
[1323, '23:25', '00:25', 1405, 1465, 60],
[1324, '23:27', '00:21', 1407, 1461, 54],
[1325, '23:28', '00:08', 1408, 1448, 40],
[1326, '23:32', '23:42', 1412, 1422, 10],
[1327, '23:34', '00:01', 1414, 1441, 27],
[1328, '23:35', '01:05', 1415, 1505, 90],
[1329, '23:37', '00:09', 1417, 1449, 32],
[1330, '23:43', '00:23', 1423, 1463, 40],
[1331, '23:43', '00:08', 1423, 1448, 25],
[1332, '23:46', '00:01', 1426, 1441, 15],
[1333, '23:47', '23:57', 1427, 1437, 10],
[1334, '23:47', '00:33', 1427, 1473, 46],
[1335, '23:52', '00:24', 1432, 1464, 32],
[1336, '23:55', '00:49', 1435, 1489, 54],
[1337, '23:57', '00:57', 1437, 1497, 60],
[1338, '23:58', '00:38', 1438, 1478, 40],
[1339, '00:02', '00:12', 1442, 1452, 10],
[1340, '00:07', '00:39', 1447, 1479, 32],
[1341, '00:13', '00:38', 1453, 1478, 25],
[1342, '00:13', '00:51', 1453, 1491, 38],
[1343, '00:15', '01:14', 1455, 1514, 59],
[1344, '00:17', '01:23', 1457, 1523, 66],
[1345, '00:23', '00:33', 1463, 1473, 10],
[1346, '00:24', '00:40', 1464, 1480, 16],
[1347, '00:25', '01:12', 1465, 1512, 47],
[1348, '00:28', '01:07', 1468, 1507, 39],
[1349, '00:33', '01:05', 1473, 1505, 32],
[1350, '00:43', '01:21', 1483, 1521, 38],
[1351, '00:44', '00:54', 1484, 1494, 10],
[1352, '00:47', '01:09', 1487, 1509, 22],
[1353, '00:47', '01:26', 1487, 1526, 39],
[1354, '00:54', '01:04', 1494, 1504, 10],
[1355, '00:57', '01:07', 1497, 1507, 10]
] # yapf:disable
def find_minimum_number_of_drivers(shifts, params):
"""Minimize the number of needed drivers."""
num_shifts = len(shifts)
# All durations are in minutes.
max_driving_time = 540 # 8 hours.
max_driving_time_without_pauses = 240 # 4 hours
min_pause_after_4h = 30
min_delay_between_shifts = 2
max_working_time = 720
min_working_time = 390 # 6.5 hours
extra_time = 10 + 25
max_break = 180
# Computed data.
total_driving_time = sum(shift[5] for shift in shifts)
min_num_drivers = int(
math.ceil(total_driving_time * 1.0 / max_driving_time))
min_start_time = min(shift[3] for shift in shifts)
max_end_time = max(shift[4] for shift in shifts)
print('Bus driver scheduling')
print(' num shifts =', num_shifts)
print(' total driving time =', total_driving_time, 'minutes')
print(' min num drivers =', min_num_drivers)
print(' min start time =', min_start_time)
print(' max end time =', max_end_time)
# We are going to build a flow from a the start of the day to the end
# of the day.
#
# Along the path, we will accumulate driving time, accrued time since the
# last break, and total working time.
model = cp_model.CpModel()
# Per node info
driving_time = {}
working_time = {}
no_break_driving_time = {}
incoming_literals = collections.defaultdict(list)
outgoing_literals = collections.defaultdict(list)
outgoing_source_literals = []
incoming_sink_literals = []
all_literals = []
# Create all the shift variables before iterating on the transitions
# between these shifts.
for shift in range(num_shifts):
driving_time[shift] = model.NewIntVar(0, max_driving_time, 'dt_%i' % shift)
no_break_driving_time[shift] = model.NewIntVar(
0, max_driving_time_without_pauses, 'nbdt_%i' % shift)
working_time[shift] = model.NewIntVar(
0, max_working_time, 'wt_%i' % shift)
for shift in range(num_shifts):
duration = shifts[shift][5]
# Arc from source to shift.
# - set the working time of the driver
# - increase driving time and driving time since the last break
source_lit = model.NewBoolVar('from source to %i' % shift)
all_literals.append(source_lit)
outgoing_source_literals.append(source_lit)
incoming_literals[shift].append(source_lit)
model.Add(driving_time[shift] == duration).OnlyEnforceIf(source_lit)
model.Add(no_break_driving_time[shift] == duration).OnlyEnforceIf(
source_lit)
model.Add(working_time[shift] == duration + extra_time).OnlyEnforceIf(
source_lit)
# Arc from shift to sink
# - checks that working time is greater than min_working_time
sink_lit = model.NewBoolVar('from %i to sink' % shift)
all_literals.append(sink_lit)
outgoing_literals[shift].append(sink_lit)
incoming_sink_literals.append(sink_lit)
model.Add(working_time[shift] >= min_working_time).OnlyEnforceIf(sink_lit)
for other in range(num_shifts):
delay = shifts[other][3] - shifts[shift][4]
if delay < min_delay_between_shifts:
continue
if delay > max_break:
break # Assumes start times are sorted.
other_duration = shifts[other][5]
lit = model.NewBoolVar('from %i to %i' % (shift, other))
all_literals.append(lit)
# Increase driving time
model.Add(driving_time[other] ==
driving_time[shift] + other_duration).OnlyEnforceIf(lit)
# Increase no_break_driving or reset it to 0 depending on the delay
if delay >= min_pause_after_4h:
model.Add(no_break_driving_time[other] ==
other_duration).OnlyEnforceIf(lit)
else:
model.Add(
no_break_driving_time[other] ==
no_break_driving_time[shift] + other_duration).OnlyEnforceIf(lit)
# Increase working time
model.Add(working_time[other] == working_time[shift] + delay +
other_duration).OnlyEnforceIf(lit)
# Add arc
outgoing_literals[shift].append(lit)
incoming_literals[other].append(lit)
# Create dag constraint.
for shift in range(num_shifts):
model.Add(sum(outgoing_literals[shift]) == 1)
model.Add(sum(incoming_literals[shift]) == 1)
# Num drivers
num_drivers = model.NewIntVar(min_num_drivers, min_num_drivers * 3, 'num_drivers')
model.Add(sum(incoming_sink_literals) == num_drivers)
model.Add(sum(outgoing_source_literals) == num_drivers)
model.Minimize(num_drivers)
# Solve model.
solver = cp_model.CpSolver()
solver.parameters.log_search_progress = True
#solver.parameters.num_search_workers = 16
# solver.parameters.boolean_encoding_level = 0
# solver.parameters.lns_focus_on_decision_variables = True
status = solver.Solve(model)
if status != cp_model.OPTIMAL and status != cp_model.FEASIBLE:
return -1
# Display solution
optimal_num_drivers = int(solver.ObjectiveValue())
print('minimal number of drivers =', optimal_num_drivers)
return optimal_num_drivers
def main(args):
"""Optimize the bus driver allocation in two passes."""
print('----------- first pass: minimize the number of drivers')
shifts = []
if args.instance == 1:
shifts = SAMPLE_SHIFTS_SMALL
elif args.instance == 2:
shifts = SAMPLE_SHIFTS_MEDIUM
elif args.instance == 3:
shifts = SAMPLE_SHIFTS_LARGE
num_drivers = find_minimum_number_of_drivers(shifts, args.params)
print('----------- second pass: minimize the sum of working times')
#bus_driver_scheduling(False, num_drivers)
if __name__ == '__main__':
main(PARSER.parse_args())
| 42.708653 | 86 | 0.472559 |
import argparse
import collections
import math
from ortools.sat.python import cp_model
PARSER = argparse.ArgumentParser()
PARSER.add_argument(
'--instance', default=1, type=int, help='Instance number (1..3).')
PARSER.add_argument(
'--output_proto',
default="",
help='Output file to write the cp_model'
'proto to.')
PARSER.add_argument('--params', default="", help='Sat solver parameters.')
SAMPLE_SHIFTS_SMALL = [
[0, '05:18', '06:00', 318, 360, 42],
[1, '05:26', '06:08', 326, 368, 42],
[2, '05:40', '05:56', 340, 356, 16],
[3, '06:06', '06:51', 366, 411, 45],
[4, '06:40', '07:52', 400, 472, 72],
[5, '06:42', '07:13', 402, 433, 31],
[6, '06:48', '08:15', 408, 495, 87],
[7, '06:59', '08:07', 419, 487, 68],
[8, '07:20', '07:36', 440, 456, 16],
[9, '07:35', '08:22', 455, 502, 47],
[10, '07:50', '08:55', 470, 535, 65],
[11, '08:00', '09:05', 480, 545, 65],
[12, '08:00', '08:35', 480, 515, 35],
[13, '08:11', '09:41', 491, 581, 90],
[14, '08:28', '08:50', 508, 530, 22],
[15, '08:35', '08:45', 515, 525, 10],
[16, '08:40', '08:50', 520, 530, 10],
[17, '09:03', '10:28', 543, 628, 85],
[18, '09:23', '09:49', 563, 589, 26],
[19, '09:30', '09:40', 570, 580, 10],
[20, '09:57', '10:20', 597, 620, 23],
[21, '10:09', '11:03', 609, 663, 54],
[22, '10:20', '10:30', 620, 630, 10],
[23, '11:00', '11:10', 660, 670, 10],
[24, '11:45', '12:24', 705, 744, 39],
[25, '12:18', '13:00', 738, 780, 42],
[26, '13:18', '14:44', 798, 884, 86],
[27, '13:53', '14:49', 833, 889, 56],
[28, '14:03', '14:50', 843, 890, 47],
[29, '14:28', '15:15', 868, 915, 47],
[30, '14:30', '15:41', 870, 941, 71],
[31, '14:48', '15:35', 888, 935, 47],
[32, '15:03', '15:50', 903, 950, 47],
[33, '15:28', '16:54', 928, 1014, 86],
[34, '15:38', '16:25', 938, 985, 47],
[35, '15:40', '15:56', 940, 956, 16],
[36, '15:58', '16:45', 958, 1005, 47],
[37, '16:04', '17:30', 964, 1050, 86],
[38, '16:28', '17:15', 988, 1035, 47],
[39, '16:36', '17:21', 996, 1041, 45],
[40, '16:50', '17:00', 1010, 1020, 10],
[41, '16:54', '18:20', 1014, 1100, 86],
[42, '17:01', '17:13', 1021, 1033, 12],
[43, '17:19', '18:31', 1039, 1111, 72],
[44, '17:23', '18:10', 1043, 1090, 47],
[45, '17:34', '18:15', 1054, 1095, 41],
[46, '18:04', '19:29', 1084, 1169, 85],
[47, '18:34', '19:58', 1114, 1198, 84],
[48, '19:56', '20:34', 1196, 1234, 38],
[49, '20:05', '20:48', 1205, 1248, 43]
]
SAMPLE_SHIFTS_MEDIUM = [
[0, '04:30', '04:53', 270, 293, 23],
[1, '04:46', '04:56', 286, 296, 10],
[2, '04:52', '05:56', 292, 356, 64],
[3, '04:53', '05:23', 293, 323, 30],
[4, '05:07', '05:44', 307, 344, 37],
[5, '05:10', '06:06', 310, 366, 56],
[6, '05:18', '06:03', 318, 363, 45],
[7, '05:30', '05:40', 330, 340, 10],
[8, '05:30', '05:40', 330, 340, 10],
[9, '05:33', '06:15', 333, 375, 42],
[10, '05:40', '05:50', 340, 350, 10],
[11, '05:43', '06:08', 343, 368, 25],
[12, '05:54', '07:20', 354, 440, 86],
[13, '06:04', '06:37', 364, 397, 33],
[14, '06:13', '06:58', 373, 418, 45],
[15, '06:14', '07:40', 374, 460, 86],
[16, '06:15', '07:15', 375, 435, 60],
[17, '06:16', '06:26', 376, 386, 10],
[18, '06:17', '06:34', 377, 394, 17],
[19, '06:20', '06:36', 380, 396, 16],
[20, '06:22', '07:06', 382, 426, 44],
[21, '06:24', '07:50', 384, 470, 86],
[22, '06:27', '06:44', 387, 404, 17],
[23, '06:30', '06:40', 390, 400, 10],
[24, '06:31', '06:43', 391, 403, 12],
[25, '06:33', '07:53', 393, 473, 80],
[26, '06:34', '07:09', 394, 429, 35],
[27, '06:40', '06:56', 400, 416, 16],
[28, '06:44', '07:17', 404, 437, 33],
[29, '06:46', '06:58', 406, 418, 12],
[30, '06:49', '07:43', 409, 463, 54],
[31, '06:50', '07:05', 410, 425, 15],
[32, '06:52', '07:36', 412, 456, 44],
[33, '06:54', '07:27', 414, 447, 33],
[34, '06:56', '08:23', 416, 503, 87],
[35, '07:04', '07:44', 424, 464, 40],
[36, '07:11', '08:36', 431, 516, 85],
[37, '07:17', '07:35', 437, 455, 18],
[38, '07:22', '08:06', 442, 486, 44],
[39, '07:27', '08:15', 447, 495, 48],
[40, '07:35', '07:45', 455, 465, 10],
[41, '07:43', '08:08', 463, 488, 25],
[42, '07:50', '08:37', 470, 517, 47],
[43, '07:58', '08:45', 478, 525, 47],
[44, '08:00', '08:35', 480, 515, 35],
[45, '08:06', '08:51', 486, 531, 45],
[46, '08:10', '08:45', 490, 525, 35],
[47, '08:15', '08:30', 495, 510, 15],
[48, '08:16', '09:00', 496, 540, 44],
[49, '08:18', '09:16', 498, 556, 58],
[50, '08:20', '08:36', 500, 516, 16],
[51, '08:27', '09:07', 507, 547, 40],
[52, '08:30', '08:45', 510, 525, 15],
[53, '08:35', '09:15', 515, 555, 40],
[54, '08:46', '09:30', 526, 570, 44],
[55, '08:51', '09:17', 531, 557, 26],
[56, '08:55', '09:15', 535, 555, 20],
[57, '08:58', '09:38', 538, 578, 40],
[58, '09:00', '09:35', 540, 575, 35],
[59, '09:00', '09:16', 540, 556, 16],
[60, '09:20', '09:36', 560, 576, 16],
[61, '09:31', '09:43', 571, 583, 12],
[62, '09:33', '10:15', 573, 615, 42],
[63, '09:54', '10:05', 594, 605, 11],
[64, '10:11', '10:38', 611, 638, 27],
[65, '10:18', '11:00', 618, 660, 42],
[66, '10:21', '10:47', 621, 647, 26],
[67, '10:25', '11:04', 625, 664, 39],
[68, '10:26', '11:08', 626, 668, 42],
[69, '10:44', '12:11', 644, 731, 87],
[70, '11:00', '11:16', 660, 676, 16],
[71, '11:15', '11:54', 675, 714, 39],
[72, '11:16', '11:28', 676, 688, 12],
[73, '11:20', '11:30', 680, 690, 10],
[74, '11:21', '11:47', 681, 707, 26],
[75, '11:25', '12:04', 685, 724, 39],
[76, '11:34', '11:45', 694, 705, 11],
[77, '11:35', '12:14', 695, 734, 39],
[78, '11:41', '12:23', 701, 743, 42],
[79, '11:44', '12:35', 704, 755, 51],
[80, '11:46', '11:58', 706, 718, 12],
[81, '12:00', '12:10', 720, 730, 10],
[82, '12:04', '12:15', 724, 735, 11],
[83, '12:04', '13:04', 724, 784, 60],
[84, '12:11', '12:38', 731, 758, 27],
[85, '12:15', '12:54', 735, 774, 39],
[86, '12:25', '13:10', 745, 790, 45],
[87, '12:30', '12:40', 750, 760, 10],
[88, '12:34', '13:58', 754, 838, 84],
[89, '12:38', '13:25', 758, 805, 47],
[90, '12:48', '13:35', 768, 815, 47],
[91, '13:00', '13:16', 780, 796, 16],
[92, '13:05', '13:44', 785, 824, 39],
[93, '13:08', '13:55', 788, 835, 47],
[94, '13:14', '14:38', 794, 878, 84],
[95, '13:23', '13:49', 803, 829, 26],
[96, '13:25', '14:04', 805, 844, 39],
[97, '13:28', '14:54', 808, 894, 86],
[98, '13:31', '13:43', 811, 823, 12],
[99, '13:34', '14:58', 814, 898, 84],
[100, '13:38', '14:25', 818, 865, 47],
[101, '13:38', '15:04', 818, 904, 86],
[102, '13:39', '14:33', 819, 873, 54],
[103, '13:40', '13:50', 820, 830, 10],
[104, '13:43', '14:10', 823, 850, 27],
[105, '13:48', '14:35', 828, 875, 47],
[106, '13:48', '14:35', 828, 875, 47],
[107, '13:53', '14:40', 833, 880, 47],
[108, '13:58', '15:24', 838, 924, 86],
[109, '13:58', '14:25', 838, 865, 27],
[110, '14:00', '14:16', 840, 856, 16],
[111, '14:13', '15:00', 853, 900, 47],
[112, '14:20', '15:31', 860, 931, 71],
[113, '14:25', '15:02', 865, 902, 37],
[114, '14:34', '14:45', 874, 885, 11],
[115, '14:40', '15:51', 880, 951, 71],
[116, '14:40', '14:56', 880, 896, 16],
[117, '14:46', '14:58', 886, 898, 12],
[118, '14:49', '15:43', 889, 943, 54],
[119, '14:52', '15:21', 892, 921, 29],
[120, '14:58', '16:24', 898, 984, 86],
[121, '14:59', '15:53', 899, 953, 54],
[122, '15:00', '15:10', 900, 910, 10],
[123, '15:00', '15:35', 900, 935, 35],
[124, '15:08', '15:45', 908, 945, 37],
[125, '15:12', '15:36', 912, 936, 24],
[126, '15:18', '16:05', 918, 965, 47],
[127, '15:24', '16:05', 924, 965, 41],
[128, '15:31', '15:43', 931, 943, 12],
[129, '15:35', '15:54', 935, 954, 19],
[130, '15:36', '16:21', 936, 981, 45],
[131, '15:39', '16:33', 939, 993, 54],
[132, '15:48', '16:35', 948, 995, 47],
[133, '15:50', '17:01', 950, 1021, 71],
[134, '16:03', '16:50', 963, 1010, 47],
[135, '16:18', '17:44', 978, 1064, 86],
[136, '16:24', '17:05', 984, 1025, 41],
[137, '16:28', '17:15', 988, 1035, 47],
[138, '16:34', '17:15', 994, 1035, 41],
[139, '16:38', '17:25', 998, 1045, 47],
[140, '16:40', '16:56', 1000, 1016, 16],
[141, '16:45', '17:04', 1005, 1024, 19],
[142, '16:52', '17:36', 1012, 1056, 44],
[143, '16:58', '17:45', 1018, 1065, 47],
[144, '17:04', '18:30', 1024, 1110, 86],
[145, '17:04', '17:45', 1024, 1065, 41],
[146, '17:09', '18:03', 1029, 1083, 54],
[147, '17:18', '18:44', 1038, 1124, 86],
[148, '17:28', '18:15', 1048, 1095, 47],
[149, '17:29', '18:41', 1049, 1121, 72],
[150, '17:36', '18:21', 1056, 1101, 45],
[151, '17:38', '18:25', 1058, 1105, 47],
[152, '17:40', '17:56', 1060, 1076, 16],
[153, '17:45', '18:04', 1065, 1084, 19],
[154, '17:46', '17:58', 1066, 1078, 12],
[155, '17:48', '18:35', 1068, 1115, 47],
[156, '17:49', '18:43', 1069, 1123, 54],
[157, '17:55', '18:14', 1075, 1094, 19],
[158, '17:58', '18:45', 1078, 1125, 47],
[159, '18:00', '19:11', 1080, 1151, 71],
[160, '18:04', '18:45', 1084, 1125, 41],
[161, '18:09', '19:03', 1089, 1143, 54],
[162, '18:13', '19:00', 1093, 1140, 47],
[163, '18:13', '18:40', 1093, 1120, 27],
[164, '18:19', '19:13', 1099, 1153, 54],
[165, '18:28', '19:25', 1108, 1165, 57],
[166, '18:48', '19:28', 1128, 1168, 40],
[167, '19:03', '19:45', 1143, 1185, 42],
[168, '19:20', '19:36', 1160, 1176, 16],
[169, '19:21', '19:31', 1161, 1171, 10],
[170, '19:25', '20:04', 1165, 1204, 39],
[171, '19:26', '20:08', 1166, 1208, 42],
[172, '19:30', '19:40', 1170, 1180, 10],
[173, '19:44', '20:33', 1184, 1233, 49],
[174, '19:48', '21:09', 1188, 1269, 81],
[175, '19:53', '21:02', 1193, 1262, 69],
[176, '20:04', '20:29', 1204, 1229, 25],
[177, '20:17', '21:03', 1217, 1263, 46],
[178, '20:20', '20:57', 1220, 1257, 37],
[179, '20:29', '21:18', 1229, 1278, 49],
[180, '20:35', '21:54', 1235, 1314, 79],
[181, '20:40', '20:50', 1240, 1250, 10],
[182, '20:47', '21:42', 1247, 1302, 55],
[183, '21:00', '21:10', 1260, 1270, 10],
[184, '21:07', '21:44', 1267, 1304, 37],
[185, '21:14', '22:03', 1274, 1323, 49],
[186, '21:39', '21:55', 1299, 1315, 16],
[187, '21:40', '22:17', 1300, 1337, 37],
[188, '21:40', '21:50', 1300, 1310, 10],
[189, '21:48', '22:03', 1308, 1323, 15],
[190, '22:17', '23:03', 1337, 1383, 46],
[191, '22:43', '23:08', 1363, 1388, 25],
[192, '23:35', '01:05', 1415, 1505, 90],
[193, '23:46', '00:01', 1426, 1441, 15],
[194, '23:47', '00:33', 1427, 1473, 46],
[195, '23:52', '00:24', 1432, 1464, 32],
[196, '23:58', '00:38', 1438, 1478, 40],
[197, '00:02', '00:12', 1442, 1452, 10],
[198, '00:07', '00:39', 1447, 1479, 32],
[199, '00:25', '01:12', 1465, 1512, 47]
]
SAMPLE_SHIFTS_LARGE = [
[0, '04:18', '05:00', 258, 300, 42],
[1, '04:27', '05:08', 267, 308, 41],
[2, '04:29', '05:26', 269, 326, 57],
[3, '04:29', '04:55', 269, 295, 26],
[4, '04:30', '04:53', 270, 293, 23],
[5, '04:30', '04:51', 270, 291, 21],
[6, '04:31', '04:53', 271, 293, 22],
[7, '04:33', '05:15', 273, 315, 42],
[8, '04:34', '04:44', 274, 284, 10],
[9, '04:34', '05:03', 274, 303, 29],
[10, '04:35', '04:50', 275, 290, 15],
[11, '04:36', '04:46', 276, 286, 10],
[12, '04:37', '05:18', 277, 318, 41],
[13, '04:41', '05:13', 281, 313, 32],
[14, '04:42', '05:23', 282, 323, 41],
[15, '04:43', '04:53', 283, 293, 10],
[16, '04:44', '05:45', 284, 345, 61],
[17, '04:45', '05:11', 285, 311, 26],
[18, '04:46', '05:01', 286, 301, 15],
[19, '04:46', '04:56', 286, 296, 10],
[20, '04:47', '05:14', 287, 314, 27],
[21, '04:48', '05:30', 288, 330, 42],
[22, '04:49', '05:41', 289, 341, 52],
[23, '04:49', '05:18', 289, 318, 29],
[24, '04:50', '05:33', 290, 333, 43],
[25, '04:52', '05:56', 292, 356, 64],
[26, '04:52', '05:07', 292, 307, 15],
[27, '04:53', '05:19', 293, 319, 26],
[28, '04:53', '05:23', 293, 323, 30],
[29, '04:55', '05:27', 295, 327, 32],
[30, '04:57', '05:38', 297, 338, 41],
[31, '05:00', '06:00', 300, 360, 60],
[32, '05:00', '05:54', 300, 354, 54],
[33, '05:01', '05:33', 301, 333, 32],
[34, '05:01', '05:26', 301, 326, 25],
[35, '05:02', '05:29', 302, 329, 27],
[36, '05:02', '05:12', 302, 312, 10],
[37, '05:03', '05:45', 303, 345, 42],
[38, '05:03', '05:18', 303, 318, 15],
[39, '05:03', '06:28', 303, 388, 85],
[40, '05:03', '05:13', 303, 313, 10],
[41, '05:04', '06:24', 304, 384, 80],
[42, '05:07', '05:44', 307, 344, 37],
[43, '05:08', '05:48', 308, 348, 40],
[44, '05:10', '06:06', 310, 366, 56],
[45, '05:11', '05:37', 311, 337, 26],
[46, '05:11', '05:53', 311, 353, 42],
[47, '05:13', '06:15', 313, 375, 62],
[48, '05:13', '05:38', 313, 338, 25],
[49, '05:16', '05:44', 316, 344, 28],
[50, '05:17', '05:27', 317, 327, 10],
[51, '05:18', '06:40', 318, 400, 82],
[52, '05:18', '06:03', 318, 363, 45],
[53, '05:18', '06:11', 318, 371, 53],
[54, '05:18', '06:00', 318, 360, 42],
[55, '05:19', '06:34', 319, 394, 75],
[56, '05:20', '06:17', 320, 377, 57],
[57, '05:22', '05:59', 322, 359, 37],
[58, '05:24', '05:48', 324, 348, 24],
[59, '05:25', '05:40', 325, 340, 15],
[60, '05:26', '06:08', 326, 368, 42],
[61, '05:27', '06:30', 327, 390, 63],
[62, '05:27', '05:54', 327, 354, 27],
[63, '05:28', '05:53', 328, 353, 25],
[64, '05:29', '05:44', 329, 344, 15],
[65, '05:30', '05:40', 330, 340, 10],
[66, '05:30', '05:40', 330, 340, 10],
[67, '05:30', '05:40', 330, 340, 10],
[68, '05:32', '06:53', 332, 413, 81],
[69, '05:33', '07:00', 333, 420, 87],
[70, '05:33', '06:15', 333, 375, 42],
[71, '05:33', '05:47', 333, 347, 14],
[72, '05:37', '06:13', 337, 373, 36],
[73, '05:37', '06:05', 337, 365, 28],
[74, '05:38', '06:33', 338, 393, 55],
[75, '05:38', '06:04', 338, 364, 26],
[76, '05:38', '06:18', 338, 378, 40],
[77, '05:39', '05:54', 339, 354, 15],
[78, '05:40', '05:56', 340, 356, 16],
[79, '05:40', '06:41', 340, 401, 61],
[80, '05:40', '05:50', 340, 350, 10],
[81, '05:41', '06:23', 341, 383, 42],
[82, '05:41', '06:01', 341, 361, 20],
[83, '05:43', '06:08', 343, 368, 25],
[84, '05:44', '07:10', 344, 430, 86],
[85, '05:44', '05:55', 344, 355, 11],
[86, '05:45', '06:44', 345, 404, 59],
[87, '05:47', '06:17', 347, 377, 30],
[88, '05:48', '07:08', 348, 428, 80],
[89, '05:48', '06:30', 348, 390, 42],
[90, '05:50', '06:50', 350, 410, 60],
[91, '05:50', '06:00', 350, 360, 10],
[92, '05:50', '06:00', 350, 360, 10],
[93, '05:50', '06:51', 350, 411, 61],
[94, '05:52', '06:33', 352, 393, 41],
[95, '05:52', '06:36', 352, 396, 44],
[96, '05:52', '06:23', 352, 383, 31],
[97, '05:54', '06:14', 354, 374, 20],
[98, '05:54', '07:20', 354, 440, 86],
[99, '05:55', '06:40', 355, 400, 45],
[100, '05:55', '06:27', 355, 387, 32],
[101, '05:56', '06:35', 356, 395, 39],
[102, '05:56', '06:06', 356, 366, 10],
[103, '05:57', '06:21', 357, 381, 24],
[104, '05:58', '07:23', 358, 443, 85],
[105, '05:58', '06:23', 358, 383, 25],
[106, '05:58', '06:08', 358, 368, 10],
[107, '05:58', '06:43', 358, 403, 45],
[108, '06:00', '06:10', 360, 370, 10],
[109, '06:00', '06:16', 360, 376, 16],
[110, '06:00', '07:01', 360, 421, 61],
[111, '06:01', '07:00', 361, 420, 59],
[112, '06:01', '06:13', 361, 373, 12],
[113, '06:01', '06:45', 361, 405, 44],
[114, '06:03', '06:50', 363, 410, 47],
[115, '06:04', '06:37', 364, 397, 33],
[116, '06:04', '07:30', 364, 450, 86],
[117, '06:05', '06:24', 365, 384, 19],
[118, '06:06', '06:51', 366, 411, 45],
[119, '06:07', '06:43', 367, 403, 36],
[120, '06:08', '07:30', 368, 450, 82],
[121, '06:10', '06:20', 370, 380, 10],
[122, '06:10', '07:17', 370, 437, 67],
[123, '06:11', '06:54', 371, 414, 43],
[124, '06:11', '06:21', 371, 381, 10],
[125, '06:13', '06:38', 373, 398, 25],
[126, '06:13', '06:58', 373, 418, 45],
[127, '06:13', '06:53', 373, 413, 40],
[128, '06:14', '07:03', 374, 423, 49],
[129, '06:14', '06:47', 374, 407, 33],
[130, '06:14', '07:40', 374, 460, 86],
[131, '06:15', '07:15', 375, 435, 60],
[132, '06:16', '06:28', 376, 388, 12],
[133, '06:16', '06:26', 376, 386, 10],
[134, '06:17', '06:34', 377, 394, 17],
[135, '06:18', '07:06', 378, 426, 48],
[136, '06:18', '07:38', 378, 458, 80],
[137, '06:18', '07:02', 378, 422, 44],
[138, '06:19', '06:53', 379, 413, 34],
[139, '06:20', '07:25', 380, 445, 65],
[140, '06:20', '06:36', 380, 396, 16],
[141, '06:20', '06:30', 380, 390, 10],
[142, '06:20', '06:30', 380, 390, 10],
[143, '06:21', '06:49', 381, 409, 28],
[144, '06:22', '07:06', 382, 426, 44],
[145, '06:24', '07:50', 384, 470, 86],
[146, '06:24', '06:57', 384, 417, 33],
[147, '06:26', '07:45', 386, 465, 79],
[148, '06:26', '07:10', 386, 430, 44],
[149, '06:27', '06:44', 387, 404, 17],
[150, '06:28', '06:53', 388, 413, 25],
[151, '06:28', '07:14', 388, 434, 46],
[152, '06:29', '07:03', 389, 423, 34],
[153, '06:30', '06:40', 390, 400, 10],
[154, '06:30', '07:37', 390, 457, 67],
[155, '06:31', '06:43', 391, 403, 12],
[156, '06:33', '07:14', 393, 434, 41],
[157, '06:33', '07:53', 393, 473, 80],
[158, '06:34', '08:16', 394, 496, 102],
[159, '06:34', '07:09', 394, 429, 35],
[160, '06:34', '07:07', 394, 427, 33],
[161, '06:36', '07:21', 396, 441, 45],
[162, '06:37', '07:22', 397, 442, 45],
[163, '06:37', '06:54', 397, 414, 17],
[164, '06:38', '07:30', 398, 450, 52],
[165, '06:38', '07:18', 398, 438, 40],
[166, '06:39', '07:33', 399, 453, 54],
[167, '06:40', '07:52', 400, 472, 72],
[168, '06:40', '06:50', 400, 410, 10],
[169, '06:40', '07:22', 400, 442, 42],
[170, '06:40', '06:56', 400, 416, 16],
[171, '06:41', '08:00', 401, 480, 79],
[172, '06:42', '07:26', 402, 446, 44],
[173, '06:42', '07:13', 402, 433, 31],
[174, '06:43', '07:08', 403, 428, 25],
[175, '06:43', '07:30', 403, 450, 47],
[176, '06:43', '07:23', 403, 443, 40],
[177, '06:44', '07:17', 404, 437, 33],
[178, '06:44', '08:13', 404, 493, 89],
[179, '06:46', '07:01', 406, 421, 15],
[180, '06:46', '06:58', 406, 418, 12],
[181, '06:47', '07:04', 407, 424, 17],
[182, '06:48', '08:15', 408, 495, 87],
[183, '06:48', '07:34', 408, 454, 46],
[184, '06:48', '07:37', 408, 457, 49],
[185, '06:49', '07:43', 409, 463, 54],
[186, '06:50', '08:00', 410, 480, 70],
[187, '06:50', '07:00', 410, 420, 10],
[188, '06:50', '07:05', 410, 425, 15],
[189, '06:51', '07:18', 411, 438, 27],
[190, '06:52', '07:36', 412, 456, 44],
[191, '06:53', '07:37', 413, 457, 44],
[192, '06:54', '08:20', 414, 500, 86],
[193, '06:54', '07:27', 414, 447, 33],
[194, '06:54', '07:20', 414, 440, 26],
[195, '06:56', '08:23', 416, 503, 87],
[196, '06:57', '07:12', 417, 432, 15],
[197, '06:57', '07:58', 417, 478, 61],
[198, '06:57', '07:45', 417, 465, 48],
[199, '06:57', '07:40', 417, 460, 43],
[200, '06:58', '07:23', 418, 443, 25],
[201, '06:59', '07:53', 419, 473, 54],
[202, '06:59', '08:07', 419, 487, 68],
[203, '07:00', '07:10', 420, 430, 10],
[204, '07:00', '07:16', 420, 436, 16],
[205, '07:01', '08:30', 421, 510, 89],
[206, '07:01', '07:13', 421, 433, 12],
[207, '07:01', '07:43', 421, 463, 42],
[208, '07:03', '08:30', 423, 510, 87],
[209, '07:04', '07:37', 424, 457, 33],
[210, '07:04', '07:44', 424, 464, 40],
[211, '07:05', '07:52', 425, 472, 47],
[212, '07:05', '08:05', 425, 485, 60],
[213, '07:05', '07:46', 425, 466, 41],
[214, '07:06', '07:51', 426, 471, 45],
[215, '07:07', '08:08', 427, 488, 61],
[216, '07:07', '07:52', 427, 472, 45],
[217, '07:07', '08:16', 427, 496, 69],
[218, '07:07', '07:27', 427, 447, 20],
[219, '07:09', '07:50', 429, 470, 41],
[220, '07:09', '08:40', 429, 520, 91],
[221, '07:09', '08:03', 429, 483, 54],
[222, '07:10', '07:20', 430, 440, 10],
[223, '07:11', '08:36', 431, 516, 85],
[224, '07:12', '08:00', 432, 480, 48],
[225, '07:12', '07:47', 432, 467, 35],
[226, '07:13', '07:54', 433, 474, 41],
[227, '07:13', '07:38', 433, 458, 25],
[228, '07:14', '07:59', 434, 479, 45],
[229, '07:16', '08:50', 436, 530, 94],
[230, '07:16', '07:28', 436, 448, 12],
[231, '07:17', '07:35', 437, 455, 18],
[232, '07:17', '07:58', 437, 478, 41],
[233, '07:18', '08:06', 438, 486, 48],
[234, '07:18', '08:44', 438, 524, 86],
[235, '07:19', '08:13', 439, 493, 54],
[236, '07:20', '08:02', 440, 482, 42],
[237, '07:20', '08:07', 440, 487, 47],
[238, '07:20', '07:30', 440, 450, 10],
[239, '07:20', '07:57', 440, 477, 37],
[240, '07:20', '07:36', 440, 456, 16],
[241, '07:21', '07:48', 441, 468, 27],
[242, '07:22', '08:06', 442, 486, 44],
[243, '07:22', '08:25', 442, 505, 63],
[244, '07:24', '08:27', 444, 507, 63],
[245, '07:24', '08:05', 444, 485, 41],
[246, '07:26', '08:23', 446, 503, 57],
[247, '07:26', '08:52', 446, 532, 86],
[248, '07:27', '08:07', 447, 487, 40],
[249, '07:27', '07:42', 447, 462, 15],
[250, '07:27', '08:15', 447, 495, 48],
[251, '07:28', '07:53', 448, 473, 25],
[252, '07:28', '08:09', 448, 489, 41],
[253, '07:28', '07:38', 448, 458, 10],
[254, '07:30', '08:35', 450, 515, 65],
[255, '07:31', '07:43', 451, 463, 12],
[256, '07:32', '08:13', 452, 493, 41],
[257, '07:34', '09:00', 454, 540, 86],
[258, '07:34', '08:33', 454, 513, 59],
[259, '07:34', '09:04', 454, 544, 90],
[260, '07:35', '08:22', 455, 502, 47],
[261, '07:35', '07:45', 455, 465, 10],
[262, '07:35', '08:16', 455, 496, 41],
[263, '07:36', '08:17', 456, 497, 41],
[264, '07:36', '08:36', 456, 516, 60],
[265, '07:37', '07:50', 457, 470, 13],
[266, '07:40', '07:56', 460, 476, 16],
[267, '07:40', '08:20', 460, 500, 40],
[268, '07:40', '08:45', 460, 525, 65],
[269, '07:41', '08:39', 461, 519, 58],
[270, '07:41', '07:51', 461, 471, 10],
[271, '07:42', '08:30', 462, 510, 48],
[272, '07:42', '08:21', 462, 501, 39],
[273, '07:43', '08:08', 463, 488, 25],
[274, '07:43', '08:24', 463, 504, 41],
[275, '07:44', '09:10', 464, 550, 86],
[276, '07:44', '08:43', 464, 523, 59],
[277, '07:46', '08:28', 466, 508, 42],
[278, '07:46', '07:58', 466, 478, 12],
[279, '07:47', '08:00', 467, 480, 13],
[280, '07:48', '09:14', 468, 554, 86],
[281, '07:49', '08:32', 469, 512, 43],
[282, '07:50', '08:55', 470, 535, 65],
[283, '07:50', '08:00', 470, 480, 10],
[284, '07:50', '08:37', 470, 517, 47],
[285, '07:50', '08:26', 470, 506, 36],
[286, '07:51', '08:18', 471, 498, 27],
[287, '07:52', '08:21', 472, 501, 29],
[288, '07:53', '08:35', 473, 515, 42],
[289, '07:54', '09:19', 474, 559, 85],
[290, '07:55', '08:53', 475, 533, 58],
[291, '07:56', '08:54', 476, 534, 58],
[292, '07:57', '08:39', 477, 519, 42],
[293, '07:57', '08:10', 477, 490, 13],
[294, '07:58', '08:45', 478, 525, 47],
[295, '07:58', '08:23', 478, 503, 25],
[296, '08:00', '08:10', 480, 490, 10],
[297, '08:00', '09:05', 480, 545, 65],
[298, '08:00', '08:16', 480, 496, 16],
[299, '08:00', '08:35', 480, 515, 35],
[300, '08:01', '08:13', 481, 493, 12],
[301, '08:01', '08:43', 481, 523, 42],
[302, '08:03', '09:26', 483, 566, 83],
[303, '08:04', '09:29', 484, 569, 85],
[304, '08:05', '08:21', 485, 501, 16],
[305, '08:05', '08:47', 485, 527, 42],
[306, '08:06', '08:51', 486, 531, 45],
[307, '08:06', '09:03', 486, 543, 57],
[308, '08:07', '08:20', 487, 500, 13],
[309, '08:08', '08:55', 488, 535, 47],
[310, '08:08', '08:50', 488, 530, 42],
[311, '08:10', '08:45', 490, 525, 35],
[312, '08:10', '09:15', 490, 555, 65],
[313, '08:10', '08:20', 490, 500, 10],
[314, '08:11', '09:41', 491, 581, 90],
[315, '08:12', '08:55', 492, 535, 43],
[316, '08:13', '08:38', 493, 518, 25],
[317, '08:14', '09:38', 494, 578, 84],
[318, '08:15', '08:30', 495, 510, 15],
[319, '08:16', '08:30', 496, 510, 14],
[320, '08:16', '08:28', 496, 508, 12],
[321, '08:16', '09:00', 496, 540, 44],
[322, '08:17', '09:13', 497, 553, 56],
[323, '08:18', '09:16', 498, 556, 58],
[324, '08:18', '09:05', 498, 545, 47],
[325, '08:20', '08:36', 500, 516, 16],
[326, '08:20', '08:55', 500, 535, 35],
[327, '08:20', '09:05', 500, 545, 45],
[328, '08:20', '08:30', 500, 510, 10],
[329, '08:20', '09:25', 500, 565, 65],
[330, '08:21', '08:38', 501, 518, 17],
[331, '08:21', '08:47', 501, 527, 26],
[332, '08:22', '08:45', 502, 525, 23],
[333, '08:23', '09:10', 503, 550, 47],
[334, '08:24', '09:48', 504, 588, 84],
[335, '08:26', '08:46', 506, 526, 20],
[336, '08:27', '09:07', 507, 547, 40],
[337, '08:28', '08:50', 508, 530, 22],
[338, '08:28', '09:56', 508, 596, 88],
[339, '08:28', '09:23', 508, 563, 55],
[340, '08:29', '09:20', 509, 560, 51],
[341, '08:30', '09:05', 510, 545, 35],
[342, '08:30', '08:45', 510, 525, 15],
[343, '08:30', '08:40', 510, 520, 10],
[344, '08:30', '09:35', 510, 575, 65],
[345, '08:31', '08:43', 511, 523, 12],
[346, '08:31', '09:13', 511, 553, 42],
[347, '08:34', '09:58', 514, 598, 84],
[348, '08:35', '08:55', 515, 535, 20],
[349, '08:35', '09:15', 515, 555, 40],
[350, '08:35', '08:45', 515, 525, 10],
[351, '08:36', '08:46', 516, 526, 10],
[352, '08:36', '09:00', 516, 540, 24],
[353, '08:38', '09:20', 518, 560, 42],
[354, '08:38', '09:35', 518, 575, 57],
[355, '08:38', '09:14', 518, 554, 36],
[356, '08:39', '09:33', 519, 573, 54],
[357, '08:40', '09:45', 520, 585, 65],
[358, '08:40', '08:50', 520, 530, 10],
[359, '08:40', '08:56', 520, 536, 16],
[360, '08:42', '09:25', 522, 565, 43],
[361, '08:43', '09:08', 523, 548, 25],
[362, '08:44', '09:35', 524, 575, 51],
[363, '08:45', '09:00', 525, 540, 15],
[364, '08:45', '09:05', 525, 545, 20],
[365, '08:46', '09:24', 526, 564, 38],
[366, '08:46', '08:58', 526, 538, 12],
[367, '08:46', '09:30', 526, 570, 44],
[368, '08:48', '10:11', 528, 611, 83],
[369, '08:48', '10:13', 528, 613, 85],
[370, '08:49', '09:43', 529, 583, 54],
[371, '08:50', '09:30', 530, 570, 40],
[372, '08:50', '10:00', 530, 600, 70],
[373, '08:50', '09:00', 530, 540, 10],
[374, '08:51', '09:17', 531, 557, 26],
[375, '08:53', '09:20', 533, 560, 27],
[376, '08:53', '09:35', 533, 575, 42],
[377, '08:55', '09:34', 535, 574, 39],
[378, '08:55', '09:15', 535, 555, 20],
[379, '08:58', '09:38', 538, 578, 40],
[380, '08:58', '10:26', 538, 626, 88],
[381, '08:59', '09:53', 539, 593, 54],
[382, '08:59', '09:50', 539, 590, 51],
[383, '09:00', '09:35', 540, 575, 35],
[384, '09:00', '09:16', 540, 556, 16],
[385, '09:00', '09:10', 540, 550, 10],
[386, '09:00', '09:16', 540, 556, 16],
[387, '09:01', '09:13', 541, 553, 12],
[388, '09:03', '09:45', 543, 585, 42],
[389, '09:03', '10:28', 543, 628, 85],
[390, '09:05', '09:44', 545, 584, 39],
[391, '09:05', '09:25', 545, 565, 20],
[392, '09:08', '09:53', 548, 593, 45],
[393, '09:08', '10:04', 548, 604, 56],
[394, '09:09', '10:03', 549, 603, 54],
[395, '09:10', '10:15', 550, 615, 65],
[396, '09:10', '09:20', 550, 560, 10],
[397, '09:11', '09:38', 551, 578, 27],
[398, '09:13', '10:00', 553, 600, 47],
[399, '09:14', '09:39', 554, 579, 25],
[400, '09:14', '10:05', 554, 605, 51],
[401, '09:15', '09:54', 555, 594, 39],
[402, '09:16', '09:28', 556, 568, 12],
[403, '09:18', '10:43', 558, 643, 85],
[404, '09:18', '10:41', 558, 641, 83],
[405, '09:18', '09:58', 558, 598, 40],
[406, '09:19', '10:13', 559, 613, 54],
[407, '09:20', '09:30', 560, 570, 10],
[408, '09:20', '09:36', 560, 576, 16],
[409, '09:21', '09:47', 561, 587, 26],
[410, '09:23', '10:30', 563, 630, 67],
[411, '09:23', '10:05', 563, 605, 42],
[412, '09:23', '09:49', 563, 589, 26],
[413, '09:24', '09:35', 564, 575, 11],
[414, '09:25', '09:35', 565, 575, 10],
[415, '09:25', '10:04', 565, 604, 39],
[416, '09:28', '10:08', 568, 608, 40],
[417, '09:29', '09:45', 569, 585, 16],
[418, '09:29', '10:20', 569, 620, 51],
[419, '09:29', '10:56', 569, 656, 87],
[420, '09:29', '10:23', 569, 623, 54],
[421, '09:30', '09:40', 570, 580, 10],
[422, '09:31', '09:43', 571, 583, 12],
[423, '09:33', '10:58', 573, 658, 85],
[424, '09:33', '10:15', 573, 615, 42],
[425, '09:34', '09:45', 574, 585, 11],
[426, '09:35', '10:14', 575, 614, 39],
[427, '09:38', '10:45', 578, 645, 67],
[428, '09:39', '10:33', 579, 633, 54],
[429, '09:40', '09:56', 580, 596, 16],
[430, '09:40', '09:50', 580, 590, 10],
[431, '09:41', '10:08', 581, 608, 27],
[432, '09:41', '10:23', 581, 623, 42],
[433, '09:44', '10:35', 584, 635, 51],
[434, '09:44', '11:11', 584, 671, 87],
[435, '09:44', '09:55', 584, 595, 11],
[436, '09:45', '10:24', 585, 624, 39],
[437, '09:46', '09:58', 586, 598, 12],
[438, '09:48', '10:30', 588, 630, 42],
[439, '09:48', '11:13', 588, 673, 85],
[440, '09:48', '10:04', 588, 604, 16],
[441, '09:49', '10:43', 589, 643, 54],
[442, '09:50', '10:00', 590, 600, 10],
[443, '09:51', '10:17', 591, 617, 26],
[444, '09:53', '10:49', 593, 649, 56],
[445, '09:53', '11:00', 593, 660, 67],
[446, '09:54', '10:05', 594, 605, 11],
[447, '09:55', '10:34', 595, 634, 39],
[448, '09:56', '10:38', 596, 638, 42],
[449, '09:57', '10:20', 597, 620, 23],
[450, '09:59', '11:26', 599, 686, 87],
[451, '09:59', '10:50', 599, 650, 51],
[452, '09:59', '10:53', 599, 653, 54],
[453, '10:00', '10:16', 600, 616, 16],
[454, '10:00', '10:10', 600, 610, 10],
[455, '10:01', '10:13', 601, 613, 12],
[456, '10:03', '11:28', 603, 688, 85],
[457, '10:03', '10:45', 603, 645, 42],
[458, '10:04', '10:15', 604, 615, 11],
[459, '10:05', '10:44', 605, 644, 39],
[460, '10:08', '11:15', 608, 675, 67],
[461, '10:09', '11:03', 609, 663, 54],
[462, '10:10', '10:20', 610, 620, 10],
[463, '10:11', '10:38', 611, 638, 27],
[464, '10:11', '10:53', 611, 653, 42],
[465, '10:14', '11:05', 614, 665, 51],
[466, '10:14', '11:41', 614, 701, 87],
[467, '10:14', '10:25', 614, 625, 11],
[468, '10:15', '10:54', 615, 654, 39],
[469, '10:16', '10:28', 616, 628, 12],
[470, '10:18', '11:43', 618, 703, 85],
[471, '10:18', '11:00', 618, 660, 42],
[472, '10:19', '11:13', 619, 673, 54],
[473, '10:20', '10:30', 620, 630, 10],
[474, '10:20', '10:36', 620, 636, 16],
[475, '10:21', '10:47', 621, 647, 26],
[476, '10:23', '11:30', 623, 690, 67],
[477, '10:23', '10:45', 623, 645, 22],
[478, '10:24', '10:35', 624, 635, 11],
[479, '10:25', '11:04', 625, 664, 39],
[480, '10:26', '11:08', 626, 668, 42],
[481, '10:29', '11:20', 629, 680, 51],
[482, '10:29', '11:23', 629, 683, 54],
[483, '10:29', '11:56', 629, 716, 87],
[484, '10:30', '10:40', 630, 640, 10],
[485, '10:31', '10:43', 631, 643, 12],
[486, '10:33', '11:15', 633, 675, 42],
[487, '10:33', '11:58', 633, 718, 85],
[488, '10:34', '10:45', 634, 645, 11],
[489, '10:35', '11:14', 635, 674, 39],
[490, '10:38', '11:45', 638, 705, 67],
[491, '10:39', '11:33', 639, 693, 54],
[492, '10:40', '10:50', 640, 650, 10],
[493, '10:40', '10:56', 640, 656, 16],
[494, '10:41', '11:23', 641, 683, 42],
[495, '10:41', '11:08', 641, 668, 27],
[496, '10:44', '12:11', 644, 731, 87],
[497, '10:44', '11:35', 644, 695, 51],
[498, '10:44', '10:55', 644, 655, 11],
[499, '10:45', '11:24', 645, 684, 39],
[500, '10:46', '10:58', 646, 658, 12],
[501, '10:48', '12:13', 648, 733, 85],
[502, '10:48', '11:30', 648, 690, 42],
[503, '10:49', '11:43', 649, 703, 54],
[504, '10:50', '11:00', 650, 660, 10],
[505, '10:51', '11:17', 651, 677, 26],
[506, '10:53', '12:00', 653, 720, 67],
[507, '10:53', '11:20', 653, 680, 27],
[508, '10:54', '11:05', 654, 665, 11],
[509, '10:55', '11:34', 655, 694, 39],
[510, '10:56', '11:38', 656, 698, 42],
[511, '10:59', '11:14', 659, 674, 15],
[512, '10:59', '12:26', 659, 746, 87],
[513, '10:59', '11:53', 659, 713, 54],
[514, '10:59', '11:50', 659, 710, 51],
[515, '11:00', '11:16', 660, 676, 16],
[516, '11:00', '11:10', 660, 670, 10],
[517, '11:01', '11:13', 661, 673, 12],
[518, '11:03', '11:45', 663, 705, 42],
[519, '11:03', '12:28', 663, 748, 85],
[520, '11:04', '11:15', 664, 675, 11],
[521, '11:05', '11:44', 665, 704, 39],
[522, '11:08', '12:15', 668, 735, 67],
[523, '11:09', '12:03', 669, 723, 54],
[524, '11:10', '11:20', 670, 680, 10],
[525, '11:11', '11:38', 671, 698, 27],
[526, '11:11', '11:53', 671, 713, 42],
[527, '11:14', '11:25', 674, 685, 11],
[528, '11:14', '12:05', 674, 725, 51],
[529, '11:14', '12:38', 674, 758, 84],
[530, '11:14', '12:41', 674, 761, 87],
[531, '11:15', '11:54', 675, 714, 39],
[532, '11:16', '11:28', 676, 688, 12],
[533, '11:18', '12:00', 678, 720, 42],
[534, '11:19', '12:13', 679, 733, 54],
[535, '11:20', '11:30', 680, 690, 10],
[536, '11:20', '11:36', 680, 696, 16],
[537, '11:21', '11:47', 681, 707, 26],
[538, '11:23', '12:30', 683, 750, 67],
[539, '11:23', '11:49', 683, 709, 26],
[540, '11:24', '12:48', 684, 768, 84],
[541, '11:24', '11:35', 684, 695, 11],
[542, '11:25', '12:04', 685, 724, 39],
[543, '11:26', '12:08', 686, 728, 42],
[544, '11:29', '11:44', 689, 704, 15],
[545, '11:29', '12:23', 689, 743, 54],
[546, '11:29', '12:20', 689, 740, 51],
[547, '11:29', '12:54', 689, 774, 85],
[548, '11:30', '11:40', 690, 700, 10],
[549, '11:31', '11:43', 691, 703, 12],
[550, '11:33', '12:15', 693, 735, 42],
[551, '11:34', '12:58', 694, 778, 84],
[552, '11:34', '11:45', 694, 705, 11],
[553, '11:35', '12:14', 695, 734, 39],
[554, '11:38', '12:45', 698, 765, 67],
[555, '11:39', '12:33', 699, 753, 54],
[556, '11:40', '11:56', 700, 716, 16],
[557, '11:40', '11:50', 700, 710, 10],
[558, '11:41', '12:08', 701, 728, 27],
[559, '11:41', '12:23', 701, 743, 42],
[560, '11:44', '11:55', 704, 715, 11],
[561, '11:44', '13:14', 704, 794, 90],
[562, '11:44', '13:08', 704, 788, 84],
[563, '11:44', '12:35', 704, 755, 51],
[564, '11:45', '12:24', 705, 744, 39],
[565, '11:46', '11:58', 706, 718, 12],
[566, '11:48', '12:30', 708, 750, 42],
[567, '11:49', '12:43', 709, 763, 54],
[568, '11:50', '12:00', 710, 720, 10],
[569, '11:51', '12:17', 711, 737, 26],
[570, '11:53', '12:49', 713, 769, 56],
[571, '11:53', '13:00', 713, 780, 67],
[572, '11:54', '13:18', 714, 798, 84],
[573, '11:54', '12:05', 714, 725, 11],
[574, '11:55', '12:40', 715, 760, 45],
[575, '11:55', '12:34', 715, 754, 39],
[576, '11:56', '12:35', 716, 755, 39],
[577, '11:57', '12:20', 717, 740, 23],
[578, '11:58', '12:29', 718, 749, 31],
[579, '11:59', '12:50', 719, 770, 51],
[580, '11:59', '12:53', 719, 773, 54],
[581, '11:59', '13:24', 719, 804, 85],
[582, '11:59', '12:14', 719, 734, 15],
[583, '12:00', '12:16', 720, 736, 16],
[584, '12:00', '12:10', 720, 730, 10],
[585, '12:01', '12:45', 721, 765, 44],
[586, '12:01', '12:13', 721, 733, 12],
[587, '12:03', '12:50', 723, 770, 47],
[588, '12:04', '12:15', 724, 735, 11],
[589, '12:04', '13:04', 724, 784, 60],
[590, '12:04', '13:28', 724, 808, 84],
[591, '12:05', '12:44', 725, 764, 39],
[592, '12:08', '13:11', 728, 791, 63],
[593, '12:08', '12:39', 728, 759, 31],
[594, '12:09', '13:03', 729, 783, 54],
[595, '12:10', '12:20', 730, 740, 10],
[596, '12:11', '12:55', 731, 775, 44],
[597, '12:11', '12:38', 731, 758, 27],
[598, '12:14', '13:05', 734, 785, 51],
[599, '12:14', '12:25', 734, 745, 11],
[600, '12:14', '13:44', 734, 824, 90],
[601, '12:14', '13:38', 734, 818, 84],
[602, '12:15', '12:54', 735, 774, 39],
[603, '12:16', '12:28', 736, 748, 12],
[604, '12:18', '13:00', 738, 780, 42],
[605, '12:19', '13:13', 739, 793, 54],
[606, '12:20', '12:30', 740, 750, 10],
[607, '12:20', '13:31', 740, 811, 71],
[608, '12:20', '12:30', 740, 750, 10],
[609, '12:20', '12:36', 740, 756, 16],
[610, '12:21', '12:47', 741, 767, 26],
[611, '12:23', '12:45', 743, 765, 22],
[612, '12:24', '12:35', 744, 755, 11],
[613, '12:24', '13:48', 744, 828, 84],
[614, '12:25', '13:10', 745, 790, 45],
[615, '12:25', '13:04', 745, 784, 39],
[616, '12:26', '13:05', 746, 785, 39],
[617, '12:28', '13:54', 748, 834, 86],
[618, '12:28', '12:38', 748, 758, 10],
[619, '12:28', '13:15', 748, 795, 47],
[620, '12:29', '13:23', 749, 803, 54],
[621, '12:30', '13:41', 750, 821, 71],
[622, '12:30', '12:40', 750, 760, 10],
[623, '12:31', '13:15', 751, 795, 44],
[624, '12:31', '12:43', 751, 763, 12],
[625, '12:33', '12:48', 753, 768, 15],
[626, '12:33', '13:20', 753, 800, 47],
[627, '12:34', '13:58', 754, 838, 84],
[628, '12:34', '13:34', 754, 814, 60],
[629, '12:34', '12:45', 754, 765, 11],
[630, '12:35', '13:14', 755, 794, 39],
[631, '12:38', '13:25', 758, 805, 47],
[632, '12:38', '13:25', 758, 805, 47],
[633, '12:38', '14:04', 758, 844, 86],
[634, '12:39', '13:33', 759, 813, 54],
[635, '12:40', '13:51', 760, 831, 71],
[636, '12:40', '12:50', 760, 770, 10],
[637, '12:40', '12:56', 760, 776, 16],
[638, '12:41', '13:08', 761, 788, 27],
[639, '12:43', '13:30', 763, 810, 47],
[640, '12:44', '12:55', 764, 775, 11],
[641, '12:44', '14:08', 764, 848, 84],
[642, '12:45', '13:24', 765, 804, 39],
[643, '12:46', '12:58', 766, 778, 12],
[644, '12:46', '13:21', 766, 801, 35],
[645, '12:48', '14:14', 768, 854, 86],
[646, '12:48', '13:35', 768, 815, 47],
[647, '12:48', '12:58', 768, 778, 10],
[648, '12:48', '13:35', 768, 815, 47],
[649, '12:49', '13:43', 769, 823, 54],
[650, '12:50', '14:01', 770, 841, 71],
[651, '12:50', '13:00', 770, 780, 10],
[652, '12:50', '13:00', 770, 780, 10],
[653, '12:51', '13:17', 771, 797, 26],
[654, '12:53', '13:20', 773, 800, 27],
[655, '12:53', '13:24', 773, 804, 31],
[656, '12:53', '13:40', 773, 820, 47],
[657, '12:54', '14:18', 774, 858, 84],
[658, '12:54', '13:05', 774, 785, 11],
[659, '12:55', '13:34', 775, 814, 39],
[660, '12:58', '14:24', 778, 864, 86],
[661, '12:58', '13:25', 778, 805, 27],
[662, '12:58', '13:45', 778, 825, 47],
[663, '12:58', '13:45', 778, 825, 47],
[664, '12:59', '13:53', 779, 833, 54],
[665, '13:00', '13:10', 780, 790, 10],
[666, '13:00', '13:16', 780, 796, 16],
[667, '13:00', '14:11', 780, 851, 71],
[668, '13:01', '13:13', 781, 793, 12],
[669, '13:03', '13:34', 783, 814, 31],
[670, '13:03', '13:50', 783, 830, 47],
[671, '13:04', '13:15', 784, 795, 11],
[672, '13:04', '14:28', 784, 868, 84],
[673, '13:05', '13:44', 785, 824, 39],
[674, '13:08', '13:55', 788, 835, 47],
[675, '13:08', '14:34', 788, 874, 86],
[676, '13:08', '13:55', 788, 835, 47],
[677, '13:09', '14:03', 789, 843, 54],
[678, '13:10', '13:20', 790, 800, 10],
[679, '13:10', '14:21', 790, 861, 71],
[680, '13:13', '14:00', 793, 840, 47],
[681, '13:13', '13:40', 793, 820, 27],
[682, '13:14', '14:38', 794, 878, 84],
[683, '13:14', '13:25', 794, 805, 11],
[684, '13:15', '13:54', 795, 834, 39],
[685, '13:16', '13:28', 796, 808, 12],
[686, '13:18', '14:05', 798, 845, 47],
[687, '13:18', '14:44', 798, 884, 86],
[688, '13:18', '14:05', 798, 845, 47],
[689, '13:19', '14:13', 799, 853, 54],
[690, '13:20', '13:36', 800, 816, 16],
[691, '13:20', '14:31', 800, 871, 71],
[692, '13:20', '13:30', 800, 810, 10],
[693, '13:21', '13:47', 801, 827, 26],
[694, '13:23', '14:10', 803, 850, 47],
[695, '13:23', '13:49', 803, 829, 26],
[696, '13:24', '14:48', 804, 888, 84],
[697, '13:24', '13:35', 804, 815, 11],
[698, '13:25', '14:04', 805, 844, 39],
[699, '13:28', '14:15', 808, 855, 47],
[700, '13:28', '14:54', 808, 894, 86],
[701, '13:28', '13:55', 808, 835, 27],
[702, '13:28', '14:15', 808, 855, 47],
[703, '13:29', '14:23', 809, 863, 54],
[704, '13:30', '13:40', 810, 820, 10],
[705, '13:30', '14:41', 810, 881, 71],
[706, '13:31', '13:43', 811, 823, 12],
[707, '13:33', '14:20', 813, 860, 47],
[708, '13:34', '14:58', 814, 898, 84],
[709, '13:34', '13:45', 814, 825, 11],
[710, '13:35', '14:14', 815, 854, 39],
[711, '13:38', '14:25', 818, 865, 47],
[712, '13:38', '14:25', 818, 865, 47],
[713, '13:38', '15:04', 818, 904, 86],
[714, '13:39', '14:33', 819, 873, 54],
[715, '13:40', '13:50', 820, 830, 10],
[716, '13:40', '13:56', 820, 836, 16],
[717, '13:40', '14:51', 820, 891, 71],
[718, '13:43', '14:30', 823, 870, 47],
[719, '13:43', '14:10', 823, 850, 27],
[720, '13:44', '15:09', 824, 909, 85],
[721, '13:44', '13:55', 824, 835, 11],
[722, '13:45', '14:24', 825, 864, 39],
[723, '13:46', '13:58', 826, 838, 12],
[724, '13:48', '14:35', 828, 875, 47],
[725, '13:48', '15:14', 828, 914, 86],
[726, '13:48', '14:35', 828, 875, 47],
[727, '13:49', '14:43', 829, 883, 54],
[728, '13:50', '14:00', 830, 840, 10],
[729, '13:50', '15:01', 830, 901, 71],
[730, '13:51', '14:17', 831, 857, 26],
[731, '13:53', '14:40', 833, 880, 47],
[732, '13:53', '14:49', 833, 889, 56],
[733, '13:54', '14:05', 834, 845, 11],
[734, '13:54', '15:19', 834, 919, 85],
[735, '13:55', '14:34', 835, 874, 39],
[736, '13:57', '14:20', 837, 860, 23],
[737, '13:58', '15:24', 838, 924, 86],
[738, '13:58', '14:45', 838, 885, 47],
[739, '13:58', '14:45', 838, 885, 47],
[740, '13:58', '14:25', 838, 865, 27],
[741, '13:59', '14:53', 839, 893, 54],
[742, '14:00', '14:16', 840, 856, 16],
[743, '14:00', '14:10', 840, 850, 10],
[744, '14:00', '15:11', 840, 911, 71],
[745, '14:01', '14:13', 841, 853, 12],
[746, '14:03', '14:50', 843, 890, 47],
[747, '14:04', '14:15', 844, 855, 11],
[748, '14:04', '15:29', 844, 929, 85],
[749, '14:05', '14:44', 845, 884, 39],
[750, '14:08', '14:55', 848, 895, 47],
[751, '14:08', '14:55', 848, 895, 47],
[752, '14:08', '15:34', 848, 934, 86],
[753, '14:09', '15:03', 849, 903, 54],
[754, '14:10', '15:21', 850, 921, 71],
[755, '14:10', '14:20', 850, 860, 10],
[756, '14:13', '15:00', 853, 900, 47],
[757, '14:13', '14:40', 853, 880, 27],
[758, '14:14', '15:40', 854, 940, 86],
[759, '14:14', '14:25', 854, 865, 11],
[760, '14:15', '14:54', 855, 894, 39],
[761, '14:16', '14:28', 856, 868, 12],
[762, '14:18', '15:05', 858, 905, 47],
[763, '14:18', '15:44', 858, 944, 86],
[764, '14:18', '15:05', 858, 905, 47],
[765, '14:19', '15:13', 859, 913, 54],
[766, '14:20', '15:31', 860, 931, 71],
[767, '14:20', '14:30', 860, 870, 10],
[768, '14:20', '14:36', 860, 876, 16],
[769, '14:21', '14:47', 861, 887, 26],
[770, '14:23', '15:10', 863, 910, 47],
[771, '14:23', '14:45', 863, 885, 22],
[772, '14:24', '15:50', 864, 950, 86],
[773, '14:24', '14:35', 864, 875, 11],
[774, '14:25', '15:02', 865, 902, 37],
[775, '14:26', '14:52', 866, 892, 26],
[776, '14:28', '15:15', 868, 915, 47],
[777, '14:28', '14:55', 868, 895, 27],
[778, '14:28', '15:54', 868, 954, 86],
[779, '14:28', '15:15', 868, 915, 47],
[780, '14:29', '15:23', 869, 923, 54],
[781, '14:30', '15:41', 870, 941, 71],
[782, '14:30', '14:40', 870, 880, 10],
[783, '14:31', '14:43', 871, 883, 12],
[784, '14:33', '15:20', 873, 920, 47],
[785, '14:34', '16:00', 874, 960, 86],
[786, '14:34', '14:45', 874, 885, 11],
[787, '14:35', '15:11', 875, 911, 36],
[788, '14:38', '15:25', 878, 925, 47],
[789, '14:38', '15:25', 878, 925, 47],
[790, '14:38', '16:04', 878, 964, 86],
[791, '14:39', '15:33', 879, 933, 54],
[792, '14:40', '14:50', 880, 890, 10],
[793, '14:40', '15:51', 880, 951, 71],
[794, '14:40', '14:56', 880, 896, 16],
[795, '14:43', '15:30', 883, 930, 47],
[796, '14:43', '15:10', 883, 910, 27],
[797, '14:44', '15:00', 884, 900, 16],
[798, '14:44', '16:10', 884, 970, 86],
[799, '14:45', '15:19', 885, 919, 34],
[800, '14:46', '14:58', 886, 898, 12],
[801, '14:48', '15:35', 888, 935, 47],
[802, '14:48', '15:35', 888, 935, 47],
[803, '14:48', '17:04', 888, 1024, 136],
[804, '14:49', '15:43', 889, 943, 54],
[805, '14:50', '16:01', 890, 961, 71],
[806, '14:50', '15:00', 890, 900, 10],
[807, '14:51', '15:17', 891, 917, 26],
[808, '14:52', '15:27', 892, 927, 35],
[809, '14:52', '15:21', 892, 921, 29],
[810, '14:53', '15:40', 893, 940, 47],
[811, '14:54', '15:08', 894, 908, 14],
[812, '14:54', '16:20', 894, 980, 86],
[813, '14:58', '16:24', 898, 984, 86],
[814, '14:58', '15:45', 898, 945, 47],
[815, '14:58', '15:25', 898, 925, 27],
[816, '14:58', '15:45', 898, 945, 47],
[817, '14:59', '15:53', 899, 953, 54],
[818, '15:00', '15:10', 900, 910, 10],
[819, '15:00', '15:35', 900, 935, 35],
[820, '15:00', '16:11', 900, 971, 71],
[821, '15:00', '15:16', 900, 916, 16],
[822, '15:01', '15:13', 901, 913, 12],
[823, '15:02', '15:16', 902, 916, 14],
[824, '15:03', '15:50', 903, 950, 47],
[825, '15:04', '16:30', 904, 990, 86],
[826, '15:08', '16:34', 908, 994, 86],
[827, '15:08', '15:55', 908, 955, 47],
[828, '15:08', '15:55', 908, 955, 47],
[829, '15:08', '15:45', 908, 945, 37],
[830, '15:09', '16:14', 909, 974, 65],
[831, '15:09', '16:03', 909, 963, 54],
[832, '15:10', '16:21', 910, 981, 71],
[833, '15:10', '15:20', 910, 920, 10],
[834, '15:11', '15:24', 911, 924, 13],
[835, '15:12', '15:36', 912, 936, 24],
[836, '15:13', '16:00', 913, 960, 47],
[837, '15:13', '15:40', 913, 940, 27],
[838, '15:14', '16:40', 914, 1000, 86],
[839, '15:16', '15:28', 916, 928, 12],
[840, '15:16', '15:55', 916, 955, 39],
[841, '15:18', '16:05', 918, 965, 47],
[842, '15:18', '16:44', 918, 1004, 86],
[843, '15:18', '16:05', 918, 965, 47],
[844, '15:19', '16:13', 919, 973, 54],
[845, '15:19', '15:34', 919, 934, 15],
[846, '15:20', '15:30', 920, 930, 10],
[847, '15:20', '16:31', 920, 991, 71],
[848, '15:20', '15:36', 920, 936, 16],
[849, '15:21', '15:47', 921, 947, 26],
[850, '15:21', '16:06', 921, 966, 45],
[851, '15:23', '16:10', 923, 970, 47],
[852, '15:24', '16:50', 924, 1010, 86],
[853, '15:24', '16:05', 924, 965, 41],
[854, '15:27', '15:51', 927, 951, 24],
[855, '15:27', '15:44', 927, 944, 17],
[856, '15:28', '16:15', 928, 975, 47],
[857, '15:28', '16:54', 928, 1014, 86],
[858, '15:28', '16:15', 928, 975, 47],
[859, '15:28', '15:55', 928, 955, 27],
[860, '15:29', '16:23', 929, 983, 54],
[861, '15:30', '16:41', 930, 1001, 71],
[862, '15:30', '15:40', 930, 940, 10],
[863, '15:31', '15:43', 931, 943, 12],
[864, '15:33', '16:20', 933, 980, 47],
[865, '15:34', '17:00', 934, 1020, 86],
[866, '15:34', '16:15', 934, 975, 41],
[867, '15:35', '15:54', 935, 954, 19],
[868, '15:36', '16:21', 936, 981, 45],
[869, '15:38', '16:25', 938, 985, 47],
[870, '15:38', '16:25', 938, 985, 47],
[871, '15:38', '16:39', 938, 999, 61],
[872, '15:39', '16:33', 939, 993, 54],
[873, '15:40', '15:50', 940, 950, 10],
[874, '15:40', '16:51', 940, 1011, 71],
[875, '15:40', '15:56', 940, 956, 16],
[876, '15:43', '16:10', 943, 970, 27],
[877, '15:43', '16:30', 943, 990, 47],
[878, '15:44', '17:10', 944, 1030, 86],
[879, '15:44', '16:25', 944, 985, 41],
[880, '15:45', '16:04', 945, 964, 19],
[881, '15:46', '15:58', 946, 958, 12],
[882, '15:48', '16:35', 948, 995, 47],
[883, '15:48', '16:35', 948, 995, 47],
[884, '15:48', '17:14', 948, 1034, 86],
[885, '15:49', '16:43', 949, 1003, 54],
[886, '15:50', '16:00', 950, 960, 10],
[887, '15:50', '17:01', 950, 1021, 71],
[888, '15:51', '16:18', 951, 978, 27],
[889, '15:52', '16:36', 952, 996, 44],
[890, '15:53', '16:40', 953, 1000, 47],
[891, '15:54', '17:20', 954, 1040, 86],
[892, '15:54', '16:35', 954, 995, 41],
[893, '15:55', '16:14', 955, 974, 19],
[894, '15:58', '16:25', 958, 985, 27],
[895, '15:58', '16:45', 958, 1005, 47],
[896, '15:58', '16:45', 958, 1005, 47],
[897, '15:58', '17:24', 958, 1044, 86],
[898, '15:59', '17:11', 959, 1031, 72],
[899, '15:59', '16:53', 959, 1013, 54],
[900, '16:00', '16:10', 960, 970, 10],
[901, '16:00', '16:16', 960, 976, 16],
[902, '16:01', '16:13', 961, 973, 12],
[903, '16:03', '16:50', 963, 1010, 47],
[904, '16:04', '17:30', 964, 1050, 86],
[905, '16:04', '16:45', 964, 1005, 41],
[906, '16:05', '16:24', 965, 984, 19],
[907, '16:06', '16:51', 966, 1011, 45],
[908, '16:08', '16:55', 968, 1015, 47],
[909, '16:08', '17:34', 968, 1054, 86],
[910, '16:08', '16:55', 968, 1015, 47],
[911, '16:09', '17:03', 969, 1023, 54],
[912, '16:09', '17:21', 969, 1041, 72],
[913, '16:10', '16:20', 970, 980, 10],
[914, '16:13', '16:40', 973, 1000, 27],
[915, '16:13', '17:00', 973, 1020, 47],
[916, '16:14', '16:55', 974, 1015, 41],
[917, '16:14', '17:40', 974, 1060, 86],
[918, '16:15', '16:34', 975, 994, 19],
[919, '16:16', '16:28', 976, 988, 12],
[920, '16:18', '17:05', 978, 1025, 47],
[921, '16:18', '17:05', 978, 1025, 47],
[922, '16:18', '17:44', 978, 1064, 86],
[923, '16:19', '17:31', 979, 1051, 72],
[924, '16:19', '17:13', 979, 1033, 54],
[925, '16:20', '16:30', 980, 990, 10],
[926, '16:20', '16:36', 980, 996, 16],
[927, '16:21', '16:48', 981, 1008, 27],
[928, '16:22', '17:06', 982, 1026, 44],
[929, '16:23', '17:10', 983, 1030, 47],
[930, '16:24', '17:05', 984, 1025, 41],
[931, '16:24', '17:50', 984, 1070, 86],
[932, '16:25', '16:44', 985, 1004, 19],
[933, '16:28', '17:15', 988, 1035, 47],
[934, '16:28', '17:15', 988, 1035, 47],
[935, '16:28', '16:55', 988, 1015, 27],
[936, '16:28', '17:54', 988, 1074, 86],
[937, '16:29', '17:23', 989, 1043, 54],
[938, '16:29', '17:41', 989, 1061, 72],
[939, '16:30', '16:40', 990, 1000, 10],
[940, '16:31', '16:43', 991, 1003, 12],
[941, '16:33', '17:20', 993, 1040, 47],
[942, '16:34', '17:15', 994, 1035, 41],
[943, '16:34', '18:00', 994, 1080, 86],
[944, '16:35', '16:54', 995, 1014, 19],
[945, '16:36', '17:21', 996, 1041, 45],
[946, '16:38', '17:25', 998, 1045, 47],
[947, '16:38', '17:25', 998, 1045, 47],
[948, '16:38', '18:04', 998, 1084, 86],
[949, '16:39', '17:33', 999, 1053, 54],
[950, '16:39', '17:51', 999, 1071, 72],
[951, '16:40', '16:56', 1000, 1016, 16],
[952, '16:40', '16:50', 1000, 1010, 10],
[953, '16:43', '17:10', 1003, 1030, 27],
[954, '16:43', '17:30', 1003, 1050, 47],
[955, '16:44', '17:25', 1004, 1045, 41],
[956, '16:44', '18:10', 1004, 1090, 86],
[957, '16:45', '17:04', 1005, 1024, 19],
[958, '16:46', '16:58', 1006, 1018, 12],
[959, '16:48', '18:14', 1008, 1094, 86],
[960, '16:48', '17:35', 1008, 1055, 47],
[961, '16:48', '17:35', 1008, 1055, 47],
[962, '16:49', '18:01', 1009, 1081, 72],
[963, '16:49', '17:43', 1009, 1063, 54],
[964, '16:50', '17:00', 1010, 1020, 10],
[965, '16:51', '17:18', 1011, 1038, 27],
[966, '16:52', '17:36', 1012, 1056, 44],
[967, '16:53', '17:40', 1013, 1060, 47],
[968, '16:54', '18:20', 1014, 1100, 86],
[969, '16:54', '17:35', 1014, 1055, 41],
[970, '16:55', '17:14', 1015, 1034, 19],
[971, '16:58', '17:25', 1018, 1045, 27],
[972, '16:58', '17:45', 1018, 1065, 47],
[973, '16:58', '17:45', 1018, 1065, 47],
[974, '16:58', '18:24', 1018, 1104, 86],
[975, '16:59', '18:11', 1019, 1091, 72],
[976, '16:59', '17:53', 1019, 1073, 54],
[977, '17:00', '17:16', 1020, 1036, 16],
[978, '17:00', '17:10', 1020, 1030, 10],
[979, '17:01', '17:13', 1021, 1033, 12],
[980, '17:03', '17:50', 1023, 1070, 47],
[981, '17:04', '18:30', 1024, 1110, 86],
[982, '17:04', '17:45', 1024, 1065, 41],
[983, '17:05', '17:24', 1025, 1044, 19],
[984, '17:06', '17:51', 1026, 1071, 45],
[985, '17:08', '17:55', 1028, 1075, 47],
[986, '17:08', '17:55', 1028, 1075, 47],
[987, '17:08', '18:34', 1028, 1114, 86],
[988, '17:09', '18:03', 1029, 1083, 54],
[989, '17:09', '18:21', 1029, 1101, 72],
[990, '17:10', '17:20', 1030, 1040, 10],
[991, '17:13', '17:40', 1033, 1060, 27],
[992, '17:13', '18:00', 1033, 1080, 47],
[993, '17:14', '17:55', 1034, 1075, 41],
[994, '17:14', '18:40', 1034, 1120, 86],
[995, '17:15', '17:34', 1035, 1054, 19],
[996, '17:16', '17:28', 1036, 1048, 12],
[997, '17:18', '18:05', 1038, 1085, 47],
[998, '17:18', '18:05', 1038, 1085, 47],
[999, '17:18', '18:44', 1038, 1124, 86],
[1000, '17:19', '18:31', 1039, 1111, 72],
[1001, '17:19', '18:13', 1039, 1093, 54],
[1002, '17:20', '17:36', 1040, 1056, 16],
[1003, '17:20', '17:30', 1040, 1050, 10],
[1004, '17:21', '17:47', 1041, 1067, 26],
[1005, '17:22', '18:06', 1042, 1086, 44],
[1006, '17:23', '18:10', 1043, 1090, 47],
[1007, '17:24', '18:50', 1044, 1130, 86],
[1008, '17:24', '18:05', 1044, 1085, 41],
[1009, '17:25', '17:44', 1045, 1064, 19],
[1010, '17:28', '17:55', 1048, 1075, 27],
[1011, '17:28', '18:15', 1048, 1095, 47],
[1012, '17:28', '18:15', 1048, 1095, 47],
[1013, '17:28', '18:54', 1048, 1134, 86],
[1014, '17:29', '18:41', 1049, 1121, 72],
[1015, '17:29', '18:23', 1049, 1103, 54],
[1016, '17:30', '17:40', 1050, 1060, 10],
[1017, '17:31', '17:43', 1051, 1063, 12],
[1018, '17:33', '18:20', 1053, 1100, 47],
[1019, '17:34', '18:15', 1054, 1095, 41],
[1020, '17:34', '19:00', 1054, 1140, 86],
[1021, '17:35', '17:54', 1055, 1074, 19],
[1022, '17:36', '18:21', 1056, 1101, 45],
[1023, '17:38', '18:25', 1058, 1105, 47],
[1024, '17:38', '19:04', 1058, 1144, 86],
[1025, '17:38', '18:25', 1058, 1105, 47],
[1026, '17:39', '18:51', 1059, 1131, 72],
[1027, '17:39', '18:33', 1059, 1113, 54],
[1028, '17:40', '17:56', 1060, 1076, 16],
[1029, '17:40', '17:50', 1060, 1070, 10],
[1030, '17:43', '18:10', 1063, 1090, 27],
[1031, '17:43', '18:30', 1063, 1110, 47],
[1032, '17:44', '18:25', 1064, 1105, 41],
[1033, '17:44', '19:14', 1064, 1154, 90],
[1034, '17:45', '18:04', 1065, 1084, 19],
[1035, '17:46', '17:58', 1066, 1078, 12],
[1036, '17:48', '18:35', 1068, 1115, 47],
[1037, '17:48', '18:35', 1068, 1115, 47],
[1038, '17:48', '19:14', 1068, 1154, 86],
[1039, '17:49', '19:01', 1069, 1141, 72],
[1040, '17:49', '18:43', 1069, 1123, 54],
[1041, '17:50', '18:00', 1070, 1080, 10],
[1042, '17:51', '18:17', 1071, 1097, 26],
[1043, '17:52', '18:36', 1072, 1116, 44],
[1044, '17:53', '18:40', 1073, 1120, 47],
[1045, '17:54', '18:35', 1074, 1115, 41],
[1046, '17:54', '18:57', 1074, 1137, 63],
[1047, '17:55', '18:14', 1075, 1094, 19],
[1048, '17:58', '18:45', 1078, 1125, 47],
[1049, '17:58', '18:45', 1078, 1125, 47],
[1050, '17:58', '18:25', 1078, 1105, 27],
[1051, '17:58', '19:26', 1078, 1166, 88],
[1052, '17:59', '18:53', 1079, 1133, 54],
[1053, '18:00', '19:11', 1080, 1151, 71],
[1054, '18:00', '18:10', 1080, 1090, 10],
[1055, '18:00', '18:16', 1080, 1096, 16],
[1056, '18:01', '18:13', 1081, 1093, 12],
[1057, '18:03', '18:50', 1083, 1130, 47],
[1058, '18:04', '18:45', 1084, 1125, 41],
[1059, '18:04', '19:29', 1084, 1169, 85],
[1060, '18:05', '18:24', 1085, 1104, 19],
[1061, '18:06', '18:51', 1086, 1131, 45],
[1062, '18:08', '18:55', 1088, 1135, 47],
[1063, '18:08', '19:06', 1088, 1146, 58],
[1064, '18:08', '18:55', 1088, 1135, 47],
[1065, '18:09', '19:03', 1089, 1143, 54],
[1066, '18:10', '18:20', 1090, 1100, 10],
[1067, '18:10', '19:21', 1090, 1161, 71],
[1068, '18:13', '19:00', 1093, 1140, 47],
[1069, '18:13', '18:40', 1093, 1120, 27],
[1070, '18:14', '19:43', 1094, 1183, 89],
[1071, '18:14', '18:55', 1094, 1135, 41],
[1072, '18:15', '18:34', 1095, 1114, 19],
[1073, '18:16', '18:28', 1096, 1108, 12],
[1074, '18:17', '18:27', 1097, 1107, 10],
[1075, '18:18', '19:41', 1098, 1181, 83],
[1076, '18:18', '18:58', 1098, 1138, 40],
[1077, '18:18', '19:05', 1098, 1145, 47],
[1078, '18:19', '19:13', 1099, 1153, 54],
[1079, '18:20', '19:31', 1100, 1171, 71],
[1080, '18:20', '18:36', 1100, 1116, 16],
[1081, '18:20', '18:30', 1100, 1110, 10],
[1082, '18:22', '19:05', 1102, 1145, 43],
[1083, '18:23', '19:05', 1103, 1145, 42],
[1084, '18:24', '19:27', 1104, 1167, 63],
[1085, '18:24', '19:05', 1104, 1145, 41],
[1086, '18:25', '18:44', 1105, 1124, 19],
[1087, '18:28', '19:25', 1108, 1165, 57],
[1088, '18:28', '18:55', 1108, 1135, 27],
[1089, '18:28', '19:08', 1108, 1148, 40],
[1090, '18:28', '19:15', 1108, 1155, 47],
[1091, '18:29', '19:23', 1109, 1163, 54],
[1092, '18:30', '19:05', 1110, 1145, 35],
[1093, '18:30', '18:40', 1110, 1120, 10],
[1094, '18:31', '18:43', 1111, 1123, 12],
[1095, '18:33', '19:15', 1113, 1155, 42],
[1096, '18:34', '19:58', 1114, 1198, 84],
[1097, '18:34', '19:14', 1114, 1154, 40],
[1098, '18:35', '18:55', 1115, 1135, 20],
[1099, '18:36', '19:20', 1116, 1160, 44],
[1100, '18:38', '19:25', 1118, 1165, 47],
[1101, '18:38', '19:23', 1118, 1163, 45],
[1102, '18:38', '19:56', 1118, 1196, 78],
[1103, '18:39', '19:33', 1119, 1173, 54],
[1104, '18:40', '18:50', 1120, 1130, 10],
[1105, '18:40', '19:45', 1120, 1185, 65],
[1106, '18:40', '18:56', 1120, 1136, 16],
[1107, '18:43', '19:10', 1123, 1150, 27],
[1108, '18:43', '19:30', 1123, 1170, 47],
[1109, '18:44', '19:24', 1124, 1164, 40],
[1110, '18:45', '19:05', 1125, 1145, 20],
[1111, '18:46', '18:58', 1126, 1138, 12],
[1112, '18:48', '19:35', 1128, 1175, 47],
[1113, '18:48', '20:12', 1128, 1212, 84],
[1114, '18:48', '20:11', 1128, 1211, 83],
[1115, '18:48', '19:28', 1128, 1168, 40],
[1116, '18:49', '19:43', 1129, 1183, 54],
[1117, '18:50', '19:00', 1130, 1140, 10],
[1118, '18:51', '19:01', 1131, 1141, 10],
[1119, '18:53', '19:35', 1133, 1175, 42],
[1120, '18:53', '19:15', 1133, 1155, 22],
[1121, '18:53', '20:00', 1133, 1200, 67],
[1122, '18:55', '19:15', 1135, 1155, 20],
[1123, '18:55', '19:34', 1135, 1174, 39],
[1124, '18:58', '19:38', 1138, 1178, 40],
[1125, '18:59', '19:53', 1139, 1193, 54],
[1126, '18:59', '19:50', 1139, 1190, 51],
[1127, '18:59', '19:53', 1139, 1193, 54],
[1128, '19:00', '19:16', 1140, 1156, 16],
[1129, '19:00', '19:10', 1140, 1150, 10],
[1130, '19:00', '19:16', 1140, 1156, 16],
[1131, '19:01', '19:13', 1141, 1153, 12],
[1132, '19:03', '20:26', 1143, 1226, 83],
[1133, '19:03', '19:45', 1143, 1185, 42],
[1134, '19:05', '19:44', 1145, 1184, 39],
[1135, '19:05', '19:25', 1145, 1165, 20],
[1136, '19:08', '20:15', 1148, 1215, 67],
[1137, '19:08', '19:35', 1148, 1175, 27],
[1138, '19:09', '19:49', 1149, 1189, 40],
[1139, '19:09', '20:03', 1149, 1203, 54],
[1140, '19:10', '19:20', 1150, 1160, 10],
[1141, '19:10', '19:20', 1150, 1160, 10],
[1142, '19:11', '19:53', 1151, 1193, 42],
[1143, '19:14', '20:26', 1154, 1226, 72],
[1144, '19:14', '19:35', 1154, 1175, 21],
[1145, '19:14', '19:24', 1154, 1164, 10],
[1146, '19:14', '20:05', 1154, 1205, 51],
[1147, '19:15', '19:30', 1155, 1170, 15],
[1148, '19:15', '19:54', 1155, 1194, 39],
[1149, '19:18', '20:39', 1158, 1239, 81],
[1150, '19:18', '20:00', 1158, 1200, 42],
[1151, '19:19', '20:14', 1159, 1214, 55],
[1152, '19:20', '19:30', 1160, 1170, 10],
[1153, '19:20', '19:36', 1160, 1176, 16],
[1154, '19:21', '19:31', 1161, 1171, 10],
[1155, '19:23', '20:30', 1163, 1230, 67],
[1156, '19:23', '19:35', 1163, 1175, 12],
[1157, '19:24', '19:45', 1164, 1185, 21],
[1158, '19:24', '19:45', 1164, 1185, 21],
[1159, '19:25', '20:04', 1165, 1204, 39],
[1160, '19:26', '20:08', 1166, 1208, 42],
[1161, '19:29', '20:02', 1169, 1202, 33],
[1162, '19:29', '20:18', 1169, 1218, 49],
[1163, '19:29', '20:41', 1169, 1241, 72],
[1164, '19:30', '19:40', 1170, 1180, 10],
[1165, '19:33', '20:54', 1173, 1254, 81],
[1166, '19:33', '20:17', 1173, 1217, 44],
[1167, '19:34', '19:55', 1174, 1195, 21],
[1168, '19:35', '20:14', 1175, 1214, 39],
[1169, '19:38', '20:05', 1178, 1205, 27],
[1170, '19:38', '20:45', 1178, 1245, 67],
[1171, '19:39', '20:12', 1179, 1212, 33],
[1172, '19:40', '19:50', 1180, 1190, 10],
[1173, '19:40', '19:56', 1180, 1196, 16],
[1174, '19:41', '20:27', 1181, 1227, 46],
[1175, '19:43', '19:55', 1183, 1195, 12],
[1176, '19:44', '20:05', 1184, 1205, 21],
[1177, '19:44', '20:33', 1184, 1233, 49],
[1178, '19:44', '21:00', 1184, 1260, 76],
[1179, '19:45', '20:24', 1185, 1224, 39],
[1180, '19:48', '20:37', 1188, 1237, 49],
[1181, '19:48', '21:09', 1188, 1269, 81],
[1182, '19:50', '20:00', 1190, 1200, 10],
[1183, '19:52', '20:29', 1192, 1229, 37],
[1184, '19:53', '20:08', 1193, 1208, 15],
[1185, '19:53', '21:02', 1193, 1262, 69],
[1186, '19:53', '20:20', 1193, 1220, 27],
[1187, '19:54', '20:19', 1194, 1219, 25],
[1188, '19:55', '20:34', 1195, 1234, 39],
[1189, '19:56', '20:34', 1196, 1234, 38],
[1190, '19:59', '20:48', 1199, 1248, 49],
[1191, '19:59', '21:20', 1199, 1280, 81],
[1192, '20:00', '20:16', 1200, 1216, 16],
[1193, '20:00', '20:10', 1200, 1210, 10],
[1194, '20:03', '20:42', 1203, 1242, 39],
[1195, '20:03', '21:24', 1203, 1284, 81],
[1196, '20:04', '20:29', 1204, 1229, 25],
[1197, '20:05', '20:48', 1205, 1248, 43],
[1198, '20:07', '20:44', 1207, 1244, 37],
[1199, '20:08', '20:40', 1208, 1240, 32],
[1200, '20:08', '20:35', 1208, 1235, 27],
[1201, '20:10', '20:20', 1210, 1220, 10],
[1202, '20:10', '20:22', 1210, 1222, 12],
[1203, '20:11', '20:47', 1211, 1247, 36],
[1204, '20:14', '21:04', 1214, 1264, 50],
[1205, '20:14', '21:03', 1214, 1263, 49],
[1206, '20:17', '21:03', 1217, 1263, 46],
[1207, '20:18', '21:39', 1218, 1299, 81],
[1208, '20:20', '20:30', 1220, 1230, 10],
[1209, '20:20', '20:57', 1220, 1257, 37],
[1210, '20:20', '20:36', 1220, 1236, 16],
[1211, '20:22', '20:59', 1222, 1259, 37],
[1212, '20:22', '20:42', 1222, 1242, 20],
[1213, '20:24', '20:49', 1224, 1249, 25],
[1214, '20:27', '21:22', 1227, 1282, 55],
[1215, '20:29', '21:18', 1229, 1278, 49],
[1216, '20:30', '21:07', 1230, 1267, 37],
[1217, '20:30', '20:40', 1230, 1240, 10],
[1218, '20:30', '20:40', 1230, 1240, 10],
[1219, '20:30', '21:40', 1230, 1300, 70],
[1220, '20:32', '21:18', 1232, 1278, 46],
[1221, '20:35', '21:54', 1235, 1314, 79],
[1222, '20:37', '21:14', 1237, 1274, 37],
[1223, '20:38', '21:08', 1238, 1268, 30],
[1224, '20:40', '20:50', 1240, 1250, 10],
[1225, '20:40', '21:17', 1240, 1277, 37],
[1226, '20:40', '20:56', 1240, 1256, 16],
[1227, '20:44', '21:33', 1244, 1293, 49],
[1228, '20:47', '21:33', 1247, 1293, 46],
[1229, '20:47', '21:42', 1247, 1302, 55],
[1230, '20:50', '21:00', 1250, 1260, 10],
[1231, '20:50', '22:00', 1250, 1320, 70],
[1232, '20:50', '22:09', 1250, 1329, 79],
[1233, '20:50', '21:27', 1250, 1287, 37],
[1234, '20:52', '21:29', 1252, 1289, 37],
[1235, '20:53', '21:20', 1253, 1280, 27],
[1236, '20:56', '21:11', 1256, 1271, 15],
[1237, '20:59', '21:48', 1259, 1308, 49],
[1238, '21:00', '21:10', 1260, 1270, 10],
[1239, '21:00', '21:37', 1260, 1297, 37],
[1240, '21:02', '21:48', 1262, 1308, 46],
[1241, '21:05', '22:24', 1265, 1344, 79],
[1242, '21:07', '21:44', 1267, 1304, 37],
[1243, '21:07', '22:02', 1267, 1322, 55],
[1244, '21:08', '21:38', 1268, 1298, 30],
[1245, '21:10', '22:25', 1270, 1345, 75],
[1246, '21:10', '21:20', 1270, 1280, 10],
[1247, '21:10', '21:47', 1270, 1307, 37],
[1248, '21:14', '22:03', 1274, 1323, 49],
[1249, '21:17', '22:03', 1277, 1323, 46],
[1250, '21:20', '22:18', 1280, 1338, 58],
[1251, '21:20', '21:57', 1280, 1317, 37],
[1252, '21:20', '21:30', 1280, 1290, 10],
[1253, '21:22', '21:59', 1282, 1319, 37],
[1254, '21:24', '21:49', 1284, 1309, 25],
[1255, '21:27', '22:21', 1287, 1341, 54],
[1256, '21:30', '22:07', 1290, 1327, 37],
[1257, '21:30', '22:20', 1290, 1340, 50],
[1258, '21:30', '21:40', 1290, 1300, 10],
[1259, '21:32', '22:18', 1292, 1338, 46],
[1260, '21:32', '22:01', 1292, 1321, 29],
[1261, '21:35', '22:54', 1295, 1374, 79],
[1262, '21:37', '22:14', 1297, 1334, 37],
[1263, '21:39', '21:55', 1299, 1315, 16],
[1264, '21:40', '22:17', 1300, 1337, 37],
[1265, '21:40', '21:50', 1300, 1310, 10],
[1266, '21:41', '22:08', 1301, 1328, 27],
[1267, '21:47', '22:16', 1307, 1336, 29],
[1268, '21:47', '22:51', 1307, 1371, 64],
[1269, '21:47', '22:33', 1307, 1353, 46],
[1270, '21:48', '22:03', 1308, 1323, 15],
[1271, '21:50', '22:55', 1310, 1375, 65],
[1272, '21:50', '22:27', 1310, 1347, 37],
[1273, '21:50', '22:00', 1310, 1320, 10],
[1274, '21:52', '22:29', 1312, 1349, 37],
[1275, '21:53', '22:19', 1313, 1339, 26],
[1276, '22:00', '22:38', 1320, 1358, 38],
[1277, '22:00', '22:10', 1320, 1330, 10],
[1278, '22:02', '22:12', 1322, 1332, 10],
[1279, '22:02', '22:48', 1322, 1368, 46],
[1280, '22:04', '22:31', 1324, 1351, 27],
[1281, '22:05', '23:24', 1325, 1404, 79],
[1282, '22:07', '22:44', 1327, 1364, 37],
[1283, '22:07', '22:39', 1327, 1359, 32],
[1284, '22:09', '22:25', 1329, 1345, 16],
[1285, '22:10', '23:25', 1330, 1405, 75],
[1286, '22:13', '22:38', 1333, 1358, 25],
[1287, '22:13', '22:53', 1333, 1373, 40],
[1288, '22:17', '22:27', 1337, 1347, 10],
[1289, '22:17', '23:03', 1337, 1383, 46],
[1290, '22:19', '22:46', 1339, 1366, 27],
[1291, '22:22', '22:59', 1342, 1379, 37],
[1292, '22:24', '22:48', 1344, 1368, 24],
[1293, '22:27', '22:52', 1347, 1372, 25],
[1294, '22:27', '23:21', 1347, 1401, 54],
[1295, '22:28', '23:08', 1348, 1388, 40],
[1296, '22:30', '23:17', 1350, 1397, 47],
[1297, '22:32', '22:42', 1352, 1362, 10],
[1298, '22:32', '23:11', 1352, 1391, 39],
[1299, '22:34', '23:01', 1354, 1381, 27],
[1300, '22:35', '23:54', 1355, 1434, 79],
[1301, '22:37', '23:14', 1357, 1394, 37],
[1302, '22:43', '23:23', 1363, 1403, 40],
[1303, '22:43', '23:08', 1363, 1388, 25],
[1304, '22:47', '23:33', 1367, 1413, 46],
[1305, '22:47', '22:57', 1367, 1377, 10],
[1306, '22:49', '23:16', 1369, 1396, 27],
[1307, '22:52', '23:29', 1372, 1409, 37],
[1308, '22:53', '23:15', 1373, 1395, 22],
[1309, '22:55', '23:55', 1375, 1435, 60],
[1310, '22:57', '23:51', 1377, 1431, 54],
[1311, '22:58', '23:38', 1378, 1418, 40],
[1312, '23:02', '23:41', 1382, 1421, 39],
[1313, '23:02', '23:12', 1382, 1392, 10],
[1314, '23:04', '23:31', 1384, 1411, 27],
[1315, '23:05', '00:24', 1385, 1464, 79],
[1316, '23:07', '23:44', 1387, 1424, 37],
[1317, '23:13', '23:53', 1393, 1433, 40],
[1318, '23:13', '23:38', 1393, 1418, 25],
[1319, '23:17', '00:03', 1397, 1443, 46],
[1320, '23:17', '23:27', 1397, 1407, 10],
[1321, '23:19', '23:46', 1399, 1426, 27],
[1322, '23:22', '23:59', 1402, 1439, 37],
[1323, '23:25', '00:25', 1405, 1465, 60],
[1324, '23:27', '00:21', 1407, 1461, 54],
[1325, '23:28', '00:08', 1408, 1448, 40],
[1326, '23:32', '23:42', 1412, 1422, 10],
[1327, '23:34', '00:01', 1414, 1441, 27],
[1328, '23:35', '01:05', 1415, 1505, 90],
[1329, '23:37', '00:09', 1417, 1449, 32],
[1330, '23:43', '00:23', 1423, 1463, 40],
[1331, '23:43', '00:08', 1423, 1448, 25],
[1332, '23:46', '00:01', 1426, 1441, 15],
[1333, '23:47', '23:57', 1427, 1437, 10],
[1334, '23:47', '00:33', 1427, 1473, 46],
[1335, '23:52', '00:24', 1432, 1464, 32],
[1336, '23:55', '00:49', 1435, 1489, 54],
[1337, '23:57', '00:57', 1437, 1497, 60],
[1338, '23:58', '00:38', 1438, 1478, 40],
[1339, '00:02', '00:12', 1442, 1452, 10],
[1340, '00:07', '00:39', 1447, 1479, 32],
[1341, '00:13', '00:38', 1453, 1478, 25],
[1342, '00:13', '00:51', 1453, 1491, 38],
[1343, '00:15', '01:14', 1455, 1514, 59],
[1344, '00:17', '01:23', 1457, 1523, 66],
[1345, '00:23', '00:33', 1463, 1473, 10],
[1346, '00:24', '00:40', 1464, 1480, 16],
[1347, '00:25', '01:12', 1465, 1512, 47],
[1348, '00:28', '01:07', 1468, 1507, 39],
[1349, '00:33', '01:05', 1473, 1505, 32],
[1350, '00:43', '01:21', 1483, 1521, 38],
[1351, '00:44', '00:54', 1484, 1494, 10],
[1352, '00:47', '01:09', 1487, 1509, 22],
[1353, '00:47', '01:26', 1487, 1526, 39],
[1354, '00:54', '01:04', 1494, 1504, 10],
[1355, '00:57', '01:07', 1497, 1507, 10]
]
def find_minimum_number_of_drivers(shifts, params):
num_shifts = len(shifts)
max_driving_time = 540
max_driving_time_without_pauses = 240
min_pause_after_4h = 30
min_delay_between_shifts = 2
max_working_time = 720
min_working_time = 390
extra_time = 10 + 25
max_break = 180
total_driving_time = sum(shift[5] for shift in shifts)
min_num_drivers = int(
math.ceil(total_driving_time * 1.0 / max_driving_time))
min_start_time = min(shift[3] for shift in shifts)
max_end_time = max(shift[4] for shift in shifts)
print('Bus driver scheduling')
print(' num shifts =', num_shifts)
print(' total driving time =', total_driving_time, 'minutes')
print(' min num drivers =', min_num_drivers)
print(' min start time =', min_start_time)
print(' max end time =', max_end_time)
model = cp_model.CpModel()
driving_time = {}
working_time = {}
no_break_driving_time = {}
incoming_literals = collections.defaultdict(list)
outgoing_literals = collections.defaultdict(list)
outgoing_source_literals = []
incoming_sink_literals = []
all_literals = []
for shift in range(num_shifts):
driving_time[shift] = model.NewIntVar(0, max_driving_time, 'dt_%i' % shift)
no_break_driving_time[shift] = model.NewIntVar(
0, max_driving_time_without_pauses, 'nbdt_%i' % shift)
working_time[shift] = model.NewIntVar(
0, max_working_time, 'wt_%i' % shift)
for shift in range(num_shifts):
duration = shifts[shift][5]
source_lit = model.NewBoolVar('from source to %i' % shift)
all_literals.append(source_lit)
outgoing_source_literals.append(source_lit)
incoming_literals[shift].append(source_lit)
model.Add(driving_time[shift] == duration).OnlyEnforceIf(source_lit)
model.Add(no_break_driving_time[shift] == duration).OnlyEnforceIf(
source_lit)
model.Add(working_time[shift] == duration + extra_time).OnlyEnforceIf(
source_lit)
sink_lit = model.NewBoolVar('from %i to sink' % shift)
all_literals.append(sink_lit)
outgoing_literals[shift].append(sink_lit)
incoming_sink_literals.append(sink_lit)
model.Add(working_time[shift] >= min_working_time).OnlyEnforceIf(sink_lit)
for other in range(num_shifts):
delay = shifts[other][3] - shifts[shift][4]
if delay < min_delay_between_shifts:
continue
if delay > max_break:
break
other_duration = shifts[other][5]
lit = model.NewBoolVar('from %i to %i' % (shift, other))
all_literals.append(lit)
model.Add(driving_time[other] ==
driving_time[shift] + other_duration).OnlyEnforceIf(lit)
if delay >= min_pause_after_4h:
model.Add(no_break_driving_time[other] ==
other_duration).OnlyEnforceIf(lit)
else:
model.Add(
no_break_driving_time[other] ==
no_break_driving_time[shift] + other_duration).OnlyEnforceIf(lit)
model.Add(working_time[other] == working_time[shift] + delay +
other_duration).OnlyEnforceIf(lit)
outgoing_literals[shift].append(lit)
incoming_literals[other].append(lit)
for shift in range(num_shifts):
model.Add(sum(outgoing_literals[shift]) == 1)
model.Add(sum(incoming_literals[shift]) == 1)
num_drivers = model.NewIntVar(min_num_drivers, min_num_drivers * 3, 'num_drivers')
model.Add(sum(incoming_sink_literals) == num_drivers)
model.Add(sum(outgoing_source_literals) == num_drivers)
model.Minimize(num_drivers)
solver = cp_model.CpSolver()
solver.parameters.log_search_progress = True
status = solver.Solve(model)
if status != cp_model.OPTIMAL and status != cp_model.FEASIBLE:
return -1
optimal_num_drivers = int(solver.ObjectiveValue())
print('minimal number of drivers =', optimal_num_drivers)
return optimal_num_drivers
def main(args):
print('----------- first pass: minimize the number of drivers')
shifts = []
if args.instance == 1:
shifts = SAMPLE_SHIFTS_SMALL
elif args.instance == 2:
shifts = SAMPLE_SHIFTS_MEDIUM
elif args.instance == 3:
shifts = SAMPLE_SHIFTS_LARGE
num_drivers = find_minimum_number_of_drivers(shifts, args.params)
print('----------- second pass: minimize the sum of working times')
if __name__ == '__main__':
main(PARSER.parse_args())
| true | true |
1c36f8727a8c0b2f265c26b2f088514cb1683637 | 2,238 | py | Python | auth0/v3/management/user_blocks.py | santiagoroman/auth0-python | b88b056d0c68eb26a1171f33273010faf8fefe63 | [
"MIT"
] | null | null | null | auth0/v3/management/user_blocks.py | santiagoroman/auth0-python | b88b056d0c68eb26a1171f33273010faf8fefe63 | [
"MIT"
] | null | null | null | auth0/v3/management/user_blocks.py | santiagoroman/auth0-python | b88b056d0c68eb26a1171f33273010faf8fefe63 | [
"MIT"
] | null | null | null | from .rest import RestClient
class UserBlocks(object):
"""Auth0 user blocks endpoints
Args:
domain (str): Your Auth0 domain, e.g: 'username.auth0.com'
token (str): Management API v2 Token
telemetry (bool, optional): Enable or disable Telemetry
(defaults to True)
timeout (float or tuple, optional): Change the requests
connect and read timeout. Pass a tuple to specify
both values separately or a float to set both to it.
(defaults to 5.0 for both)
"""
def __init__(self, domain, token, telemetry=True, timeout=5.0):
self.domain = domain
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout)
def _url(self, id=None):
url = 'https://{}/api/v2/user-blocks'.format(self.domain)
if id is not None:
return '{}/{}'.format(url, id)
return url
def get_by_identifier(self, identifier):
"""Gets blocks by identifier
Args:
identifier (str): Should be any of: username, phone_number, email.
See: https://auth0.com/docs/api/management/v2#!/User_Blocks/get_user_blocks
"""
params = {'identifier': identifier}
return self.client.get(self._url(), params=params)
def unblock_by_identifier(self, identifier):
"""Unblocks by identifier
Args:
identifier (str): Should be any of: username, phone_number, email.
See: https://auth0.com/docs/api/management/v2#!/User_Blocks/delete_user_blocks
"""
params = {'identifier': identifier}
return self.client.delete(self._url(), params=params)
def get(self, id):
"""Get a user's blocks
Args:
id (str): The user_id of the user to retrieve.
See: https://auth0.com/docs/api/management/v2#!/User_Blocks/get_user_blocks_by_id
"""
return self.client.get(self._url(id))
def unblock(self, id):
"""Unblock a user
Args:
id (str): The user_id of the user to update.
See: https://auth0.com/docs/api/management/v2#!/User_Blocks/delete_user_blocks_by_id
"""
return self.client.delete(self._url(id))
| 28.692308 | 92 | 0.613941 | from .rest import RestClient
class UserBlocks(object):
def __init__(self, domain, token, telemetry=True, timeout=5.0):
self.domain = domain
self.client = RestClient(jwt=token, telemetry=telemetry, timeout=timeout)
def _url(self, id=None):
url = 'https://{}/api/v2/user-blocks'.format(self.domain)
if id is not None:
return '{}/{}'.format(url, id)
return url
def get_by_identifier(self, identifier):
params = {'identifier': identifier}
return self.client.get(self._url(), params=params)
def unblock_by_identifier(self, identifier):
params = {'identifier': identifier}
return self.client.delete(self._url(), params=params)
def get(self, id):
return self.client.get(self._url(id))
def unblock(self, id):
return self.client.delete(self._url(id))
| true | true |
1c36fa0d3df2bd6a7220128477fc2e436484191f | 4,762 | py | Python | tests/test_cli.py | repo-helper/simple503 | 21e7f0c55ef11ac79e541206678afdff54c67fa4 | [
"MIT"
] | null | null | null | tests/test_cli.py | repo-helper/simple503 | 21e7f0c55ef11ac79e541206678afdff54c67fa4 | [
"MIT"
] | 5 | 2021-06-26T22:26:03.000Z | 2022-02-03T13:40:49.000Z | tests/test_cli.py | repo-helper/simple503 | 21e7f0c55ef11ac79e541206678afdff54c67fa4 | [
"MIT"
] | 1 | 2021-12-01T13:45:09.000Z | 2021-12-01T13:45:09.000Z | # 3rd party
import pytest
from apeye import URL
from bs4 import BeautifulSoup # type: ignore
from coincidence.regressions import AdvancedDataRegressionFixture, AdvancedFileRegressionFixture
from consolekit.testing import CliRunner
from domdf_python_tools.paths import PathPlus, sort_paths
from shippinglabel.checksum import check_sha256_hash
# this package
from simple503.__main__ import main
def test_inplace(
wheel_directory: PathPlus,
tmp_pathplus: PathPlus,
advanced_data_regression: AdvancedDataRegressionFixture,
cli_runner: CliRunner,
):
result = cli_runner.invoke(main, args=[wheel_directory.as_posix()])
assert result.exit_code == 0
assert not result.stdout
dir_content = [p.relative_to(tmp_pathplus) for p in wheel_directory.iterchildren()]
advanced_data_regression.check(sort_paths(*dir_content))
def test_inplace_explicit_same_target(
wheel_directory: PathPlus,
tmp_pathplus: PathPlus,
advanced_data_regression: AdvancedDataRegressionFixture,
cli_runner: CliRunner,
):
result = cli_runner.invoke(main, args=[wheel_directory.as_posix(), wheel_directory.as_posix()])
assert result.exit_code == 0
assert not result.stdout
dir_content = [p.relative_to(tmp_pathplus) for p in wheel_directory.iterchildren()]
advanced_data_regression.check(sort_paths(*dir_content))
def test_to_target(
wheel_directory: PathPlus,
tmp_pathplus: PathPlus,
advanced_data_regression: AdvancedDataRegressionFixture,
cli_runner: CliRunner,
):
target = tmp_pathplus / "target"
result = cli_runner.invoke(main, args=[wheel_directory.as_posix(), target.as_posix()])
assert result.exit_code == 0
assert not result.stdout
origin_content = [p.relative_to(tmp_pathplus) for p in wheel_directory.iterchildren()]
target_content = [p.relative_to(tmp_pathplus) for p in target.iterchildren()]
advanced_data_regression.check({
"origin": sort_paths(*origin_content),
"target": sort_paths(*target_content),
})
@pytest.mark.usefixtures("fixed_version")
def test_to_target_move(
wheel_directory: PathPlus,
tmp_pathplus: PathPlus,
advanced_data_regression: AdvancedDataRegressionFixture,
advanced_file_regression: AdvancedFileRegressionFixture,
cli_runner: CliRunner,
):
target = tmp_pathplus / "target"
result = cli_runner.invoke(main, args=[wheel_directory.as_posix(), target.as_posix(), "--move"])
assert result.exit_code == 0
assert not result.stdout
origin_content = [p.relative_to(tmp_pathplus) for p in wheel_directory.iterchildren()]
target_content = [p.relative_to(tmp_pathplus) for p in target.iterchildren()]
advanced_data_regression.check({
"origin": sort_paths(*origin_content),
"target": sort_paths(*target_content),
})
advanced_file_regression.check_file(target / "domdf-python-tools" / "index.html")
@pytest.mark.usefixtures("fixed_version")
def test_index_page(
wheel_directory: PathPlus,
advanced_file_regression: AdvancedFileRegressionFixture,
cli_runner: CliRunner,
):
result = cli_runner.invoke(main, args=[wheel_directory.as_posix()])
assert result.exit_code == 0
assert not result.stdout
advanced_file_regression.check_file(wheel_directory / "index.html")
soup = BeautifulSoup((wheel_directory / "index.html").read_text(), "html5lib")
all_anchors = soup.findAll('a')
assert len(all_anchors) == 39
for anchor in all_anchors:
href = URL(anchor["href"])
file = wheel_directory / href.path.name
assert file.is_dir()
assert (file / "index.html").is_file()
@pytest.mark.usefixtures("fixed_version")
def test_project_page(
wheel_directory: PathPlus,
advanced_file_regression: AdvancedFileRegressionFixture,
cli_runner: CliRunner,
):
result = cli_runner.invoke(main, args=[wheel_directory.as_posix()])
assert result.exit_code == 0
assert not result.stdout
advanced_file_regression.check_file(wheel_directory / "domdf-python-tools" / "index.html")
soup = BeautifulSoup((wheel_directory / "domdf-python-tools" / "index.html").read_text(), "html5lib")
all_anchors = soup.findAll('a')
assert len(all_anchors) == 14
for anchor in all_anchors:
href = URL(anchor["href"])
file = wheel_directory / href.path.name
assert file.name.startswith("domdf_python_tools")
assert file.suffix == ".whl"
assert href.fragment is not None
hash_name, hash_value = href.fragment.split('=', 1)
assert hash_name == "sha256"
check_sha256_hash(file, hash_value)
metadata_file = file.with_suffix(f"{file.suffix}.metadata")
assert metadata_file.suffix == ".metadata"
assert metadata_file.is_file()
metadata_hash_name, hash_value = anchor["data-dist-info-metadata"].split('=', 1)
assert metadata_hash_name == "sha256"
check_sha256_hash(metadata_file, hash_value)
assert anchor["data-requires-python"] in {">=3.6.1", ">=3.6"}
| 32.616438 | 102 | 0.773625 |
import pytest
from apeye import URL
from bs4 import BeautifulSoup
from coincidence.regressions import AdvancedDataRegressionFixture, AdvancedFileRegressionFixture
from consolekit.testing import CliRunner
from domdf_python_tools.paths import PathPlus, sort_paths
from shippinglabel.checksum import check_sha256_hash
from simple503.__main__ import main
def test_inplace(
wheel_directory: PathPlus,
tmp_pathplus: PathPlus,
advanced_data_regression: AdvancedDataRegressionFixture,
cli_runner: CliRunner,
):
result = cli_runner.invoke(main, args=[wheel_directory.as_posix()])
assert result.exit_code == 0
assert not result.stdout
dir_content = [p.relative_to(tmp_pathplus) for p in wheel_directory.iterchildren()]
advanced_data_regression.check(sort_paths(*dir_content))
def test_inplace_explicit_same_target(
wheel_directory: PathPlus,
tmp_pathplus: PathPlus,
advanced_data_regression: AdvancedDataRegressionFixture,
cli_runner: CliRunner,
):
result = cli_runner.invoke(main, args=[wheel_directory.as_posix(), wheel_directory.as_posix()])
assert result.exit_code == 0
assert not result.stdout
dir_content = [p.relative_to(tmp_pathplus) for p in wheel_directory.iterchildren()]
advanced_data_regression.check(sort_paths(*dir_content))
def test_to_target(
wheel_directory: PathPlus,
tmp_pathplus: PathPlus,
advanced_data_regression: AdvancedDataRegressionFixture,
cli_runner: CliRunner,
):
target = tmp_pathplus / "target"
result = cli_runner.invoke(main, args=[wheel_directory.as_posix(), target.as_posix()])
assert result.exit_code == 0
assert not result.stdout
origin_content = [p.relative_to(tmp_pathplus) for p in wheel_directory.iterchildren()]
target_content = [p.relative_to(tmp_pathplus) for p in target.iterchildren()]
advanced_data_regression.check({
"origin": sort_paths(*origin_content),
"target": sort_paths(*target_content),
})
@pytest.mark.usefixtures("fixed_version")
def test_to_target_move(
wheel_directory: PathPlus,
tmp_pathplus: PathPlus,
advanced_data_regression: AdvancedDataRegressionFixture,
advanced_file_regression: AdvancedFileRegressionFixture,
cli_runner: CliRunner,
):
target = tmp_pathplus / "target"
result = cli_runner.invoke(main, args=[wheel_directory.as_posix(), target.as_posix(), "--move"])
assert result.exit_code == 0
assert not result.stdout
origin_content = [p.relative_to(tmp_pathplus) for p in wheel_directory.iterchildren()]
target_content = [p.relative_to(tmp_pathplus) for p in target.iterchildren()]
advanced_data_regression.check({
"origin": sort_paths(*origin_content),
"target": sort_paths(*target_content),
})
advanced_file_regression.check_file(target / "domdf-python-tools" / "index.html")
@pytest.mark.usefixtures("fixed_version")
def test_index_page(
wheel_directory: PathPlus,
advanced_file_regression: AdvancedFileRegressionFixture,
cli_runner: CliRunner,
):
result = cli_runner.invoke(main, args=[wheel_directory.as_posix()])
assert result.exit_code == 0
assert not result.stdout
advanced_file_regression.check_file(wheel_directory / "index.html")
soup = BeautifulSoup((wheel_directory / "index.html").read_text(), "html5lib")
all_anchors = soup.findAll('a')
assert len(all_anchors) == 39
for anchor in all_anchors:
href = URL(anchor["href"])
file = wheel_directory / href.path.name
assert file.is_dir()
assert (file / "index.html").is_file()
@pytest.mark.usefixtures("fixed_version")
def test_project_page(
wheel_directory: PathPlus,
advanced_file_regression: AdvancedFileRegressionFixture,
cli_runner: CliRunner,
):
result = cli_runner.invoke(main, args=[wheel_directory.as_posix()])
assert result.exit_code == 0
assert not result.stdout
advanced_file_regression.check_file(wheel_directory / "domdf-python-tools" / "index.html")
soup = BeautifulSoup((wheel_directory / "domdf-python-tools" / "index.html").read_text(), "html5lib")
all_anchors = soup.findAll('a')
assert len(all_anchors) == 14
for anchor in all_anchors:
href = URL(anchor["href"])
file = wheel_directory / href.path.name
assert file.name.startswith("domdf_python_tools")
assert file.suffix == ".whl"
assert href.fragment is not None
hash_name, hash_value = href.fragment.split('=', 1)
assert hash_name == "sha256"
check_sha256_hash(file, hash_value)
metadata_file = file.with_suffix(f"{file.suffix}.metadata")
assert metadata_file.suffix == ".metadata"
assert metadata_file.is_file()
metadata_hash_name, hash_value = anchor["data-dist-info-metadata"].split('=', 1)
assert metadata_hash_name == "sha256"
check_sha256_hash(metadata_file, hash_value)
assert anchor["data-requires-python"] in {">=3.6.1", ">=3.6"}
| true | true |
1c36fbbeb9e27780692065c9591c3f9718265124 | 2,083 | py | Python | setup.py | demonzyj56/compare_gan | 560697ee213f91048c6b4231ab79fcdd9bf20381 | [
"Apache-2.0"
] | 2 | 2019-07-25T20:49:33.000Z | 2019-08-07T02:54:34.000Z | setup.py | xiao7199/compare_gan | ac821a979ccb5ed46e0a441f87abc9bfd3c37417 | [
"Apache-2.0"
] | null | null | null | setup.py | xiao7199/compare_gan | ac821a979ccb5ed46e0a441f87abc9bfd3c37417 | [
"Apache-2.0"
] | 1 | 2019-10-16T21:02:08.000Z | 2019-10-16T21:02:08.000Z | # coding=utf-8
# Copyright 2018 Google LLC & Hwalsuk Lee.
#
# 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.
"""Install compare_gan."""
from setuptools import find_packages
from setuptools import setup
setup(
name='compare_gan',
version='1.0',
description=('Compare GAN - code from "Are GANs created equal? '
'A Large Scale Study" paper'),
author='Google LLC',
author_email='no-reply@google.com',
url='http://github.com/TODO',
license='Apache 2.0',
packages=find_packages(),
package_data={
},
scripts=[
'compare_gan/bin/compare_gan_generate_tasks',
'compare_gan/bin/compare_gan_prepare_datasets.sh',
'compare_gan/bin/compare_gan_run_one_task',
'compare_gan/bin/compare_gan_run_test.sh',
],
install_requires=[
'future',
'numpy',
'pandas',
'protobuf',
'six',
'tensor2tensor',
],
extras_require={
'matplotlib': ['matplotlib>=1.5.2'],
'pillow': ['pillow>=5.0.0'],
'pandas': ['pandas>=0.23.0'],
'pstar': ['pstar>=0.1.6'],
'scipy': ['scipy>=1.0.0'],
'tensorflow': ['tensorflow>=1.7'],
'tensorflow_gpu': ['tensorflow-gpu>=1.4.1'],
},
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
],
keywords='tensorflow machine learning gan',
)
| 32.046154 | 74 | 0.635622 |
from setuptools import find_packages
from setuptools import setup
setup(
name='compare_gan',
version='1.0',
description=('Compare GAN - code from "Are GANs created equal? '
'A Large Scale Study" paper'),
author='Google LLC',
author_email='no-reply@google.com',
url='http://github.com/TODO',
license='Apache 2.0',
packages=find_packages(),
package_data={
},
scripts=[
'compare_gan/bin/compare_gan_generate_tasks',
'compare_gan/bin/compare_gan_prepare_datasets.sh',
'compare_gan/bin/compare_gan_run_one_task',
'compare_gan/bin/compare_gan_run_test.sh',
],
install_requires=[
'future',
'numpy',
'pandas',
'protobuf',
'six',
'tensor2tensor',
],
extras_require={
'matplotlib': ['matplotlib>=1.5.2'],
'pillow': ['pillow>=5.0.0'],
'pandas': ['pandas>=0.23.0'],
'pstar': ['pstar>=0.1.6'],
'scipy': ['scipy>=1.0.0'],
'tensorflow': ['tensorflow>=1.7'],
'tensorflow_gpu': ['tensorflow-gpu>=1.4.1'],
},
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
],
keywords='tensorflow machine learning gan',
)
| true | true |
1c36fc0e7fdff83e271e1a2652306a4f105405b5 | 5,000 | py | Python | Day_4_Loops/forloops.py | ValRCS/Python_TietoEvry_Sep2021 | e11dac38deb17ba695ce8ad9dab9cf78b4adb99d | [
"MIT"
] | null | null | null | Day_4_Loops/forloops.py | ValRCS/Python_TietoEvry_Sep2021 | e11dac38deb17ba695ce8ad9dab9cf78b4adb99d | [
"MIT"
] | null | null | null | Day_4_Loops/forloops.py | ValRCS/Python_TietoEvry_Sep2021 | e11dac38deb17ba695ce8ad9dab9cf78b4adb99d | [
"MIT"
] | null | null | null | # # # # # # for loops are for definite iteration
# # # # # #
# for num in range(5): # range is sort of half ready number sequence , num is a variable created for each iteration
# # range starts with 0 and ends with 4
# print(num)
# print("Hello there!")
# print("Number is", num)
# print("out of loop", num)
# # # # so range takes range(start(default 0), end(not included), step)
#
# for i in range(1, 11): # so careful of off-by-one errors, remember range will stop at 10 not 11 here!
# print(f"I like this {i} better")
#
# # we can also iterate over strings
# my_name = "Valdis Saul"
# # # my_name = "Kaķis Ņauva"
# for c in my_name: # c could be also char, or my_c, c is just shorter
# print("Letter ", c)
# print(f"Letter {c} Unicode is {ord(c)}")
# # # # # if c < "a": # this would include digits space,etc
# if c.isupper(): #works even on Latvian capital letters such as Ņ Ā etc
# print("You are using uppercase letter are you not?", c)
# else:
# print("not an uppercase character could be anything else", c)
# # #
# # # # #
# # print("This happens after the loop is done")
# # #
# range with 2 parameters we have start inclusive and until end exclusive
# for n in range(20,25): # we loop until 24
# print(n)
# # # # # #
#
# range allows us to add step parameter
# for my_num in range(100,110+1,2): # i can add step to range, I added +1 to make it inclusive
# print(my_num)
# # # #
# start = 10
# end = 37
# step = 4
# early_break = 27
# for my_num in range(start,end+1,step): # i can add step to range
# print(my_num)
# if my_num > early_break:
# print(f"Reached our early break threshold {early_break}")
# break
#
# # #
# # #
# # # # # #
# # # # # #
# for _ in range(23): # _ means that we do not care about the variable, i just want to do something 23 times
# print("We do not need the number in this case")
# # # # #
# # #
# we can nest loops
# big_total = 0
# even_number_count = 0
# for i in range(1,5): # outer loop
# for j in range(1, 3): #inner loop
# result = i * j
# print(f"{i}x{j}={result}")
# big_total += result
# if result % 2 == 0:
# print("oh even number", result)
# even_number_count += 1
#
# print("Total is", big_total)
# print("Even number count is", even_number_count)
# # # # # #
# # # # # # my_name = "Valdis"
# # # # # # for c in my_name:
# # # # # # print("Letter ", c)
# # # # # #
# # # # # my_list = [1,2,100,105,"Valdis","potatoes", 9000, 107.35]
# # # # # total = 0
# # # # # big_items = 0
# # # # # for item in my_list:
# # # # # print("Working with item: ", item)
# # # # # if type(item) == int or type(item) == float:
# # # # # total += item
# # # # # if item > 100:
# # # # # big_items += 1
# # # # # #
# # # # my_num_list = [1,6,17,7,-6,49,642,6,2,-5555] # this is a list
# # # # # #
# # # # my_max = None
# # # # for num in my_num_list:
# # # # print("Checking", num)
# # # # if my_max is None: # this will happen with first item
# # # # my_max = num
# # # # if num > my_max:
# # # # print("New max is", num)
# # # # my_max = num
# # # # # #
# # # # print("My max is", my_max)
# # # # print(max(*my_num_list)) # short way of finding max in list
# # # # #
# # # # # # So what do we do when we need and index
# # # # # my_name = "Valdis Saulespurēns"
# # # # # print(f"{my_name} is {len(my_name)} characters long")
# # # # # print(my_name[0])
# # # # # print(my_name[5])
# # # # # # anti-pattern do not write this way in Python
# # # # # for n in range(0, len(my_name)):
# # # # # print(n, my_name[n])
# # # # # #
# # # # # # more Pythonic is using enumerate:
# # # # # # use this if you need index
# # # #
my_name = "Valdis"
for index, c in enumerate(my_name): # i could have used i instead of index
print(f"Letter {index} is {c}")
print("Letter", index, "is",c)
# # # #
# for index, c in enumerate(my_name,start=1):
# print("Letter", index, "is",c)
# # # # # #
# # # # # # if i do not like 0 i can start with any number
# # # # # for i, c in enumerate(my_name, start=101):
# # # # # print("Letter", i, "is",c)
# # # # #
# # # # #
# # # # # my_num = 20
# # # # # for n in range(1,11):
# # # # # reminder = my_num % n
# # # # # result = my_num // n # whole number
# # # # # print(f"{my_num} divided by {n} gives {result} with {reminder} as reminder")
# # # #
# for n in range(1,21): # from 1 until 20
# if n%2 == 0: # even numbers have no reminder when divided by 2
# print(f"{n} is even")
# else:
# print(f"{n} is odd")
# # # #
# # # # print by default has end value \n - newline
# # # # we can change this
# # print("Fizz", end=",")
# # print("Buzz", end=",")
# # print("342", end="****")
# # #
print(" "*10+"*"*6)
# # #same as above
# # for _ in range(10):
# # print(" ", end="")
# # for _ in range(6):
# # print("*", end="")
# # print() # prints new line | 33.333333 | 116 | 0.539 | true | true | |
1c36fcd88bce4cd7e7306fd04a45ece8623f9ccb | 20,343 | py | Python | test/functional/test_runner.py | danigarcia3k/Sikacoin | 82ef600cfeed1d8f163df6071d8d080fb9dac6b0 | [
"MIT"
] | null | null | null | test/functional/test_runner.py | danigarcia3k/Sikacoin | 82ef600cfeed1d8f163df6071d8d080fb9dac6b0 | [
"MIT"
] | null | null | null | test/functional/test_runner.py | danigarcia3k/Sikacoin | 82ef600cfeed1d8f163df6071d8d080fb9dac6b0 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Sikacoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Run regression test suite.
This module calls down into individual test cases via subprocess. It will
forward all unrecognized arguments onto the individual test scripts.
Functional tests are disabled on Windows by default. Use --force to run them anyway.
For a description of arguments recognized by test scripts, see
`test/functional/test_framework/test_framework.py:SikacoinTestFramework.main`.
"""
import argparse
import configparser
import datetime
import os
import time
import shutil
import signal
import sys
import subprocess
import tempfile
import re
import logging
# Formatting. Default colors to empty strings.
BOLD, BLUE, RED, GREY = ("", ""), ("", ""), ("", ""), ("", "")
try:
# Make sure python thinks it can write unicode to its stdout
"\u2713".encode("utf_8").decode(sys.stdout.encoding)
TICK = "✓ "
CROSS = "✖ "
CIRCLE = "○ "
except UnicodeDecodeError:
TICK = "P "
CROSS = "x "
CIRCLE = "o "
if os.name == 'posix':
# primitive formatting on supported
# terminal via ANSI escape sequences:
BOLD = ('\033[0m', '\033[1m')
BLUE = ('\033[0m', '\033[0;34m')
RED = ('\033[0m', '\033[0;31m')
GREY = ('\033[0m', '\033[1;30m')
TEST_EXIT_PASSED = 0
TEST_EXIT_SKIPPED = 77
BASE_SCRIPTS= [
# Scripts that are run by the travis build process.
# Longest test should go first, to favor running tests in parallel
'wallet-hd.py',
'walletbackup.py',
# vv Tests less than 5m vv
'p2p-fullblocktest.py',
'fundrawtransaction.py',
'p2p-compactblocks.py',
'segwit.py',
# vv Tests less than 2m vv
'wallet.py',
'wallet-accounts.py',
'p2p-segwit.py',
'wallet-dump.py',
'listtransactions.py',
# vv Tests less than 60s vv
'sendheaders.py',
'zapwallettxes.py',
'importmulti.py',
'mempool_limit.py',
'merkle_blocks.py',
'receivedby.py',
'abandonconflict.py',
'bip68-112-113-p2p.py',
'rawtransactions.py',
'reindex.py',
# vv Tests less than 30s vv
'keypool-topup.py',
'zmq_test.py',
'sikacoin_cli.py',
'mempool_resurrect_test.py',
'txn_doublespend.py --mineblock',
'txn_clone.py',
'getchaintips.py',
'rest.py',
'mempool_spendcoinbase.py',
'mempool_reorg.py',
'mempool_persist.py',
'multiwallet.py',
'httpbasics.py',
'multi_rpc.py',
'proxy_test.py',
'signrawtransactions.py',
'disconnect_ban.py',
'decodescript.py',
'blockchain.py',
'disablewallet.py',
'net.py',
'keypool.py',
'p2p-mempool.py',
'prioritise_transaction.py',
'invalidblockrequest.py',
'invalidtxrequest.py',
'p2p-versionbits-warning.py',
'preciousblock.py',
'importprunedfunds.py',
'signmessages.py',
'nulldummy.py',
'import-rescan.py',
'mining.py',
'bumpfee.py',
'rpcnamedargs.py',
'listsinceblock.py',
'p2p-leaktests.py',
'wallet-encryption.py',
'bipdersig-p2p.py',
'bip65-cltv-p2p.py',
'uptime.py',
'resendwallettransactions.py',
'minchainwork.py',
'p2p-acceptblock.py',
]
EXTENDED_SCRIPTS = [
# These tests are not run by the travis build process.
# Longest test should go first, to favor running tests in parallel
'pruning.py',
# vv Tests less than 20m vv
'smartfees.py',
# vv Tests less than 5m vv
'maxuploadtarget.py',
'mempool_packages.py',
'dbcrash.py',
# vv Tests less than 2m vv
'bip68-sequence.py',
'getblocktemplate_longpoll.py',
'p2p-timeouts.py',
# vv Tests less than 60s vv
'bip9-softforks.py',
'p2p-feefilter.py',
'rpcbind_test.py',
# vv Tests less than 30s vv
'assumevalid.py',
'example_test.py',
'txn_doublespend.py',
'txn_clone.py --mineblock',
'forknotify.py',
'invalidateblock.py',
'replace-by-fee.py',
]
# Place EXTENDED_SCRIPTS first since it has the 3 longest running tests
ALL_SCRIPTS = EXTENDED_SCRIPTS + BASE_SCRIPTS
NON_SCRIPTS = [
# These are python files that live in the functional tests directory, but are not test scripts.
"combine_logs.py",
"create_cache.py",
"test_runner.py",
]
def main():
# Parse arguments and pass through unrecognised args
parser = argparse.ArgumentParser(add_help=False,
usage='%(prog)s [test_runner.py options] [script options] [scripts]',
description=__doc__,
epilog='''
Help text and arguments for individual test script:''',
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--coverage', action='store_true', help='generate a basic coverage report for the RPC interface')
parser.add_argument('--exclude', '-x', help='specify a comma-seperated-list of scripts to exclude.')
parser.add_argument('--extended', action='store_true', help='run the extended test suite in addition to the basic tests')
parser.add_argument('--force', '-f', action='store_true', help='run tests even on platforms where they are disabled by default (e.g. windows).')
parser.add_argument('--help', '-h', '-?', action='store_true', help='print help text and exit')
parser.add_argument('--jobs', '-j', type=int, default=4, help='how many test scripts to run in parallel. Default=4.')
parser.add_argument('--keepcache', '-k', action='store_true', help='the default behavior is to flush the cache directory on startup. --keepcache retains the cache from the previous testrun.')
parser.add_argument('--quiet', '-q', action='store_true', help='only print results summary and failure logs')
parser.add_argument('--tmpdirprefix', '-t', default=tempfile.gettempdir(), help="Root directory for datadirs")
args, unknown_args = parser.parse_known_args()
# args to be passed on always start with two dashes; tests are the remaining unknown args
tests = [arg for arg in unknown_args if arg[:2] != "--"]
passon_args = [arg for arg in unknown_args if arg[:2] == "--"]
# Read config generated by configure.
config = configparser.ConfigParser()
configfile = os.path.abspath(os.path.dirname(__file__)) + "/../config.ini"
config.read_file(open(configfile))
passon_args.append("--configfile=%s" % configfile)
# Set up logging
logging_level = logging.INFO if args.quiet else logging.DEBUG
logging.basicConfig(format='%(message)s', level=logging_level)
# Create base test directory
tmpdir = "%s/sikacoin_test_runner_%s" % (args.tmpdirprefix, datetime.datetime.now().strftime("%Y%m%d_%H%M%S"))
os.makedirs(tmpdir)
logging.debug("Temporary test directory at %s" % tmpdir)
enable_wallet = config["components"].getboolean("ENABLE_WALLET")
enable_utils = config["components"].getboolean("ENABLE_UTILS")
enable_sikacoind = config["components"].getboolean("ENABLE_SIKACOIND")
if config["environment"]["EXEEXT"] == ".exe" and not args.force:
# https://github.com/sikacoin/sikacoin/commit/d52802551752140cf41f0d9a225a43e84404d3e9
# https://github.com/sikacoin/sikacoin/pull/5677#issuecomment-136646964
print("Tests currently disabled on Windows by default. Use --force option to enable")
sys.exit(0)
if not (enable_wallet and enable_utils and enable_sikacoind):
print("No functional tests to run. Wallet, utils, and sikacoind must all be enabled")
print("Rerun `configure` with -enable-wallet, -with-utils and -with-daemon and rerun make")
sys.exit(0)
# Build list of tests
if tests:
# Individual tests have been specified. Run specified tests that exist
# in the ALL_SCRIPTS list. Accept the name with or without .py extension.
tests = [re.sub("\.py$", "", t) + ".py" for t in tests]
test_list = []
for t in tests:
if t in ALL_SCRIPTS:
test_list.append(t)
else:
print("{}WARNING!{} Test '{}' not found in full test list.".format(BOLD[1], BOLD[0], t))
else:
# No individual tests have been specified.
# Run all base tests, and optionally run extended tests.
test_list = BASE_SCRIPTS
if args.extended:
# place the EXTENDED_SCRIPTS first since the three longest ones
# are there and the list is shorter
test_list = EXTENDED_SCRIPTS + test_list
# Remove the test cases that the user has explicitly asked to exclude.
if args.exclude:
tests_excl = [re.sub("\.py$", "", t) + ".py" for t in args.exclude.split(',')]
for exclude_test in tests_excl:
if exclude_test in test_list:
test_list.remove(exclude_test)
else:
print("{}WARNING!{} Test '{}' not found in current test list.".format(BOLD[1], BOLD[0], exclude_test))
if not test_list:
print("No valid test scripts specified. Check that your test is in one "
"of the test lists in test_runner.py, or run test_runner.py with no arguments to run all tests")
sys.exit(0)
if args.help:
# Print help for test_runner.py, then print help of the first script (with args removed) and exit.
parser.print_help()
subprocess.check_call([(config["environment"]["SRCDIR"] + '/test/functional/' + test_list[0].split()[0])] + ['-h'])
sys.exit(0)
check_script_list(config["environment"]["SRCDIR"])
if not args.keepcache:
shutil.rmtree("%s/test/cache" % config["environment"]["BUILDDIR"], ignore_errors=True)
run_tests(test_list, config["environment"]["SRCDIR"], config["environment"]["BUILDDIR"], config["environment"]["EXEEXT"], tmpdir, args.jobs, args.coverage, passon_args)
def run_tests(test_list, src_dir, build_dir, exeext, tmpdir, jobs=1, enable_coverage=False, args=[]):
# Warn if sikacoind is already running (unix only)
try:
if subprocess.check_output(["pidof", "sikacoind"]) is not None:
print("%sWARNING!%s There is already a sikacoind process running on this system. Tests may fail unexpectedly due to resource contention!" % (BOLD[1], BOLD[0]))
except (OSError, subprocess.SubprocessError):
pass
# Warn if there is a cache directory
cache_dir = "%s/test/cache" % build_dir
if os.path.isdir(cache_dir):
print("%sWARNING!%s There is a cache directory here: %s. If tests fail unexpectedly, try deleting the cache directory." % (BOLD[1], BOLD[0], cache_dir))
#Set env vars
if "SIKACOIND" not in os.environ:
os.environ["SIKACOIND"] = build_dir + '/src/sikacoind' + exeext
os.environ["SIKACOINCLI"] = build_dir + '/src/sikacoin-cli' + exeext
tests_dir = src_dir + '/test/functional/'
flags = ["--srcdir={}/src".format(build_dir)] + args
flags.append("--cachedir=%s" % cache_dir)
if enable_coverage:
coverage = RPCCoverage()
flags.append(coverage.flag)
logging.debug("Initializing coverage directory at %s" % coverage.dir)
else:
coverage = None
if len(test_list) > 1 and jobs > 1:
# Populate cache
subprocess.check_output([tests_dir + 'create_cache.py'] + flags + ["--tmpdir=%s/cache" % tmpdir])
#Run Tests
job_queue = TestHandler(jobs, tests_dir, tmpdir, test_list, flags)
time0 = time.time()
test_results = []
max_len_name = len(max(test_list, key=len))
for _ in range(len(test_list)):
test_result, stdout, stderr = job_queue.get_next()
test_results.append(test_result)
if test_result.status == "Passed":
logging.debug("\n%s%s%s passed, Duration: %s s" % (BOLD[1], test_result.name, BOLD[0], test_result.time))
elif test_result.status == "Skipped":
logging.debug("\n%s%s%s skipped" % (BOLD[1], test_result.name, BOLD[0]))
else:
print("\n%s%s%s failed, Duration: %s s\n" % (BOLD[1], test_result.name, BOLD[0], test_result.time))
print(BOLD[1] + 'stdout:\n' + BOLD[0] + stdout + '\n')
print(BOLD[1] + 'stderr:\n' + BOLD[0] + stderr + '\n')
print_results(test_results, max_len_name, (int(time.time() - time0)))
if coverage:
coverage.report_rpc_coverage()
logging.debug("Cleaning up coverage data")
coverage.cleanup()
# Clear up the temp directory if all subdirectories are gone
if not os.listdir(tmpdir):
os.rmdir(tmpdir)
all_passed = all(map(lambda test_result: test_result.was_successful, test_results))
sys.exit(not all_passed)
def print_results(test_results, max_len_name, runtime):
results = "\n" + BOLD[1] + "%s | %s | %s\n\n" % ("TEST".ljust(max_len_name), "STATUS ", "DURATION") + BOLD[0]
test_results.sort(key=lambda result: result.name.lower())
all_passed = True
time_sum = 0
for test_result in test_results:
all_passed = all_passed and test_result.was_successful
time_sum += test_result.time
test_result.padding = max_len_name
results += str(test_result)
status = TICK + "Passed" if all_passed else CROSS + "Failed"
results += BOLD[1] + "\n%s | %s | %s s (accumulated) \n" % ("ALL".ljust(max_len_name), status.ljust(9), time_sum) + BOLD[0]
results += "Runtime: %s s\n" % (runtime)
print(results)
class TestHandler:
"""
Trigger the testscrips passed in via the list.
"""
def __init__(self, num_tests_parallel, tests_dir, tmpdir, test_list=None, flags=None):
assert(num_tests_parallel >= 1)
self.num_jobs = num_tests_parallel
self.tests_dir = tests_dir
self.tmpdir = tmpdir
self.test_list = test_list
self.flags = flags
self.num_running = 0
# In case there is a graveyard of zombie sikacoinds, we can apply a
# pseudorandom offset to hopefully jump over them.
# (625 is PORT_RANGE/MAX_NODES)
self.portseed_offset = int(time.time() * 1000) % 625
self.jobs = []
def get_next(self):
while self.num_running < self.num_jobs and self.test_list:
# Add tests
self.num_running += 1
t = self.test_list.pop(0)
portseed = len(self.test_list) + self.portseed_offset
portseed_arg = ["--portseed={}".format(portseed)]
log_stdout = tempfile.SpooledTemporaryFile(max_size=2**16)
log_stderr = tempfile.SpooledTemporaryFile(max_size=2**16)
test_argv = t.split()
tmpdir = ["--tmpdir=%s/%s_%s" % (self.tmpdir, re.sub(".py$", "", test_argv[0]), portseed)]
self.jobs.append((t,
time.time(),
subprocess.Popen([self.tests_dir + test_argv[0]] + test_argv[1:] + self.flags + portseed_arg + tmpdir,
universal_newlines=True,
stdout=log_stdout,
stderr=log_stderr),
log_stdout,
log_stderr))
if not self.jobs:
raise IndexError('pop from empty list')
while True:
# Return first proc that finishes
time.sleep(.5)
for j in self.jobs:
(name, time0, proc, log_out, log_err) = j
if os.getenv('TRAVIS') == 'true' and int(time.time() - time0) > 20 * 60:
# In travis, timeout individual tests after 20 minutes (to stop tests hanging and not
# providing useful output.
proc.send_signal(signal.SIGINT)
if proc.poll() is not None:
log_out.seek(0), log_err.seek(0)
[stdout, stderr] = [l.read().decode('utf-8') for l in (log_out, log_err)]
log_out.close(), log_err.close()
if proc.returncode == TEST_EXIT_PASSED and stderr == "":
status = "Passed"
elif proc.returncode == TEST_EXIT_SKIPPED:
status = "Skipped"
else:
status = "Failed"
self.num_running -= 1
self.jobs.remove(j)
return TestResult(name, status, int(time.time() - time0)), stdout, stderr
print('.', end='', flush=True)
class TestResult():
def __init__(self, name, status, time):
self.name = name
self.status = status
self.time = time
self.padding = 0
def __repr__(self):
if self.status == "Passed":
color = BLUE
glyph = TICK
elif self.status == "Failed":
color = RED
glyph = CROSS
elif self.status == "Skipped":
color = GREY
glyph = CIRCLE
return color[1] + "%s | %s%s | %s s\n" % (self.name.ljust(self.padding), glyph, self.status.ljust(7), self.time) + color[0]
@property
def was_successful(self):
return self.status != "Failed"
def check_script_list(src_dir):
"""Check scripts directory.
Check that there are no scripts in the functional tests directory which are
not being run by pull-tester.py."""
script_dir = src_dir + '/test/functional/'
python_files = set([t for t in os.listdir(script_dir) if t[-3:] == ".py"])
missed_tests = list(python_files - set(map(lambda x: x.split()[0], ALL_SCRIPTS + NON_SCRIPTS)))
if len(missed_tests) != 0:
print("%sWARNING!%s The following scripts are not being run: %s. Check the test lists in test_runner.py." % (BOLD[1], BOLD[0], str(missed_tests)))
if os.getenv('TRAVIS') == 'true':
# On travis this warning is an error to prevent merging incomplete commits into master
sys.exit(1)
class RPCCoverage(object):
"""
Coverage reporting utilities for test_runner.
Coverage calculation works by having each test script subprocess write
coverage files into a particular directory. These files contain the RPC
commands invoked during testing, as well as a complete listing of RPC
commands per `sikacoin-cli help` (`rpc_interface.txt`).
After all tests complete, the commands run are combined and diff'd against
the complete list to calculate uncovered RPC commands.
See also: test/functional/test_framework/coverage.py
"""
def __init__(self):
self.dir = tempfile.mkdtemp(prefix="coverage")
self.flag = '--coveragedir=%s' % self.dir
def report_rpc_coverage(self):
"""
Print out RPC commands that were unexercised by tests.
"""
uncovered = self._get_uncovered_rpc_commands()
if uncovered:
print("Uncovered RPC commands:")
print("".join((" - %s\n" % i) for i in sorted(uncovered)))
else:
print("All RPC commands covered.")
def cleanup(self):
return shutil.rmtree(self.dir)
def _get_uncovered_rpc_commands(self):
"""
Return a set of currently untested RPC commands.
"""
# This is shared from `test/functional/test-framework/coverage.py`
reference_filename = 'rpc_interface.txt'
coverage_file_prefix = 'coverage.'
coverage_ref_filename = os.path.join(self.dir, reference_filename)
coverage_filenames = set()
all_cmds = set()
covered_cmds = set()
if not os.path.isfile(coverage_ref_filename):
raise RuntimeError("No coverage reference found")
with open(coverage_ref_filename, 'r') as f:
all_cmds.update([i.strip() for i in f.readlines()])
for root, dirs, files in os.walk(self.dir):
for filename in files:
if filename.startswith(coverage_file_prefix):
coverage_filenames.add(os.path.join(root, filename))
for filename in coverage_filenames:
with open(filename, 'r') as f:
covered_cmds.update([i.strip() for i in f.readlines()])
return all_cmds - covered_cmds
if __name__ == '__main__':
main()
| 38.455577 | 195 | 0.624588 |
import argparse
import configparser
import datetime
import os
import time
import shutil
import signal
import sys
import subprocess
import tempfile
import re
import logging
BOLD, BLUE, RED, GREY = ("", ""), ("", ""), ("", ""), ("", "")
try:
"\u2713".encode("utf_8").decode(sys.stdout.encoding)
TICK = "✓ "
CROSS = "✖ "
CIRCLE = "○ "
except UnicodeDecodeError:
TICK = "P "
CROSS = "x "
CIRCLE = "o "
if os.name == 'posix':
BOLD = ('\033[0m', '\033[1m')
BLUE = ('\033[0m', '\033[0;34m')
RED = ('\033[0m', '\033[0;31m')
GREY = ('\033[0m', '\033[1;30m')
TEST_EXIT_PASSED = 0
TEST_EXIT_SKIPPED = 77
BASE_SCRIPTS= [
'wallet-hd.py',
'walletbackup.py',
'p2p-fullblocktest.py',
'fundrawtransaction.py',
'p2p-compactblocks.py',
'segwit.py',
'wallet.py',
'wallet-accounts.py',
'p2p-segwit.py',
'wallet-dump.py',
'listtransactions.py',
'sendheaders.py',
'zapwallettxes.py',
'importmulti.py',
'mempool_limit.py',
'merkle_blocks.py',
'receivedby.py',
'abandonconflict.py',
'bip68-112-113-p2p.py',
'rawtransactions.py',
'reindex.py',
'keypool-topup.py',
'zmq_test.py',
'sikacoin_cli.py',
'mempool_resurrect_test.py',
'txn_doublespend.py --mineblock',
'txn_clone.py',
'getchaintips.py',
'rest.py',
'mempool_spendcoinbase.py',
'mempool_reorg.py',
'mempool_persist.py',
'multiwallet.py',
'httpbasics.py',
'multi_rpc.py',
'proxy_test.py',
'signrawtransactions.py',
'disconnect_ban.py',
'decodescript.py',
'blockchain.py',
'disablewallet.py',
'net.py',
'keypool.py',
'p2p-mempool.py',
'prioritise_transaction.py',
'invalidblockrequest.py',
'invalidtxrequest.py',
'p2p-versionbits-warning.py',
'preciousblock.py',
'importprunedfunds.py',
'signmessages.py',
'nulldummy.py',
'import-rescan.py',
'mining.py',
'bumpfee.py',
'rpcnamedargs.py',
'listsinceblock.py',
'p2p-leaktests.py',
'wallet-encryption.py',
'bipdersig-p2p.py',
'bip65-cltv-p2p.py',
'uptime.py',
'resendwallettransactions.py',
'minchainwork.py',
'p2p-acceptblock.py',
]
EXTENDED_SCRIPTS = [
'pruning.py',
'smartfees.py',
'maxuploadtarget.py',
'mempool_packages.py',
'dbcrash.py',
'bip68-sequence.py',
'getblocktemplate_longpoll.py',
'p2p-timeouts.py',
'bip9-softforks.py',
'p2p-feefilter.py',
'rpcbind_test.py',
'assumevalid.py',
'example_test.py',
'txn_doublespend.py',
'txn_clone.py --mineblock',
'forknotify.py',
'invalidateblock.py',
'replace-by-fee.py',
]
ALL_SCRIPTS = EXTENDED_SCRIPTS + BASE_SCRIPTS
NON_SCRIPTS = [
"combine_logs.py",
"create_cache.py",
"test_runner.py",
]
def main():
parser = argparse.ArgumentParser(add_help=False,
usage='%(prog)s [test_runner.py options] [script options] [scripts]',
description=__doc__,
epilog='''
Help text and arguments for individual test script:''',
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--coverage', action='store_true', help='generate a basic coverage report for the RPC interface')
parser.add_argument('--exclude', '-x', help='specify a comma-seperated-list of scripts to exclude.')
parser.add_argument('--extended', action='store_true', help='run the extended test suite in addition to the basic tests')
parser.add_argument('--force', '-f', action='store_true', help='run tests even on platforms where they are disabled by default (e.g. windows).')
parser.add_argument('--help', '-h', '-?', action='store_true', help='print help text and exit')
parser.add_argument('--jobs', '-j', type=int, default=4, help='how many test scripts to run in parallel. Default=4.')
parser.add_argument('--keepcache', '-k', action='store_true', help='the default behavior is to flush the cache directory on startup. --keepcache retains the cache from the previous testrun.')
parser.add_argument('--quiet', '-q', action='store_true', help='only print results summary and failure logs')
parser.add_argument('--tmpdirprefix', '-t', default=tempfile.gettempdir(), help="Root directory for datadirs")
args, unknown_args = parser.parse_known_args()
tests = [arg for arg in unknown_args if arg[:2] != "--"]
passon_args = [arg for arg in unknown_args if arg[:2] == "--"]
config = configparser.ConfigParser()
configfile = os.path.abspath(os.path.dirname(__file__)) + "/../config.ini"
config.read_file(open(configfile))
passon_args.append("--configfile=%s" % configfile)
logging_level = logging.INFO if args.quiet else logging.DEBUG
logging.basicConfig(format='%(message)s', level=logging_level)
tmpdir = "%s/sikacoin_test_runner_%s" % (args.tmpdirprefix, datetime.datetime.now().strftime("%Y%m%d_%H%M%S"))
os.makedirs(tmpdir)
logging.debug("Temporary test directory at %s" % tmpdir)
enable_wallet = config["components"].getboolean("ENABLE_WALLET")
enable_utils = config["components"].getboolean("ENABLE_UTILS")
enable_sikacoind = config["components"].getboolean("ENABLE_SIKACOIND")
if config["environment"]["EXEEXT"] == ".exe" and not args.force:
urrently disabled on Windows by default. Use --force option to enable")
sys.exit(0)
if not (enable_wallet and enable_utils and enable_sikacoind):
print("No functional tests to run. Wallet, utils, and sikacoind must all be enabled")
print("Rerun `configure` with -enable-wallet, -with-utils and -with-daemon and rerun make")
sys.exit(0)
if tests:
tests = [re.sub("\.py$", "", t) + ".py" for t in tests]
test_list = []
for t in tests:
if t in ALL_SCRIPTS:
test_list.append(t)
else:
print("{}WARNING!{} Test '{}' not found in full test list.".format(BOLD[1], BOLD[0], t))
else:
test_list = BASE_SCRIPTS
if args.extended:
test_list = EXTENDED_SCRIPTS + test_list
if args.exclude:
tests_excl = [re.sub("\.py$", "", t) + ".py" for t in args.exclude.split(',')]
for exclude_test in tests_excl:
if exclude_test in test_list:
test_list.remove(exclude_test)
else:
print("{}WARNING!{} Test '{}' not found in current test list.".format(BOLD[1], BOLD[0], exclude_test))
if not test_list:
print("No valid test scripts specified. Check that your test is in one "
"of the test lists in test_runner.py, or run test_runner.py with no arguments to run all tests")
sys.exit(0)
if args.help:
parser.print_help()
subprocess.check_call([(config["environment"]["SRCDIR"] + '/test/functional/' + test_list[0].split()[0])] + ['-h'])
sys.exit(0)
check_script_list(config["environment"]["SRCDIR"])
if not args.keepcache:
shutil.rmtree("%s/test/cache" % config["environment"]["BUILDDIR"], ignore_errors=True)
run_tests(test_list, config["environment"]["SRCDIR"], config["environment"]["BUILDDIR"], config["environment"]["EXEEXT"], tmpdir, args.jobs, args.coverage, passon_args)
def run_tests(test_list, src_dir, build_dir, exeext, tmpdir, jobs=1, enable_coverage=False, args=[]):
try:
if subprocess.check_output(["pidof", "sikacoind"]) is not None:
print("%sWARNING!%s There is already a sikacoind process running on this system. Tests may fail unexpectedly due to resource contention!" % (BOLD[1], BOLD[0]))
except (OSError, subprocess.SubprocessError):
pass
cache_dir = "%s/test/cache" % build_dir
if os.path.isdir(cache_dir):
print("%sWARNING!%s There is a cache directory here: %s. If tests fail unexpectedly, try deleting the cache directory." % (BOLD[1], BOLD[0], cache_dir))
if "SIKACOIND" not in os.environ:
os.environ["SIKACOIND"] = build_dir + '/src/sikacoind' + exeext
os.environ["SIKACOINCLI"] = build_dir + '/src/sikacoin-cli' + exeext
tests_dir = src_dir + '/test/functional/'
flags = ["--srcdir={}/src".format(build_dir)] + args
flags.append("--cachedir=%s" % cache_dir)
if enable_coverage:
coverage = RPCCoverage()
flags.append(coverage.flag)
logging.debug("Initializing coverage directory at %s" % coverage.dir)
else:
coverage = None
if len(test_list) > 1 and jobs > 1:
subprocess.check_output([tests_dir + 'create_cache.py'] + flags + ["--tmpdir=%s/cache" % tmpdir])
job_queue = TestHandler(jobs, tests_dir, tmpdir, test_list, flags)
time0 = time.time()
test_results = []
max_len_name = len(max(test_list, key=len))
for _ in range(len(test_list)):
test_result, stdout, stderr = job_queue.get_next()
test_results.append(test_result)
if test_result.status == "Passed":
logging.debug("\n%s%s%s passed, Duration: %s s" % (BOLD[1], test_result.name, BOLD[0], test_result.time))
elif test_result.status == "Skipped":
logging.debug("\n%s%s%s skipped" % (BOLD[1], test_result.name, BOLD[0]))
else:
print("\n%s%s%s failed, Duration: %s s\n" % (BOLD[1], test_result.name, BOLD[0], test_result.time))
print(BOLD[1] + 'stdout:\n' + BOLD[0] + stdout + '\n')
print(BOLD[1] + 'stderr:\n' + BOLD[0] + stderr + '\n')
print_results(test_results, max_len_name, (int(time.time() - time0)))
if coverage:
coverage.report_rpc_coverage()
logging.debug("Cleaning up coverage data")
coverage.cleanup()
if not os.listdir(tmpdir):
os.rmdir(tmpdir)
all_passed = all(map(lambda test_result: test_result.was_successful, test_results))
sys.exit(not all_passed)
def print_results(test_results, max_len_name, runtime):
results = "\n" + BOLD[1] + "%s | %s | %s\n\n" % ("TEST".ljust(max_len_name), "STATUS ", "DURATION") + BOLD[0]
test_results.sort(key=lambda result: result.name.lower())
all_passed = True
time_sum = 0
for test_result in test_results:
all_passed = all_passed and test_result.was_successful
time_sum += test_result.time
test_result.padding = max_len_name
results += str(test_result)
status = TICK + "Passed" if all_passed else CROSS + "Failed"
results += BOLD[1] + "\n%s | %s | %s s (accumulated) \n" % ("ALL".ljust(max_len_name), status.ljust(9), time_sum) + BOLD[0]
results += "Runtime: %s s\n" % (runtime)
print(results)
class TestHandler:
def __init__(self, num_tests_parallel, tests_dir, tmpdir, test_list=None, flags=None):
assert(num_tests_parallel >= 1)
self.num_jobs = num_tests_parallel
self.tests_dir = tests_dir
self.tmpdir = tmpdir
self.test_list = test_list
self.flags = flags
self.num_running = 0
self.portseed_offset = int(time.time() * 1000) % 625
self.jobs = []
def get_next(self):
while self.num_running < self.num_jobs and self.test_list:
self.num_running += 1
t = self.test_list.pop(0)
portseed = len(self.test_list) + self.portseed_offset
portseed_arg = ["--portseed={}".format(portseed)]
log_stdout = tempfile.SpooledTemporaryFile(max_size=2**16)
log_stderr = tempfile.SpooledTemporaryFile(max_size=2**16)
test_argv = t.split()
tmpdir = ["--tmpdir=%s/%s_%s" % (self.tmpdir, re.sub(".py$", "", test_argv[0]), portseed)]
self.jobs.append((t,
time.time(),
subprocess.Popen([self.tests_dir + test_argv[0]] + test_argv[1:] + self.flags + portseed_arg + tmpdir,
universal_newlines=True,
stdout=log_stdout,
stderr=log_stderr),
log_stdout,
log_stderr))
if not self.jobs:
raise IndexError('pop from empty list')
while True:
time.sleep(.5)
for j in self.jobs:
(name, time0, proc, log_out, log_err) = j
if os.getenv('TRAVIS') == 'true' and int(time.time() - time0) > 20 * 60:
proc.send_signal(signal.SIGINT)
if proc.poll() is not None:
log_out.seek(0), log_err.seek(0)
[stdout, stderr] = [l.read().decode('utf-8') for l in (log_out, log_err)]
log_out.close(), log_err.close()
if proc.returncode == TEST_EXIT_PASSED and stderr == "":
status = "Passed"
elif proc.returncode == TEST_EXIT_SKIPPED:
status = "Skipped"
else:
status = "Failed"
self.num_running -= 1
self.jobs.remove(j)
return TestResult(name, status, int(time.time() - time0)), stdout, stderr
print('.', end='', flush=True)
class TestResult():
def __init__(self, name, status, time):
self.name = name
self.status = status
self.time = time
self.padding = 0
def __repr__(self):
if self.status == "Passed":
color = BLUE
glyph = TICK
elif self.status == "Failed":
color = RED
glyph = CROSS
elif self.status == "Skipped":
color = GREY
glyph = CIRCLE
return color[1] + "%s | %s%s | %s s\n" % (self.name.ljust(self.padding), glyph, self.status.ljust(7), self.time) + color[0]
@property
def was_successful(self):
return self.status != "Failed"
def check_script_list(src_dir):
script_dir = src_dir + '/test/functional/'
python_files = set([t for t in os.listdir(script_dir) if t[-3:] == ".py"])
missed_tests = list(python_files - set(map(lambda x: x.split()[0], ALL_SCRIPTS + NON_SCRIPTS)))
if len(missed_tests) != 0:
print("%sWARNING!%s The following scripts are not being run: %s. Check the test lists in test_runner.py." % (BOLD[1], BOLD[0], str(missed_tests)))
if os.getenv('TRAVIS') == 'true':
sys.exit(1)
class RPCCoverage(object):
def __init__(self):
self.dir = tempfile.mkdtemp(prefix="coverage")
self.flag = '--coveragedir=%s' % self.dir
def report_rpc_coverage(self):
uncovered = self._get_uncovered_rpc_commands()
if uncovered:
print("Uncovered RPC commands:")
print("".join((" - %s\n" % i) for i in sorted(uncovered)))
else:
print("All RPC commands covered.")
def cleanup(self):
return shutil.rmtree(self.dir)
def _get_uncovered_rpc_commands(self):
reference_filename = 'rpc_interface.txt'
coverage_file_prefix = 'coverage.'
coverage_ref_filename = os.path.join(self.dir, reference_filename)
coverage_filenames = set()
all_cmds = set()
covered_cmds = set()
if not os.path.isfile(coverage_ref_filename):
raise RuntimeError("No coverage reference found")
with open(coverage_ref_filename, 'r') as f:
all_cmds.update([i.strip() for i in f.readlines()])
for root, dirs, files in os.walk(self.dir):
for filename in files:
if filename.startswith(coverage_file_prefix):
coverage_filenames.add(os.path.join(root, filename))
for filename in coverage_filenames:
with open(filename, 'r') as f:
covered_cmds.update([i.strip() for i in f.readlines()])
return all_cmds - covered_cmds
if __name__ == '__main__':
main()
| true | true |
1c36fcd9466fe0ce60710afead213d504cee3a79 | 3,309 | py | Python | src/python/turicreate/toolkits/_data_zoo.py | duoxiu/turicreate | befe2d300dcbf6297db5ca139b4500dc38739884 | [
"BSD-3-Clause"
] | 1 | 2020-02-21T02:24:45.000Z | 2020-02-21T02:24:45.000Z | src/python/turicreate/toolkits/_data_zoo.py | lukereichold/turicreate | 8b4b56b54e5f232caf3ba85cab9d24ab43c9ce48 | [
"BSD-3-Clause"
] | null | null | null | src/python/turicreate/toolkits/_data_zoo.py | lukereichold/turicreate | 8b4b56b54e5f232caf3ba85cab9d24ab43c9ce48 | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright © 2019 Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can
# be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
from __future__ import print_function as _
from __future__ import division as _
from __future__ import absolute_import as _
import os as _os
import turicreate as _tc
import shutil as _shutil
import tarfile as _tarfile
from six.moves.urllib import parse as _urlparse
from ._pre_trained_models import _download_and_checksum_files
from ._pre_trained_models import _get_cache_dir
DATA_URL_ROOT = "https://docs-assets.developer.apple.com/turicreate/data/"
class OneShotObjectDetectorBackgroundData(object):
def __init__(self):
self.source_tar_filename = "one_shot_backgrounds.sarray.tar"
self.destination_tar_filename = "one_shot_backgrounds.sarray.tar"
self.destination_sarray_filename = "one_shot_backgrounds.sarray"
self.destination_sarray_path = _os.path.join(
_get_cache_dir("data"), self.destination_sarray_filename
)
self.sarray_url = _urlparse.urljoin(DATA_URL_ROOT, self.source_tar_filename)
self.sarray_url_md5_pairs = [
(self.sarray_url, "08830e90771897c1cd187a07cdcb52b4")
]
self.extracted_file_to_md5 = {
'dir_archive.ini': '160fe6e7cb81cb0a29fd09239fdb2559',
'm_d761047844237e5d.0000': 'd29b68f8ba196f60e0ad115f7bfde863',
'm_d761047844237e5d.sidx': '22b0c297aabb836a21d3179c05c9c455',
'objects.bin': 'd41d8cd98f00b204e9800998ecf8427e'
}
def get_backgrounds(self):
# Download tar file, if not already downloaded
# Get tar file path
tarfile_path = _download_and_checksum_files(
self.sarray_url_md5_pairs, _get_cache_dir("data")
)[0]
# Extract SArray from tar file, if not already extracted
if _os.path.exists(self.destination_sarray_path):
backgrounds_tar = _tarfile.open(tarfile_path)
backgrounds_tar.extractall(_get_cache_dir("data"))
# Verify and load the extracted SArray
try:
# Check we extracted the file we expected
expected_extracted_files = set(self.extracted_file_to_md5.keys())
extracted_files = set(_os.listdir(self.destination_sarray_path))
assert expected_extracted_files == extracted_files
# Check each of the files is what we expect
for filename, expected_md5 in self.extracted_file_to_md5.items():
full_path = _os.path.join(_get_cache_dir("data"), filename)
md5 = hashlib.md5(full_path).hexdigest()
assert md5 == expected_md5
backgrounds = _tc.SArray(self.destination_sarray_path)
except:
# delete the incompletely/incorrectly extracted tarball bits on disk
if _os.path.exists(self.destination_sarray_path):
_shutil.rmtree(self.destination_sarray_path)
# and re-extract
backgrounds_tar = _tarfile.open(tarfile_path)
backgrounds_tar.extractall(_get_cache_dir("data"))
backgrounds = _tc.SArray(self.destination_sarray_path)
return backgrounds
| 42.423077 | 85 | 0.697794 |
from __future__ import print_function as _
from __future__ import division as _
from __future__ import absolute_import as _
import os as _os
import turicreate as _tc
import shutil as _shutil
import tarfile as _tarfile
from six.moves.urllib import parse as _urlparse
from ._pre_trained_models import _download_and_checksum_files
from ._pre_trained_models import _get_cache_dir
DATA_URL_ROOT = "https://docs-assets.developer.apple.com/turicreate/data/"
class OneShotObjectDetectorBackgroundData(object):
def __init__(self):
self.source_tar_filename = "one_shot_backgrounds.sarray.tar"
self.destination_tar_filename = "one_shot_backgrounds.sarray.tar"
self.destination_sarray_filename = "one_shot_backgrounds.sarray"
self.destination_sarray_path = _os.path.join(
_get_cache_dir("data"), self.destination_sarray_filename
)
self.sarray_url = _urlparse.urljoin(DATA_URL_ROOT, self.source_tar_filename)
self.sarray_url_md5_pairs = [
(self.sarray_url, "08830e90771897c1cd187a07cdcb52b4")
]
self.extracted_file_to_md5 = {
'dir_archive.ini': '160fe6e7cb81cb0a29fd09239fdb2559',
'm_d761047844237e5d.0000': 'd29b68f8ba196f60e0ad115f7bfde863',
'm_d761047844237e5d.sidx': '22b0c297aabb836a21d3179c05c9c455',
'objects.bin': 'd41d8cd98f00b204e9800998ecf8427e'
}
def get_backgrounds(self):
tarfile_path = _download_and_checksum_files(
self.sarray_url_md5_pairs, _get_cache_dir("data")
)[0]
if _os.path.exists(self.destination_sarray_path):
backgrounds_tar = _tarfile.open(tarfile_path)
backgrounds_tar.extractall(_get_cache_dir("data"))
try:
expected_extracted_files = set(self.extracted_file_to_md5.keys())
extracted_files = set(_os.listdir(self.destination_sarray_path))
assert expected_extracted_files == extracted_files
for filename, expected_md5 in self.extracted_file_to_md5.items():
full_path = _os.path.join(_get_cache_dir("data"), filename)
md5 = hashlib.md5(full_path).hexdigest()
assert md5 == expected_md5
backgrounds = _tc.SArray(self.destination_sarray_path)
except:
if _os.path.exists(self.destination_sarray_path):
_shutil.rmtree(self.destination_sarray_path)
backgrounds_tar = _tarfile.open(tarfile_path)
backgrounds_tar.extractall(_get_cache_dir("data"))
backgrounds = _tc.SArray(self.destination_sarray_path)
return backgrounds
| true | true |
1c36fd721dd54f2efa5b0a79b0e253d84c2132e1 | 1,028 | py | Python | dsh.py | joeportela/tinyAPI | f2469c38a605b00519acd0b79af17d0041f5ae7b | [
"MIT"
] | 6 | 2016-11-18T22:32:44.000Z | 2021-04-01T17:02:13.000Z | dsh.py | joeportela/tinyAPI | f2469c38a605b00519acd0b79af17d0041f5ae7b | [
"MIT"
] | 1 | 2018-12-20T23:07:52.000Z | 2018-12-20T23:07:52.000Z | dsh.py | joeportela/tinyAPI | f2469c38a605b00519acd0b79af17d0041f5ae7b | [
"MIT"
] | 10 | 2018-02-23T00:08:21.000Z | 2020-10-01T03:06:12.000Z | # ----- Info ------------------------------------------------------------------
__author__ = 'Michael Montero <mcmontero@gmail.com>'
# ----- Imports ---------------------------------------------------------------
from tinyAPI.base.data_store.provider import DataStoreNOOP
from tinyAPI.base.data_store.provider import DataStoreProvider
import tinyAPI
__all__ = [
'dsh'
]
# ----- Instructions ----------------------------------------------------------
class __DSH(object):
def __init__(self):
self.__provider = None
def __call__(self):
return \
(self.__provider
if self.__provider is not None else
DataStoreNOOP())
def select_db(self, connection, db, persistent=True):
self.__provider = \
DataStoreProvider() \
.get_data_store_handle(
connection,
db,
tinyAPI.env_cli() is not True and persistent
)
return self
dsh = __DSH()
| 24.47619 | 79 | 0.467899 |
__author__ = 'Michael Montero <mcmontero@gmail.com>'
from tinyAPI.base.data_store.provider import DataStoreNOOP
from tinyAPI.base.data_store.provider import DataStoreProvider
import tinyAPI
__all__ = [
'dsh'
]
class __DSH(object):
def __init__(self):
self.__provider = None
def __call__(self):
return \
(self.__provider
if self.__provider is not None else
DataStoreNOOP())
def select_db(self, connection, db, persistent=True):
self.__provider = \
DataStoreProvider() \
.get_data_store_handle(
connection,
db,
tinyAPI.env_cli() is not True and persistent
)
return self
dsh = __DSH()
| true | true |
1c36fe3469e8630cf2977884381c3dcbc4804759 | 4,498 | py | Python | alerta/auth/utils.py | middelthun/alerta | dd335ffe319dd235b68508105542a90627810326 | [
"Apache-2.0"
] | null | null | null | alerta/auth/utils.py | middelthun/alerta | dd335ffe319dd235b68508105542a90627810326 | [
"Apache-2.0"
] | null | null | null | alerta/auth/utils.py | middelthun/alerta | dd335ffe319dd235b68508105542a90627810326 | [
"Apache-2.0"
] | null | null | null | import logging
from datetime import datetime, timedelta
from flask import request, current_app
from six import text_type
from uuid import uuid4
from alerta.exceptions import ApiError, NoCustomerMatch
from alerta.models.customer import Customer
from alerta.models.permission import Permission
from alerta.models.token import Jwt
from alerta.utils.api import absolute_url
try:
import bcrypt # type: ignore
def generate_password_hash(password):
if isinstance(password, text_type):
password = password.encode('utf-8')
return bcrypt.hashpw(password, bcrypt.gensalt(prefix=b'2a')).decode('utf-8')
def check_password_hash(pwhash, password):
return bcrypt.checkpw(password.encode('utf-8'), pwhash.encode('utf-8'))
except ImportError: # Google App Engine
from werkzeug.security import generate_password_hash, check_password_hash
def not_authorized(allowed_setting, groups):
return (current_app.config['AUTH_REQUIRED']
and not ('*' in current_app.config[allowed_setting]
or set(current_app.config[allowed_setting]).intersection(set(groups))))
def get_customers(login, groups):
if current_app.config['CUSTOMER_VIEWS']:
try:
return Customer.lookup(login, groups)
except NoCustomerMatch as e:
raise ApiError(str(e), 403)
else:
return
def create_token(user_id, name, login, provider, customers, orgs=None, groups=None, roles=None, email=None, email_verified=None):
now = datetime.utcnow()
scopes = Permission.lookup(login, groups=(roles or []) + (groups or []) + (orgs or []))
return Jwt(
iss=request.url_root,
sub=user_id,
aud=current_app.config.get('OAUTH2_CLIENT_ID', None) or request.url_root,
exp=(now + timedelta(days=current_app.config['TOKEN_EXPIRE_DAYS'])),
nbf=now,
iat=now,
jti=str(uuid4()),
name=name,
preferred_username=login,
orgs=orgs,
roles=roles,
groups=groups,
provider=provider,
scopes=scopes,
email=email,
email_verified=email_verified,
customers=customers
)
try:
import smtplib
import socket
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
except ImportError:
pass
def send_confirmation(user, hash):
smtp_host = current_app.config['SMTP_HOST']
smtp_port = current_app.config['SMTP_PORT']
mail_localhost = current_app.config['MAIL_LOCALHOST']
ssl_key_file = current_app.config['SSL_KEY_FILE']
ssl_cert_file = current_app.config['SSL_CERT_FILE']
mail_from = current_app.config['MAIL_FROM']
smtp_username = current_app.config.get('SMTP_USERNAME', mail_from)
smtp_password = current_app.config['SMTP_PASSWORD']
msg = MIMEMultipart('related')
msg['Subject'] = "[Alerta] Please verify your email '%s'" % user.email
msg['From'] = mail_from
msg['To'] = user.email
msg.preamble = "[Alerta] Please verify your email '%s'" % user.email
text = 'Hello {name}!\n\n' \
'Please verify your email address is {email} by clicking on the link below:\n\n' \
'{url}\n\n' \
'You\'re receiving this email because you recently created a new Alerta account.' \
' If this wasn\'t you, please ignore this email.'.format(
name=user.name, email=user.email, url=absolute_url('/auth/confirm/' + hash)
)
msg_text = MIMEText(text, 'plain', 'utf-8')
msg.attach(msg_text)
try:
if current_app.config['SMTP_USE_SSL']:
mx = smtplib.SMTP_SSL(smtp_host, smtp_port, local_hostname=mail_localhost, keyfile=ssl_key_file, certfile=ssl_cert_file)
else:
mx = smtplib.SMTP(smtp_host, smtp_port, local_hostname=mail_localhost)
if current_app.config['DEBUG']:
mx.set_debuglevel(True)
mx.ehlo()
if current_app.config['SMTP_STARTTLS']:
mx.starttls()
if smtp_password:
mx.login(smtp_username, smtp_password)
mx.sendmail(mail_from, [user.email], msg.as_string())
mx.close()
except smtplib.SMTPException as e:
logging.error('Failed to send email : %s', str(e))
except (socket.error, socket.herror, socket.gaierror) as e:
logging.error('Mail server connection error: %s', str(e))
return
except Exception as e:
logging.error('Unhandled exception: %s', str(e))
| 33.819549 | 132 | 0.667408 | import logging
from datetime import datetime, timedelta
from flask import request, current_app
from six import text_type
from uuid import uuid4
from alerta.exceptions import ApiError, NoCustomerMatch
from alerta.models.customer import Customer
from alerta.models.permission import Permission
from alerta.models.token import Jwt
from alerta.utils.api import absolute_url
try:
import bcrypt
def generate_password_hash(password):
if isinstance(password, text_type):
password = password.encode('utf-8')
return bcrypt.hashpw(password, bcrypt.gensalt(prefix=b'2a')).decode('utf-8')
def check_password_hash(pwhash, password):
return bcrypt.checkpw(password.encode('utf-8'), pwhash.encode('utf-8'))
except ImportError:
from werkzeug.security import generate_password_hash, check_password_hash
def not_authorized(allowed_setting, groups):
return (current_app.config['AUTH_REQUIRED']
and not ('*' in current_app.config[allowed_setting]
or set(current_app.config[allowed_setting]).intersection(set(groups))))
def get_customers(login, groups):
if current_app.config['CUSTOMER_VIEWS']:
try:
return Customer.lookup(login, groups)
except NoCustomerMatch as e:
raise ApiError(str(e), 403)
else:
return
def create_token(user_id, name, login, provider, customers, orgs=None, groups=None, roles=None, email=None, email_verified=None):
now = datetime.utcnow()
scopes = Permission.lookup(login, groups=(roles or []) + (groups or []) + (orgs or []))
return Jwt(
iss=request.url_root,
sub=user_id,
aud=current_app.config.get('OAUTH2_CLIENT_ID', None) or request.url_root,
exp=(now + timedelta(days=current_app.config['TOKEN_EXPIRE_DAYS'])),
nbf=now,
iat=now,
jti=str(uuid4()),
name=name,
preferred_username=login,
orgs=orgs,
roles=roles,
groups=groups,
provider=provider,
scopes=scopes,
email=email,
email_verified=email_verified,
customers=customers
)
try:
import smtplib
import socket
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
except ImportError:
pass
def send_confirmation(user, hash):
smtp_host = current_app.config['SMTP_HOST']
smtp_port = current_app.config['SMTP_PORT']
mail_localhost = current_app.config['MAIL_LOCALHOST']
ssl_key_file = current_app.config['SSL_KEY_FILE']
ssl_cert_file = current_app.config['SSL_CERT_FILE']
mail_from = current_app.config['MAIL_FROM']
smtp_username = current_app.config.get('SMTP_USERNAME', mail_from)
smtp_password = current_app.config['SMTP_PASSWORD']
msg = MIMEMultipart('related')
msg['Subject'] = "[Alerta] Please verify your email '%s'" % user.email
msg['From'] = mail_from
msg['To'] = user.email
msg.preamble = "[Alerta] Please verify your email '%s'" % user.email
text = 'Hello {name}!\n\n' \
'Please verify your email address is {email} by clicking on the link below:\n\n' \
'{url}\n\n' \
'You\'re receiving this email because you recently created a new Alerta account.' \
' If this wasn\'t you, please ignore this email.'.format(
name=user.name, email=user.email, url=absolute_url('/auth/confirm/' + hash)
)
msg_text = MIMEText(text, 'plain', 'utf-8')
msg.attach(msg_text)
try:
if current_app.config['SMTP_USE_SSL']:
mx = smtplib.SMTP_SSL(smtp_host, smtp_port, local_hostname=mail_localhost, keyfile=ssl_key_file, certfile=ssl_cert_file)
else:
mx = smtplib.SMTP(smtp_host, smtp_port, local_hostname=mail_localhost)
if current_app.config['DEBUG']:
mx.set_debuglevel(True)
mx.ehlo()
if current_app.config['SMTP_STARTTLS']:
mx.starttls()
if smtp_password:
mx.login(smtp_username, smtp_password)
mx.sendmail(mail_from, [user.email], msg.as_string())
mx.close()
except smtplib.SMTPException as e:
logging.error('Failed to send email : %s', str(e))
except (socket.error, socket.herror, socket.gaierror) as e:
logging.error('Mail server connection error: %s', str(e))
return
except Exception as e:
logging.error('Unhandled exception: %s', str(e))
| true | true |
1c36fea3b329a56b54983a4c212098e2526b8ecd | 548 | py | Python | homeassistant/components/uptime/__init__.py | MrDelik/core | 93a66cc357b226389967668441000498a10453bb | [
"Apache-2.0"
] | 30,023 | 2016-04-13T10:17:53.000Z | 2020-03-02T12:56:31.000Z | homeassistant/components/uptime/__init__.py | MrDelik/core | 93a66cc357b226389967668441000498a10453bb | [
"Apache-2.0"
] | 24,710 | 2016-04-13T08:27:26.000Z | 2020-03-02T12:59:13.000Z | homeassistant/components/uptime/__init__.py | MrDelik/core | 93a66cc357b226389967668441000498a10453bb | [
"Apache-2.0"
] | 11,956 | 2016-04-13T18:42:31.000Z | 2020-03-02T09:32:12.000Z | """The Uptime integration."""
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from .const import PLATFORMS
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up from a config entry."""
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
| 32.235294 | 78 | 0.773723 | from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from .const import PLATFORMS
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
| true | true |
1c36ffae08435340133585e2a0680cd7af417f6e | 9,131 | py | Python | dcgan.py | csquigley/dcgan | 985280b5c6875062f728afe37cfb76d93a58dfb1 | [
"MIT"
] | null | null | null | dcgan.py | csquigley/dcgan | 985280b5c6875062f728afe37cfb76d93a58dfb1 | [
"MIT"
] | null | null | null | dcgan.py | csquigley/dcgan | 985280b5c6875062f728afe37cfb76d93a58dfb1 | [
"MIT"
] | null | null | null | from __future__ import print_function
#%matplotlib inline
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython.display import HTML
# Set random seed for reproducibility
manualSeed = random.randint(1, 10000)
print("Random Seed: ", manualSeed)
random.seed(manualSeed)
torch.manual_seed(manualSeed)
# Root directory for dataset
dataroot = "data/celeba"
# Number of workers for dataloader
workers = 2
# Batch size during training
batch_size = 128
# Spatial size of training images. All images will be resized to this
# size using a transformer.
image_size = 128
# Number of channels in the training images. For color images this is 3
nc = 3
# Size of z latent vector (i.e. size of generator input)
nz = 100
# Size of feature maps in generator
ngf = 64
# Size of feature maps in discriminator
ndf = 64
# Number of training epochs
num_epochs = 5
# Learning rate for optimizers
lr = 0.0002
# Beta1 hyperparam for Adam optimizers
beta1 = 0.5
# Number of GPUs available. Use 0 for CPU mode.
ngpu = 2
# We can use an image folder dataset the way we have it setup.
# Create the dataset
dataset = dset.ImageFolder(root=dataroot,
transform=transforms.Compose([
transforms.Resize(image_size),
transforms.CenterCrop(image_size),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
]))
# Create the dataloader
dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size,
shuffle=True, num_workers=workers)
# Decide which device we want to run on
device = torch.device("cuda:0" if (torch.cuda.is_available() and ngpu > 0) else "cpu")
# Plot some training images
real_batch = next(iter(dataloader))
plt.figure(figsize=(8,8))
plt.axis("off")
plt.title("Training Images")
plt.imshow(np.transpose(vutils.make_grid(real_batch[0].to(device)[:64], padding=2, normalize=True).cpu(),(1,2,0)))
# custom weights initialization called on netG and netD
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
nn.init.normal_(m.weight.data, 0.0, 0.02)
elif classname.find('BatchNorm') != -1:
nn.init.normal_(m.weight.data, 1.0, 0.02)
nn.init.constant_(m.bias.data, 0)
# Generator Code
class Generator(nn.Module):
def __init__(self, ngpu):
super(Generator, self).__init__()
self.ngpu = ngpu
self.main = nn.Sequential(
# input is Z, going into a convolution
nn.ConvTranspose2d( nz, ngf * 8, 4, 1, 0, bias=False),
nn.BatchNorm2d(ngf * 8),
nn.ReLU(True),
# state size. (ngf*8) x 4 x 4
nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf * 4),
nn.ReLU(True),
# state size. (ngf*4) x 8 x 8
nn.ConvTranspose2d( ngf * 4, ngf * 2, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf * 2),
nn.ReLU(True),
# state size. (ngf*2) x 16 x 16
nn.ConvTranspose2d( ngf * 2, ngf, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf),
nn.ReLU(True),
# state size. (ngf) x 32 x 32
nn.ConvTranspose2d( ngf, nc, 4, 2, 1, bias=False),
nn.Tanh()
# state size. (nc) x 64 x 64
)
def forward(self, input):
return self.main(input)
# Create the generator
netG = Generator(ngpu).to(device)
# Handle multi-gpu if desired
if (device.type == 'cuda') and (ngpu > 1):
netG = nn.DataParallel(netG, list(range(ngpu)))
# Apply the weights_init function to randomly initialize all weights
# to mean=0, stdev=0.02.
netG.apply(weights_init)
# Print the model
print(netG)
class Discriminator(nn.Module):
def __init__(self, ngpu):
super(Discriminator, self).__init__()
self.ngpu = ngpu
self.main = nn.Sequential(
# input is (nc) x 64 x 64
nn.Conv2d(nc, ndf, 4, 2, 1, bias=False),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ndf) x 32 x 32
nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=False),
nn.BatchNorm2d(ndf * 2),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ndf*2) x 16 x 16
nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 1, bias=False),
nn.BatchNorm2d(ndf * 4),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ndf*4) x 8 x 8
nn.Conv2d(ndf * 4, ndf * 8, 4, 2, 1, bias=False),
nn.BatchNorm2d(ndf * 8),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ndf*8) x 4 x 4
nn.Conv2d(ndf * 8, 1, 4, 1, 0, bias=False),
nn.Sigmoid()
)
def forward(self, input):
return self.main(input)
# Create the Discriminator
netD = Discriminator(ngpu).to(device)
# Handle multi-gpu if desired
if (device.type == 'cuda') and (ngpu > 1):
netD = nn.DataParallel(netD, list(range(ngpu)))
# Apply the weights_init function to randomly initialize all weights
# to mean=0, stdev=0.2.
netD.apply(weights_init)
# Print the model
print(netD)
# Initialize BCELoss function
criterion = nn.BCELoss()
# Create batch of latent vectors that we will use to visualize
# the progression of the generator
fixed_noise = torch.randn(64, nz, 1, 1, device=device)
# Establish convention for real and fake labels during training
real_label = 1.
fake_label = 0.
# Setup Adam optimizers for both G and D
optimizerD = optim.Adam(netD.parameters(), lr=lr, betas=(beta1, 0.999))
optimizerG = optim.Adam(netG.parameters(), lr=lr, betas=(beta1, 0.999))
# Training Loop
# Lists to keep track of progress
img_list = []
G_losses = []
D_losses = []
iters = 0
print("Starting Training Loop...")
# For each epoch
for epoch in range(num_epochs):
# For each batch in the dataloader
for i, data in enumerate(dataloader, 0):
############################
# (1) Update D network: maximize log(D(x)) + log(1 - D(G(z)))
###########################
## Train with all-real batch
netD.zero_grad()
# Format batch
real_cpu = data[0].to(device)
b_size = real_cpu.size(0)
label = torch.full((b_size,), real_label, dtype=torch.float, device=device)
# Forward pass real batch through D
output = netD(real_cpu).view(-1)
# Calculate loss on all-real batch
errD_real = criterion(output, label)
# Calculate gradients for D in backward pass
errD_real.backward()
D_x = output.mean().item()
## Train with all-fake batch
# Generate batch of latent vectors
noise = torch.randn(b_size, nz, 1, 1, device=device)
# Generate fake image batch with G
fake = netG(noise)
label.fill_(fake_label)
# Classify all fake batch with D
output = netD(fake.detach()).view(-1)
# Calculate D's loss on the all-fake batch
errD_fake = criterion(output, label)
# Calculate the gradients for this batch, accumulated (summed) with previous gradients
errD_fake.backward()
D_G_z1 = output.mean().item()
# Compute error of D as sum over the fake and the real batches
errD = errD_real + errD_fake
# Update D
optimizerD.step()
############################
# (2) Update G network: maximize log(D(G(z)))
###########################
netG.zero_grad()
label.fill_(real_label) # fake labels are real for generator cost
# Since we just updated D, perform another forward pass of all-fake batch through D
output = netD(fake).view(-1)
# Calculate G's loss based on this output
errG = criterion(output, label)
# Calculate gradients for G
errG.backward()
D_G_z2 = output.mean().item()
# Update G
optimizerG.step()
# Output training stats
if i % 50 == 0:
print('[%d/%d][%d/%d]\tLoss_D: %.4f\tLoss_G: %.4f\tD(x): %.4f\tD(G(z)): %.4f / %.4f'
% (epoch, num_epochs, i, len(dataloader),
errD.item(), errG.item(), D_x, D_G_z1, D_G_z2))
# Save Losses for plotting later
G_losses.append(errG.item())
D_losses.append(errD.item())
# Check how the generator is doing by saving G's output on fixed_noise
if (iters % 500 == 0) or ((epoch == num_epochs-1) and (i == len(dataloader)-1)):
with torch.no_grad():
fake = netG(fixed_noise).detach().cpu()
img_list.append(vutils.make_grid(fake, padding=2, normalize=True))
iters += 1
| 32.963899 | 114 | 0.606724 | from __future__ import print_function
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython.display import HTML
manualSeed = random.randint(1, 10000)
print("Random Seed: ", manualSeed)
random.seed(manualSeed)
torch.manual_seed(manualSeed)
dataroot = "data/celeba"
workers = 2
batch_size = 128
image_size = 128
nc = 3
nz = 100
ngf = 64
ndf = 64
num_epochs = 5
lr = 0.0002
beta1 = 0.5
ngpu = 2
dataset = dset.ImageFolder(root=dataroot,
transform=transforms.Compose([
transforms.Resize(image_size),
transforms.CenterCrop(image_size),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
]))
dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size,
shuffle=True, num_workers=workers)
device = torch.device("cuda:0" if (torch.cuda.is_available() and ngpu > 0) else "cpu")
real_batch = next(iter(dataloader))
plt.figure(figsize=(8,8))
plt.axis("off")
plt.title("Training Images")
plt.imshow(np.transpose(vutils.make_grid(real_batch[0].to(device)[:64], padding=2, normalize=True).cpu(),(1,2,0)))
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
nn.init.normal_(m.weight.data, 0.0, 0.02)
elif classname.find('BatchNorm') != -1:
nn.init.normal_(m.weight.data, 1.0, 0.02)
nn.init.constant_(m.bias.data, 0)
class Generator(nn.Module):
def __init__(self, ngpu):
super(Generator, self).__init__()
self.ngpu = ngpu
self.main = nn.Sequential(
nn.ConvTranspose2d( nz, ngf * 8, 4, 1, 0, bias=False),
nn.BatchNorm2d(ngf * 8),
nn.ReLU(True),
nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf * 4),
nn.ReLU(True),
nn.ConvTranspose2d( ngf * 4, ngf * 2, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf * 2),
nn.ReLU(True),
nn.ConvTranspose2d( ngf * 2, ngf, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf),
nn.ReLU(True),
nn.ConvTranspose2d( ngf, nc, 4, 2, 1, bias=False),
nn.Tanh()
)
def forward(self, input):
return self.main(input)
netG = Generator(ngpu).to(device)
if (device.type == 'cuda') and (ngpu > 1):
netG = nn.DataParallel(netG, list(range(ngpu)))
netG.apply(weights_init)
print(netG)
class Discriminator(nn.Module):
def __init__(self, ngpu):
super(Discriminator, self).__init__()
self.ngpu = ngpu
self.main = nn.Sequential(
nn.Conv2d(nc, ndf, 4, 2, 1, bias=False),
nn.LeakyReLU(0.2, inplace=True),
nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=False),
nn.BatchNorm2d(ndf * 2),
nn.LeakyReLU(0.2, inplace=True),
nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 1, bias=False),
nn.BatchNorm2d(ndf * 4),
nn.LeakyReLU(0.2, inplace=True),
nn.Conv2d(ndf * 4, ndf * 8, 4, 2, 1, bias=False),
nn.BatchNorm2d(ndf * 8),
nn.LeakyReLU(0.2, inplace=True),
nn.Conv2d(ndf * 8, 1, 4, 1, 0, bias=False),
nn.Sigmoid()
)
def forward(self, input):
return self.main(input)
netD = Discriminator(ngpu).to(device)
if (device.type == 'cuda') and (ngpu > 1):
netD = nn.DataParallel(netD, list(range(ngpu)))
netD.apply(weights_init)
print(netD)
criterion = nn.BCELoss()
fixed_noise = torch.randn(64, nz, 1, 1, device=device)
real_label = 1.
fake_label = 0.
optimizerD = optim.Adam(netD.parameters(), lr=lr, betas=(beta1, 0.999))
optimizerG = optim.Adam(netG.parameters(), lr=lr, betas=(beta1, 0.999))
img_list = []
G_losses = []
D_losses = []
iters = 0
print("Starting Training Loop...")
for epoch in range(num_epochs):
for i, data in enumerate(dataloader, 0):
D_G_z1 = output.mean().item()
# Compute error of D as sum over the fake and the real batches
errD = errD_real + errD_fake
# Update D
optimizerD.step()
############################
# (2) Update G network: maximize log(D(G(z)))
###########################
netG.zero_grad()
label.fill_(real_label) # fake labels are real for generator cost
# Since we just updated D, perform another forward pass of all-fake batch through D
output = netD(fake).view(-1)
# Calculate G's loss based on this output
errG = criterion(output, label)
errG.backward()
D_G_z2 = output.mean().item()
optimizerG.step()
if i % 50 == 0:
print('[%d/%d][%d/%d]\tLoss_D: %.4f\tLoss_G: %.4f\tD(x): %.4f\tD(G(z)): %.4f / %.4f'
% (epoch, num_epochs, i, len(dataloader),
errD.item(), errG.item(), D_x, D_G_z1, D_G_z2))
G_losses.append(errG.item())
D_losses.append(errD.item())
if (iters % 500 == 0) or ((epoch == num_epochs-1) and (i == len(dataloader)-1)):
with torch.no_grad():
fake = netG(fixed_noise).detach().cpu()
img_list.append(vutils.make_grid(fake, padding=2, normalize=True))
iters += 1
| true | true |
1c37008de8c4cd8a308668060f85a86108ea0e09 | 429 | py | Python | rename_list_midi_files.py | pyweeker/my_audio_toolbox | 49afbd00a5bbb3fd6f2a19d2a531f18ce7ab432e | [
"MIT"
] | null | null | null | rename_list_midi_files.py | pyweeker/my_audio_toolbox | 49afbd00a5bbb3fd6f2a19d2a531f18ce7ab432e | [
"MIT"
] | null | null | null | rename_list_midi_files.py | pyweeker/my_audio_toolbox | 49afbd00a5bbb3fd6f2a19d2a531f18ce7ab432e | [
"MIT"
] | null | null | null | import os
cwd = os.getcwd()
files = [f for f in os.listdir(cwd) if os.path.isfile(f)]
print(files)
for file in files:
if file.endswith('.mid'):
filename, file_extension = os.path.splitext(file)
print(f" filename {filename}")
#print(f" file_extension {file_extension}")
#os.rename(filename, filename[2:-2])
os.rename(filename+'.mid', filename[2:-2]+'.mid')
| 16.5 | 57 | 0.589744 | import os
cwd = os.getcwd()
files = [f for f in os.listdir(cwd) if os.path.isfile(f)]
print(files)
for file in files:
if file.endswith('.mid'):
filename, file_extension = os.path.splitext(file)
print(f" filename {filename}")
os.rename(filename+'.mid', filename[2:-2]+'.mid')
| true | true |
1c3701584832569ff925fc02a62c5db6b1631211 | 1,144 | py | Python | setup.py | saumalya75/parseval | d5e8c0c6cab2b8c236d1f728314eeb0a804401a7 | [
"MIT"
] | 1 | 2020-08-02T10:24:56.000Z | 2020-08-02T10:24:56.000Z | setup.py | saumalya75/parseval | d5e8c0c6cab2b8c236d1f728314eeb0a804401a7 | [
"MIT"
] | 25 | 2020-07-25T14:51:52.000Z | 2020-08-29T15:26:04.000Z | setup.py | saumalya75/parseval | d5e8c0c6cab2b8c236d1f728314eeb0a804401a7 | [
"MIT"
] | null | null | null | from setuptools import setup
def _long_description():
with open("README.md", "r") as fh:
return fh.read()
setup(
name='parseval',
packages=["parseval"],
version="1.0.0",
license='MIT',
description='parseval is a data validation tool for python. It provides numerous API to parse and validate data for all native data-types. it handles data on atomic level and focuses on validation part primarily.',
author='Saumalya Sarkar',
author_email='saumalya75@gmail.com',
url='https://parseval.readthedocs.io/en/latest/',
download_url='https://github.com/saumalya75/parseval/archive/v1.0.0.tar.gz',
keywords=['python'],
install_requires=[],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Topic :: Software Development',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8'
],
long_description=_long_description(),
long_description_content_type="text/markdown"
)
| 34.666667 | 218 | 0.663462 | from setuptools import setup
def _long_description():
with open("README.md", "r") as fh:
return fh.read()
setup(
name='parseval',
packages=["parseval"],
version="1.0.0",
license='MIT',
description='parseval is a data validation tool for python. It provides numerous API to parse and validate data for all native data-types. it handles data on atomic level and focuses on validation part primarily.',
author='Saumalya Sarkar',
author_email='saumalya75@gmail.com',
url='https://parseval.readthedocs.io/en/latest/',
download_url='https://github.com/saumalya75/parseval/archive/v1.0.0.tar.gz',
keywords=['python'],
install_requires=[],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Topic :: Software Development',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8'
],
long_description=_long_description(),
long_description_content_type="text/markdown"
)
| true | true |
1c370199f03f0316f9ba7ccc1ad8d26703c09ed0 | 330 | py | Python | hashtable/451 sort characters by frequency.py | windowssocket/py_leetcode | 241dbf8d7dab7db5215c2526321fcdb378b45492 | [
"Apache-2.0"
] | 3 | 2018-05-29T02:29:40.000Z | 2020-02-05T03:28:16.000Z | hashtable/451 sort characters by frequency.py | xidongc/py_leetcode | 241dbf8d7dab7db5215c2526321fcdb378b45492 | [
"Apache-2.0"
] | 1 | 2019-03-08T13:22:32.000Z | 2019-03-08T13:22:32.000Z | hashtable/451 sort characters by frequency.py | xidongc/py_leetcode | 241dbf8d7dab7db5215c2526321fcdb378b45492 | [
"Apache-2.0"
] | 3 | 2018-05-29T11:50:24.000Z | 2018-11-27T12:31:01.000Z | import collections
class Solution(object):
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
count = collections.Counter(s).most_common()
res = ''
for c, v in count:
res += c * v
return res
s = Solution()
print(s.frequencySort('tree'))
| 18.333333 | 52 | 0.512121 | import collections
class Solution(object):
def frequencySort(self, s):
count = collections.Counter(s).most_common()
res = ''
for c, v in count:
res += c * v
return res
s = Solution()
print(s.frequencySort('tree'))
| true | true |
1c370219ff490e2774c463d12a828e17f522874b | 569 | py | Python | src/glod/api/counterparty_leaf.py | gordon-elliott/glod | a381e21455d05d9c005942a3dee4ac67e10f366a | [
"MIT"
] | null | null | null | src/glod/api/counterparty_leaf.py | gordon-elliott/glod | a381e21455d05d9c005942a3dee4ac67e10f366a | [
"MIT"
] | 1 | 2021-03-10T16:48:34.000Z | 2021-03-10T16:48:34.000Z | src/glod/api/counterparty_leaf.py | gordon-elliott/glod | a381e21455d05d9c005942a3dee4ac67e10f366a | [
"MIT"
] | null | null | null | __copyright__ = 'Copyright(c) Gordon Elliott 2018'
"""
"""
import graphene
from a_tuin.api import id_with_session, OBJECT_REFERENCE_MAP, leaf_class_interfaces
from glod.db.counterparty import Counterparty, CounterpartyInstanceQuery
class CounterpartyLeaf(graphene.ObjectType):
class Meta:
interfaces = leaf_class_interfaces(Counterparty)
@classmethod
@id_with_session
def get_node(cls, id_, context, info, session):
return CounterpartyInstanceQuery(session).instance(id_)
OBJECT_REFERENCE_MAP['counterparty'] = CounterpartyLeaf
| 24.73913 | 83 | 0.778559 | __copyright__ = 'Copyright(c) Gordon Elliott 2018'
import graphene
from a_tuin.api import id_with_session, OBJECT_REFERENCE_MAP, leaf_class_interfaces
from glod.db.counterparty import Counterparty, CounterpartyInstanceQuery
class CounterpartyLeaf(graphene.ObjectType):
class Meta:
interfaces = leaf_class_interfaces(Counterparty)
@classmethod
@id_with_session
def get_node(cls, id_, context, info, session):
return CounterpartyInstanceQuery(session).instance(id_)
OBJECT_REFERENCE_MAP['counterparty'] = CounterpartyLeaf
| true | true |
1c37029903262d6febcc779f9f35a9c6597d9f4a | 1,918 | py | Python | tools/intogen/lib/python/intogensm/ma/service.py | globusgenomics/galaxy | 7caf74d9700057587b3e3434c64e82c5b16540f1 | [
"CC-BY-3.0"
] | 1 | 2021-02-05T13:19:58.000Z | 2021-02-05T13:19:58.000Z | chapter2/intogen-mutations/master/lib/python/intogensm/ma/service.py | chris-zen/phd-thesis | 1eefdff8e7ca1910304e27ae42551dc64496b101 | [
"Unlicense"
] | null | null | null | chapter2/intogen-mutations/master/lib/python/intogensm/ma/service.py | chris-zen/phd-thesis | 1eefdff8e7ca1910304e27ae42551dc64496b101 | [
"Unlicense"
] | null | null | null | import re
import tempfile
from bgcore.request import Request
from intogensm.utils import cast_type
from model import MaResult
class MaService(object):
HOST = "mutationassessor.org"
ISSUE_UNKNOWN_ID_TYPE = re.compile(r"unknown ID type")
ISSUE_REFERENCE_ALLELE = re.compile(r"reference allele: ([ACGT])")
def __init__(self, assembly, cache_path=None, max_retries=3, max_freq=3):
self.assembly = assembly
self.cache_path = cache_path
self.__restful = Request(max_retries=max_retries, max_freq=max_freq)
def get(self, chr, strand, start, ref, alt, var_id=None):
done = False
while not done:
response = self.__restful.get("http://{0}/".format(self.HOST),
params={
"cm" : "var",
"var" : "{0},{1},{2},{3},{4}".format(self.assembly, chr, start, ref, alt),
"frm" : "txt",
"fts" : "all"
})
if response is None:
return None
hdr = response.readline().rstrip("\n").split("\t")
fields = response.readline().rstrip("\n").split("\t")
hlen = len(hdr)
if hlen == 0 or hlen != len(fields):
return None
r = {}
for i in range(hlen):
r[hdr[i]] = fields[i] if len(fields[i]) > 0 else None
mapping_issue = r["Mapping issue"]
if mapping_issue is not None:
if self.ISSUE_UNKNOWN_ID_TYPE.match(mapping_issue):
return None
m = self.ISSUE_REFERENCE_ALLELE.match(mapping_issue)
if m is not None:
ref = m.group(1)
strand = {"+" : "-", "-" : "+"}[strand]
continue
#TODO check: raise Exception("Infinite mapping issue for reference allele")
done = True
uniprot=r["Uniprot"]
fi_score=cast_type(r["FI score"], float)
snps_pos=r["SNPs@position"]
if uniprot is not None or fi_score is not None or snps_pos is not None:
return MaResult(
var_id=var_id, chr=chr, start=start, ref=ref, alt=alt,
uniprot=uniprot, fi_score=fi_score, snps_pos=snps_pos)
else:
return None
def close(self):
pass | 26.273973 | 80 | 0.662148 | import re
import tempfile
from bgcore.request import Request
from intogensm.utils import cast_type
from model import MaResult
class MaService(object):
HOST = "mutationassessor.org"
ISSUE_UNKNOWN_ID_TYPE = re.compile(r"unknown ID type")
ISSUE_REFERENCE_ALLELE = re.compile(r"reference allele: ([ACGT])")
def __init__(self, assembly, cache_path=None, max_retries=3, max_freq=3):
self.assembly = assembly
self.cache_path = cache_path
self.__restful = Request(max_retries=max_retries, max_freq=max_freq)
def get(self, chr, strand, start, ref, alt, var_id=None):
done = False
while not done:
response = self.__restful.get("http://{0}/".format(self.HOST),
params={
"cm" : "var",
"var" : "{0},{1},{2},{3},{4}".format(self.assembly, chr, start, ref, alt),
"frm" : "txt",
"fts" : "all"
})
if response is None:
return None
hdr = response.readline().rstrip("\n").split("\t")
fields = response.readline().rstrip("\n").split("\t")
hlen = len(hdr)
if hlen == 0 or hlen != len(fields):
return None
r = {}
for i in range(hlen):
r[hdr[i]] = fields[i] if len(fields[i]) > 0 else None
mapping_issue = r["Mapping issue"]
if mapping_issue is not None:
if self.ISSUE_UNKNOWN_ID_TYPE.match(mapping_issue):
return None
m = self.ISSUE_REFERENCE_ALLELE.match(mapping_issue)
if m is not None:
ref = m.group(1)
strand = {"+" : "-", "-" : "+"}[strand]
continue
done = True
uniprot=r["Uniprot"]
fi_score=cast_type(r["FI score"], float)
snps_pos=r["SNPs@position"]
if uniprot is not None or fi_score is not None or snps_pos is not None:
return MaResult(
var_id=var_id, chr=chr, start=start, ref=ref, alt=alt,
uniprot=uniprot, fi_score=fi_score, snps_pos=snps_pos)
else:
return None
def close(self):
pass | true | true |
1c3702a4725dc95ec597e423aab944458ad0b795 | 15,261 | py | Python | homeassistant/setup.py | charithmadhuranga/core | 06329a2f43ba82df6e0c6250fa6965f9259cfe8a | [
"Apache-2.0"
] | 1 | 2021-12-02T23:28:50.000Z | 2021-12-02T23:28:50.000Z | homeassistant/setup.py | charithmadhuranga/core | 06329a2f43ba82df6e0c6250fa6965f9259cfe8a | [
"Apache-2.0"
] | 277 | 2021-10-04T06:39:33.000Z | 2021-12-28T22:04:17.000Z | homeassistant/setup.py | charithmadhuranga/core | 06329a2f43ba82df6e0c6250fa6965f9259cfe8a | [
"Apache-2.0"
] | 1 | 2022-01-12T22:14:01.000Z | 2022-01-12T22:14:01.000Z | """All methods needed to bootstrap a Home Assistant instance."""
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable, Generator, Iterable
import contextlib
import logging.handlers
from timeit import default_timer as timer
from types import ModuleType
from typing import Any
from . import config as conf_util, core, loader, requirements
from .config import async_notify_setup_error
from .const import (
EVENT_COMPONENT_LOADED,
EVENT_HOMEASSISTANT_START,
PLATFORM_FORMAT,
Platform,
)
from .core import CALLBACK_TYPE
from .exceptions import HomeAssistantError
from .helpers.typing import ConfigType
from .util import dt as dt_util, ensure_unique_string
_LOGGER = logging.getLogger(__name__)
ATTR_COMPONENT = "component"
BASE_PLATFORMS = {platform.value for platform in Platform}
DATA_SETUP_DONE = "setup_done"
DATA_SETUP_STARTED = "setup_started"
DATA_SETUP_TIME = "setup_time"
DATA_SETUP = "setup_tasks"
DATA_DEPS_REQS = "deps_reqs_processed"
SLOW_SETUP_WARNING = 10
SLOW_SETUP_MAX_WAIT = 300
@core.callback
def async_set_domains_to_be_loaded(hass: core.HomeAssistant, domains: set[str]) -> None:
"""Set domains that are going to be loaded from the config.
This will allow us to properly handle after_dependencies.
"""
hass.data[DATA_SETUP_DONE] = {domain: asyncio.Event() for domain in domains}
def setup_component(hass: core.HomeAssistant, domain: str, config: ConfigType) -> bool:
"""Set up a component and all its dependencies."""
return asyncio.run_coroutine_threadsafe(
async_setup_component(hass, domain, config), hass.loop
).result()
async def async_setup_component(
hass: core.HomeAssistant, domain: str, config: ConfigType
) -> bool:
"""Set up a component and all its dependencies.
This method is a coroutine.
"""
if domain in hass.config.components:
return True
setup_tasks = hass.data.setdefault(DATA_SETUP, {})
if domain in setup_tasks:
return await setup_tasks[domain] # type: ignore
task = setup_tasks[domain] = hass.async_create_task(
_async_setup_component(hass, domain, config)
)
try:
return await task
finally:
if domain in hass.data.get(DATA_SETUP_DONE, {}):
hass.data[DATA_SETUP_DONE].pop(domain).set()
async def _async_process_dependencies(
hass: core.HomeAssistant, config: ConfigType, integration: loader.Integration
) -> bool:
"""Ensure all dependencies are set up."""
dependencies_tasks = {
dep: hass.loop.create_task(async_setup_component(hass, dep, config))
for dep in integration.dependencies
if dep not in hass.config.components
}
after_dependencies_tasks = {}
to_be_loaded = hass.data.get(DATA_SETUP_DONE, {})
for dep in integration.after_dependencies:
if (
dep not in dependencies_tasks
and dep in to_be_loaded
and dep not in hass.config.components
):
after_dependencies_tasks[dep] = hass.loop.create_task(
to_be_loaded[dep].wait()
)
if not dependencies_tasks and not after_dependencies_tasks:
return True
if dependencies_tasks:
_LOGGER.debug(
"Dependency %s will wait for dependencies %s",
integration.domain,
list(dependencies_tasks),
)
if after_dependencies_tasks:
_LOGGER.debug(
"Dependency %s will wait for after dependencies %s",
integration.domain,
list(after_dependencies_tasks),
)
async with hass.timeout.async_freeze(integration.domain):
results = await asyncio.gather(
*dependencies_tasks.values(), *after_dependencies_tasks.values()
)
failed = [
domain for idx, domain in enumerate(dependencies_tasks) if not results[idx]
]
if failed:
_LOGGER.error(
"Unable to set up dependencies of %s. Setup failed for dependencies: %s",
integration.domain,
", ".join(failed),
)
return False
return True
async def _async_setup_component(
hass: core.HomeAssistant, domain: str, config: ConfigType
) -> bool:
"""Set up a component for Home Assistant.
This method is a coroutine.
"""
def log_error(msg: str, link: str | None = None) -> None:
"""Log helper."""
_LOGGER.error("Setup failed for %s: %s", domain, msg)
async_notify_setup_error(hass, domain, link)
try:
integration = await loader.async_get_integration(hass, domain)
except loader.IntegrationNotFound:
log_error("Integration not found.")
return False
if integration.disabled:
log_error(f"Dependency is disabled - {integration.disabled}")
return False
# Validate all dependencies exist and there are no circular dependencies
if not await integration.resolve_dependencies():
return False
# Process requirements as soon as possible, so we can import the component
# without requiring imports to be in functions.
try:
await async_process_deps_reqs(hass, config, integration)
except HomeAssistantError as err:
log_error(str(err), integration.documentation)
return False
# Some integrations fail on import because they call functions incorrectly.
# So we do it before validating config to catch these errors.
try:
component = integration.get_component()
except ImportError as err:
log_error(f"Unable to import component: {err}", integration.documentation)
return False
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Setup failed for %s: unknown error", domain)
return False
processed_config = await conf_util.async_process_component_config(
hass, config, integration
)
if processed_config is None:
log_error("Invalid config.", integration.documentation)
return False
start = timer()
_LOGGER.info("Setting up %s", domain)
with async_start_setup(hass, [domain]):
if hasattr(component, "PLATFORM_SCHEMA"):
# Entity components have their own warning
warn_task = None
else:
warn_task = hass.loop.call_later(
SLOW_SETUP_WARNING,
_LOGGER.warning,
"Setup of %s is taking over %s seconds.",
domain,
SLOW_SETUP_WARNING,
)
task = None
result: Any | bool = True
try:
if hasattr(component, "async_setup"):
task = component.async_setup(hass, processed_config)
elif hasattr(component, "setup"):
# This should not be replaced with hass.async_add_executor_job because
# we don't want to track this task in case it blocks startup.
task = hass.loop.run_in_executor(
None, component.setup, hass, processed_config
)
elif not hasattr(component, "async_setup_entry"):
log_error("No setup or config entry setup function defined.")
return False
if task:
async with hass.timeout.async_timeout(SLOW_SETUP_MAX_WAIT, domain):
result = await task
except asyncio.TimeoutError:
_LOGGER.error(
"Setup of %s is taking longer than %s seconds."
" Startup will proceed without waiting any longer",
domain,
SLOW_SETUP_MAX_WAIT,
)
return False
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Error during setup of component %s", domain)
async_notify_setup_error(hass, domain, integration.documentation)
return False
finally:
end = timer()
if warn_task:
warn_task.cancel()
_LOGGER.info("Setup of domain %s took %.1f seconds", domain, end - start)
if result is False:
log_error("Integration failed to initialize.")
return False
if result is not True:
log_error(
f"Integration {domain!r} did not return boolean if setup was "
"successful. Disabling component."
)
return False
# Flush out async_setup calling create_task. Fragile but covered by test.
await asyncio.sleep(0)
await hass.config_entries.flow.async_wait_init_flow_finish(domain)
await asyncio.gather(
*(
entry.async_setup(hass, integration=integration)
for entry in hass.config_entries.async_entries(domain)
)
)
hass.config.components.add(domain)
# Cleanup
if domain in hass.data[DATA_SETUP]:
hass.data[DATA_SETUP].pop(domain)
hass.bus.async_fire(EVENT_COMPONENT_LOADED, {ATTR_COMPONENT: domain})
return True
async def async_prepare_setup_platform(
hass: core.HomeAssistant, hass_config: ConfigType, domain: str, platform_name: str
) -> ModuleType | None:
"""Load a platform and makes sure dependencies are setup.
This method is a coroutine.
"""
platform_path = PLATFORM_FORMAT.format(domain=domain, platform=platform_name)
def log_error(msg: str) -> None:
"""Log helper."""
_LOGGER.error("Unable to prepare setup for platform %s: %s", platform_path, msg)
async_notify_setup_error(hass, platform_path)
try:
integration = await loader.async_get_integration(hass, platform_name)
except loader.IntegrationNotFound:
log_error("Integration not found")
return None
# Process deps and reqs as soon as possible, so that requirements are
# available when we import the platform.
try:
await async_process_deps_reqs(hass, hass_config, integration)
except HomeAssistantError as err:
log_error(str(err))
return None
try:
platform = integration.get_platform(domain)
except ImportError as exc:
log_error(f"Platform not found ({exc}).")
return None
# Already loaded
if platform_path in hass.config.components:
return platform
# Platforms cannot exist on their own, they are part of their integration.
# If the integration is not set up yet, and can be set up, set it up.
if integration.domain not in hass.config.components:
try:
component = integration.get_component()
except ImportError as exc:
log_error(f"Unable to import the component ({exc}).")
return None
if (
hasattr(component, "setup") or hasattr(component, "async_setup")
) and not await async_setup_component(hass, integration.domain, hass_config):
log_error("Unable to set up component.")
return None
return platform
async def async_process_deps_reqs(
hass: core.HomeAssistant, config: ConfigType, integration: loader.Integration
) -> None:
"""Process all dependencies and requirements for a module.
Module is a Python module of either a component or platform.
"""
if (processed := hass.data.get(DATA_DEPS_REQS)) is None:
processed = hass.data[DATA_DEPS_REQS] = set()
elif integration.domain in processed:
return
if not await _async_process_dependencies(hass, config, integration):
raise HomeAssistantError("Could not set up all dependencies.")
if not hass.config.skip_pip and integration.requirements:
async with hass.timeout.async_freeze(integration.domain):
await requirements.async_get_integration_with_requirements(
hass, integration.domain
)
processed.add(integration.domain)
@core.callback
def async_when_setup(
hass: core.HomeAssistant,
component: str,
when_setup_cb: Callable[[core.HomeAssistant, str], Awaitable[None]],
) -> None:
"""Call a method when a component is setup."""
_async_when_setup(hass, component, when_setup_cb, False)
@core.callback
def async_when_setup_or_start(
hass: core.HomeAssistant,
component: str,
when_setup_cb: Callable[[core.HomeAssistant, str], Awaitable[None]],
) -> None:
"""Call a method when a component is setup or state is fired."""
_async_when_setup(hass, component, when_setup_cb, True)
@core.callback
def _async_when_setup(
hass: core.HomeAssistant,
component: str,
when_setup_cb: Callable[[core.HomeAssistant, str], Awaitable[None]],
start_event: bool,
) -> None:
"""Call a method when a component is setup or the start event fires."""
async def when_setup() -> None:
"""Call the callback."""
try:
await when_setup_cb(hass, component)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Error handling when_setup callback for %s", component)
if component in hass.config.components:
hass.async_create_task(when_setup())
return
listeners: list[CALLBACK_TYPE] = []
async def _matched_event(event: core.Event) -> None:
"""Call the callback when we matched an event."""
for listener in listeners:
listener()
await when_setup()
async def _loaded_event(event: core.Event) -> None:
"""Call the callback if we loaded the expected component."""
if event.data[ATTR_COMPONENT] == component:
await _matched_event(event)
listeners.append(hass.bus.async_listen(EVENT_COMPONENT_LOADED, _loaded_event))
if start_event:
listeners.append(
hass.bus.async_listen(EVENT_HOMEASSISTANT_START, _matched_event)
)
@core.callback
def async_get_loaded_integrations(hass: core.HomeAssistant) -> set[str]:
"""Return the complete list of loaded integrations."""
integrations = set()
for component in hass.config.components:
if "." not in component:
integrations.add(component)
continue
domain, platform = component.split(".", 1)
if domain in BASE_PLATFORMS:
integrations.add(platform)
return integrations
@contextlib.contextmanager
def async_start_setup(
hass: core.HomeAssistant, components: Iterable[str]
) -> Generator[None, None, None]:
"""Keep track of when setup starts and finishes."""
setup_started = hass.data.setdefault(DATA_SETUP_STARTED, {})
started = dt_util.utcnow()
unique_components = {}
for domain in components:
unique = ensure_unique_string(domain, setup_started)
unique_components[unique] = domain
setup_started[unique] = started
yield
setup_time = hass.data.setdefault(DATA_SETUP_TIME, {})
time_taken = dt_util.utcnow() - started
for unique, domain in unique_components.items():
del setup_started[unique]
if "." in domain:
_, integration = domain.split(".", 1)
else:
integration = domain
if integration in setup_time:
setup_time[integration] += time_taken
else:
setup_time[integration] = time_taken
| 33.176087 | 88 | 0.659197 | from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable, Generator, Iterable
import contextlib
import logging.handlers
from timeit import default_timer as timer
from types import ModuleType
from typing import Any
from . import config as conf_util, core, loader, requirements
from .config import async_notify_setup_error
from .const import (
EVENT_COMPONENT_LOADED,
EVENT_HOMEASSISTANT_START,
PLATFORM_FORMAT,
Platform,
)
from .core import CALLBACK_TYPE
from .exceptions import HomeAssistantError
from .helpers.typing import ConfigType
from .util import dt as dt_util, ensure_unique_string
_LOGGER = logging.getLogger(__name__)
ATTR_COMPONENT = "component"
BASE_PLATFORMS = {platform.value for platform in Platform}
DATA_SETUP_DONE = "setup_done"
DATA_SETUP_STARTED = "setup_started"
DATA_SETUP_TIME = "setup_time"
DATA_SETUP = "setup_tasks"
DATA_DEPS_REQS = "deps_reqs_processed"
SLOW_SETUP_WARNING = 10
SLOW_SETUP_MAX_WAIT = 300
@core.callback
def async_set_domains_to_be_loaded(hass: core.HomeAssistant, domains: set[str]) -> None:
hass.data[DATA_SETUP_DONE] = {domain: asyncio.Event() for domain in domains}
def setup_component(hass: core.HomeAssistant, domain: str, config: ConfigType) -> bool:
return asyncio.run_coroutine_threadsafe(
async_setup_component(hass, domain, config), hass.loop
).result()
async def async_setup_component(
hass: core.HomeAssistant, domain: str, config: ConfigType
) -> bool:
if domain in hass.config.components:
return True
setup_tasks = hass.data.setdefault(DATA_SETUP, {})
if domain in setup_tasks:
return await setup_tasks[domain]
task = setup_tasks[domain] = hass.async_create_task(
_async_setup_component(hass, domain, config)
)
try:
return await task
finally:
if domain in hass.data.get(DATA_SETUP_DONE, {}):
hass.data[DATA_SETUP_DONE].pop(domain).set()
async def _async_process_dependencies(
hass: core.HomeAssistant, config: ConfigType, integration: loader.Integration
) -> bool:
dependencies_tasks = {
dep: hass.loop.create_task(async_setup_component(hass, dep, config))
for dep in integration.dependencies
if dep not in hass.config.components
}
after_dependencies_tasks = {}
to_be_loaded = hass.data.get(DATA_SETUP_DONE, {})
for dep in integration.after_dependencies:
if (
dep not in dependencies_tasks
and dep in to_be_loaded
and dep not in hass.config.components
):
after_dependencies_tasks[dep] = hass.loop.create_task(
to_be_loaded[dep].wait()
)
if not dependencies_tasks and not after_dependencies_tasks:
return True
if dependencies_tasks:
_LOGGER.debug(
"Dependency %s will wait for dependencies %s",
integration.domain,
list(dependencies_tasks),
)
if after_dependencies_tasks:
_LOGGER.debug(
"Dependency %s will wait for after dependencies %s",
integration.domain,
list(after_dependencies_tasks),
)
async with hass.timeout.async_freeze(integration.domain):
results = await asyncio.gather(
*dependencies_tasks.values(), *after_dependencies_tasks.values()
)
failed = [
domain for idx, domain in enumerate(dependencies_tasks) if not results[idx]
]
if failed:
_LOGGER.error(
"Unable to set up dependencies of %s. Setup failed for dependencies: %s",
integration.domain,
", ".join(failed),
)
return False
return True
async def _async_setup_component(
hass: core.HomeAssistant, domain: str, config: ConfigType
) -> bool:
def log_error(msg: str, link: str | None = None) -> None:
_LOGGER.error("Setup failed for %s: %s", domain, msg)
async_notify_setup_error(hass, domain, link)
try:
integration = await loader.async_get_integration(hass, domain)
except loader.IntegrationNotFound:
log_error("Integration not found.")
return False
if integration.disabled:
log_error(f"Dependency is disabled - {integration.disabled}")
return False
if not await integration.resolve_dependencies():
return False
try:
await async_process_deps_reqs(hass, config, integration)
except HomeAssistantError as err:
log_error(str(err), integration.documentation)
return False
try:
component = integration.get_component()
except ImportError as err:
log_error(f"Unable to import component: {err}", integration.documentation)
return False
except Exception:
_LOGGER.exception("Setup failed for %s: unknown error", domain)
return False
processed_config = await conf_util.async_process_component_config(
hass, config, integration
)
if processed_config is None:
log_error("Invalid config.", integration.documentation)
return False
start = timer()
_LOGGER.info("Setting up %s", domain)
with async_start_setup(hass, [domain]):
if hasattr(component, "PLATFORM_SCHEMA"):
warn_task = None
else:
warn_task = hass.loop.call_later(
SLOW_SETUP_WARNING,
_LOGGER.warning,
"Setup of %s is taking over %s seconds.",
domain,
SLOW_SETUP_WARNING,
)
task = None
result: Any | bool = True
try:
if hasattr(component, "async_setup"):
task = component.async_setup(hass, processed_config)
elif hasattr(component, "setup"):
task = hass.loop.run_in_executor(
None, component.setup, hass, processed_config
)
elif not hasattr(component, "async_setup_entry"):
log_error("No setup or config entry setup function defined.")
return False
if task:
async with hass.timeout.async_timeout(SLOW_SETUP_MAX_WAIT, domain):
result = await task
except asyncio.TimeoutError:
_LOGGER.error(
"Setup of %s is taking longer than %s seconds."
" Startup will proceed without waiting any longer",
domain,
SLOW_SETUP_MAX_WAIT,
)
return False
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Error during setup of component %s", domain)
async_notify_setup_error(hass, domain, integration.documentation)
return False
finally:
end = timer()
if warn_task:
warn_task.cancel()
_LOGGER.info("Setup of domain %s took %.1f seconds", domain, end - start)
if result is False:
log_error("Integration failed to initialize.")
return False
if result is not True:
log_error(
f"Integration {domain!r} did not return boolean if setup was "
"successful. Disabling component."
)
return False
# Flush out async_setup calling create_task. Fragile but covered by test.
await asyncio.sleep(0)
await hass.config_entries.flow.async_wait_init_flow_finish(domain)
await asyncio.gather(
*(
entry.async_setup(hass, integration=integration)
for entry in hass.config_entries.async_entries(domain)
)
)
hass.config.components.add(domain)
# Cleanup
if domain in hass.data[DATA_SETUP]:
hass.data[DATA_SETUP].pop(domain)
hass.bus.async_fire(EVENT_COMPONENT_LOADED, {ATTR_COMPONENT: domain})
return True
async def async_prepare_setup_platform(
hass: core.HomeAssistant, hass_config: ConfigType, domain: str, platform_name: str
) -> ModuleType | None:
platform_path = PLATFORM_FORMAT.format(domain=domain, platform=platform_name)
def log_error(msg: str) -> None:
_LOGGER.error("Unable to prepare setup for platform %s: %s", platform_path, msg)
async_notify_setup_error(hass, platform_path)
try:
integration = await loader.async_get_integration(hass, platform_name)
except loader.IntegrationNotFound:
log_error("Integration not found")
return None
# Process deps and reqs as soon as possible, so that requirements are
# available when we import the platform.
try:
await async_process_deps_reqs(hass, hass_config, integration)
except HomeAssistantError as err:
log_error(str(err))
return None
try:
platform = integration.get_platform(domain)
except ImportError as exc:
log_error(f"Platform not found ({exc}).")
return None
# Already loaded
if platform_path in hass.config.components:
return platform
# Platforms cannot exist on their own, they are part of their integration.
# If the integration is not set up yet, and can be set up, set it up.
if integration.domain not in hass.config.components:
try:
component = integration.get_component()
except ImportError as exc:
log_error(f"Unable to import the component ({exc}).")
return None
if (
hasattr(component, "setup") or hasattr(component, "async_setup")
) and not await async_setup_component(hass, integration.domain, hass_config):
log_error("Unable to set up component.")
return None
return platform
async def async_process_deps_reqs(
hass: core.HomeAssistant, config: ConfigType, integration: loader.Integration
) -> None:
if (processed := hass.data.get(DATA_DEPS_REQS)) is None:
processed = hass.data[DATA_DEPS_REQS] = set()
elif integration.domain in processed:
return
if not await _async_process_dependencies(hass, config, integration):
raise HomeAssistantError("Could not set up all dependencies.")
if not hass.config.skip_pip and integration.requirements:
async with hass.timeout.async_freeze(integration.domain):
await requirements.async_get_integration_with_requirements(
hass, integration.domain
)
processed.add(integration.domain)
@core.callback
def async_when_setup(
hass: core.HomeAssistant,
component: str,
when_setup_cb: Callable[[core.HomeAssistant, str], Awaitable[None]],
) -> None:
_async_when_setup(hass, component, when_setup_cb, False)
@core.callback
def async_when_setup_or_start(
hass: core.HomeAssistant,
component: str,
when_setup_cb: Callable[[core.HomeAssistant, str], Awaitable[None]],
) -> None:
_async_when_setup(hass, component, when_setup_cb, True)
@core.callback
def _async_when_setup(
hass: core.HomeAssistant,
component: str,
when_setup_cb: Callable[[core.HomeAssistant, str], Awaitable[None]],
start_event: bool,
) -> None:
async def when_setup() -> None:
try:
await when_setup_cb(hass, component)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Error handling when_setup callback for %s", component)
if component in hass.config.components:
hass.async_create_task(when_setup())
return
listeners: list[CALLBACK_TYPE] = []
async def _matched_event(event: core.Event) -> None:
for listener in listeners:
listener()
await when_setup()
async def _loaded_event(event: core.Event) -> None:
if event.data[ATTR_COMPONENT] == component:
await _matched_event(event)
listeners.append(hass.bus.async_listen(EVENT_COMPONENT_LOADED, _loaded_event))
if start_event:
listeners.append(
hass.bus.async_listen(EVENT_HOMEASSISTANT_START, _matched_event)
)
@core.callback
def async_get_loaded_integrations(hass: core.HomeAssistant) -> set[str]:
integrations = set()
for component in hass.config.components:
if "." not in component:
integrations.add(component)
continue
domain, platform = component.split(".", 1)
if domain in BASE_PLATFORMS:
integrations.add(platform)
return integrations
@contextlib.contextmanager
def async_start_setup(
hass: core.HomeAssistant, components: Iterable[str]
) -> Generator[None, None, None]:
setup_started = hass.data.setdefault(DATA_SETUP_STARTED, {})
started = dt_util.utcnow()
unique_components = {}
for domain in components:
unique = ensure_unique_string(domain, setup_started)
unique_components[unique] = domain
setup_started[unique] = started
yield
setup_time = hass.data.setdefault(DATA_SETUP_TIME, {})
time_taken = dt_util.utcnow() - started
for unique, domain in unique_components.items():
del setup_started[unique]
if "." in domain:
_, integration = domain.split(".", 1)
else:
integration = domain
if integration in setup_time:
setup_time[integration] += time_taken
else:
setup_time[integration] = time_taken
| true | true |
1c3702fa54938d319ceb2262c8dde1b46ab76ac7 | 3,223 | py | Python | tests/test_tools/generators.py | Saran-nns/cunumeric | 3472109aa3fd6a9d42409586efd39dcb5924e0b5 | [
"Apache-2.0"
] | 118 | 2021-04-12T18:06:59.000Z | 2021-10-12T21:30:24.000Z | tests/test_tools/generators.py | Saran-nns/cunumeric | 3472109aa3fd6a9d42409586efd39dcb5924e0b5 | [
"Apache-2.0"
] | 51 | 2021-04-21T10:40:13.000Z | 2021-09-10T22:09:26.000Z | tests/test_tools/generators.py | Saran-nns/cunumeric | 3472109aa3fd6a9d42409586efd39dcb5924e0b5 | [
"Apache-2.0"
] | 9 | 2021-04-14T03:07:42.000Z | 2021-09-22T17:02:53.000Z | # Copyright 2021 NVIDIA Corporation
#
# 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 itertools import permutations, product
import numpy as np
from legate.core import LEGATE_MAX_DIM
def scalar_gen(lib, val):
"""
Generates different kinds of scalar-like arrays that contain the given
value.
"""
# pure scalar values
yield lib.array(val)
# ()-shape arrays
yield lib.full((), val)
for ndim in range(1, LEGATE_MAX_DIM + 1):
# singleton arrays
yield lib.full(ndim * (1,), val)
# singleton slices of larger arrays
yield lib.full(ndim * (5,), val)[ndim * (slice(1, 2),)]
def mk_0to1_array(lib, shape):
"""
Constructs an array of the required shape, containing (in C order)
sequential real values uniformly spaced in the range (0,1].
"""
size = np.prod(shape)
if size == 1:
# Avoid zeros, since those are more likely to cause arithmetic issues
# or produce degenerate outputs.
return lib.full(shape, 0.5)
return mk_seq_array(lib, shape) / size
def mk_seq_array(lib, shape):
"""
Constructs an array of the required shape, containing (in C order)
sequential integer values starting from 1.
"""
arr = lib.zeros(shape, dtype=int)
size = np.prod(shape)
# Don't return the reshaped array directly, instead use it to update
# the contents of an existing array of the same shape, thus producing a
# Store without transformations, that has been tiled in the natural way
arr[:] = lib.arange(1, size + 1).reshape(shape)
return arr
def broadcasts_to(lib, tgt_shape, mk_array=mk_0to1_array):
"""
Generates a collection of arrays that will broadcast to the given shape.
"""
past_first = False
for mask in product([True, False], repeat=len(tgt_shape)):
if not past_first:
past_first = True
continue
src_shape = tuple(
d if keep else 1 for (d, keep) in zip(tgt_shape, mask)
)
yield mk_array(lib, src_shape)
def permutes_to(lib, tgt_shape, mk_array=mk_0to1_array):
"""
Generates all the possible ways that an array can be transposed to meet a
given shape.
All arrays returned will have the same shape, `tgt_shape`, but are the
result of tranposing a base array of a different shape.
"""
past_first = False
for axes in permutations(range(len(tgt_shape))):
if not past_first:
past_first = True
continue
src_shape = [-1] * len(tgt_shape)
for (i, j) in enumerate(axes):
src_shape[j] = tgt_shape[i]
src_shape = tuple(src_shape)
yield mk_array(lib, src_shape).transpose(axes)
| 32.555556 | 77 | 0.66615 |
from itertools import permutations, product
import numpy as np
from legate.core import LEGATE_MAX_DIM
def scalar_gen(lib, val):
yield lib.array(val)
yield lib.full((), val)
for ndim in range(1, LEGATE_MAX_DIM + 1):
yield lib.full(ndim * (1,), val)
yield lib.full(ndim * (5,), val)[ndim * (slice(1, 2),)]
def mk_0to1_array(lib, shape):
size = np.prod(shape)
if size == 1:
return lib.full(shape, 0.5)
return mk_seq_array(lib, shape) / size
def mk_seq_array(lib, shape):
arr = lib.zeros(shape, dtype=int)
size = np.prod(shape)
# the contents of an existing array of the same shape, thus producing a
# Store without transformations, that has been tiled in the natural way
arr[:] = lib.arange(1, size + 1).reshape(shape)
return arr
def broadcasts_to(lib, tgt_shape, mk_array=mk_0to1_array):
past_first = False
for mask in product([True, False], repeat=len(tgt_shape)):
if not past_first:
past_first = True
continue
src_shape = tuple(
d if keep else 1 for (d, keep) in zip(tgt_shape, mask)
)
yield mk_array(lib, src_shape)
def permutes_to(lib, tgt_shape, mk_array=mk_0to1_array):
past_first = False
for axes in permutations(range(len(tgt_shape))):
if not past_first:
past_first = True
continue
src_shape = [-1] * len(tgt_shape)
for (i, j) in enumerate(axes):
src_shape[j] = tgt_shape[i]
src_shape = tuple(src_shape)
yield mk_array(lib, src_shape).transpose(axes)
| true | true |
1c37031ff8fe7181319220c17e93cf7cc1a98777 | 3,868 | py | Python | Lab4/Code/DataPreprocess/preprocess.py | keithnull/EE101 | 298f2c1dc3c1d6437815525632c0f56b13602f3d | [
"MIT"
] | 2 | 2018-06-12T07:14:33.000Z | 2019-06-03T01:53:13.000Z | Lab4/Code/DataPreprocess/preprocess.py | keithnull/Learning-EE101 | 298f2c1dc3c1d6437815525632c0f56b13602f3d | [
"MIT"
] | null | null | null | Lab4/Code/DataPreprocess/preprocess.py | keithnull/Learning-EE101 | 298f2c1dc3c1d6437815525632c0f56b13602f3d | [
"MIT"
] | null | null | null | # coding:utf8
from load_data import load_data, timer
from feature import FeatureExtracter
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
import pymysql
from itertools import combinations
@timer
def train_SVM(X_train, y_train):
model = SVC(kernel="linear", C=1, gamma=0.125)
#model = LogisticRegression()
print("Start to train the SVM model.")
model.fit(X_train, y_train)
print("Finished.")
return model
def score_SVM(model, X_test, y_test):
return model.score(X_test, y_test)
def connect_to_db(user, password, db, host="localhost", port=3306, charset="utf8"):
connection = pymysql.connect(host=host, user=user, password=password, db=db, port=port, charset=charset)
cursor = connection.cursor()
return connection, cursor
def process_one_paper(paper_id, feature_extracter, db_cursor, model):
query_for_authors = """SELECT authorid FROM paper_author_affiliation WHERE paperid="{0}";""".format(paper_id)
try:
db_cursor.execute(query_for_authors)
authors = [row[0] for row in db_cursor.fetchall()]
authors.sort() # notice
# print(authors)
# input()
for pair in combinations(authors, 2):
author1, author2 = pair
query_for_existence = """SELECT * FROM author_relationship WHERE authorid1="{0}" AND authorid2="{1}";""".format(author1, author2)
existence = db_cursor.execute(query_for_existence)
# print(existence)
if not existence:
feature = feature_extracter.extract_feature(author1, author2)
# print(feature)
relation = model.predict([feature])[0]
# print(relation)
if(relation == 0): # predict whether author2 is the instructor of author1
feature = feature_extracter.extract_feature(author2, author1)
relation = -model.predict([feature])[0]
query_to_insert = """INSERT INTO author_relationship VALUES("{0}","{1}",{2},{3})""".format(author1, author2, 1, relation)
db_cursor.execute(query_to_insert)
else:
# print("HERE!!!!!!")
times = db_cursor.fetchone()[2]+1
# print(times)
query_to_update = """
UPDATE author_relationship SET cooperationtimes={0} WHERE authorid1="{1}" AND authorid2="{2}";""".format(times, author1, author2)
db_cursor.execute(query_to_update)
except Exception as e:
print(e)
def get_all_papers(db_cursor):
query = """SELECT paperid FROM papers;"""
try:
result_num = db_cursor.execute(query)
print("Result num:{0}".format(result_num))
for i in range(result_num):
yield db_cursor.fetchone()[0]
except:
print("ERROR when trying to get all papers.")
@timer
def main():
X_train, y_train, X_test, y_test = load_data("")
model = train_SVM(X_train, y_train)
feature_extracter = FeatureExtracter()
feature_extracter.connect("root", "", "academicdb")
db_connection1, db_cursor1 = connect_to_db("root", "", "academicdb")
db_connection2, db_cursor2 = connect_to_db("root", "", "academicdb")
cnt = 0
for paper in get_all_papers(db_cursor1):
try:
# print(paper)
cnt += 1
print("\r{0}".format(cnt), end="")
process_one_paper(paper, feature_extracter, db_cursor2, model)
if(cnt % 100 == 0):
db_connection2.commit()
except:
print("ERROR")
if __name__ == '__main__':
main()
'''
Start to load training data from feature file.
Runtime:0.239s
Start to load testinging data from feature file.
Runtime:0.147s
Start to train the SVM model.
Finished.
Runtime:4.348s
Result num:98215
98215Runtime:2473.511s
'''
| 33.929825 | 141 | 0.635212 |
from load_data import load_data, timer
from feature import FeatureExtracter
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
import pymysql
from itertools import combinations
@timer
def train_SVM(X_train, y_train):
model = SVC(kernel="linear", C=1, gamma=0.125)
print("Start to train the SVM model.")
model.fit(X_train, y_train)
print("Finished.")
return model
def score_SVM(model, X_test, y_test):
return model.score(X_test, y_test)
def connect_to_db(user, password, db, host="localhost", port=3306, charset="utf8"):
connection = pymysql.connect(host=host, user=user, password=password, db=db, port=port, charset=charset)
cursor = connection.cursor()
return connection, cursor
def process_one_paper(paper_id, feature_extracter, db_cursor, model):
query_for_authors = """SELECT authorid FROM paper_author_affiliation WHERE paperid="{0}";""".format(paper_id)
try:
db_cursor.execute(query_for_authors)
authors = [row[0] for row in db_cursor.fetchall()]
authors.sort()
for pair in combinations(authors, 2):
author1, author2 = pair
query_for_existence = """SELECT * FROM author_relationship WHERE authorid1="{0}" AND authorid2="{1}";""".format(author1, author2)
existence = db_cursor.execute(query_for_existence)
if not existence:
feature = feature_extracter.extract_feature(author1, author2)
relation = model.predict([feature])[0]
if(relation == 0):
feature = feature_extracter.extract_feature(author2, author1)
relation = -model.predict([feature])[0]
query_to_insert = """INSERT INTO author_relationship VALUES("{0}","{1}",{2},{3})""".format(author1, author2, 1, relation)
db_cursor.execute(query_to_insert)
else:
times = db_cursor.fetchone()[2]+1
query_to_update = """
UPDATE author_relationship SET cooperationtimes={0} WHERE authorid1="{1}" AND authorid2="{2}";""".format(times, author1, author2)
db_cursor.execute(query_to_update)
except Exception as e:
print(e)
def get_all_papers(db_cursor):
query = """SELECT paperid FROM papers;"""
try:
result_num = db_cursor.execute(query)
print("Result num:{0}".format(result_num))
for i in range(result_num):
yield db_cursor.fetchone()[0]
except:
print("ERROR when trying to get all papers.")
@timer
def main():
X_train, y_train, X_test, y_test = load_data("")
model = train_SVM(X_train, y_train)
feature_extracter = FeatureExtracter()
feature_extracter.connect("root", "", "academicdb")
db_connection1, db_cursor1 = connect_to_db("root", "", "academicdb")
db_connection2, db_cursor2 = connect_to_db("root", "", "academicdb")
cnt = 0
for paper in get_all_papers(db_cursor1):
try:
cnt += 1
print("\r{0}".format(cnt), end="")
process_one_paper(paper, feature_extracter, db_cursor2, model)
if(cnt % 100 == 0):
db_connection2.commit()
except:
print("ERROR")
if __name__ == '__main__':
main()
| true | true |
1c3703c14d9cc8f1d2454aa4174d30f3785cd729 | 2,134 | py | Python | src/euchre/table.py | lawhitmi/euchre | 26ab5d7d182872cf27188acb67b6d9df7e927bc3 | [
"MIT"
] | null | null | null | src/euchre/table.py | lawhitmi/euchre | 26ab5d7d182872cf27188acb67b6d9df7e927bc3 | [
"MIT"
] | null | null | null | src/euchre/table.py | lawhitmi/euchre | 26ab5d7d182872cf27188acb67b6d9df7e927bc3 | [
"MIT"
] | null | null | null |
class Table:
"""
Controls the table printout and trick scoring
"""
def __init__(self, user, computer, bidcard=None):
self.computer = computer
self.user = user
self.bidcard = bidcard
self.trumpsuit = ""
self.tricks = {self.user: 0, self.computer: 0}
def show_table(self, playedcard1="", playedcard2="", score=None):
"""
Prints the playing table, Computer Hand, Field, User Hand, Scores, etc.
:param playedcard1: Card type Card played by first player
:param playedcard2: Card type Card played by second player
:param score: dict Individual trick score
:return: None
"""
print("*"*80)
print("Score: User " + str(self.tricks[self.user]) + " Computer " + str(self.tricks[self.computer])
+ " Trump Suit: " + str(self.trumpsuit))
scoreline = ""
if score:
scoreline += "Hand Score: "
for i, j in score.items():
scoreline += str(i.name + ": " + str(j) + " ")
print(scoreline)
print(self.computer)
if playedcard1:
if playedcard2:
print(str(playedcard1) + " " + str(playedcard2))
else:
print(playedcard1)
elif self.bidcard:
print("Bidcard: " + str(self.bidcard))
else:
print("")
print(self.user)
def flip_bidcard(self):
"""
Removes bidcard when not picked up
:return: None
"""
self.bidcard = ""
def set_bidcard(self, card):
"""
Setter method for storing the card on which to bid.
:param card: Card type
:return: None
"""
self.bidcard = card
def set_trumpsuit(self, suit):
"""
Setter method for trick phase trumpsuit
:param suit: string i.e. 'Spades'
:return: None
"""
self.trumpsuit = suit
def clear_table(self):
"""
Resets table for next round
:return: None
"""
self.trumpsuit = ""
self.bidcard = ""
| 28.453333 | 107 | 0.527648 |
class Table:
def __init__(self, user, computer, bidcard=None):
self.computer = computer
self.user = user
self.bidcard = bidcard
self.trumpsuit = ""
self.tricks = {self.user: 0, self.computer: 0}
def show_table(self, playedcard1="", playedcard2="", score=None):
print("*"*80)
print("Score: User " + str(self.tricks[self.user]) + " Computer " + str(self.tricks[self.computer])
+ " Trump Suit: " + str(self.trumpsuit))
scoreline = ""
if score:
scoreline += "Hand Score: "
for i, j in score.items():
scoreline += str(i.name + ": " + str(j) + " ")
print(scoreline)
print(self.computer)
if playedcard1:
if playedcard2:
print(str(playedcard1) + " " + str(playedcard2))
else:
print(playedcard1)
elif self.bidcard:
print("Bidcard: " + str(self.bidcard))
else:
print("")
print(self.user)
def flip_bidcard(self):
self.bidcard = ""
def set_bidcard(self, card):
self.bidcard = card
def set_trumpsuit(self, suit):
self.trumpsuit = suit
def clear_table(self):
self.trumpsuit = ""
self.bidcard = ""
| true | true |
1c37044b4e4177925e4f73319dd19a41dcfe4d41 | 2,897 | py | Python | CPX_GBoard/universal/code.py | albinger/Adafruit_Learning_System_Guides | 4fe2da261fe5d1ca282b86bd3b93ee1466346fa7 | [
"MIT"
] | null | null | null | CPX_GBoard/universal/code.py | albinger/Adafruit_Learning_System_Guides | 4fe2da261fe5d1ca282b86bd3b93ee1466346fa7 | [
"MIT"
] | null | null | null | CPX_GBoard/universal/code.py | albinger/Adafruit_Learning_System_Guides | 4fe2da261fe5d1ca282b86bd3b93ee1466346fa7 | [
"MIT"
] | null | null | null | # SPDX-FileCopyrightText: 2018 Dave Astels for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
Circuit Playground Express GBoard: universal/customizable version
Adafruit invests time and resources providing this open source code.
Please support Adafruit and open source hardware by purchasing
products from Adafruit!
Written by Dave Astels for Adafruit Industries
Copyright (c) 2018 Adafruit Industries
Licensed under the MIT license.
All text above must be included in any redistribution.
"""
# pylint: disable=unused-import
import time
from adafruit_circuitplayground.express import cpx
# Uncomment the next 2 lines if you want to use external buttons
# from digitalio import DigitalInOut, Direction, Pull
# import board
# Uncomment the next 3 lines if you want to use HID output
# from adafruit_hid.keyboard import Keyboard
# from adafruit_hid.keycode import Keycode
# import usb_hid
DOT_DURATION = 0.20
DASH_DURATION = 0.5
# You can adjust this to get the level of sensitivity you want.
# Uncomment the next line if you want to use capacitive touch.
# cpx.adjust_touch_threshold(100)
# Uncomment the next 6 lines if you want to use external buttons
# button_a = DigitalInOut(board.A4)
# button_a.direction = Direction.INPUT
# button_a.pull = Pull.UP
# button_b = DigitalInOut(board.A3)
# button_b.direction = Direction.INPUT
# button_b.pull = Pull.UP
# Uncomment the next line if you want to use HID output
# kbd = Keyboard(usb_hid.devices)
def touch_a():
# Uncomment the next line if you want to use the on-board buttons
# return cpx.button_a
# Uncomment the next line if you want to use capacitive touch
# return cpx.touch_A4
# Uncomment the next line if you want to use external buttons
# return not button_a.value
return False # a fail-safe to keep python happy
def touch_b():
# Uncomment the next line if you want to use the on-board buttons
# return cpx.button_b
# Uncomment the next line if you want to use capacitive touch
# return cpx.touch_A3
# Uncomment the next line if you want to use external buttons
# return not button_b.value
return False # a fail-safe to keep python happy
def dot():
# Uncomment the next 2 lines if you want tones played
# cpx.play_tone(4000, DOT_DURATION)
# time.sleep(0.1)
# Uncomment the next line if you want to use HID output
# kbd.send(Keycode.PERIOD)
pass # a fail-safe to keep python happy
def dash():
# Uncomment the next 2 lines if you want tones played
# cpx.play_tone(4000, DASH_DURATION)
# time.sleep(0.1)
# Uncomment the next line if you want to use HID output
# kbd.send(Keycode.MINUS)
pass # a fail-safe to keep python happy
while True:
if touch_a():
dot()
while touch_a():
pass
elif touch_b():
dash()
while touch_b():
pass
| 26.577982 | 69 | 0.722126 |
import time
from adafruit_circuitplayground.express import cpx
DOT_DURATION = 0.20
DASH_DURATION = 0.5
def touch_a():
return False
def touch_b():
return False
def dot():
pass
def dash():
pass
while True:
if touch_a():
dot()
while touch_a():
pass
elif touch_b():
dash()
while touch_b():
pass
| true | true |
1c37069c91fd874e7d4b8325001cf39f9c41f9ae | 743 | py | Python | BB8-MindWave-TestColor.py | titos-carrasco/MindWave-BB8-Python | f1d4b9bb3f7bdac08b01f5a795c3fd2772bb014e | [
"MIT"
] | null | null | null | BB8-MindWave-TestColor.py | titos-carrasco/MindWave-BB8-Python | f1d4b9bb3f7bdac08b01f5a795c3fd2772bb014e | [
"MIT"
] | null | null | null | BB8-MindWave-TestColor.py | titos-carrasco/MindWave-BB8-Python | f1d4b9bb3f7bdac08b01f5a795c3fd2772bb014e | [
"MIT"
] | null | null | null | #!/usr/bin/env python
from __future__ import print_function
import time
from rcr.SpheroBB8 import SpheroBB8
from rcr.mindwave.MindWave import *
sphero = SpheroBB8.Sphero( 'FA:8B:91:F4:9D:22' )
mw = MindWave( "/dev/ttyUSB0", 1000, 0X0000 )
if( mw.connect() ):
mwd = MindWaveData()
sphero.setRGBLedOutput( 0, 0, 0 )
last = 0
t = time.time()
while( time.time() - t < 60 ):
mw.fillMindWaveData( mwd )
attention = int( ( mwd.attentionESense * 255 )/100.0 )
print( mwd.poorSignalQuality, mwd.attentionESense, attention )
if( attention != last ):
sphero.setRGBLedOutput( 0, attention, 0 )
last = attention
time.sleep( 0.001 )
mw.disconnect()
sphero.close()
| 26.535714 | 70 | 0.629879 |
from __future__ import print_function
import time
from rcr.SpheroBB8 import SpheroBB8
from rcr.mindwave.MindWave import *
sphero = SpheroBB8.Sphero( 'FA:8B:91:F4:9D:22' )
mw = MindWave( "/dev/ttyUSB0", 1000, 0X0000 )
if( mw.connect() ):
mwd = MindWaveData()
sphero.setRGBLedOutput( 0, 0, 0 )
last = 0
t = time.time()
while( time.time() - t < 60 ):
mw.fillMindWaveData( mwd )
attention = int( ( mwd.attentionESense * 255 )/100.0 )
print( mwd.poorSignalQuality, mwd.attentionESense, attention )
if( attention != last ):
sphero.setRGBLedOutput( 0, attention, 0 )
last = attention
time.sleep( 0.001 )
mw.disconnect()
sphero.close()
| true | true |
1c370808538c07636c42fc8d7996e45d389055b3 | 2,165 | py | Python | qriscloud/_vendor/ldap3/protocol/sasl/plain.py | UQ-RCC/uq-globus-tools | a5191cd223b841fd404eddc90402947247b6504f | [
"Apache-2.0"
] | 2 | 2021-12-15T21:58:43.000Z | 2021-12-15T22:17:26.000Z | qriscloud/_vendor/ldap3/protocol/sasl/plain.py | UQ-RCC/uq-globus-tools | a5191cd223b841fd404eddc90402947247b6504f | [
"Apache-2.0"
] | null | null | null | qriscloud/_vendor/ldap3/protocol/sasl/plain.py | UQ-RCC/uq-globus-tools | a5191cd223b841fd404eddc90402947247b6504f | [
"Apache-2.0"
] | 1 | 2021-12-19T17:02:02.000Z | 2021-12-19T17:02:02.000Z | """
"""
# Created on 2014.01.04
#
# Author: Giovanni Cannata
#
# Copyright 2014 - 2020 Giovanni Cannata
#
# This file is part of ldap3.
#
# ldap3 is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ldap3 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with ldap3 in the COPYING and COPYING.LESSER files.
# If not, see <http://www.gnu.org/licenses/>.
# payload for PLAIN mechanism
# message = [authzid] UTF8NUL authcid UTF8NUL passwd
# authcid = 1*SAFE ; MUST accept up to 255 octets
# authzid = 1*SAFE ; MUST accept up to 255 octets
# passwd = 1*SAFE ; MUST accept up to 255 octets
# UTF8NUL = %x00 ; UTF-8 encoded NUL character
#
# SAFE = UTF1 / UTF2 / UTF3 / UTF4
# ;; any UTF-8 encoded Unicode character except NUL
#
# UTF1 = %x01-7F ;; except NUL
# UTF2 = %xC2-DF UTF0
# UTF3 = %xE0 %xA0-BF UTF0 / %xE1-EC 2(UTF0) /
# %xED %x80-9F UTF0 / %xEE-EF 2(UTF0)
# UTF4 = %xF0 %x90-BF 2(UTF0) / %xF1-F3 3(UTF0) /
# %xF4 %x80-8F 2(UTF0)
# UTF0 = %x80-BF
from ...protocol.sasl.sasl import send_sasl_negotiation
from .sasl import sasl_prep
from ...utils.conv import to_raw, to_unicode
def sasl_plain(connection, controls):
authzid = connection.sasl_credentials[0]
authcid = connection.sasl_credentials[1]
passwd = connection.sasl_credentials[2]
payload = b''
if authzid:
payload += to_raw(sasl_prep(to_unicode(authzid)))
payload += b'\0'
if authcid:
payload += to_raw(sasl_prep(to_unicode(authcid)))
payload += b'\0'
if passwd:
payload += to_raw(sasl_prep(to_unicode(passwd)))
result = send_sasl_negotiation(connection, controls, payload)
return result
| 30.492958 | 74 | 0.67806 |
from ...protocol.sasl.sasl import send_sasl_negotiation
from .sasl import sasl_prep
from ...utils.conv import to_raw, to_unicode
def sasl_plain(connection, controls):
authzid = connection.sasl_credentials[0]
authcid = connection.sasl_credentials[1]
passwd = connection.sasl_credentials[2]
payload = b''
if authzid:
payload += to_raw(sasl_prep(to_unicode(authzid)))
payload += b'\0'
if authcid:
payload += to_raw(sasl_prep(to_unicode(authcid)))
payload += b'\0'
if passwd:
payload += to_raw(sasl_prep(to_unicode(passwd)))
result = send_sasl_negotiation(connection, controls, payload)
return result
| true | true |
1c370ad31b9d3ffba5a530eca0f05b3ede73c539 | 1,061 | py | Python | examples/cattools_merging_cat.py | CHEN-Zhaohui/geoist | 06a00db3e0ed3d92abf3e45b7b3bfbef6a858a5b | [
"MIT"
] | null | null | null | examples/cattools_merging_cat.py | CHEN-Zhaohui/geoist | 06a00db3e0ed3d92abf3e45b7b3bfbef6a858a5b | [
"MIT"
] | null | null | null | examples/cattools_merging_cat.py | CHEN-Zhaohui/geoist | 06a00db3e0ed3d92abf3e45b7b3bfbef6a858a5b | [
"MIT"
] | null | null | null | """
EXAMPLE 5 - CATALOGUE MERGING
"""
from os.path import dirname
from geoist.cattools import Catalogue as Cat
from geoist.cattools import Selection as Sel
from geoist.cattools import MagRules as MR
#-----------------------------------------------------------------------------------------
# Import Catalogues
pathname = dirname(__file__)
Db1 = Cat.Database()
Db1.Load(pathname+'/data/isc-rev-africa-select.bin')
Db2 = Cat.Database()
Db2.Load(pathname+'/data/isc-gem-v3.bin')
#-----------------------------------------------------------------------------------------
# Duplicate findings
# Between Catalogues
Db3, Log = Sel.MergeDuplicate(Db1,Db2,Twin=60.,Swin=50.,Log=1, Owrite=False)
# Within a catalogue
Log = Sel.MergeDuplicate(Db1,Twin=60.,Swin=50.,Log=1)
#-----------------------------------------------------------------------------------------
# Magnitude conversion
# Apply to all agency
Sel.MagConvert(Db1,'*',['Ms','MS'],'Mw',MR.Ms_Mw_Lin_DiGiacomo2015)
# Apply to single agency
Sel.MagConvert(Db1,'ISC','Ms','Mw',MR.Ms_Mw_Exp_DiGiacomo2015)
| 30.314286 | 90 | 0.556079 | from os.path import dirname
from geoist.cattools import Catalogue as Cat
from geoist.cattools import Selection as Sel
from geoist.cattools import MagRules as MR
pathname = dirname(__file__)
Db1 = Cat.Database()
Db1.Load(pathname+'/data/isc-rev-africa-select.bin')
Db2 = Cat.Database()
Db2.Load(pathname+'/data/isc-gem-v3.bin')
Db3, Log = Sel.MergeDuplicate(Db1,Db2,Twin=60.,Swin=50.,Log=1, Owrite=False)
Log = Sel.MergeDuplicate(Db1,Twin=60.,Swin=50.,Log=1)
Sel.MagConvert(Db1,'*',['Ms','MS'],'Mw',MR.Ms_Mw_Lin_DiGiacomo2015)
Sel.MagConvert(Db1,'ISC','Ms','Mw',MR.Ms_Mw_Exp_DiGiacomo2015)
| true | true |
1c370b05c5cc627069d70811b53fb4f1c442b302 | 611 | py | Python | asreview/webapp/tests/__init__.py | DominiqueMaciejewski/asreview | eb1066074613a5f6f930ff610ff92184e9244f4f | [
"Apache-2.0"
] | 280 | 2020-02-06T12:40:16.000Z | 2022-03-19T21:13:55.000Z | asreview/webapp/tests/__init__.py | DominiqueMaciejewski/asreview | eb1066074613a5f6f930ff610ff92184e9244f4f | [
"Apache-2.0"
] | 519 | 2020-02-06T12:08:29.000Z | 2022-03-31T16:02:01.000Z | asreview/webapp/tests/__init__.py | DominiqueMaciejewski/asreview | eb1066074613a5f6f930ff610ff92184e9244f4f | [
"Apache-2.0"
] | 77 | 2020-03-06T15:22:08.000Z | 2022-03-30T11:21:06.000Z | # Copyright 2019-2021 The ASReview Authors. 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.
| 43.642857 | 74 | 0.765957 | true | true | |
1c370b4e461c0ea748683076354b39a440ba6a14 | 3,331 | py | Python | pykrita/camera_layer/ui/camera_layer_widget.py | akirfin/krita_python_fun | 74173d140b39f7f80f43f9474381e4adfa3b5f01 | [
"MIT"
] | 1 | 2021-10-01T00:25:43.000Z | 2021-10-01T00:25:43.000Z | pykrita/camera_layer/ui/camera_layer_widget.py | akirfin/krita_python_fun | 74173d140b39f7f80f43f9474381e4adfa3b5f01 | [
"MIT"
] | null | null | null | pykrita/camera_layer/ui/camera_layer_widget.py | akirfin/krita_python_fun | 74173d140b39f7f80f43f9474381e4adfa3b5f01 | [
"MIT"
] | null | null | null |
from krita import Krita, Node
from PyQt5.QtCore import Qt
from PyQt5.QtCore import pyqtSlot as QSlot
from PyQt5.QtCore import pyqtSignal as QSignal
from PyQt5.QtCore import pyqtProperty as QProperty
from PyQt5.QtWidgets import \
QWidget, QComboBox, QPushButton, QFormLayout
from camera_layer.common.utils_qt import \
get_enum_str
from camera_layer.common.utils_kis import \
find_document_for
from camera_layer.camera_layer import \
CameraLayer
from camera_layer.data_types import \
CameraLayerData
class CameraLayerWidget(QWidget):
def __init__(self, parent=None):
super(CameraLayerWidget, self).__init__(parent=parent)
self._camera_layer = None
self.create_ui()
def create_ui(self):
layout = QFormLayout()
self.setLayout(layout)
self._camera_id = QComboBox()
layout.addRow(i18n("camera_id"), self._camera_id)
self._mode = QComboBox()
layout.addRow(i18n("mode"), self._mode)
#self._transform = TranformWidget()
#layout.addRow("transform", self._transform)
self._capture = QPushButton(i18n("Capture")) # toggle/click button with red dot
layout.addRow(self._capture)
def on_capture(self):
self.camera_layer.capture()
def update(self):
self._camera_id.setText()
self._mode.setText()
self._transform.setText()
return super(CameraLayerWidget, self).update()
def get_node(self):
return self._node
@QSlot(object)
def set_node(self, new_node):
if not isinstance(new_node, (Node, type(None))):
raise RuntimeError("Bad node, must be Node or None. (did get: {new_node})".format(**locals()))
old_node = self.get_node()
if new_node != old_node:
self._node = new_node
self.camera_layer = extension.instance().get_camera_layer(self._node)
self.node_changed.emit(self.get_node())
node_changed = QSignal(object)
node = QProperty(object, fget=get_node, fset=set_node, notify=node_changed)
def get_camera_layer(self):
return self._camera_layer
QSlot(object)
def set_camera_layer(self, new_camera_layer):
old_camera_layer = self._camera_layer
if new_camera_layer != old_camera_layer:
if old_camera_layer is not None:
old_camera_layer.data_changed.disconnect(self.on_camera_layer_data_changed)
self._camera_layer = new_camera_layer
if new_camera_layer is not None:
new_camera_layer.data_changed.connect(self.on_camera_layer_data_changed)
self.update()
self.camera_layer_changed.emit(self.get_camera_layer())
camera_layer_changed = QSignal(object)
camera_layer = QProperty(object, fget=get_camera_layer, fset=set_camera_layer, notify=camera_layer_changed)
def on_camera_layer_data_changed(self, new_data):
self.update()
self.data_changed.emit(new_data)
def get_data(self):
return self._camera_layer.data
QSlot(CameraLayerData)
def set_data(self, new_data):
self._camera_layer.data = new_data
data_changed = QSignal(CameraLayerData)
data = QProperty(CameraLayerData, fget=get_data, fset=set_data, notify=data_changed, user=True)
| 30.559633 | 111 | 0.687181 |
from krita import Krita, Node
from PyQt5.QtCore import Qt
from PyQt5.QtCore import pyqtSlot as QSlot
from PyQt5.QtCore import pyqtSignal as QSignal
from PyQt5.QtCore import pyqtProperty as QProperty
from PyQt5.QtWidgets import \
QWidget, QComboBox, QPushButton, QFormLayout
from camera_layer.common.utils_qt import \
get_enum_str
from camera_layer.common.utils_kis import \
find_document_for
from camera_layer.camera_layer import \
CameraLayer
from camera_layer.data_types import \
CameraLayerData
class CameraLayerWidget(QWidget):
def __init__(self, parent=None):
super(CameraLayerWidget, self).__init__(parent=parent)
self._camera_layer = None
self.create_ui()
def create_ui(self):
layout = QFormLayout()
self.setLayout(layout)
self._camera_id = QComboBox()
layout.addRow(i18n("camera_id"), self._camera_id)
self._mode = QComboBox()
layout.addRow(i18n("mode"), self._mode)
self._capture = QPushButton(i18n("Capture"))
layout.addRow(self._capture)
def on_capture(self):
self.camera_layer.capture()
def update(self):
self._camera_id.setText()
self._mode.setText()
self._transform.setText()
return super(CameraLayerWidget, self).update()
def get_node(self):
return self._node
@QSlot(object)
def set_node(self, new_node):
if not isinstance(new_node, (Node, type(None))):
raise RuntimeError("Bad node, must be Node or None. (did get: {new_node})".format(**locals()))
old_node = self.get_node()
if new_node != old_node:
self._node = new_node
self.camera_layer = extension.instance().get_camera_layer(self._node)
self.node_changed.emit(self.get_node())
node_changed = QSignal(object)
node = QProperty(object, fget=get_node, fset=set_node, notify=node_changed)
def get_camera_layer(self):
return self._camera_layer
QSlot(object)
def set_camera_layer(self, new_camera_layer):
old_camera_layer = self._camera_layer
if new_camera_layer != old_camera_layer:
if old_camera_layer is not None:
old_camera_layer.data_changed.disconnect(self.on_camera_layer_data_changed)
self._camera_layer = new_camera_layer
if new_camera_layer is not None:
new_camera_layer.data_changed.connect(self.on_camera_layer_data_changed)
self.update()
self.camera_layer_changed.emit(self.get_camera_layer())
camera_layer_changed = QSignal(object)
camera_layer = QProperty(object, fget=get_camera_layer, fset=set_camera_layer, notify=camera_layer_changed)
def on_camera_layer_data_changed(self, new_data):
self.update()
self.data_changed.emit(new_data)
def get_data(self):
return self._camera_layer.data
QSlot(CameraLayerData)
def set_data(self, new_data):
self._camera_layer.data = new_data
data_changed = QSignal(CameraLayerData)
data = QProperty(CameraLayerData, fget=get_data, fset=set_data, notify=data_changed, user=True)
| true | true |
1c370d7e2a52c30783c1af1f149612a6ccffc521 | 12,133 | py | Python | pymatgen/io/tests/test_gaussian.py | MahdiDavari/pymatgen | eb6cd95230c11ac761a96ebf82b98f71177bb71f | [
"MIT"
] | null | null | null | pymatgen/io/tests/test_gaussian.py | MahdiDavari/pymatgen | eb6cd95230c11ac761a96ebf82b98f71177bb71f | [
"MIT"
] | null | null | null | pymatgen/io/tests/test_gaussian.py | MahdiDavari/pymatgen | eb6cd95230c11ac761a96ebf82b98f71177bb71f | [
"MIT"
] | 1 | 2018-04-09T21:49:14.000Z | 2018-04-09T21:49:14.000Z | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import division, unicode_literals
"""
Created on Apr 17, 2012
"""
__author__ = "Shyue Ping Ong"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "0.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "shyuep@gmail.com"
__date__ = "Apr 17, 2012"
import unittest2 as unittest
import os
from pymatgen import Molecule
from pymatgen.io.gaussian import GaussianInput, GaussianOutput
from pymatgen.electronic_structure.core import Spin
test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..",
'test_files', "molecules")
class GaussianInputTest(unittest.TestCase):
def setUp(self):
coords = [[0.000000, 0.000000, 0.000000],
[0.000000, 0.000000, 1.089000],
[1.026719, 0.000000, -0.363000],
[-0.513360, -0.889165, -0.363000],
[-0.513360, 0.889165, -0.363000]]
self.coords = coords
mol = Molecule(["C", "H", "H", "H", "H"], coords)
self.gau = GaussianInput(
mol, route_parameters={'SP': "", "SCF": "Tight"},
input_parameters={"EPS": 12})
def test_init(self):
mol = Molecule(["C", "H", "H", "H", "H"], self.coords)
gau = GaussianInput(mol, charge=1, route_parameters={'SP': "",
"SCF": "Tight"})
self.assertEqual(gau.spin_multiplicity, 2)
mol = Molecule(["C", "H", "H", "H", "H"], self.coords, charge=-1)
gau = GaussianInput(mol, route_parameters={'SP': "", "SCF": "Tight"})
self.assertEqual(gau.spin_multiplicity, 2)
self.assertRaises(ValueError, GaussianInput, mol, spin_multiplicity=1)
def test_str_and_from_string(self):
ans = """#P HF/6-31G(d) SCF=Tight SP
H4 C1
0 1
C
H 1 B1
H 1 B2 2 A2
H 1 B3 2 A3 3 D3
H 1 B4 2 A4 4 D4
B1=1.089000
B2=1.089000
A2=109.471221
B3=1.089000
A3=109.471213
D3=120.000017
B4=1.089000
A4=109.471213
D4=119.999966
EPS=12
"""
self.assertEqual(str(self.gau), ans)
gau = GaussianInput.from_string(ans)
self.assertEqual(gau.functional, 'HF')
self.assertEqual(gau.input_parameters['EPS'], '12')
def test_from_file(self):
filepath = os.path.join(test_dir, 'MethylPyrrolidine_drawn.gjf')
gau = GaussianInput.from_file(filepath)
self.assertEqual(gau.molecule.composition.formula, "H11 C5 N1")
self.assertIn("opt", gau.route_parameters)
self.assertEqual(gau.route_parameters["geom"], "connectivity")
self.assertEqual(gau.functional, "b3lyp")
self.assertEqual(gau.basis_set, "6-311+g(d,p)")
filepath = os.path.join(test_dir, "g305_hb.txt")
with open(filepath) as f:
txt = f.read()
toks = txt.split("--link1--")
for i, t in enumerate(toks):
lines = t.strip().split("\n")
lines = [l.strip() for l in lines]
gau = GaussianInput.from_string("\n".join(lines))
self.assertIsNotNone(gau.molecule)
if i == 0:
mol = gau.molecule
ans = """Full Formula (H4 O2)
Reduced Formula: H2O
Charge = 0, Spin Mult = 1
Sites (6)
0 O 0.000000 0.000000 0.000000
1 O 0.000000 0.000000 2.912902
2 H 0.892596 0.000000 -0.373266
3 H 0.143970 0.000219 0.964351
4 H -0.582554 0.765401 3.042783
5 H -0.580711 -0.766761 3.043012"""
self.assertEqual(str(mol), ans)
def test_from_string(self):
gau_str = """%mem=5000000
%chk=filename
# mp2/6-31g* scf=direct
SIH4+ H2---SIH2+ CS //MP2(full)/6-31G* MP2=-290.9225259
1,2
Si
X,1,1.
H,1,R1,2,HALF1
H,1,R1,2,HALF1,3,180.,0
X,1,1.,2,90.,3,90.,0
X,1,1.,5,THETA,2,180.,0
H,1,R3,6,HALF3,5,0.,0
H,1,R4,6,HALF3,7,180.,0
R1=1.47014
R3=1.890457
R4=1.83514
HALF1=60.633314
THETA=10.35464
HALF3=11.861807"""
gau = GaussianInput.from_string(gau_str)
self.assertEqual("X3SiH4", gau.molecule.composition.reduced_formula)
def test_gen_basis(self):
gau_str = """#N B3LYP/Gen Pseudo=Read
Test
0 1
C
H 1 B1
H 1 B2 2 A2
H 1 B3 2 A3 3 D3
H 1 B4 2 A4 4 D4
B1=1.089000
B2=1.089000
A2=109.471221
B3=1.089000
A3=109.471213
D3=120.000017
B4=1.089000
A4=109.471213
D4=119.999966
C 0
6-31G(d,p)
****
H 0
6-31G
****
"""
mol = Molecule(["C", "H", "H", "H", "H"], self.coords)
gen_basis = "C 0\n6-31G(d,p)\n****\nH 0\n6-31G\n****"
gau = GaussianInput(mol, functional="B3LYP", gen_basis=gen_basis,
dieze_tag="#N", route_parameters={"Pseudo": "Read"},
title="Test")
self.assertEqual(gau.to_string(cart_coords=False), gau_str)
class GaussianOutputTest(unittest.TestCase):
# todo: Add unittest for PCM type output.
def setUp(self):
self.gauout = GaussianOutput(os.path.join(test_dir, "methane.log"))
def test_resume(self):
resume = self.gauout.resumes[0]
methane_resume = r"""1\1\GINC-SHYUE-LAPTOP\FOpt\RHF\3-21G\C1H4\SHYUE\27-Feb-2008\0\\#p hf/3
-21G opt\\Title Card Required\\0,1\C,0.,0.,0.\H,0.,0.,1.0829014152\H,1
.0209692454,0.,-0.3609671384\H,-0.5104846227,-0.884185303,-0.360967138
4\H,-0.5104846227,0.884185303,-0.3609671384\\Version=IA32L-G03RevD.01\
State=1-A1\HF=-39.9768776\RMSD=3.210e-09\RMSF=5.014e-08\Thermal=0.\Dip
ole=0.,0.,0.\PG=TD [O(C1),4C3(H1)]\\@"""
methane_resume = "".join([r.strip() for r in methane_resume.split("\n")])
self.assertEqual(resume, methane_resume)
def test_props(self):
gau = self.gauout
self.assertEqual(len(gau.energies), 3)
self.assertAlmostEqual(gau.energies[-1], -39.9768775602)
self.assertEqual(len(gau.structures), 4)
for mol in gau.structures:
self.assertEqual(mol.formula, 'H4 C1')
self.assertIn("opt", gau.route)
self.assertEqual("Minimum", gau.stationary_type)
self.assertEqual("hf", gau.functional)
self.assertEqual("3-21G", gau.basis_set)
self.assertEqual(17, gau.num_basis_func)
d = gau.as_dict()
self.assertEqual(d["input"]["functional"], "hf")
self.assertAlmostEqual(d["output"]["final_energy"], -39.9768775602)
self.assertEqual(len(gau.cart_forces), 3)
self.assertEqual(gau.cart_forces[0][5], 0.009791094)
self.assertEqual(gau.cart_forces[0][-1], -0.003263698)
self.assertEqual(gau.cart_forces[2][-1], -0.000000032)
self.assertEqual(gau.eigenvalues[Spin.up][-1], 1.95586)
self.assertEqual(gau.num_basis_func, 17)
self.assertEqual(gau.is_spin, False)
ch2o_co2 = GaussianOutput(os.path.join(test_dir, "CH2O_CO2.log"))
self.assertEqual(len(ch2o_co2.frequencies), 2)
self.assertEqual(len(ch2o_co2.frequencies[0]), 6)
self.assertEqual(len(ch2o_co2.frequencies[1]), 4)
self.assertEqual(ch2o_co2.frequencies[0][0]["frequency"], 1203.1940)
self.assertEqual(ch2o_co2.frequencies[0][0]["symmetry"], "A\"")
self.assertEqual(ch2o_co2.frequencies[0][3]["IR_intensity"], 60.9575)
self.assertEqual(ch2o_co2.frequencies[0][3]["r_mass"], 3.7543)
self.assertEqual(ch2o_co2.frequencies[0][4]["f_constant"], 5.4175)
self.assertListEqual(ch2o_co2.frequencies[0][1]["mode"], [0.15, 0.00, 0.00,
-0.26, 0.65, 0.00,
-0.26, -0.65, 0.00,
-0.08, 0.00, 0.00])
self.assertListEqual(ch2o_co2.frequencies[1][3]["mode"], [0.00, 0.00, 0.88,
0.00, 0.00, -0.33,
0.00, 0.00, -0.33])
self.assertEqual(ch2o_co2.frequencies[1][3]["symmetry"], "SGU")
self.assertEqual(ch2o_co2.eigenvalues[Spin.up][3], -1.18394)
h2o = GaussianOutput(os.path.join(test_dir, "H2O_gau_vib.out"))
self.assertEqual(len(h2o.frequencies[0]), 3)
self.assertEqual(h2o.frequencies[0][0]["frequency"], 1662.8033)
self.assertEqual(h2o.frequencies[0][1]["symmetry"], "A'")
self.assertEqual(h2o.hessian[0, 0], 0.356872)
self.assertEqual(h2o.hessian.shape, (9, 9))
self.assertEqual(h2o.hessian[8, :].tolist(), [-0.143692e-01, 0.780136e-01,
-0.362637e-01, -0.176193e-01,
0.277304e-01, -0.583237e-02,
0.319885e-01, -0.105744e+00,
0.420960e-01])
def test_pop(self):
gau = GaussianOutput(os.path.join(test_dir, "H2O_gau.out"))
self.assertEqual(gau.num_basis_func, 13)
self.assertEqual(gau.electrons, (5, 5))
self.assertEqual(gau.is_spin, True)
self.assertListEqual(gau.eigenvalues[Spin.down], [-20.55343, -1.35264,
-0.72655, -0.54824,
-0.49831, 0.20705,
0.30297, 1.10569,
1.16144, 1.16717,
1.20460, 1.38903,
1.67608])
mo = gau.molecular_orbital
self.assertEqual(len(mo), 2) # la 6
self.assertEqual(len(mo[Spin.down]), 13)
self.assertEqual(len(mo[Spin.down][0]), 3)
self.assertEqual(mo[Spin.down][5][0]["1S"], -0.08771)
self.assertEqual(mo[Spin.down][5][0]["2PZ"], -0.21625)
self.assertListEqual(gau.eigenvectors[Spin.up][:, 5].tolist(), [-0.08771,
0.10840,
0.00000,
0.00000,
-0.21625,
1.21165,
0.00000,
0.00000,
-0.44481,
-0.06348,
-1.00532,
-0.06348,
-1.00532])
self.assertListEqual(gau.atom_basis_labels[0], ["1S", "2S", "2PX", "2PY",
"2PZ", "3S", "3PX", "3PY",
"3PZ"])
self.assertListEqual(gau.atom_basis_labels[2], ["1S", "2S"])
def test_scan(self):
gau = GaussianOutput(os.path.join(test_dir, "so2_scan.log"))
d = gau.read_scan()
self.assertAlmostEqual(-548.02102, d["energies"][-1])
self.assertEqual(len(d["coords"]), 1)
self.assertEqual(len(d["energies"]), len(gau.energies))
self.assertEqual(len(d["energies"]), 21)
def test_td(self):
gau = GaussianOutput(os.path.join(test_dir, "so2_td.log"))
transitions = gau.read_excitation_energies()
self.assertEqual(len(transitions), 4)
self.assertAlmostEqual(transitions[0], (3.9281, 315.64, 0.0054))
if __name__ == "__main__":
unittest.main()
| 39.392857 | 99 | 0.515042 |
from __future__ import division, unicode_literals
__author__ = "Shyue Ping Ong"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "0.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "shyuep@gmail.com"
__date__ = "Apr 17, 2012"
import unittest2 as unittest
import os
from pymatgen import Molecule
from pymatgen.io.gaussian import GaussianInput, GaussianOutput
from pymatgen.electronic_structure.core import Spin
test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..",
'test_files', "molecules")
class GaussianInputTest(unittest.TestCase):
def setUp(self):
coords = [[0.000000, 0.000000, 0.000000],
[0.000000, 0.000000, 1.089000],
[1.026719, 0.000000, -0.363000],
[-0.513360, -0.889165, -0.363000],
[-0.513360, 0.889165, -0.363000]]
self.coords = coords
mol = Molecule(["C", "H", "H", "H", "H"], coords)
self.gau = GaussianInput(
mol, route_parameters={'SP': "", "SCF": "Tight"},
input_parameters={"EPS": 12})
def test_init(self):
mol = Molecule(["C", "H", "H", "H", "H"], self.coords)
gau = GaussianInput(mol, charge=1, route_parameters={'SP': "",
"SCF": "Tight"})
self.assertEqual(gau.spin_multiplicity, 2)
mol = Molecule(["C", "H", "H", "H", "H"], self.coords, charge=-1)
gau = GaussianInput(mol, route_parameters={'SP': "", "SCF": "Tight"})
self.assertEqual(gau.spin_multiplicity, 2)
self.assertRaises(ValueError, GaussianInput, mol, spin_multiplicity=1)
def test_str_and_from_string(self):
ans = """#P HF/6-31G(d) SCF=Tight SP
H4 C1
0 1
C
H 1 B1
H 1 B2 2 A2
H 1 B3 2 A3 3 D3
H 1 B4 2 A4 4 D4
B1=1.089000
B2=1.089000
A2=109.471221
B3=1.089000
A3=109.471213
D3=120.000017
B4=1.089000
A4=109.471213
D4=119.999966
EPS=12
"""
self.assertEqual(str(self.gau), ans)
gau = GaussianInput.from_string(ans)
self.assertEqual(gau.functional, 'HF')
self.assertEqual(gau.input_parameters['EPS'], '12')
def test_from_file(self):
filepath = os.path.join(test_dir, 'MethylPyrrolidine_drawn.gjf')
gau = GaussianInput.from_file(filepath)
self.assertEqual(gau.molecule.composition.formula, "H11 C5 N1")
self.assertIn("opt", gau.route_parameters)
self.assertEqual(gau.route_parameters["geom"], "connectivity")
self.assertEqual(gau.functional, "b3lyp")
self.assertEqual(gau.basis_set, "6-311+g(d,p)")
filepath = os.path.join(test_dir, "g305_hb.txt")
with open(filepath) as f:
txt = f.read()
toks = txt.split("--link1--")
for i, t in enumerate(toks):
lines = t.strip().split("\n")
lines = [l.strip() for l in lines]
gau = GaussianInput.from_string("\n".join(lines))
self.assertIsNotNone(gau.molecule)
if i == 0:
mol = gau.molecule
ans = """Full Formula (H4 O2)
Reduced Formula: H2O
Charge = 0, Spin Mult = 1
Sites (6)
0 O 0.000000 0.000000 0.000000
1 O 0.000000 0.000000 2.912902
2 H 0.892596 0.000000 -0.373266
3 H 0.143970 0.000219 0.964351
4 H -0.582554 0.765401 3.042783
5 H -0.580711 -0.766761 3.043012"""
self.assertEqual(str(mol), ans)
def test_from_string(self):
gau_str = """%mem=5000000
%chk=filename
# mp2/6-31g* scf=direct
SIH4+ H2---SIH2+ CS //MP2(full)/6-31G* MP2=-290.9225259
1,2
Si
X,1,1.
H,1,R1,2,HALF1
H,1,R1,2,HALF1,3,180.,0
X,1,1.,2,90.,3,90.,0
X,1,1.,5,THETA,2,180.,0
H,1,R3,6,HALF3,5,0.,0
H,1,R4,6,HALF3,7,180.,0
R1=1.47014
R3=1.890457
R4=1.83514
HALF1=60.633314
THETA=10.35464
HALF3=11.861807"""
gau = GaussianInput.from_string(gau_str)
self.assertEqual("X3SiH4", gau.molecule.composition.reduced_formula)
def test_gen_basis(self):
gau_str = """#N B3LYP/Gen Pseudo=Read
Test
0 1
C
H 1 B1
H 1 B2 2 A2
H 1 B3 2 A3 3 D3
H 1 B4 2 A4 4 D4
B1=1.089000
B2=1.089000
A2=109.471221
B3=1.089000
A3=109.471213
D3=120.000017
B4=1.089000
A4=109.471213
D4=119.999966
C 0
6-31G(d,p)
****
H 0
6-31G
****
"""
mol = Molecule(["C", "H", "H", "H", "H"], self.coords)
gen_basis = "C 0\n6-31G(d,p)\n****\nH 0\n6-31G\n****"
gau = GaussianInput(mol, functional="B3LYP", gen_basis=gen_basis,
dieze_tag="#N", route_parameters={"Pseudo": "Read"},
title="Test")
self.assertEqual(gau.to_string(cart_coords=False), gau_str)
class GaussianOutputTest(unittest.TestCase):
def setUp(self):
self.gauout = GaussianOutput(os.path.join(test_dir, "methane.log"))
def test_resume(self):
resume = self.gauout.resumes[0]
methane_resume = r"""1\1\GINC-SHYUE-LAPTOP\FOpt\RHF\3-21G\C1H4\SHYUE\27-Feb-2008\0\\#p hf/3
-21G opt\\Title Card Required\\0,1\C,0.,0.,0.\H,0.,0.,1.0829014152\H,1
.0209692454,0.,-0.3609671384\H,-0.5104846227,-0.884185303,-0.360967138
4\H,-0.5104846227,0.884185303,-0.3609671384\\Version=IA32L-G03RevD.01\
State=1-A1\HF=-39.9768776\RMSD=3.210e-09\RMSF=5.014e-08\Thermal=0.\Dip
ole=0.,0.,0.\PG=TD [O(C1),4C3(H1)]\\@"""
methane_resume = "".join([r.strip() for r in methane_resume.split("\n")])
self.assertEqual(resume, methane_resume)
def test_props(self):
gau = self.gauout
self.assertEqual(len(gau.energies), 3)
self.assertAlmostEqual(gau.energies[-1], -39.9768775602)
self.assertEqual(len(gau.structures), 4)
for mol in gau.structures:
self.assertEqual(mol.formula, 'H4 C1')
self.assertIn("opt", gau.route)
self.assertEqual("Minimum", gau.stationary_type)
self.assertEqual("hf", gau.functional)
self.assertEqual("3-21G", gau.basis_set)
self.assertEqual(17, gau.num_basis_func)
d = gau.as_dict()
self.assertEqual(d["input"]["functional"], "hf")
self.assertAlmostEqual(d["output"]["final_energy"], -39.9768775602)
self.assertEqual(len(gau.cart_forces), 3)
self.assertEqual(gau.cart_forces[0][5], 0.009791094)
self.assertEqual(gau.cart_forces[0][-1], -0.003263698)
self.assertEqual(gau.cart_forces[2][-1], -0.000000032)
self.assertEqual(gau.eigenvalues[Spin.up][-1], 1.95586)
self.assertEqual(gau.num_basis_func, 17)
self.assertEqual(gau.is_spin, False)
ch2o_co2 = GaussianOutput(os.path.join(test_dir, "CH2O_CO2.log"))
self.assertEqual(len(ch2o_co2.frequencies), 2)
self.assertEqual(len(ch2o_co2.frequencies[0]), 6)
self.assertEqual(len(ch2o_co2.frequencies[1]), 4)
self.assertEqual(ch2o_co2.frequencies[0][0]["frequency"], 1203.1940)
self.assertEqual(ch2o_co2.frequencies[0][0]["symmetry"], "A\"")
self.assertEqual(ch2o_co2.frequencies[0][3]["IR_intensity"], 60.9575)
self.assertEqual(ch2o_co2.frequencies[0][3]["r_mass"], 3.7543)
self.assertEqual(ch2o_co2.frequencies[0][4]["f_constant"], 5.4175)
self.assertListEqual(ch2o_co2.frequencies[0][1]["mode"], [0.15, 0.00, 0.00,
-0.26, 0.65, 0.00,
-0.26, -0.65, 0.00,
-0.08, 0.00, 0.00])
self.assertListEqual(ch2o_co2.frequencies[1][3]["mode"], [0.00, 0.00, 0.88,
0.00, 0.00, -0.33,
0.00, 0.00, -0.33])
self.assertEqual(ch2o_co2.frequencies[1][3]["symmetry"], "SGU")
self.assertEqual(ch2o_co2.eigenvalues[Spin.up][3], -1.18394)
h2o = GaussianOutput(os.path.join(test_dir, "H2O_gau_vib.out"))
self.assertEqual(len(h2o.frequencies[0]), 3)
self.assertEqual(h2o.frequencies[0][0]["frequency"], 1662.8033)
self.assertEqual(h2o.frequencies[0][1]["symmetry"], "A'")
self.assertEqual(h2o.hessian[0, 0], 0.356872)
self.assertEqual(h2o.hessian.shape, (9, 9))
self.assertEqual(h2o.hessian[8, :].tolist(), [-0.143692e-01, 0.780136e-01,
-0.362637e-01, -0.176193e-01,
0.277304e-01, -0.583237e-02,
0.319885e-01, -0.105744e+00,
0.420960e-01])
def test_pop(self):
gau = GaussianOutput(os.path.join(test_dir, "H2O_gau.out"))
self.assertEqual(gau.num_basis_func, 13)
self.assertEqual(gau.electrons, (5, 5))
self.assertEqual(gau.is_spin, True)
self.assertListEqual(gau.eigenvalues[Spin.down], [-20.55343, -1.35264,
-0.72655, -0.54824,
-0.49831, 0.20705,
0.30297, 1.10569,
1.16144, 1.16717,
1.20460, 1.38903,
1.67608])
mo = gau.molecular_orbital
self.assertEqual(len(mo), 2) # la 6
self.assertEqual(len(mo[Spin.down]), 13)
self.assertEqual(len(mo[Spin.down][0]), 3)
self.assertEqual(mo[Spin.down][5][0]["1S"], -0.08771)
self.assertEqual(mo[Spin.down][5][0]["2PZ"], -0.21625)
self.assertListEqual(gau.eigenvectors[Spin.up][:, 5].tolist(), [-0.08771,
0.10840,
0.00000,
0.00000,
-0.21625,
1.21165,
0.00000,
0.00000,
-0.44481,
-0.06348,
-1.00532,
-0.06348,
-1.00532])
self.assertListEqual(gau.atom_basis_labels[0], ["1S", "2S", "2PX", "2PY",
"2PZ", "3S", "3PX", "3PY",
"3PZ"])
self.assertListEqual(gau.atom_basis_labels[2], ["1S", "2S"])
def test_scan(self):
gau = GaussianOutput(os.path.join(test_dir, "so2_scan.log"))
d = gau.read_scan()
self.assertAlmostEqual(-548.02102, d["energies"][-1])
self.assertEqual(len(d["coords"]), 1)
self.assertEqual(len(d["energies"]), len(gau.energies))
self.assertEqual(len(d["energies"]), 21)
def test_td(self):
gau = GaussianOutput(os.path.join(test_dir, "so2_td.log"))
transitions = gau.read_excitation_energies()
self.assertEqual(len(transitions), 4)
self.assertAlmostEqual(transitions[0], (3.9281, 315.64, 0.0054))
if __name__ == "__main__":
unittest.main()
| true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.