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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f716683184b12be70591300c446fc7951aa0428a | 4,386 | py | Python | contrib/seeds/generate-seeds.py | FcoinFup/litecoin | f60e79f2bf373dafd258264ae197cee44ab4a314 | [
"MIT"
] | null | null | null | contrib/seeds/generate-seeds.py | FcoinFup/litecoin | f60e79f2bf373dafd258264ae197cee44ab4a314 | [
"MIT"
] | null | null | null | contrib/seeds/generate-seeds.py | FcoinFup/litecoin | f60e79f2bf373dafd258264ae197cee44ab4a314 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# Copyright (c) 2014-2017 Wladimir J. van der Laan
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Script to generate list of seed nodes for chainparams.cpp.
This script expects two text files in the directory that is passed as an
argument:
nodes_main.txt
nodes_test.txt
These files must consist of lines in the format
<ip>
<ip>:<port>
[<ipv6>]
[<ipv6>]:<port>
<onion>.onion
0xDDBBCCAA (IPv4 little-endian old pnSeeds format)
The output will be two data structures with the peers in binary format:
static SeedSpec6 pnSeed6_main[]={
...
}
static SeedSpec6 pnSeed6_test[]={
...
}
These should be pasted into `src/chainparamsseeds.h`.
'''
from base64 import b32decode
from binascii import a2b_hex
import sys
import os
import re
# ipv4 in ipv6 prefix
pchIPv4 = bytearray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff])
# tor-specific ipv6 prefix
pchOnionCat = bytearray([0xFD,0x87,0xD8,0x7E,0xEB,0x43])
def name_to_ipv6(addr):
if len(addr)>6 and addr.endswith('.onion'):
vchAddr = b32decode(addr[0:-6], True)
if len(vchAddr) != 16-len(pchOnionCat):
raise ValueError('Invalid onion %s' % vchAddr)
return pchOnionCat + vchAddr
elif '.' in addr: # IPv4
return pchIPv4 + bytearray((int(x) for x in addr.split('.')))
elif ':' in addr: # IPv6
sub = [[], []] # prefix, suffix
x = 0
addr = addr.split(':')
for i,comp in enumerate(addr):
if comp == '':
if i == 0 or i == (len(addr)-1): # skip empty component at beginning or end
continue
x += 1 # :: skips to suffix
assert(x < 2)
else: # two bytes per component
val = int(comp, 16)
sub[x].append(val >> 8)
sub[x].append(val & 0xff)
nullbytes = 16 - len(sub[0]) - len(sub[1])
assert((x == 0 and nullbytes == 0) or (x == 1 and nullbytes > 0))
return bytearray(sub[0] + ([0] * nullbytes) + sub[1])
elif addr.startswith('0x'): # IPv4-in-little-endian
return pchIPv4 + bytearray(reversed(a2b_hex(addr[2:])))
else:
raise ValueError('Could not parse address %s' % addr)
def parse_spec(s, defaultport):
match = re.match('\[([0-9a-fA-F:]+)\](?::([0-9]+))?$', s)
if match: # ipv6
host = match.group(1)
port = match.group(2)
elif s.count(':') > 1: # ipv6, no port
host = s
port = ''
else:
(host,_,port) = s.partition(':')
if not port:
port = defaultport
else:
port = int(port)
host = name_to_ipv6(host)
return (host,port)
def process_nodes(g, f, structname, defaultport):
g.write('static SeedSpec6 %s[] = {\n' % structname)
first = True
for line in f:
comment = line.find('#')
if comment != -1:
line = line[0:comment]
line = line.strip()
if not line:
continue
if not first:
g.write(',\n')
first = False
(host,port) = parse_spec(line, defaultport)
hoststr = ','.join(('0x%02x' % b) for b in host)
g.write(' {{%s}, %i}' % (hoststr, port))
g.write('\n};\n')
def main():
if len(sys.argv)<2:
print(('Usage: %s <path_to_nodes_txt>' % sys.argv[0]), file=sys.stderr)
sys.exit(1)
g = sys.stdout
indir = sys.argv[1]
g.write('#ifndef BITCOIN_CHAINPARAMSSEEDS_H\n')
g.write('#define BITCOIN_CHAINPARAMSSEEDS_H\n')
g.write('/**\n')
g.write(' * List of fixed seed nodes for the deliverycoin network\n')
g.write(' * AUTOGENERATED by contrib/seeds/generate-seeds.py\n')
g.write(' *\n')
g.write(' * Each line contains a 16-byte IPv6 address and a port.\n')
g.write(' * IPv4 as well as onion addresses are wrapped inside an IPv6 address accordingly.\n')
g.write(' */\n')
with open(os.path.join(indir,'nodes_main.txt'), 'r', encoding="utf8") as f:
process_nodes(g, f, 'pnSeed6_main', 2333)
g.write('\n')
with open(os.path.join(indir,'nodes_test.txt'), 'r', encoding="utf8") as f:
process_nodes(g, f, 'pnSeed6_test', 19335)
g.write('#endif // BITCOIN_CHAINPARAMSSEEDS_H\n')
if __name__ == '__main__':
main()
| 31.328571 | 99 | 0.583903 |
from base64 import b32decode
from binascii import a2b_hex
import sys
import os
import re
pchIPv4 = bytearray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff])
pchOnionCat = bytearray([0xFD,0x87,0xD8,0x7E,0xEB,0x43])
def name_to_ipv6(addr):
if len(addr)>6 and addr.endswith('.onion'):
vchAddr = b32decode(addr[0:-6], True)
if len(vchAddr) != 16-len(pchOnionCat):
raise ValueError('Invalid onion %s' % vchAddr)
return pchOnionCat + vchAddr
elif '.' in addr:
return pchIPv4 + bytearray((int(x) for x in addr.split('.')))
elif ':' in addr:
sub = [[], []]
x = 0
addr = addr.split(':')
for i,comp in enumerate(addr):
if comp == '':
if i == 0 or i == (len(addr)-1):
continue
x += 1
assert(x < 2)
else:
val = int(comp, 16)
sub[x].append(val >> 8)
sub[x].append(val & 0xff)
nullbytes = 16 - len(sub[0]) - len(sub[1])
assert((x == 0 and nullbytes == 0) or (x == 1 and nullbytes > 0))
return bytearray(sub[0] + ([0] * nullbytes) + sub[1])
elif addr.startswith('0x'):
return pchIPv4 + bytearray(reversed(a2b_hex(addr[2:])))
else:
raise ValueError('Could not parse address %s' % addr)
def parse_spec(s, defaultport):
match = re.match('\[([0-9a-fA-F:]+)\](?::([0-9]+))?$', s)
if match:
host = match.group(1)
port = match.group(2)
elif s.count(':') > 1:
host = s
port = ''
else:
(host,_,port) = s.partition(':')
if not port:
port = defaultport
else:
port = int(port)
host = name_to_ipv6(host)
return (host,port)
def process_nodes(g, f, structname, defaultport):
g.write('static SeedSpec6 %s[] = {\n' % structname)
first = True
for line in f:
comment = line.find('#')
if comment != -1:
line = line[0:comment]
line = line.strip()
if not line:
continue
if not first:
g.write(',\n')
first = False
(host,port) = parse_spec(line, defaultport)
hoststr = ','.join(('0x%02x' % b) for b in host)
g.write(' {{%s}, %i}' % (hoststr, port))
g.write('\n};\n')
def main():
if len(sys.argv)<2:
print(('Usage: %s <path_to_nodes_txt>' % sys.argv[0]), file=sys.stderr)
sys.exit(1)
g = sys.stdout
indir = sys.argv[1]
g.write('#ifndef BITCOIN_CHAINPARAMSSEEDS_H\n')
g.write('#define BITCOIN_CHAINPARAMSSEEDS_H\n')
g.write('/**\n')
g.write(' * List of fixed seed nodes for the deliverycoin network\n')
g.write(' * AUTOGENERATED by contrib/seeds/generate-seeds.py\n')
g.write(' *\n')
g.write(' * Each line contains a 16-byte IPv6 address and a port.\n')
g.write(' * IPv4 as well as onion addresses are wrapped inside an IPv6 address accordingly.\n')
g.write(' */\n')
with open(os.path.join(indir,'nodes_main.txt'), 'r', encoding="utf8") as f:
process_nodes(g, f, 'pnSeed6_main', 2333)
g.write('\n')
with open(os.path.join(indir,'nodes_test.txt'), 'r', encoding="utf8") as f:
process_nodes(g, f, 'pnSeed6_test', 19335)
g.write('#endif // BITCOIN_CHAINPARAMSSEEDS_H\n')
if __name__ == '__main__':
main()
| true | true |
f71669461b57160bac0b4efc0928e6826dc11176 | 15,093 | py | Python | tests/test_collections.py | fperetti/callee | 58740f73ff9a76f5fe0075bf18d7345a0f9d961c | [
"BSD-3-Clause"
] | 72 | 2016-03-21T03:58:33.000Z | 2022-03-29T10:24:51.000Z | tests/test_collections.py | fperetti/callee | 58740f73ff9a76f5fe0075bf18d7345a0f9d961c | [
"BSD-3-Clause"
] | 14 | 2016-03-21T03:58:39.000Z | 2021-09-07T16:26:03.000Z | tests/test_collections.py | fperetti/callee | 58740f73ff9a76f5fe0075bf18d7345a0f9d961c | [
"BSD-3-Clause"
] | 9 | 2016-10-26T14:39:00.000Z | 2021-08-13T17:39:35.000Z | """
Tests for collections' matchers.
"""
import collections
from taipan.testing import skipIf
from callee._compat import OrderedDict as _OrderedDict
import callee.collections as __unit__
from tests import MatcherTestCase
class Iterable(MatcherTestCase):
test_none = lambda self: self.assert_no_match(None)
test_zero = lambda self: self.assert_no_match(0)
test_empty_string = lambda self: self.assert_match('')
test_empty_list = lambda self: self.assert_match([])
test_empty_tuple = lambda self: self.assert_match(())
test_empty_dict = lambda self: self.assert_match({})
test_empty_generator = lambda self: self.assert_match(x for x in ())
test_some_string = lambda self: self.assert_match("Alice has a cat")
test_some_number = lambda self: self.assert_no_match(42)
test_some_list = lambda self: self.assert_match([1, 2, 3, 5, 8, 13])
test_some_tuple = lambda self: self.assert_match(('foo', -1, ['bar']))
def test_some_generator(self):
gen = (x for x in [1, 2, 5])
self.assert_match(gen)
self.assertNotEmpty(
gen, msg="matcher shouldn't have iterated over the generator")
test_some_object = lambda self: self.assert_no_match(object())
test_repr = lambda self: self.assert_repr(__unit__.Iterable())
# Assertion functions
def assert_match(self, value):
return super(Iterable, self).assert_match(__unit__.Iterable(), value)
def assert_no_match(self, value):
return super(Iterable, self) \
.assert_no_match(__unit__.Iterable(), value)
class Generator(MatcherTestCase):
test_none = lambda self: self.assert_no_match(None)
test_zero = lambda self: self.assert_no_match(0)
test_empty_string = lambda self: self.assert_no_match('')
test_empty_list = lambda self: self.assert_no_match([])
test_empty_tuple = lambda self: self.assert_no_match(())
test_empty_dict = lambda self: self.assert_no_match({})
test_empty_generator = lambda self: self.assert_match(x for x in ())
test_some_string = lambda self: self.assert_no_match("Alice has a cat")
test_some_number = lambda self: self.assert_no_match(42)
test_some_list = lambda self: self.assert_no_match([1, 2, 3, 5, 8, 13])
test_some_tuple = lambda self: self.assert_no_match(('foo', -1, ['bar']))
def test_some_generator(self):
gen = (x for x in [1, 2, 5])
self.assert_match(gen)
self.assertNotEmpty(
gen, msg="matcher shouldn't have iterated over the generator")
test_some_object = lambda self: self.assert_no_match(object())
test_repr = lambda self: self.assert_repr(__unit__.Generator())
# Assertion functions
def assert_match(self, value):
return super(Generator, self).assert_match(__unit__.Generator(), value)
def assert_no_match(self, value):
return super(Generator, self) \
.assert_no_match(__unit__.Generator(), value)
# Ordinary collections
class Sequence(MatcherTestCase):
test_none = lambda self: self.assert_no_match(None)
test_zero = lambda self: self.assert_no_match(0)
test_empty_string = lambda self: self.assert_match('')
test_empty_list = lambda self: self.assert_match([])
test_empty_set = lambda self: self.assert_no_match(set())
test_empty_tuple = lambda self: self.assert_match(())
test_empty_dict = lambda self: self.assert_no_match({})
test_empty_generator = lambda self: self.assert_no_match(x for x in ())
def test_some_string(self):
s = "Alice has a cat"
self.assert_match(s)
self.assert_match(s, of=str)
test_some_number = lambda self: self.assert_no_match(42)
def test_some_list(self):
l = [1, 2, 3, 5, 8, 13]
self.assert_match(l)
self.assert_match(l, of=int)
test_some_tuple = lambda self: self.assert_match(('foo', -1, ['bar']))
test_some_generator = lambda self: self.assert_no_match(x for x in [1, 2])
test_some_object = lambda self: self.assert_no_match(object())
test_repr = lambda self: self.assert_repr(__unit__.Sequence())
# Assertion functions
def assert_match(self, value, of=None):
return super(Sequence, self).assert_match(__unit__.Sequence(of), value)
def assert_no_match(self, value, of=None):
return super(Sequence, self) \
.assert_no_match(__unit__.Sequence(of), value)
class List(MatcherTestCase):
test_none = lambda self: self.assert_no_match(None)
test_zero = lambda self: self.assert_no_match(0)
test_empty_string = lambda self: self.assert_no_match('')
test_empty_list = lambda self: self.assert_match([])
test_empty_set = lambda self: self.assert_no_match(set())
test_empty_tuple = lambda self: self.assert_no_match(())
test_empty_dict = lambda self: self.assert_no_match({})
test_empty_generator = lambda self: self.assert_no_match(x for x in ())
test_some_string = lambda self: self.assert_no_match("Alice has a cat")
test_some_number = lambda self: self.assert_no_match(42)
test_some_list = lambda self: self.assert_match([1, 2, 3, 5, 8, 13], int)
test_some_tuple = lambda self: self.assert_no_match(('foo', -1, ['bar']))
test_some_generator = lambda self: self.assert_no_match(x for x in [1, 2])
test_some_object = lambda self: self.assert_no_match(object())
test_repr = lambda self: self.assert_repr(__unit__.List())
# Assertion functions
def assert_match(self, value, of=None):
return super(List, self).assert_match(__unit__.List(of), value)
def assert_no_match(self, value, of=None):
return super(List, self).assert_no_match(__unit__.List(of), value)
class Set(MatcherTestCase):
test_none = lambda self: self.assert_no_match(None)
test_zero = lambda self: self.assert_no_match(0)
test_empty_string = lambda self: self.assert_no_match('')
test_empty_list = lambda self: self.assert_no_match([])
test_empty_set = lambda self: self.assert_match(set())
test_empty_tuple = lambda self: self.assert_no_match(())
test_empty_dict = lambda self: self.assert_no_match({})
test_empty_generator = lambda self: self.assert_no_match(x for x in ())
test_some_string = lambda self: self.assert_no_match("Alice has a cat")
test_some_number = lambda self: self.assert_no_match(42)
test_some_list = lambda self: self.assert_no_match([1, 2, 3, 5, 8, 13])
test_some_set = lambda self: self.assert_match(set([2, 4, 6, 8, 10]), int)
test_some_tuple = lambda self: self.assert_no_match(('foo', -1, ['bar']))
test_some_generator = lambda self: self.assert_no_match(x for x in [1, 2])
test_some_object = lambda self: self.assert_no_match(object())
test_repr = lambda self: self.assert_repr(__unit__.Set())
# Assertion functions
def assert_match(self, value, of=None):
return super(Set, self).assert_match(__unit__.Set(of), value)
def assert_no_match(self, value, of=None):
return super(Set, self).assert_no_match(__unit__.Set(of), value)
# Mappings
class CustomDict(collections.MutableMapping):
""""Custom, no-op mapping class that just wraps a regular Python dict
but is not a Python dict itself.
"""
def __init__(self, iterable=(), **kwargs):
if isinstance(iterable, collections.Mapping):
iterable = iterable.items()
self.d = {}
for k, v in iterable:
self.d[k] = v
self.d.update(kwargs)
def __delitem__(self, key):
del self.d[key]
def __getitem__(self, key):
return self.d[key]
def __iter__(self):
return iter(self.d)
def __len__(self):
return len(self.d)
def __setitem__(self, key, value):
self.d[key] = value
class Mapping(MatcherTestCase):
def test_invalid_arg(self):
with self.assertRaises(TypeError):
self.assert_match(None, of='not a pair of matchers')
test_none = lambda self: self.assert_no_match(None)
test_zero = lambda self: self.assert_no_match(0)
test_empty_string = lambda self: self.assert_no_match('')
test_empty_list = lambda self: self.assert_no_match([])
test_empty_set = lambda self: self.assert_no_match(set())
test_empty_tuple = lambda self: self.assert_no_match(())
def test_empty_dict__regular(self):
d = {}
self.assert_match(d)
self.assert_match(d, str, int)
self.assert_match(d, keys=str, values=int)
self.assert_match(d, of=(str, int))
def test_empty_dict__custom(self):
d = CustomDict()
self.assert_match(d)
self.assert_match(d, str, int)
self.assert_match(d, keys=str, values=int)
self.assert_match(d, of=(str, int))
test_empty_generator = lambda self: self.assert_no_match(x for x in ())
test_some_string = lambda self: self.assert_no_match("Alice has a cat")
test_some_number = lambda self: self.assert_no_match(42)
test_some_list = lambda self: self.assert_no_match([1, 2, 3, 5, 8, 13])
test_some_set = lambda self: self.assert_no_match(set([2, 4, 6, 8, 10]))
test_some_tuple = lambda self: self.assert_no_match(('foo', -1, ['bar']))
def test_some_dict__regular(self):
d = {'a': 1}
self.assert_match(d)
self.assert_match(d, str, int)
self.assert_match(d, keys=str, values=int)
self.assert_match(d, of=(str, int))
def test_some_dict__custom(self):
d = CustomDict({'a': 1})
self.assert_match(d)
self.assert_match(d, str, int)
self.assert_match(d, keys=str, values=int)
self.assert_match(d, of=(str, int))
test_some_generator = lambda self: self.assert_no_match(x for x in [1, 2])
test_some_object = lambda self: self.assert_no_match(object())
test_repr = lambda self: self.assert_repr(__unit__.Mapping())
# Assertion functions
def assert_match(self, value, *args, **kwargs):
return super(Mapping, self)\
.assert_match(__unit__.Mapping(*args, **kwargs), value)
def assert_no_match(self, value, *args, **kwargs):
return super(Mapping, self) \
.assert_no_match(__unit__.Mapping(*args, **kwargs), value)
class Dict(MatcherTestCase):
def test_invalid_arg(self):
with self.assertRaises(TypeError):
self.assert_match(None, of='not a pair of matchers')
test_none = lambda self: self.assert_no_match(None)
test_zero = lambda self: self.assert_no_match(0)
test_empty_string = lambda self: self.assert_no_match('')
test_empty_list = lambda self: self.assert_no_match([])
test_empty_set = lambda self: self.assert_no_match(set())
test_empty_tuple = lambda self: self.assert_no_match(())
def test_empty_dict__regular(self):
d = {}
self.assert_match(d)
self.assert_match(d, str, int)
self.assert_match(d, keys=str, values=int)
self.assert_match(d, of=(str, int))
def test_empty_dict__custom(self):
d = CustomDict()
self.assert_no_match(d)
self.assert_no_match(d, str, int)
self.assert_no_match(d, keys=str, values=int)
self.assert_no_match(d, of=(str, int))
test_empty_generator = lambda self: self.assert_no_match(x for x in ())
test_some_string = lambda self: self.assert_no_match("Alice has a cat")
test_some_number = lambda self: self.assert_no_match(42)
test_some_list = lambda self: self.assert_no_match([1, 2, 3, 5, 8, 13])
test_some_set = lambda self: self.assert_no_match(set([2, 4, 6, 8, 10]))
test_some_tuple = lambda self: self.assert_no_match(('foo', -1, ['bar']))
def test_some_dict__regular(self):
d = {'a': 1}
self.assert_match(d)
self.assert_match(d, str, int)
self.assert_match(d, keys=str, values=int)
self.assert_match(d, of=(str, int))
def test_some_dict__custom(self):
d = CustomDict({'a': 1})
self.assert_no_match(d)
self.assert_no_match(d, str, int)
self.assert_no_match(d, keys=str, values=int)
self.assert_no_match(d, of=(str, int))
test_some_generator = lambda self: self.assert_no_match(x for x in [1, 2])
test_some_object = lambda self: self.assert_no_match(object())
test_repr = lambda self: self.assert_repr(__unit__.Dict())
# Assertion functions
def assert_match(self, value, *args, **kwargs):
return super(Dict, self) \
.assert_match(__unit__.Dict(*args, **kwargs), value)
def assert_no_match(self, value, *args, **kwargs):
return super(Dict, self) \
.assert_no_match(__unit__.Dict(*args, **kwargs), value)
class OrderedDict(MatcherTestCase):
def test_invalid_arg(self):
with self.assertRaises(TypeError):
self.assert_match(None, of='not a pair of matchers')
test_none = lambda self: self.assert_no_match(None)
test_zero = lambda self: self.assert_no_match(0)
test_empty_string = lambda self: self.assert_no_match('')
test_empty_list = lambda self: self.assert_no_match([])
test_empty_set = lambda self: self.assert_no_match(set())
test_empty_tuple = lambda self: self.assert_no_match(())
test_empty_dict__regular = lambda self: self.assert_no_match({})
test_empty_dict__custom = lambda self: self.assert_no_match(CustomDict())
@skipIf(_OrderedDict is None,
"requires Python 2.6 or the ordereddict package")
def test_empty_ordereddict(self):
d = _OrderedDict()
self.assert_match(d)
self.assert_match(d, str, int)
self.assert_match(d, keys=str, values=int)
self.assert_match(d, of=(str, int))
test_empty_generator = lambda self: self.assert_no_match(x for x in ())
test_some_string = lambda self: self.assert_no_match("Alice has a cat")
test_some_number = lambda self: self.assert_no_match(42)
test_some_list = lambda self: self.assert_no_match([1, 2, 3, 5, 8, 13])
test_some_set = lambda self: self.assert_no_match(set([2, 4, 6, 8, 10]))
test_some_tuple = lambda self: self.assert_no_match(('foo', -1, ['bar']))
test_some_dict = lambda self: self.assert_no_match({'a': 1})
@skipIf(_OrderedDict is None,
"requires Python 2.6 or the ordereddict package")
def test_some_ordereddict(self):
d = _OrderedDict([('a', 1)])
self.assert_match(d)
self.assert_match(d, str, int)
self.assert_match(d, keys=str, values=int)
self.assert_match(d, of=(str, int))
test_some_generator = lambda self: self.assert_no_match(x for x in [1, 2])
test_some_object = lambda self: self.assert_no_match(object())
test_repr = lambda self: self.assert_repr(__unit__.OrderedDict())
# Assertion functions
def assert_match(self, value, *args, **kwargs):
return super(OrderedDict, self) \
.assert_match(__unit__.OrderedDict(*args, **kwargs), value)
def assert_no_match(self, value, *args, **kwargs):
return super(OrderedDict, self) \
.assert_no_match(__unit__.OrderedDict(*args, **kwargs), value)
| 38.899485 | 79 | 0.681309 | import collections
from taipan.testing import skipIf
from callee._compat import OrderedDict as _OrderedDict
import callee.collections as __unit__
from tests import MatcherTestCase
class Iterable(MatcherTestCase):
test_none = lambda self: self.assert_no_match(None)
test_zero = lambda self: self.assert_no_match(0)
test_empty_string = lambda self: self.assert_match('')
test_empty_list = lambda self: self.assert_match([])
test_empty_tuple = lambda self: self.assert_match(())
test_empty_dict = lambda self: self.assert_match({})
test_empty_generator = lambda self: self.assert_match(x for x in ())
test_some_string = lambda self: self.assert_match("Alice has a cat")
test_some_number = lambda self: self.assert_no_match(42)
test_some_list = lambda self: self.assert_match([1, 2, 3, 5, 8, 13])
test_some_tuple = lambda self: self.assert_match(('foo', -1, ['bar']))
def test_some_generator(self):
gen = (x for x in [1, 2, 5])
self.assert_match(gen)
self.assertNotEmpty(
gen, msg="matcher shouldn't have iterated over the generator")
test_some_object = lambda self: self.assert_no_match(object())
test_repr = lambda self: self.assert_repr(__unit__.Iterable())
# Assertion functions
def assert_match(self, value):
return super(Iterable, self).assert_match(__unit__.Iterable(), value)
def assert_no_match(self, value):
return super(Iterable, self) \
.assert_no_match(__unit__.Iterable(), value)
class Generator(MatcherTestCase):
test_none = lambda self: self.assert_no_match(None)
test_zero = lambda self: self.assert_no_match(0)
test_empty_string = lambda self: self.assert_no_match('')
test_empty_list = lambda self: self.assert_no_match([])
test_empty_tuple = lambda self: self.assert_no_match(())
test_empty_dict = lambda self: self.assert_no_match({})
test_empty_generator = lambda self: self.assert_match(x for x in ())
test_some_string = lambda self: self.assert_no_match("Alice has a cat")
test_some_number = lambda self: self.assert_no_match(42)
test_some_list = lambda self: self.assert_no_match([1, 2, 3, 5, 8, 13])
test_some_tuple = lambda self: self.assert_no_match(('foo', -1, ['bar']))
def test_some_generator(self):
gen = (x for x in [1, 2, 5])
self.assert_match(gen)
self.assertNotEmpty(
gen, msg="matcher shouldn't have iterated over the generator")
test_some_object = lambda self: self.assert_no_match(object())
test_repr = lambda self: self.assert_repr(__unit__.Generator())
def assert_match(self, value):
return super(Generator, self).assert_match(__unit__.Generator(), value)
def assert_no_match(self, value):
return super(Generator, self) \
.assert_no_match(__unit__.Generator(), value)
class Sequence(MatcherTestCase):
test_none = lambda self: self.assert_no_match(None)
test_zero = lambda self: self.assert_no_match(0)
test_empty_string = lambda self: self.assert_match('')
test_empty_list = lambda self: self.assert_match([])
test_empty_set = lambda self: self.assert_no_match(set())
test_empty_tuple = lambda self: self.assert_match(())
test_empty_dict = lambda self: self.assert_no_match({})
test_empty_generator = lambda self: self.assert_no_match(x for x in ())
def test_some_string(self):
s = "Alice has a cat"
self.assert_match(s)
self.assert_match(s, of=str)
test_some_number = lambda self: self.assert_no_match(42)
def test_some_list(self):
l = [1, 2, 3, 5, 8, 13]
self.assert_match(l)
self.assert_match(l, of=int)
test_some_tuple = lambda self: self.assert_match(('foo', -1, ['bar']))
test_some_generator = lambda self: self.assert_no_match(x for x in [1, 2])
test_some_object = lambda self: self.assert_no_match(object())
test_repr = lambda self: self.assert_repr(__unit__.Sequence())
def assert_match(self, value, of=None):
return super(Sequence, self).assert_match(__unit__.Sequence(of), value)
def assert_no_match(self, value, of=None):
return super(Sequence, self) \
.assert_no_match(__unit__.Sequence(of), value)
class List(MatcherTestCase):
test_none = lambda self: self.assert_no_match(None)
test_zero = lambda self: self.assert_no_match(0)
test_empty_string = lambda self: self.assert_no_match('')
test_empty_list = lambda self: self.assert_match([])
test_empty_set = lambda self: self.assert_no_match(set())
test_empty_tuple = lambda self: self.assert_no_match(())
test_empty_dict = lambda self: self.assert_no_match({})
test_empty_generator = lambda self: self.assert_no_match(x for x in ())
test_some_string = lambda self: self.assert_no_match("Alice has a cat")
test_some_number = lambda self: self.assert_no_match(42)
test_some_list = lambda self: self.assert_match([1, 2, 3, 5, 8, 13], int)
test_some_tuple = lambda self: self.assert_no_match(('foo', -1, ['bar']))
test_some_generator = lambda self: self.assert_no_match(x for x in [1, 2])
test_some_object = lambda self: self.assert_no_match(object())
test_repr = lambda self: self.assert_repr(__unit__.List())
def assert_match(self, value, of=None):
return super(List, self).assert_match(__unit__.List(of), value)
def assert_no_match(self, value, of=None):
return super(List, self).assert_no_match(__unit__.List(of), value)
class Set(MatcherTestCase):
test_none = lambda self: self.assert_no_match(None)
test_zero = lambda self: self.assert_no_match(0)
test_empty_string = lambda self: self.assert_no_match('')
test_empty_list = lambda self: self.assert_no_match([])
test_empty_set = lambda self: self.assert_match(set())
test_empty_tuple = lambda self: self.assert_no_match(())
test_empty_dict = lambda self: self.assert_no_match({})
test_empty_generator = lambda self: self.assert_no_match(x for x in ())
test_some_string = lambda self: self.assert_no_match("Alice has a cat")
test_some_number = lambda self: self.assert_no_match(42)
test_some_list = lambda self: self.assert_no_match([1, 2, 3, 5, 8, 13])
test_some_set = lambda self: self.assert_match(set([2, 4, 6, 8, 10]), int)
test_some_tuple = lambda self: self.assert_no_match(('foo', -1, ['bar']))
test_some_generator = lambda self: self.assert_no_match(x for x in [1, 2])
test_some_object = lambda self: self.assert_no_match(object())
test_repr = lambda self: self.assert_repr(__unit__.Set())
def assert_match(self, value, of=None):
return super(Set, self).assert_match(__unit__.Set(of), value)
def assert_no_match(self, value, of=None):
return super(Set, self).assert_no_match(__unit__.Set(of), value)
class CustomDict(collections.MutableMapping):
def __init__(self, iterable=(), **kwargs):
if isinstance(iterable, collections.Mapping):
iterable = iterable.items()
self.d = {}
for k, v in iterable:
self.d[k] = v
self.d.update(kwargs)
def __delitem__(self, key):
del self.d[key]
def __getitem__(self, key):
return self.d[key]
def __iter__(self):
return iter(self.d)
def __len__(self):
return len(self.d)
def __setitem__(self, key, value):
self.d[key] = value
class Mapping(MatcherTestCase):
def test_invalid_arg(self):
with self.assertRaises(TypeError):
self.assert_match(None, of='not a pair of matchers')
test_none = lambda self: self.assert_no_match(None)
test_zero = lambda self: self.assert_no_match(0)
test_empty_string = lambda self: self.assert_no_match('')
test_empty_list = lambda self: self.assert_no_match([])
test_empty_set = lambda self: self.assert_no_match(set())
test_empty_tuple = lambda self: self.assert_no_match(())
def test_empty_dict__regular(self):
d = {}
self.assert_match(d)
self.assert_match(d, str, int)
self.assert_match(d, keys=str, values=int)
self.assert_match(d, of=(str, int))
def test_empty_dict__custom(self):
d = CustomDict()
self.assert_match(d)
self.assert_match(d, str, int)
self.assert_match(d, keys=str, values=int)
self.assert_match(d, of=(str, int))
test_empty_generator = lambda self: self.assert_no_match(x for x in ())
test_some_string = lambda self: self.assert_no_match("Alice has a cat")
test_some_number = lambda self: self.assert_no_match(42)
test_some_list = lambda self: self.assert_no_match([1, 2, 3, 5, 8, 13])
test_some_set = lambda self: self.assert_no_match(set([2, 4, 6, 8, 10]))
test_some_tuple = lambda self: self.assert_no_match(('foo', -1, ['bar']))
def test_some_dict__regular(self):
d = {'a': 1}
self.assert_match(d)
self.assert_match(d, str, int)
self.assert_match(d, keys=str, values=int)
self.assert_match(d, of=(str, int))
def test_some_dict__custom(self):
d = CustomDict({'a': 1})
self.assert_match(d)
self.assert_match(d, str, int)
self.assert_match(d, keys=str, values=int)
self.assert_match(d, of=(str, int))
test_some_generator = lambda self: self.assert_no_match(x for x in [1, 2])
test_some_object = lambda self: self.assert_no_match(object())
test_repr = lambda self: self.assert_repr(__unit__.Mapping())
def assert_match(self, value, *args, **kwargs):
return super(Mapping, self)\
.assert_match(__unit__.Mapping(*args, **kwargs), value)
def assert_no_match(self, value, *args, **kwargs):
return super(Mapping, self) \
.assert_no_match(__unit__.Mapping(*args, **kwargs), value)
class Dict(MatcherTestCase):
def test_invalid_arg(self):
with self.assertRaises(TypeError):
self.assert_match(None, of='not a pair of matchers')
test_none = lambda self: self.assert_no_match(None)
test_zero = lambda self: self.assert_no_match(0)
test_empty_string = lambda self: self.assert_no_match('')
test_empty_list = lambda self: self.assert_no_match([])
test_empty_set = lambda self: self.assert_no_match(set())
test_empty_tuple = lambda self: self.assert_no_match(())
def test_empty_dict__regular(self):
d = {}
self.assert_match(d)
self.assert_match(d, str, int)
self.assert_match(d, keys=str, values=int)
self.assert_match(d, of=(str, int))
def test_empty_dict__custom(self):
d = CustomDict()
self.assert_no_match(d)
self.assert_no_match(d, str, int)
self.assert_no_match(d, keys=str, values=int)
self.assert_no_match(d, of=(str, int))
test_empty_generator = lambda self: self.assert_no_match(x for x in ())
test_some_string = lambda self: self.assert_no_match("Alice has a cat")
test_some_number = lambda self: self.assert_no_match(42)
test_some_list = lambda self: self.assert_no_match([1, 2, 3, 5, 8, 13])
test_some_set = lambda self: self.assert_no_match(set([2, 4, 6, 8, 10]))
test_some_tuple = lambda self: self.assert_no_match(('foo', -1, ['bar']))
def test_some_dict__regular(self):
d = {'a': 1}
self.assert_match(d)
self.assert_match(d, str, int)
self.assert_match(d, keys=str, values=int)
self.assert_match(d, of=(str, int))
def test_some_dict__custom(self):
d = CustomDict({'a': 1})
self.assert_no_match(d)
self.assert_no_match(d, str, int)
self.assert_no_match(d, keys=str, values=int)
self.assert_no_match(d, of=(str, int))
test_some_generator = lambda self: self.assert_no_match(x for x in [1, 2])
test_some_object = lambda self: self.assert_no_match(object())
test_repr = lambda self: self.assert_repr(__unit__.Dict())
def assert_match(self, value, *args, **kwargs):
return super(Dict, self) \
.assert_match(__unit__.Dict(*args, **kwargs), value)
def assert_no_match(self, value, *args, **kwargs):
return super(Dict, self) \
.assert_no_match(__unit__.Dict(*args, **kwargs), value)
class OrderedDict(MatcherTestCase):
def test_invalid_arg(self):
with self.assertRaises(TypeError):
self.assert_match(None, of='not a pair of matchers')
test_none = lambda self: self.assert_no_match(None)
test_zero = lambda self: self.assert_no_match(0)
test_empty_string = lambda self: self.assert_no_match('')
test_empty_list = lambda self: self.assert_no_match([])
test_empty_set = lambda self: self.assert_no_match(set())
test_empty_tuple = lambda self: self.assert_no_match(())
test_empty_dict__regular = lambda self: self.assert_no_match({})
test_empty_dict__custom = lambda self: self.assert_no_match(CustomDict())
@skipIf(_OrderedDict is None,
"requires Python 2.6 or the ordereddict package")
def test_empty_ordereddict(self):
d = _OrderedDict()
self.assert_match(d)
self.assert_match(d, str, int)
self.assert_match(d, keys=str, values=int)
self.assert_match(d, of=(str, int))
test_empty_generator = lambda self: self.assert_no_match(x for x in ())
test_some_string = lambda self: self.assert_no_match("Alice has a cat")
test_some_number = lambda self: self.assert_no_match(42)
test_some_list = lambda self: self.assert_no_match([1, 2, 3, 5, 8, 13])
test_some_set = lambda self: self.assert_no_match(set([2, 4, 6, 8, 10]))
test_some_tuple = lambda self: self.assert_no_match(('foo', -1, ['bar']))
test_some_dict = lambda self: self.assert_no_match({'a': 1})
@skipIf(_OrderedDict is None,
"requires Python 2.6 or the ordereddict package")
def test_some_ordereddict(self):
d = _OrderedDict([('a', 1)])
self.assert_match(d)
self.assert_match(d, str, int)
self.assert_match(d, keys=str, values=int)
self.assert_match(d, of=(str, int))
test_some_generator = lambda self: self.assert_no_match(x for x in [1, 2])
test_some_object = lambda self: self.assert_no_match(object())
test_repr = lambda self: self.assert_repr(__unit__.OrderedDict())
def assert_match(self, value, *args, **kwargs):
return super(OrderedDict, self) \
.assert_match(__unit__.OrderedDict(*args, **kwargs), value)
def assert_no_match(self, value, *args, **kwargs):
return super(OrderedDict, self) \
.assert_no_match(__unit__.OrderedDict(*args, **kwargs), value)
| true | true |
f71669ba767a939cc5d439ef370d6333952c145a | 226 | py | Python | course_api/templatetags/time_converter.py | dragonbone81/bobcat-courses-backend | d0f98b837f37eb16a89a24ce9bd3f3f0fd52064c | [
"MIT"
] | 3 | 2018-10-25T12:41:33.000Z | 2019-09-19T19:47:39.000Z | course_api/templatetags/time_converter.py | dragonbone81/bobcat-courses-backend | d0f98b837f37eb16a89a24ce9bd3f3f0fd52064c | [
"MIT"
] | 22 | 2018-04-01T02:43:01.000Z | 2022-03-11T23:15:55.000Z | course_api/templatetags/time_converter.py | dragonbone81/cse120 | d0f98b837f37eb16a89a24ce9bd3f3f0fd52064c | [
"MIT"
] | 1 | 2019-09-19T19:48:59.000Z | 2019-09-19T19:48:59.000Z | from django.template.defaulttags import register
@register.filter
def get_item(dictionary, key):
return dictionary.get(key)
@register.filter
def get_item_dict(dictionary, key):
return {'data': dictionary.get(key)}
| 18.833333 | 48 | 0.761062 | from django.template.defaulttags import register
@register.filter
def get_item(dictionary, key):
return dictionary.get(key)
@register.filter
def get_item_dict(dictionary, key):
return {'data': dictionary.get(key)}
| true | true |
f71669f5529851928377789218c8de2abda6eaf6 | 5,513 | py | Python | 测试/tensorflow_hello/2.practices_on_nlp.py | shayxu-ai/A-Repository-for-Machine-Learning | 4b4cea15bb005d1c58f4395fde97cadf44fb0186 | [
"Apache-2.0"
] | null | null | null | 测试/tensorflow_hello/2.practices_on_nlp.py | shayxu-ai/A-Repository-for-Machine-Learning | 4b4cea15bb005d1c58f4395fde97cadf44fb0186 | [
"Apache-2.0"
] | null | null | null | 测试/tensorflow_hello/2.practices_on_nlp.py | shayxu-ai/A-Repository-for-Machine-Learning | 4b4cea15bb005d1c58f4395fde97cadf44fb0186 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# @Time: 2020/2/5,005 22:02
# @Last Update: 2020/2/5,005 22:02
# @Author: 徐缘
# @FileName: 2.practices_on_nlp.py
# @Software: PyCharm
from __future__ import absolute_import, division, print_function, unicode_literals # 导入一些熟悉的陌生人
# 绝对引入,精确除法,print,unicode类型字符串。都是为了适配python2,不加也罢
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense, Flatten, Conv2D
from tensorflow.keras import Model
from tensorflow import keras
import tensorflow_hub as hub # 模型库
import tensorflow_datasets as tfds # 数据|库 https://tensorflow.google.cn/datasets/api_docs/python/tfds?hl=en
tfds.disable_progress_bar()
def version():
"""
国际惯例,先看下版本
"""
print("Eager mode: ", tf.executing_eagerly())
print("Hub version: ", hub.__version__)
print("tfds version", tfds.__version__)
print("GPU is", "available" if tf.config.experimental.list_physical_devices("GPU") else "NOT AVAILABLE")
def tf_hub_hello():
"""
预训练word2vector(迁移学习) + 全连接层
loss: 0.329
accuracy: 0.858 我记得 cnn 文本分类可以有95%呢
"""
train_data, validation_data, test_data = tfds.load(
name="imdb_reviews", split=('train[:60%]', 'train[60%:]', 'test'),
as_supervised=True)
train_examples_batch, train_labels_batch = next(iter(train_data.batch(10)))
print(train_examples_batch)
print(train_labels_batch)
embedding = "https://hub.tensorflow.google.cn/google/tf2-preview/gnews-swivel-20dim/1"
hub_layer = hub.KerasLayer(embedding, input_shape=[],
dtype=tf.string, trainable=True)
print(hub_layer(train_examples_batch[:3]))
model = tf.keras.Sequential()
model.add(hub_layer)
model.add(tf.keras.layers.Dense(16, activation='relu'))
model.add(tf.keras.layers.Dense(1, activation='sigmoid'))
# model.summary()
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
history = model.fit(train_data.shuffle(10000).batch(512),
epochs=20,
validation_data=validation_data.batch(512),
verbose=1)
results = model.evaluate(test_data.batch(512), verbose=2)
for name, value in zip(model.metrics_names, results):
print("%s: %.3f" % (name, value))
def preprocess_text():
"""
"""
(train_data, test_data), info = tfds.load(
# Use the version pre-encoded with an ~8k vocabulary.
'imdb_reviews/subwords8k',
# Return the train/test datasets as a tuple.
split=(tfds.Split.TRAIN, tfds.Split.TEST),
# Return (example, label) pairs from the dataset (instead of a dictionary).
as_supervised=True,
# Also return the `info` structure.
with_info=True)
encoder = info.features['text'].encoder
print('Vocabulary size: {}'.format(encoder.vocab_size))
sample_string = 'Hello TensorFlow.'
encoded_string = encoder.encode(sample_string)
print('Encoded string is {}'.format(encoded_string))
original_string = encoder.decode(encoded_string)
print('The original string: "{}"'.format(original_string))
assert original_string == sample_string
for ts in encoded_string:
print('{} ----> {}'.format(ts, encoder.decode([ts])))
for train_example, train_label in train_data.take(1):
print('Encoded text:', train_example[:10].numpy())
print('Label:', train_label.numpy())
encoder.decode(train_example)
BUFFER_SIZE = 1000
train_batches = (
train_data
.shuffle(BUFFER_SIZE)
.padded_batch(32, train_data.output_shapes))
test_batches = (
test_data
.padded_batch(32, train_data.output_shapes))
for example_batch, label_batch in train_batches.take(2):
print("Batch shape:", example_batch.shape)
print("label shape:", label_batch.shape)
model = keras.Sequential([
keras.layers.Embedding(encoder.vocab_size, 16),
keras.layers.GlobalAveragePooling1D(),
keras.layers.Dense(1, activation='sigmoid')])
model.summary()
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
history = model.fit(train_batches,
epochs=10,
validation_data=test_batches,
validation_steps=30)
loss, accuracy = model.evaluate(test_batches)
print("Loss: ", loss)
print("Accuracy: ", accuracy)
history_dict = history.history
history_dict.keys()
import matplotlib.pyplot as plt
acc = history_dict['accuracy']
val_acc = history_dict['val_accuracy']
loss = history_dict['loss']
val_loss = history_dict['val_loss']
epochs = range(1, len(acc) + 1)
# "bo" is for "blue dot"
plt.plot(epochs, loss, 'bo', label='Training loss')
# b is for "solid blue line"
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
plt.clf() # clear figure
plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend(loc='lower right')
plt.show()
return
if __name__ == '__main__':
# version()
preprocess_text()
| 29.169312 | 108 | 0.643751 |
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense, Flatten, Conv2D
from tensorflow.keras import Model
from tensorflow import keras
import tensorflow_hub as hub
import tensorflow_datasets as tfds
tfds.disable_progress_bar()
def version():
print("Eager mode: ", tf.executing_eagerly())
print("Hub version: ", hub.__version__)
print("tfds version", tfds.__version__)
print("GPU is", "available" if tf.config.experimental.list_physical_devices("GPU") else "NOT AVAILABLE")
def tf_hub_hello():
train_data, validation_data, test_data = tfds.load(
name="imdb_reviews", split=('train[:60%]', 'train[60%:]', 'test'),
as_supervised=True)
train_examples_batch, train_labels_batch = next(iter(train_data.batch(10)))
print(train_examples_batch)
print(train_labels_batch)
embedding = "https://hub.tensorflow.google.cn/google/tf2-preview/gnews-swivel-20dim/1"
hub_layer = hub.KerasLayer(embedding, input_shape=[],
dtype=tf.string, trainable=True)
print(hub_layer(train_examples_batch[:3]))
model = tf.keras.Sequential()
model.add(hub_layer)
model.add(tf.keras.layers.Dense(16, activation='relu'))
model.add(tf.keras.layers.Dense(1, activation='sigmoid'))
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
history = model.fit(train_data.shuffle(10000).batch(512),
epochs=20,
validation_data=validation_data.batch(512),
verbose=1)
results = model.evaluate(test_data.batch(512), verbose=2)
for name, value in zip(model.metrics_names, results):
print("%s: %.3f" % (name, value))
def preprocess_text():
(train_data, test_data), info = tfds.load(
'imdb_reviews/subwords8k',
split=(tfds.Split.TRAIN, tfds.Split.TEST),
as_supervised=True,
with_info=True)
encoder = info.features['text'].encoder
print('Vocabulary size: {}'.format(encoder.vocab_size))
sample_string = 'Hello TensorFlow.'
encoded_string = encoder.encode(sample_string)
print('Encoded string is {}'.format(encoded_string))
original_string = encoder.decode(encoded_string)
print('The original string: "{}"'.format(original_string))
assert original_string == sample_string
for ts in encoded_string:
print('{} ----> {}'.format(ts, encoder.decode([ts])))
for train_example, train_label in train_data.take(1):
print('Encoded text:', train_example[:10].numpy())
print('Label:', train_label.numpy())
encoder.decode(train_example)
BUFFER_SIZE = 1000
train_batches = (
train_data
.shuffle(BUFFER_SIZE)
.padded_batch(32, train_data.output_shapes))
test_batches = (
test_data
.padded_batch(32, train_data.output_shapes))
for example_batch, label_batch in train_batches.take(2):
print("Batch shape:", example_batch.shape)
print("label shape:", label_batch.shape)
model = keras.Sequential([
keras.layers.Embedding(encoder.vocab_size, 16),
keras.layers.GlobalAveragePooling1D(),
keras.layers.Dense(1, activation='sigmoid')])
model.summary()
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
history = model.fit(train_batches,
epochs=10,
validation_data=test_batches,
validation_steps=30)
loss, accuracy = model.evaluate(test_batches)
print("Loss: ", loss)
print("Accuracy: ", accuracy)
history_dict = history.history
history_dict.keys()
import matplotlib.pyplot as plt
acc = history_dict['accuracy']
val_acc = history_dict['val_accuracy']
loss = history_dict['loss']
val_loss = history_dict['val_loss']
epochs = range(1, len(acc) + 1)
plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
plt.clf()
plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend(loc='lower right')
plt.show()
return
if __name__ == '__main__':
preprocess_text()
| true | true |
f7166a5ae2764771f45e5ae446f7d0e4b402bd2c | 3,231 | py | Python | test/test_default_api.py | cinaq/axxell-client-python | a862dd36552ef8149517c5d5034a52a37abc2d33 | [
"Apache-2.0"
] | null | null | null | test/test_default_api.py | cinaq/axxell-client-python | a862dd36552ef8149517c5d5034a52a37abc2d33 | [
"Apache-2.0"
] | null | null | null | test/test_default_api.py | cinaq/axxell-client-python | a862dd36552ef8149517c5d5034a52a37abc2d33 | [
"Apache-2.0"
] | null | null | null | # coding: utf-8
"""
axxell-api
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from __future__ import absolute_import
import os
import sys
import unittest
import AxxellClient
from AxxellClient.rest import ApiException
from AxxellClient.apis.default_api import DefaultApi
class TestDefaultApi(unittest.TestCase):
""" DefaultApi unit test stubs """
def setUp(self):
self.api = AxxellClient.apis.default_api.DefaultApi()
def tearDown(self):
pass
def test_aggregate_count_events(self):
"""
Test case for aggregate_count_events
"""
pass
def test_aggregate_effective(self):
"""
Test case for aggregate_effective
"""
pass
def test_aggregate_events(self):
"""
Test case for aggregate_events
"""
pass
def test_aggregate_recent(self):
"""
Test case for aggregate_recent
"""
pass
def test_aggregate_top(self):
"""
Test case for aggregate_top
"""
pass
def test_auth_store(self):
"""
Test case for auth_store
"""
pass
def test_delete_all_events(self):
"""
Test case for delete_all_events
"""
pass
def test_delete_all_items(self):
"""
Test case for delete_all_items
"""
pass
def test_delete_item(self):
"""
Test case for delete_item
"""
pass
def test_recommend_interesting(self):
"""
Test case for recommend_interesting
"""
pass
def test_recommend_similar(self):
"""
Test case for recommend_similar
"""
pass
def test_register_event(self):
"""
Test case for register_event
"""
pass
def test_register_item(self):
"""
Test case for register_item
"""
pass
def test_register_store(self):
"""
Test case for register_store
"""
pass
def test_retrieve_events(self):
"""
Test case for retrieve_events
"""
pass
def test_retrieve_items(self):
"""
Test case for retrieve_items
"""
pass
if __name__ == '__main__':
unittest.main()
| 18.357955 | 105 | 0.573197 |
from __future__ import absolute_import
import os
import sys
import unittest
import AxxellClient
from AxxellClient.rest import ApiException
from AxxellClient.apis.default_api import DefaultApi
class TestDefaultApi(unittest.TestCase):
def setUp(self):
self.api = AxxellClient.apis.default_api.DefaultApi()
def tearDown(self):
pass
def test_aggregate_count_events(self):
pass
def test_aggregate_effective(self):
pass
def test_aggregate_events(self):
pass
def test_aggregate_recent(self):
pass
def test_aggregate_top(self):
pass
def test_auth_store(self):
pass
def test_delete_all_events(self):
pass
def test_delete_all_items(self):
pass
def test_delete_item(self):
pass
def test_recommend_interesting(self):
pass
def test_recommend_similar(self):
pass
def test_register_event(self):
pass
def test_register_item(self):
pass
def test_register_store(self):
pass
def test_retrieve_events(self):
pass
def test_retrieve_items(self):
pass
if __name__ == '__main__':
unittest.main()
| true | true |
f7166ab579b24ca3fb29824e02008e934e83680a | 22,183 | py | Python | openmdao/components/interp_util/interp.py | friedenhe/OpenMDAO | db1d7e22a8bf9f66afa82ec3544b7244d5545f6d | [
"Apache-2.0"
] | null | null | null | openmdao/components/interp_util/interp.py | friedenhe/OpenMDAO | db1d7e22a8bf9f66afa82ec3544b7244d5545f6d | [
"Apache-2.0"
] | null | null | null | openmdao/components/interp_util/interp.py | friedenhe/OpenMDAO | db1d7e22a8bf9f66afa82ec3544b7244d5545f6d | [
"Apache-2.0"
] | null | null | null | """
Base class for interpolation methods that calculate values for each dimension independently.
Based on Tables in NPSS, and was added to bridge the gap between some of the slower scipy
implementations.
"""
import numpy as np
from openmdao.components.interp_util.interp_akima import InterpAkima, Interp1DAkima
from openmdao.components.interp_util.interp_bsplines import InterpBSplines
from openmdao.components.interp_util.interp_cubic import InterpCubic
from openmdao.components.interp_util.interp_lagrange2 import InterpLagrange2, Interp3DLagrange2
from openmdao.components.interp_util.interp_lagrange3 import InterpLagrange3, Interp3DLagrange3
from openmdao.components.interp_util.interp_scipy import InterpScipy
from openmdao.components.interp_util.interp_slinear import InterpLinear, Interp3DSlinear, \
Interp1DSlinear, Interp2DSlinear
from openmdao.components.interp_util.outofbounds_error import OutOfBoundsError
from openmdao.utils.om_warnings import warn_deprecation
INTERP_METHODS = {
'slinear': InterpLinear,
'lagrange2': InterpLagrange2,
'lagrange3': InterpLagrange3,
'cubic': InterpCubic,
'akima': InterpAkima,
'scipy_cubic': InterpScipy,
'scipy_slinear': InterpScipy,
'scipy_quintic': InterpScipy,
'bsplines': InterpBSplines,
'1D-slinear': Interp1DSlinear,
'2D-slinear': Interp2DSlinear,
'3D-slinear': Interp3DSlinear,
'3D-lagrange2': Interp3DLagrange2,
'3D-lagrange3': Interp3DLagrange3,
'1D-akima': Interp1DAkima,
'trilinear': Interp3DSlinear, # Deprecated
'akima1D': Interp1DAkima, # Deprecated
}
TABLE_METHODS = ['slinear', 'lagrange2', 'lagrange3', 'cubic', 'akima',
'scipy_cubic', 'scipy_slinear', 'scipy_quintic',
'trilinear', 'akima1D', # These two are Deprecated
'3D-slinear', '2D-slinear', '1D-slinear',
'1D-akima',
'3D-lagrange2', '3D-lagrange3']
SPLINE_METHODS = ['slinear', 'lagrange2', 'lagrange3', 'cubic', 'akima', 'bsplines',
'scipy_cubic', 'scipy_slinear', 'scipy_quintic']
class InterpND(object):
"""
Interpolation on a regular grid of arbitrary dimensions.
The data must be defined on a regular grid; the grid spacing however may be uneven. Several
interpolation methods are supported. These are defined in the child classes. Gradients are
provided for all interpolation methods. Gradients with respect to grid values are also
available optionally.
Parameters
----------
method : str
Name of interpolation method.
points : ndarray or tuple of ndarray
The points defining the regular grid in n dimensions.
For 1D interpolation, this can be an ndarray of table locations.
For table interpolation, it can be a tuple or an ndarray. If it is a tuple, it should
contain one ndarray for each table dimension.
For spline evaluation, num_cp can be specified instead of points.
values : ndarray or tuple of ndarray or None
These must be specified for interpolation.
The data on the regular grid in n dimensions.
x_interp : ndarray or None
If we are always interpolating at a fixed set of locations, then they can be
specified here.
extrapolate : bool
If False, when interpolated values are requested outside of the domain of the input
data, a ValueError is raised. If True, then the methods are allowed to extrapolate.
Default is True (raise an exception).
num_cp : None or int
Optional. When specified, use a linear distribution of num_cp control points. If you
are using 'bsplines' as the method, then num_cp must be set instead of points.
**kwargs : dict
Interpolator-specific options to pass onward.
Attributes
----------
extrapolate : bool
If False, when interpolated values are requested outside of the domain of the input data,
a ValueError is raised. If True, then the methods are allowed to extrapolate.
Default is True.
grid : tuple
Collection of points that determine the regular grid.
table : <InterpTable>
Table object that contains algorithm that performs the interpolation.
values : array_like, shape (m1, ..., mn, ...)
The data on the regular grid in n dimensions.
x_interp : ndarray
Cached non-decreasing vector of points to be interpolated when used as an order-reducing
spline.
_compute_d_dvalues : bool
When set to True, compute gradients with respect to the grid values.
_compute_d_dx : bool
When set to True, compute gradients with respect to the interpolated point location.
_d_dx : ndarray
Cache of computed gradients with respect to evaluation point.
_d_dvalues : ndarray
Cache of computed gradients with respect to table values.
_interp : class
Class specified as interpolation algorithm, used to regenerate if needed.
_interp_config : dict
Configuration object that stores the number of points required for each interpolation
method.
_interp_options : dict
Dictionary of cached interpolator-specific options.
_xi : ndarray
Cache of current evaluation point.
"""
def __init__(self, method="slinear", points=None, values=None, x_interp=None, extrapolate=False,
num_cp=None, **kwargs):
"""
Initialize an InterpND object.
This object can be setup and used to interpolate on a curve or multi-dimensional table.
It can also be used to setup an interpolating spline that can be evaluated at fixed
locations.
For interpolation, specify values and points.
For spline evaluation, specifiy x_interp and either points or num_cp.
"""
if not isinstance(method, str):
msg = "Argument 'method' should be a string."
raise ValueError(msg)
elif method not in INTERP_METHODS:
all_m = ', '.join(['"' + m + '"' for m in INTERP_METHODS])
raise ValueError('Interpolation method "%s" is not defined. Valid methods are '
'%s.' % (method, all_m))
elif method == 'akima1D':
warn_deprecation("The 'akima1D' method has been renamed to '1D-akima'.")
elif method == 'trilinear':
warn_deprecation("The 'trilinear' method has been renamed to '3D-slinear'.")
self.extrapolate = extrapolate
# The table points are always defined, by specifying either the points directly, or num_cp.
if points is None:
if num_cp is not None:
points = [np.linspace(0.0, 1.0, num_cp)]
else:
msg = "Either 'points' or 'num_cp' must be specified."
raise ValueError(msg)
else:
if isinstance(points, np.ndarray):
points = [points]
for i, p in enumerate(points):
n_p = len(p)
if not np.all(np.diff(p) > 0.):
raise ValueError("The points in dimension %d must be strictly "
"ascending" % i)
if not np.asarray(p).ndim == 1:
raise ValueError("The points in dimension %d must be "
"1-dimensional" % i)
# Table Interpolation
if x_interp is None:
if values is None:
msg = "Either 'values' or 'x_interp' must be specified."
raise ValueError(msg)
if method == 'bsplines':
msg = "Method 'bsplines' is not supported for table interpolation."
raise ValueError(msg)
if not hasattr(values, 'ndim'):
# allow reasonable duck-typed values
values = np.asarray(values)
if hasattr(values, 'dtype') and hasattr(values, 'astype'):
if not np.issubdtype(values.dtype, np.inexact):
values = values.astype(float)
if len(points) > values.ndim:
raise ValueError("There are %d point arrays, but values has %d "
"dimensions" % (len(points), values.ndim))
if (method.startswith('scipy') or method == 'akima') and \
(np.iscomplexobj(values[:]) or np.any(np.iscomplex(points[0]))):
msg = f"Interpolation method '{method}' does not support complex points or values."
raise ValueError(msg)
for i, p in enumerate(points):
n_p = len(p)
if values.shape[i] != n_p:
raise ValueError("There are %d points and %d values in "
"dimension %d" % (len(p), values.shape[i], i))
self.grid = tuple([np.asarray(p) for p in points])
self.values = values
self.x_interp = x_interp
self._xi = None
self._d_dx = None
self._d_dvalues = None
self._compute_d_dvalues = False
self._compute_d_dx = True
# Cache spline coefficients.
interp = INTERP_METHODS[method]
if method.startswith('scipy'):
kwargs['interp_method'] = method
table = interp(self.grid, values, interp, **kwargs)
table.check_config()
self.table = table
self._interp = interp
self._interp_options = kwargs
def interpolate(self, x, compute_derivative=False):
"""
Interpolate at the sample coordinates.
Parameters
----------
x : ndarray or tuple
Locations to interpolate.
compute_derivative : bool
Set to True to compute derivatives with respect to x.
Returns
-------
ndarray
Value of interpolant at all sample points.
ndarray
Value of derivative of interpolated output with respect to input x. (Only when
compute_derivative is True).
"""
self._compute_d_dx = compute_derivative
self.table._compute_d_dx = compute_derivative
self.table._compute_d_dvalues = False
if isinstance(x, np.ndarray):
if len(x.shape) < 2:
if len(self.grid) > 1:
# Input is an array containing multi-D coordinates of a single point.
x = np.atleast_2d(x)
else:
# Input is an array of separate points on a 1D table.
x = np.atleast_2d(x).T
else:
# Input is a list or tuple of separate points.
x = np.atleast_2d(x)
# cache latest evaluation point for gradient method's use later
self._xi = x
xnew = self._interpolate(x)
if compute_derivative:
return xnew, self._d_dx
else:
return xnew
def evaluate_spline(self, values, compute_derivative=False):
"""
Interpolate at all fixed output coordinates given the new table values.
Parameters
----------
values : ndarray(n_points)
New data values for all points on the regular grid.
compute_derivative : bool
Set to True to compute derivatives with respect to x.
Returns
-------
ndarray
Value of interpolant at all sample points.
ndarray
Value of derivative of interpolated output with respect to values.
"""
self._compute_d_dvalues = compute_derivative
self.table._compute_d_dvalues = compute_derivative
self.table._compute_d_dx = False
if len(values.shape) == 1:
values = np.expand_dims(values, axis=0)
# cache latest evaluation point for gradient method's use later
self._xi = self.x_interp.copy()
result = self._evaluate_spline(values)
if result.shape[0] == 1:
# Not vectorized, so drop the extra dimension.
result = result.ravel()
if compute_derivative:
d_dvalues = self.spline_gradient()
if d_dvalues.shape[0] == 1:
d_dvalues = d_dvalues[0]
return result, d_dvalues
else:
return result
def _interpolate(self, xi):
"""
Interpolate at the sample coordinates.
This method is called from OpenMDAO, and is not meant for standalone use.
Parameters
----------
xi : ndarray of shape (..., ndim)
The coordinates to sample the gridded data.
Returns
-------
ndarray
Value of interpolant at all sample points.
"""
if not self.extrapolate:
for i, p in enumerate(xi.T):
if np.isnan(p).any():
raise OutOfBoundsError("One of the requested xi contains a NaN",
i, np.NaN, self.grid[i][0], self.grid[i][-1])
eps = 1e-14 * self.grid[i][-1]
if np.any(p < self.grid[i][0] - eps) or np.any(p > self.grid[i][-1] + eps):
p1 = np.where(self.grid[i][0] > p)[0]
p2 = np.where(p > self.grid[i][-1])[0]
# First violating entry is enough to direct the user.
violated_idx = set(p1).union(p2).pop()
value = p[violated_idx]
raise OutOfBoundsError("One of the requested xi is out of bounds",
i, value, self.grid[i][0], self.grid[i][-1])
if self._compute_d_dvalues:
# If the table grid or values are component inputs, then we need to create a new table
# each iteration.
interp = self._interp
self.table = interp(self.grid, self.values, interp, **self._interp_options)
if not self.table._supports_d_dvalues:
raise RuntimeError(f'Method {self.table._name} does not support the '
'"training_data_gradients" option.')
self.table._compute_d_dvalues = True
table = self.table
if table.vectorized(xi):
result, derivs_x, derivs_val, derivs_grid = table.evaluate_vectorized(xi)
else:
n_nodes, nx = xi.shape
result = np.empty((n_nodes, ), dtype=xi.dtype)
derivs_x = np.empty((n_nodes, nx), dtype=xi.dtype)
derivs_val = None
# TODO: it might be possible to vectorize over n_nodes.
for j in range(n_nodes):
val, d_x, d_values, d_grid = table.evaluate(xi[j, ...])
result[j] = val
derivs_x[j, :] = d_x.ravel()
if d_values is not None:
if derivs_val is None:
dv_shape = [n_nodes]
dv_shape.extend(self.values.shape)
derivs_val = np.zeros(dv_shape, dtype=xi.dtype)
in_slice = table._full_slice
full_slice = [slice(j, j + 1)]
full_slice.extend(in_slice)
shape = derivs_val[tuple(full_slice)].shape
derivs_val[tuple(full_slice)] = d_values.reshape(shape)
# Cache derivatives
self._d_dx = derivs_x
self._d_dvalues = derivs_val
return result
def _evaluate_spline(self, values):
"""
Interpolate at all fixed output coordinates given the new table values.
This method is called from OpenMDAO, and is not meant for standalone use.
Parameters
----------
values : ndarray(n_nodes x n_points)
The data on the regular grid in n dimensions.
Returns
-------
ndarray
Value of interpolant at all sample points.
"""
xi = self.x_interp
self.values = values
table = self.table
if table._vectorized:
if table._name == 'bsplines':
# bsplines is fully vectorized.
table.values = values
result, _, derivs_val, _ = table.evaluate_vectorized(xi)
else:
# Scipy implementation vectorized over lookups, but not over multiple table values.
interp = self._interp
n_nodes, _ = values.shape
nx = np.prod(xi.shape)
result = np.empty((n_nodes, nx), dtype=values.dtype)
derivs_val = None
for j in range(n_nodes):
table = interp(self.grid, values[j, :], interp, **self._interp_options)
table._compute_d_dvalues = False
table._compute_d_dx = False
result[j, :], _, _, _ = table.evaluate_vectorized(xi.reshape((nx, 1)))
else:
interp = self._interp
n_nodes, _ = values.shape
nx = np.prod(xi.shape)
result = np.empty((n_nodes, nx), dtype=values.dtype)
derivs_val = None
# TODO: it might be possible to vectorize over n_nodes.
for j in range(n_nodes):
table = interp(self.grid, values[j, :], interp, **self._interp_options)
table._compute_d_dvalues = True
table._compute_d_dx = False
for k in range(nx):
x_pt = np.atleast_2d(xi[k])
val, _, d_values, _ = table.evaluate(x_pt)
result[j, k] = val
if d_values is not None:
if derivs_val is None:
dv_shape = [n_nodes, nx]
dv_shape.extend(values.shape[1:])
derivs_val = np.zeros(dv_shape, dtype=values.dtype)
in_slice = table._full_slice
full_slice = [slice(j, j + 1), slice(k, k + 1)]
full_slice.extend(in_slice)
shape = derivs_val[tuple(full_slice)].shape
derivs_val[tuple(full_slice)] = d_values.reshape(shape)
# Cache derivatives
self._d_dvalues = derivs_val
self.table = table
return result
def gradient(self, xi):
"""
Compute the gradients at the specified point.
Most of the gradients are computed as the interpolation itself is performed,
but are cached and returned separately by this method.
If the point for evaluation differs from the point used to produce
the currently cached gradient, the interpolation is re-performed in
order to return the correct gradient.
Parameters
----------
xi : ndarray of shape (..., ndim)
The coordinates to sample the gridded data at.
Returns
-------
ndarray
Vector of gradients of the interpolated values with respect to each value in xi.
"""
if (self._xi is None) or (not np.array_equal(xi, self._xi)):
# If inputs have changed since last computation, then re-interpolate.
self.interpolate(xi)
return self._gradient().reshape(np.asarray(xi).shape)
def _gradient(self):
"""
Return the pre-computed gradients.
Returns
-------
ndarray
Vector of gradients of the interpolated values with respect to each value in xi.
"""
return self._d_dx
def training_gradients(self, pt):
"""
Compute the training gradient for the vector of training points.
Parameters
----------
pt : ndarray
Training point values.
Returns
-------
ndarray
Gradient of output with respect to training point values.
"""
if self.table._vectorized:
return self.table.training_gradients(pt)
else:
grid = self.grid
interp = self._interp
opts = self._interp_options
for i, axis in enumerate(grid):
ngrid = axis.size
values = np.zeros(ngrid)
deriv_i = np.zeros(ngrid)
for j in range(ngrid):
values[j] = 1.0
table = interp([grid[i]], values, interp, **opts)
table._compute_d_dvalues = False
deriv_i[j], _, _, _ = table.evaluate(pt[i:i + 1])
values[j] = 0.0
if i == 0:
deriv_running = deriv_i.copy()
else:
deriv_running = np.outer(deriv_running, deriv_i)
return deriv_running
def spline_gradient(self):
"""
Return derivative of spline with respect to its control points.
Returns
-------
ndarray
Gradient of output with respect to training point values.
"""
vec_size, n_cp = self.values.shape
x_interp = self.x_interp
n_interp = len(x_interp)
d_dvalues = self._d_dvalues
if d_dvalues is not None:
dy_ddata = np.zeros((vec_size, n_interp, n_cp), dtype=d_dvalues.dtype)
if d_dvalues.shape[0] == vec_size:
# Akima precomputes derivs at all points in vec_size.
dy_ddata[:] = d_dvalues
else:
# Bsplines computed derivative is the same at all points in vec_size.
dy_ddata[:] = np.broadcast_to(d_dvalues.toarray(), (vec_size, n_interp, n_cp))
else:
# Note: These derivatives are independent of control point y values, so they will never
# be complex dtype.
dy_ddata = np.zeros((n_interp, n_cp))
# This way works for the rest of the interpolation methods.
for k in range(n_interp):
val = self.training_gradients(x_interp[k:k + 1])
dy_ddata[k, :] = val
dy_ddata = np.broadcast_to(dy_ddata, (vec_size, n_interp, n_cp))
return dy_ddata
| 38.246552 | 100 | 0.580129 | import numpy as np
from openmdao.components.interp_util.interp_akima import InterpAkima, Interp1DAkima
from openmdao.components.interp_util.interp_bsplines import InterpBSplines
from openmdao.components.interp_util.interp_cubic import InterpCubic
from openmdao.components.interp_util.interp_lagrange2 import InterpLagrange2, Interp3DLagrange2
from openmdao.components.interp_util.interp_lagrange3 import InterpLagrange3, Interp3DLagrange3
from openmdao.components.interp_util.interp_scipy import InterpScipy
from openmdao.components.interp_util.interp_slinear import InterpLinear, Interp3DSlinear, \
Interp1DSlinear, Interp2DSlinear
from openmdao.components.interp_util.outofbounds_error import OutOfBoundsError
from openmdao.utils.om_warnings import warn_deprecation
INTERP_METHODS = {
'slinear': InterpLinear,
'lagrange2': InterpLagrange2,
'lagrange3': InterpLagrange3,
'cubic': InterpCubic,
'akima': InterpAkima,
'scipy_cubic': InterpScipy,
'scipy_slinear': InterpScipy,
'scipy_quintic': InterpScipy,
'bsplines': InterpBSplines,
'1D-slinear': Interp1DSlinear,
'2D-slinear': Interp2DSlinear,
'3D-slinear': Interp3DSlinear,
'3D-lagrange2': Interp3DLagrange2,
'3D-lagrange3': Interp3DLagrange3,
'1D-akima': Interp1DAkima,
'trilinear': Interp3DSlinear,
'akima1D': Interp1DAkima,
}
TABLE_METHODS = ['slinear', 'lagrange2', 'lagrange3', 'cubic', 'akima',
'scipy_cubic', 'scipy_slinear', 'scipy_quintic',
'trilinear', 'akima1D',
'3D-slinear', '2D-slinear', '1D-slinear',
'1D-akima',
'3D-lagrange2', '3D-lagrange3']
SPLINE_METHODS = ['slinear', 'lagrange2', 'lagrange3', 'cubic', 'akima', 'bsplines',
'scipy_cubic', 'scipy_slinear', 'scipy_quintic']
class InterpND(object):
def __init__(self, method="slinear", points=None, values=None, x_interp=None, extrapolate=False,
num_cp=None, **kwargs):
if not isinstance(method, str):
msg = "Argument 'method' should be a string."
raise ValueError(msg)
elif method not in INTERP_METHODS:
all_m = ', '.join(['"' + m + '"' for m in INTERP_METHODS])
raise ValueError('Interpolation method "%s" is not defined. Valid methods are '
'%s.' % (method, all_m))
elif method == 'akima1D':
warn_deprecation("The 'akima1D' method has been renamed to '1D-akima'.")
elif method == 'trilinear':
warn_deprecation("The 'trilinear' method has been renamed to '3D-slinear'.")
self.extrapolate = extrapolate
if points is None:
if num_cp is not None:
points = [np.linspace(0.0, 1.0, num_cp)]
else:
msg = "Either 'points' or 'num_cp' must be specified."
raise ValueError(msg)
else:
if isinstance(points, np.ndarray):
points = [points]
for i, p in enumerate(points):
n_p = len(p)
if not np.all(np.diff(p) > 0.):
raise ValueError("The points in dimension %d must be strictly "
"ascending" % i)
if not np.asarray(p).ndim == 1:
raise ValueError("The points in dimension %d must be "
"1-dimensional" % i)
if x_interp is None:
if values is None:
msg = "Either 'values' or 'x_interp' must be specified."
raise ValueError(msg)
if method == 'bsplines':
msg = "Method 'bsplines' is not supported for table interpolation."
raise ValueError(msg)
if not hasattr(values, 'ndim'):
values = np.asarray(values)
if hasattr(values, 'dtype') and hasattr(values, 'astype'):
if not np.issubdtype(values.dtype, np.inexact):
values = values.astype(float)
if len(points) > values.ndim:
raise ValueError("There are %d point arrays, but values has %d "
"dimensions" % (len(points), values.ndim))
if (method.startswith('scipy') or method == 'akima') and \
(np.iscomplexobj(values[:]) or np.any(np.iscomplex(points[0]))):
msg = f"Interpolation method '{method}' does not support complex points or values."
raise ValueError(msg)
for i, p in enumerate(points):
n_p = len(p)
if values.shape[i] != n_p:
raise ValueError("There are %d points and %d values in "
"dimension %d" % (len(p), values.shape[i], i))
self.grid = tuple([np.asarray(p) for p in points])
self.values = values
self.x_interp = x_interp
self._xi = None
self._d_dx = None
self._d_dvalues = None
self._compute_d_dvalues = False
self._compute_d_dx = True
interp = INTERP_METHODS[method]
if method.startswith('scipy'):
kwargs['interp_method'] = method
table = interp(self.grid, values, interp, **kwargs)
table.check_config()
self.table = table
self._interp = interp
self._interp_options = kwargs
def interpolate(self, x, compute_derivative=False):
self._compute_d_dx = compute_derivative
self.table._compute_d_dx = compute_derivative
self.table._compute_d_dvalues = False
if isinstance(x, np.ndarray):
if len(x.shape) < 2:
if len(self.grid) > 1:
x = np.atleast_2d(x)
else:
x = np.atleast_2d(x).T
else:
x = np.atleast_2d(x)
self._xi = x
xnew = self._interpolate(x)
if compute_derivative:
return xnew, self._d_dx
else:
return xnew
def evaluate_spline(self, values, compute_derivative=False):
self._compute_d_dvalues = compute_derivative
self.table._compute_d_dvalues = compute_derivative
self.table._compute_d_dx = False
if len(values.shape) == 1:
values = np.expand_dims(values, axis=0)
# cache latest evaluation point for gradient method's use later
self._xi = self.x_interp.copy()
result = self._evaluate_spline(values)
if result.shape[0] == 1:
result = result.ravel()
if compute_derivative:
d_dvalues = self.spline_gradient()
if d_dvalues.shape[0] == 1:
d_dvalues = d_dvalues[0]
return result, d_dvalues
else:
return result
def _interpolate(self, xi):
if not self.extrapolate:
for i, p in enumerate(xi.T):
if np.isnan(p).any():
raise OutOfBoundsError("One of the requested xi contains a NaN",
i, np.NaN, self.grid[i][0], self.grid[i][-1])
eps = 1e-14 * self.grid[i][-1]
if np.any(p < self.grid[i][0] - eps) or np.any(p > self.grid[i][-1] + eps):
p1 = np.where(self.grid[i][0] > p)[0]
p2 = np.where(p > self.grid[i][-1])[0]
violated_idx = set(p1).union(p2).pop()
value = p[violated_idx]
raise OutOfBoundsError("One of the requested xi is out of bounds",
i, value, self.grid[i][0], self.grid[i][-1])
if self._compute_d_dvalues:
interp = self._interp
self.table = interp(self.grid, self.values, interp, **self._interp_options)
if not self.table._supports_d_dvalues:
raise RuntimeError(f'Method {self.table._name} does not support the '
'"training_data_gradients" option.')
self.table._compute_d_dvalues = True
table = self.table
if table.vectorized(xi):
result, derivs_x, derivs_val, derivs_grid = table.evaluate_vectorized(xi)
else:
n_nodes, nx = xi.shape
result = np.empty((n_nodes, ), dtype=xi.dtype)
derivs_x = np.empty((n_nodes, nx), dtype=xi.dtype)
derivs_val = None
for j in range(n_nodes):
val, d_x, d_values, d_grid = table.evaluate(xi[j, ...])
result[j] = val
derivs_x[j, :] = d_x.ravel()
if d_values is not None:
if derivs_val is None:
dv_shape = [n_nodes]
dv_shape.extend(self.values.shape)
derivs_val = np.zeros(dv_shape, dtype=xi.dtype)
in_slice = table._full_slice
full_slice = [slice(j, j + 1)]
full_slice.extend(in_slice)
shape = derivs_val[tuple(full_slice)].shape
derivs_val[tuple(full_slice)] = d_values.reshape(shape)
self._d_dx = derivs_x
self._d_dvalues = derivs_val
return result
def _evaluate_spline(self, values):
xi = self.x_interp
self.values = values
table = self.table
if table._vectorized:
if table._name == 'bsplines':
table.values = values
result, _, derivs_val, _ = table.evaluate_vectorized(xi)
else:
interp = self._interp
n_nodes, _ = values.shape
nx = np.prod(xi.shape)
result = np.empty((n_nodes, nx), dtype=values.dtype)
derivs_val = None
for j in range(n_nodes):
table = interp(self.grid, values[j, :], interp, **self._interp_options)
table._compute_d_dvalues = False
table._compute_d_dx = False
result[j, :], _, _, _ = table.evaluate_vectorized(xi.reshape((nx, 1)))
else:
interp = self._interp
n_nodes, _ = values.shape
nx = np.prod(xi.shape)
result = np.empty((n_nodes, nx), dtype=values.dtype)
derivs_val = None
for j in range(n_nodes):
table = interp(self.grid, values[j, :], interp, **self._interp_options)
table._compute_d_dvalues = True
table._compute_d_dx = False
for k in range(nx):
x_pt = np.atleast_2d(xi[k])
val, _, d_values, _ = table.evaluate(x_pt)
result[j, k] = val
if d_values is not None:
if derivs_val is None:
dv_shape = [n_nodes, nx]
dv_shape.extend(values.shape[1:])
derivs_val = np.zeros(dv_shape, dtype=values.dtype)
in_slice = table._full_slice
full_slice = [slice(j, j + 1), slice(k, k + 1)]
full_slice.extend(in_slice)
shape = derivs_val[tuple(full_slice)].shape
derivs_val[tuple(full_slice)] = d_values.reshape(shape)
self._d_dvalues = derivs_val
self.table = table
return result
def gradient(self, xi):
if (self._xi is None) or (not np.array_equal(xi, self._xi)):
self.interpolate(xi)
return self._gradient().reshape(np.asarray(xi).shape)
def _gradient(self):
return self._d_dx
def training_gradients(self, pt):
if self.table._vectorized:
return self.table.training_gradients(pt)
else:
grid = self.grid
interp = self._interp
opts = self._interp_options
for i, axis in enumerate(grid):
ngrid = axis.size
values = np.zeros(ngrid)
deriv_i = np.zeros(ngrid)
for j in range(ngrid):
values[j] = 1.0
table = interp([grid[i]], values, interp, **opts)
table._compute_d_dvalues = False
deriv_i[j], _, _, _ = table.evaluate(pt[i:i + 1])
values[j] = 0.0
if i == 0:
deriv_running = deriv_i.copy()
else:
deriv_running = np.outer(deriv_running, deriv_i)
return deriv_running
def spline_gradient(self):
vec_size, n_cp = self.values.shape
x_interp = self.x_interp
n_interp = len(x_interp)
d_dvalues = self._d_dvalues
if d_dvalues is not None:
dy_ddata = np.zeros((vec_size, n_interp, n_cp), dtype=d_dvalues.dtype)
if d_dvalues.shape[0] == vec_size:
dy_ddata[:] = d_dvalues
else:
dy_ddata[:] = np.broadcast_to(d_dvalues.toarray(), (vec_size, n_interp, n_cp))
else:
dy_ddata = np.zeros((n_interp, n_cp))
for k in range(n_interp):
val = self.training_gradients(x_interp[k:k + 1])
dy_ddata[k, :] = val
dy_ddata = np.broadcast_to(dy_ddata, (vec_size, n_interp, n_cp))
return dy_ddata
| true | true |
f7166b29a260dc30035dc8c5f38d515125a10b02 | 1,410 | py | Python | data/shape_dataset.py | mremilien/object-deformnet | bb07fe05f1ee3983835ebe071252541cee5c42f8 | [
"MIT"
] | 66 | 2020-07-17T05:15:42.000Z | 2022-02-22T12:28:01.000Z | data/shape_dataset.py | mremilien/object-deformnet | bb07fe05f1ee3983835ebe071252541cee5c42f8 | [
"MIT"
] | 25 | 2020-07-17T11:45:16.000Z | 2022-02-07T06:11:44.000Z | data/shape_dataset.py | mremilien/object-deformnet | bb07fe05f1ee3983835ebe071252541cee5c42f8 | [
"MIT"
] | 16 | 2020-07-18T22:15:20.000Z | 2022-01-05T09:05:40.000Z | import h5py
import numpy as np
import torch.utils.data as data
class ShapeDataset(data.Dataset):
def __init__(self, h5_file, mode, n_points=2048, augment=False):
assert (mode == 'train' or mode == 'val'), 'Mode must be "train" or "val".'
self.mode = mode
self.n_points = n_points
self.augment = augment
# load data from h5py file
with h5py.File(h5_file, 'r') as f:
self.length = f[self.mode].attrs['len']
self.data = f[self.mode]['data'][:]
self.label = f[self.mode]['label'][:]
# augmentation parameters
self.sigma = 0.01
self.clip = 0.02
self.shift_range = 0.02
def __len__(self):
return self.length
def __getitem__(self, index):
xyz = self.data[index]
label = self.label[index] - 1 # data saved indexed from 1
# randomly downsample
np_data = xyz.shape[0]
assert np_data >= self.n_points, 'Not enough points in shape.'
idx = np.random.choice(np_data, self.n_points)
xyz = xyz[idx, :]
# data augmentation
if self.augment:
jitter = np.clip(self.sigma*np.random.randn(self.n_points, 3), -self.clip, self.clip)
xyz[:, :3] += jitter
shift = np.random.uniform(-self.shift_range, self.shift_range, (1, 3))
xyz[:, :3] += shift
return xyz, label
| 35.25 | 97 | 0.576596 | import h5py
import numpy as np
import torch.utils.data as data
class ShapeDataset(data.Dataset):
def __init__(self, h5_file, mode, n_points=2048, augment=False):
assert (mode == 'train' or mode == 'val'), 'Mode must be "train" or "val".'
self.mode = mode
self.n_points = n_points
self.augment = augment
with h5py.File(h5_file, 'r') as f:
self.length = f[self.mode].attrs['len']
self.data = f[self.mode]['data'][:]
self.label = f[self.mode]['label'][:]
self.sigma = 0.01
self.clip = 0.02
self.shift_range = 0.02
def __len__(self):
return self.length
def __getitem__(self, index):
xyz = self.data[index]
label = self.label[index] - 1
np_data = xyz.shape[0]
assert np_data >= self.n_points, 'Not enough points in shape.'
idx = np.random.choice(np_data, self.n_points)
xyz = xyz[idx, :]
if self.augment:
jitter = np.clip(self.sigma*np.random.randn(self.n_points, 3), -self.clip, self.clip)
xyz[:, :3] += jitter
shift = np.random.uniform(-self.shift_range, self.shift_range, (1, 3))
xyz[:, :3] += shift
return xyz, label
| true | true |
f7166b34ac455a0f2c35b9f39db244c8be3a6461 | 1,936 | py | Python | evalai/utils/urls.py | Ram81/evalai-cli | 3fee2108b013461b3de8aa354473ba6eaba6539b | [
"BSD-3-Clause"
] | null | null | null | evalai/utils/urls.py | Ram81/evalai-cli | 3fee2108b013461b3de8aa354473ba6eaba6539b | [
"BSD-3-Clause"
] | null | null | null | evalai/utils/urls.py | Ram81/evalai-cli | 3fee2108b013461b3de8aa354473ba6eaba6539b | [
"BSD-3-Clause"
] | null | null | null | from enum import Enum
class URLS(Enum):
login = "/api/auth/login"
challenge_list = "/api/challenges/challenge/all"
past_challenge_list = "/api/challenges/challenge/past"
future_challenge_list = "/api/challenges/challenge/future"
challenge_details = "/api/challenges/challenge/{}"
challenge_phase_details = "/api/challenges/challenge/phase/{}/"
participant_teams = "/api/participants/participant_team"
host_teams = "/api/hosts/challenge_host_team/"
host_challenges = "/api/challenges/challenge_host_team/{}/challenge"
challenge_phase_split_detail = "/api/challenges/{}/challenge_phase_split"
create_host_team = "/api/hosts/create_challenge_host_team"
host_team_list = "/api/hosts/challenge_host_team/"
participant_challenges = "/api/participants/participant_team/{}/challenge"
participant_team_list = "/api/participants/participant_team"
participate_in_a_challenge = (
"/api/challenges/challenge/{}/participant_team/{}"
)
challenge_phase_list = "/api/challenges/challenge/{}/challenge_phase"
challenge_phase_detail = "/api/challenges/challenge/{}/challenge_phase/{}"
my_submissions = "/api/jobs/challenge/{}/challenge_phase/{}/submission/"
make_submission = "/api/jobs/challenge/{}/challenge_phase/{}/submission/"
get_submission = "/api/jobs/submission/{}"
leaderboard = "/api/jobs/challenge_phase_split/{}/leaderboard/"
get_aws_credentials = (
"/api/challenges/phases/{}/participant_team/aws/credentials/"
)
download_file = "/api/jobs/submission_files/?bucket={}&key={}"
phase_details_using_slug = "/api/challenges/phase/{}/"
get_presigned_url_for_annotation_file = "/api/challenges/phases/{}/get_annotation_file_presigned_url/"
get_presigned_url_for_submission_file = "/api/jobs/phases/{}/get_submission_file_presigned_url/"
send_submission_message = "/api/jobs/phases/{}/send_submission_message/{}/"
| 53.777778 | 106 | 0.741736 | from enum import Enum
class URLS(Enum):
login = "/api/auth/login"
challenge_list = "/api/challenges/challenge/all"
past_challenge_list = "/api/challenges/challenge/past"
future_challenge_list = "/api/challenges/challenge/future"
challenge_details = "/api/challenges/challenge/{}"
challenge_phase_details = "/api/challenges/challenge/phase/{}/"
participant_teams = "/api/participants/participant_team"
host_teams = "/api/hosts/challenge_host_team/"
host_challenges = "/api/challenges/challenge_host_team/{}/challenge"
challenge_phase_split_detail = "/api/challenges/{}/challenge_phase_split"
create_host_team = "/api/hosts/create_challenge_host_team"
host_team_list = "/api/hosts/challenge_host_team/"
participant_challenges = "/api/participants/participant_team/{}/challenge"
participant_team_list = "/api/participants/participant_team"
participate_in_a_challenge = (
"/api/challenges/challenge/{}/participant_team/{}"
)
challenge_phase_list = "/api/challenges/challenge/{}/challenge_phase"
challenge_phase_detail = "/api/challenges/challenge/{}/challenge_phase/{}"
my_submissions = "/api/jobs/challenge/{}/challenge_phase/{}/submission/"
make_submission = "/api/jobs/challenge/{}/challenge_phase/{}/submission/"
get_submission = "/api/jobs/submission/{}"
leaderboard = "/api/jobs/challenge_phase_split/{}/leaderboard/"
get_aws_credentials = (
"/api/challenges/phases/{}/participant_team/aws/credentials/"
)
download_file = "/api/jobs/submission_files/?bucket={}&key={}"
phase_details_using_slug = "/api/challenges/phase/{}/"
get_presigned_url_for_annotation_file = "/api/challenges/phases/{}/get_annotation_file_presigned_url/"
get_presigned_url_for_submission_file = "/api/jobs/phases/{}/get_submission_file_presigned_url/"
send_submission_message = "/api/jobs/phases/{}/send_submission_message/{}/"
| true | true |
f7166c21c50fd68775ca54dcd3b3e04554955178 | 581 | py | Python | insta/migrations/0007_profile_editor.py | SheilaKamotho/InstaClone | 7dd644118dfb5523fa253d3454d4aa0f2f599c69 | [
"Unlicense",
"MIT"
] | null | null | null | insta/migrations/0007_profile_editor.py | SheilaKamotho/InstaClone | 7dd644118dfb5523fa253d3454d4aa0f2f599c69 | [
"Unlicense",
"MIT"
] | null | null | null | insta/migrations/0007_profile_editor.py | SheilaKamotho/InstaClone | 7dd644118dfb5523fa253d3454d4aa0f2f599c69 | [
"Unlicense",
"MIT"
] | null | null | null | # Generated by Django 2.0.2 on 2020-10-19 10:32
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('insta', '0006_image_editor'),
]
operations = [
migrations.AddField(
model_name='profile',
name='editor',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]
| 26.409091 | 121 | 0.672978 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('insta', '0006_image_editor'),
]
operations = [
migrations.AddField(
model_name='profile',
name='editor',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]
| true | true |
f7166c87d0624aa75acb312538b76c621625e86c | 7,883 | py | Python | .history/docs/conf_20191028085309.py | bkraft4257/kaggle_titanic | f29ea1773773109a867278c001dbd21a9f7b21dd | [
"MIT"
] | null | null | null | .history/docs/conf_20191028085309.py | bkraft4257/kaggle_titanic | f29ea1773773109a867278c001dbd21a9f7b21dd | [
"MIT"
] | null | null | null | .history/docs/conf_20191028085309.py | bkraft4257/kaggle_titanic | f29ea1773773109a867278c001dbd21a9f7b21dd | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
#
# kaggle_titanic documentation build configuration file, created by
# sphinx-quickstart.
#
# 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.
import os
import sys
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = []
extensions = ['sphinx.ext.todo', 'sphinx.ext.viewcode', 'sphinx.ext.autodoc']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'kaggle_titanic'
# The version info for the project 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 = '0.1'
# The full version, including alpha/beta/rc tags.
release = '0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# 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 = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# 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']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'kaggle_titanicdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
# 'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index',
'kaggle_titanic.tex',
u'kaggle_titanic Documentation',
u"Bob Kraft", 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'kaggle_titanic', u'kaggle_titanic Documentation',
[u"Bob Kraft"], 1)
]
# If true, show URL addresses after external links.
# man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'kaggle_titanic', u'kaggle_titanic Documentation',
u"Bob Kraft", 'kaggle_titanic',
'First Kaggle competition', 'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
# texinfo_appendices = []
# If false, no module index is generated.
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'
| 32.044715 | 80 | 0.708487 |
import os
import sys
extensions = []
extensions = ['sphinx.ext.todo', 'sphinx.ext.viewcode', 'sphinx.ext.autodoc']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'kaggle_titanic'
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.1'
# The full version, including alpha/beta/rc tags.
release = '0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# 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 = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# 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']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'kaggle_titanicdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
# 'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index',
'kaggle_titanic.tex',
u'kaggle_titanic Documentation',
u"Bob Kraft", 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'kaggle_titanic', u'kaggle_titanic Documentation',
[u"Bob Kraft"], 1)
]
# If true, show URL addresses after external links.
# man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'kaggle_titanic', u'kaggle_titanic Documentation',
u"Bob Kraft", 'kaggle_titanic',
'First Kaggle competition', 'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
# texinfo_appendices = []
# If false, no module index is generated.
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'
| true | true |
f7166ed99d1178bc1af8dfbf95b904d906ba4586 | 12,868 | py | Python | src/python/src/grpc/framework/assembly/implementations.py | jonywtf/grpc | 124f3c5a4b65bb88f13be7c68482eb83d945ad02 | [
"BSD-3-Clause"
] | 1 | 2022-01-14T04:25:01.000Z | 2022-01-14T04:25:01.000Z | src/python/src/grpc/framework/assembly/implementations.py | jonywtf/grpc | 124f3c5a4b65bb88f13be7c68482eb83d945ad02 | [
"BSD-3-Clause"
] | null | null | null | src/python/src/grpc/framework/assembly/implementations.py | jonywtf/grpc | 124f3c5a4b65bb88f13be7c68482eb83d945ad02 | [
"BSD-3-Clause"
] | 1 | 2022-01-14T04:25:02.000Z | 2022-01-14T04:25:02.000Z | # Copyright 2015, Google Inc.
# 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 Google Inc. 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
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Implementations for assembling RPC framework values."""
import threading
# tickets_interfaces, face_interfaces, and activated are referenced from
# specification in this module.
from grpc.framework.assembly import interfaces
from grpc.framework.base import util as base_utilities
from grpc.framework.base.packets import implementations as tickets_implementations
from grpc.framework.base.packets import interfaces as tickets_interfaces # pylint: disable=unused-import
from grpc.framework.common import cardinality
from grpc.framework.common import style
from grpc.framework.face import implementations as face_implementations
from grpc.framework.face import interfaces as face_interfaces # pylint: disable=unused-import
from grpc.framework.face import utilities as face_utilities
from grpc.framework.foundation import activated # pylint: disable=unused-import
from grpc.framework.foundation import logging_pool
_ONE_DAY_IN_SECONDS = 60 * 60 * 24
_THREAD_POOL_SIZE = 100
class _FaceStub(object):
def __init__(self, rear_link):
self._rear_link = rear_link
self._lock = threading.Lock()
self._pool = None
self._front = None
self._under_stub = None
def __enter__(self):
with self._lock:
self._pool = logging_pool.pool(_THREAD_POOL_SIZE)
self._front = tickets_implementations.front(
self._pool, self._pool, self._pool)
self._rear_link.start()
self._rear_link.join_fore_link(self._front)
self._front.join_rear_link(self._rear_link)
self._under_stub = face_implementations.stub(self._front, self._pool)
def __exit__(self, exc_type, exc_val, exc_tb):
with self._lock:
self._under_stub = None
self._rear_link.stop()
base_utilities.wait_for_idle(self._front)
self._front = None
self._pool.shutdown(wait=True)
self._pool = None
return False
def __getattr__(self, attr):
with self._lock:
if self._under_stub is None:
raise ValueError('Called out of context!')
else:
return getattr(self._under_stub, attr)
def _behaviors(implementations, front, pool):
behaviors = {}
stub = face_implementations.stub(front, pool)
for name, implementation in implementations.iteritems():
if implementation.cardinality is cardinality.Cardinality.UNARY_UNARY:
behaviors[name] = stub.unary_unary_sync_async(name)
elif implementation.cardinality is cardinality.Cardinality.UNARY_STREAM:
behaviors[name] = lambda request, context, bound_name=name: (
stub.inline_value_in_stream_out(bound_name, request, context))
elif implementation.cardinality is cardinality.Cardinality.STREAM_UNARY:
behaviors[name] = stub.stream_unary_sync_async(name)
elif implementation.cardinality is cardinality.Cardinality.STREAM_STREAM:
behaviors[name] = lambda request_iterator, context, bound_name=name: (
stub.inline_stream_in_stream_out(
bound_name, request_iterator, context))
return behaviors
class _DynamicInlineStub(object):
def __init__(self, implementations, rear_link):
self._implementations = implementations
self._rear_link = rear_link
self._lock = threading.Lock()
self._pool = None
self._front = None
self._behaviors = None
def __enter__(self):
with self._lock:
self._pool = logging_pool.pool(_THREAD_POOL_SIZE)
self._front = tickets_implementations.front(
self._pool, self._pool, self._pool)
self._rear_link.start()
self._rear_link.join_fore_link(self._front)
self._front.join_rear_link(self._rear_link)
self._behaviors = _behaviors(
self._implementations, self._front, self._pool)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
with self._lock:
self._behaviors = None
self._rear_link.stop()
base_utilities.wait_for_idle(self._front)
self._front = None
self._pool.shutdown(wait=True)
self._pool = None
return False
def __getattr__(self, attr):
with self._lock:
behavior = self._behaviors.get(attr)
if behavior is None:
for name, behavior in self._behaviors.iteritems():
last_slash_index = name.rfind('/')
if 0 <= last_slash_index and name[last_slash_index + 1:] == attr:
return behavior
else:
raise AttributeError(
'_DynamicInlineStub instance has no attribute "%s"!' % attr)
else:
return behavior
def _servicer(implementations, pool):
inline_value_in_value_out_methods = {}
inline_value_in_stream_out_methods = {}
inline_stream_in_value_out_methods = {}
inline_stream_in_stream_out_methods = {}
event_value_in_value_out_methods = {}
event_value_in_stream_out_methods = {}
event_stream_in_value_out_methods = {}
event_stream_in_stream_out_methods = {}
for name, implementation in implementations.iteritems():
if implementation.cardinality is cardinality.Cardinality.UNARY_UNARY:
if implementation.style is style.Service.INLINE:
inline_value_in_value_out_methods[name] = (
face_utilities.inline_unary_unary_method(implementation.unary_unary_inline))
elif implementation.style is style.Service.EVENT:
event_value_in_value_out_methods[name] = (
face_utilities.event_unary_unary_method(implementation.unary_unary_event))
elif implementation.cardinality is cardinality.Cardinality.UNARY_STREAM:
if implementation.style is style.Service.INLINE:
inline_value_in_stream_out_methods[name] = (
face_utilities.inline_unary_stream_method(implementation.unary_stream_inline))
elif implementation.style is style.Service.EVENT:
event_value_in_stream_out_methods[name] = (
face_utilities.event_unary_stream_method(implementation.unary_stream_event))
if implementation.cardinality is cardinality.Cardinality.STREAM_UNARY:
if implementation.style is style.Service.INLINE:
inline_stream_in_value_out_methods[name] = (
face_utilities.inline_stream_unary_method(implementation.stream_unary_inline))
elif implementation.style is style.Service.EVENT:
event_stream_in_value_out_methods[name] = (
face_utilities.event_stream_unary_method(implementation.stream_unary_event))
elif implementation.cardinality is cardinality.Cardinality.STREAM_STREAM:
if implementation.style is style.Service.INLINE:
inline_stream_in_stream_out_methods[name] = (
face_utilities.inline_stream_stream_method(implementation.stream_stream_inline))
elif implementation.style is style.Service.EVENT:
event_stream_in_stream_out_methods[name] = (
face_utilities.event_stream_stream_method(implementation.stream_stream_event))
return face_implementations.servicer(
pool,
inline_value_in_value_out_methods=inline_value_in_value_out_methods,
inline_value_in_stream_out_methods=inline_value_in_stream_out_methods,
inline_stream_in_value_out_methods=inline_stream_in_value_out_methods,
inline_stream_in_stream_out_methods=inline_stream_in_stream_out_methods,
event_value_in_value_out_methods=event_value_in_value_out_methods,
event_value_in_stream_out_methods=event_value_in_stream_out_methods,
event_stream_in_value_out_methods=event_stream_in_value_out_methods,
event_stream_in_stream_out_methods=event_stream_in_stream_out_methods)
class _ServiceAssembly(interfaces.Server):
def __init__(self, implementations, fore_link):
self._implementations = implementations
self._fore_link = fore_link
self._lock = threading.Lock()
self._pool = None
self._back = None
def _start(self):
with self._lock:
self._pool = logging_pool.pool(_THREAD_POOL_SIZE)
servicer = _servicer(self._implementations, self._pool)
self._back = tickets_implementations.back(
servicer, self._pool, self._pool, self._pool, _ONE_DAY_IN_SECONDS,
_ONE_DAY_IN_SECONDS)
self._fore_link.start()
self._fore_link.join_rear_link(self._back)
self._back.join_fore_link(self._fore_link)
def _stop(self):
with self._lock:
self._fore_link.stop()
base_utilities.wait_for_idle(self._back)
self._back = None
self._pool.shutdown(wait=True)
self._pool = None
def __enter__(self):
self._start()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self._stop()
return False
def start(self):
return self._start()
def stop(self):
self._stop()
def port(self):
with self._lock:
return self._fore_link.port()
def assemble_face_stub(activated_rear_link):
"""Assembles a face_interfaces.Stub.
The returned object is a context manager and may only be used in context to
invoke RPCs.
Args:
activated_rear_link: An object that is both a tickets_interfaces.RearLink
and an activated.Activated. The object should be in the inactive state
when passed to this method.
Returns:
A face_interfaces.Stub on which, in context, RPCs can be invoked.
"""
return _FaceStub(activated_rear_link)
def assemble_dynamic_inline_stub(implementations, activated_rear_link):
"""Assembles a stub with method names for attributes.
The returned object is a context manager and may only be used in context to
invoke RPCs.
The returned object, when used in context, will respond to attribute access
as follows: if the requested attribute is the name of a unary-unary RPC
method, the value of the attribute will be a
face_interfaces.UnaryUnarySyncAsync with which to invoke the RPC method. If
the requested attribute is the name of a unary-stream RPC method, the value
of the attribute will be a callable with the semantics of
face_interfaces.Stub.inline_value_in_stream_out, minus the "name" parameter,
with which to invoke the RPC method. If the requested attribute is the name
of a stream-unary RPC method, the value of the attribute will be a
face_interfaces.StreamUnarySyncAsync with which to invoke the RPC method. If
the requested attribute is the name of a stream-stream RPC method, the value
of the attribute will be a callable with the semantics of
face_interfaces.Stub.inline_stream_in_stream_out, minus the "name" parameter,
with which to invoke the RPC method.
Args:
implementations: A dictionary from RPC method name to
interfaces.MethodImplementation.
activated_rear_link: An object that is both a tickets_interfaces.RearLink
and an activated.Activated. The object should be in the inactive state
when passed to this method.
Returns:
A stub on which, in context, RPCs can be invoked.
"""
return _DynamicInlineStub(implementations, activated_rear_link)
def assemble_service(implementations, activated_fore_link):
"""Assembles the service-side of the RPC Framework stack.
Args:
implementations: A dictionary from RPC method name to
interfaces.MethodImplementation.
activated_fore_link: An object that is both a tickets_interfaces.ForeLink
and an activated.Activated. The object should be in the inactive state
when passed to this method.
Returns:
An interfaces.Server encapsulating RPC service.
"""
return _ServiceAssembly(implementations, activated_fore_link)
| 40.465409 | 105 | 0.756062 |
import threading
from grpc.framework.assembly import interfaces
from grpc.framework.base import util as base_utilities
from grpc.framework.base.packets import implementations as tickets_implementations
from grpc.framework.base.packets import interfaces as tickets_interfaces
from grpc.framework.common import cardinality
from grpc.framework.common import style
from grpc.framework.face import implementations as face_implementations
from grpc.framework.face import interfaces as face_interfaces
from grpc.framework.face import utilities as face_utilities
from grpc.framework.foundation import activated
from grpc.framework.foundation import logging_pool
_ONE_DAY_IN_SECONDS = 60 * 60 * 24
_THREAD_POOL_SIZE = 100
class _FaceStub(object):
def __init__(self, rear_link):
self._rear_link = rear_link
self._lock = threading.Lock()
self._pool = None
self._front = None
self._under_stub = None
def __enter__(self):
with self._lock:
self._pool = logging_pool.pool(_THREAD_POOL_SIZE)
self._front = tickets_implementations.front(
self._pool, self._pool, self._pool)
self._rear_link.start()
self._rear_link.join_fore_link(self._front)
self._front.join_rear_link(self._rear_link)
self._under_stub = face_implementations.stub(self._front, self._pool)
def __exit__(self, exc_type, exc_val, exc_tb):
with self._lock:
self._under_stub = None
self._rear_link.stop()
base_utilities.wait_for_idle(self._front)
self._front = None
self._pool.shutdown(wait=True)
self._pool = None
return False
def __getattr__(self, attr):
with self._lock:
if self._under_stub is None:
raise ValueError('Called out of context!')
else:
return getattr(self._under_stub, attr)
def _behaviors(implementations, front, pool):
behaviors = {}
stub = face_implementations.stub(front, pool)
for name, implementation in implementations.iteritems():
if implementation.cardinality is cardinality.Cardinality.UNARY_UNARY:
behaviors[name] = stub.unary_unary_sync_async(name)
elif implementation.cardinality is cardinality.Cardinality.UNARY_STREAM:
behaviors[name] = lambda request, context, bound_name=name: (
stub.inline_value_in_stream_out(bound_name, request, context))
elif implementation.cardinality is cardinality.Cardinality.STREAM_UNARY:
behaviors[name] = stub.stream_unary_sync_async(name)
elif implementation.cardinality is cardinality.Cardinality.STREAM_STREAM:
behaviors[name] = lambda request_iterator, context, bound_name=name: (
stub.inline_stream_in_stream_out(
bound_name, request_iterator, context))
return behaviors
class _DynamicInlineStub(object):
def __init__(self, implementations, rear_link):
self._implementations = implementations
self._rear_link = rear_link
self._lock = threading.Lock()
self._pool = None
self._front = None
self._behaviors = None
def __enter__(self):
with self._lock:
self._pool = logging_pool.pool(_THREAD_POOL_SIZE)
self._front = tickets_implementations.front(
self._pool, self._pool, self._pool)
self._rear_link.start()
self._rear_link.join_fore_link(self._front)
self._front.join_rear_link(self._rear_link)
self._behaviors = _behaviors(
self._implementations, self._front, self._pool)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
with self._lock:
self._behaviors = None
self._rear_link.stop()
base_utilities.wait_for_idle(self._front)
self._front = None
self._pool.shutdown(wait=True)
self._pool = None
return False
def __getattr__(self, attr):
with self._lock:
behavior = self._behaviors.get(attr)
if behavior is None:
for name, behavior in self._behaviors.iteritems():
last_slash_index = name.rfind('/')
if 0 <= last_slash_index and name[last_slash_index + 1:] == attr:
return behavior
else:
raise AttributeError(
'_DynamicInlineStub instance has no attribute "%s"!' % attr)
else:
return behavior
def _servicer(implementations, pool):
inline_value_in_value_out_methods = {}
inline_value_in_stream_out_methods = {}
inline_stream_in_value_out_methods = {}
inline_stream_in_stream_out_methods = {}
event_value_in_value_out_methods = {}
event_value_in_stream_out_methods = {}
event_stream_in_value_out_methods = {}
event_stream_in_stream_out_methods = {}
for name, implementation in implementations.iteritems():
if implementation.cardinality is cardinality.Cardinality.UNARY_UNARY:
if implementation.style is style.Service.INLINE:
inline_value_in_value_out_methods[name] = (
face_utilities.inline_unary_unary_method(implementation.unary_unary_inline))
elif implementation.style is style.Service.EVENT:
event_value_in_value_out_methods[name] = (
face_utilities.event_unary_unary_method(implementation.unary_unary_event))
elif implementation.cardinality is cardinality.Cardinality.UNARY_STREAM:
if implementation.style is style.Service.INLINE:
inline_value_in_stream_out_methods[name] = (
face_utilities.inline_unary_stream_method(implementation.unary_stream_inline))
elif implementation.style is style.Service.EVENT:
event_value_in_stream_out_methods[name] = (
face_utilities.event_unary_stream_method(implementation.unary_stream_event))
if implementation.cardinality is cardinality.Cardinality.STREAM_UNARY:
if implementation.style is style.Service.INLINE:
inline_stream_in_value_out_methods[name] = (
face_utilities.inline_stream_unary_method(implementation.stream_unary_inline))
elif implementation.style is style.Service.EVENT:
event_stream_in_value_out_methods[name] = (
face_utilities.event_stream_unary_method(implementation.stream_unary_event))
elif implementation.cardinality is cardinality.Cardinality.STREAM_STREAM:
if implementation.style is style.Service.INLINE:
inline_stream_in_stream_out_methods[name] = (
face_utilities.inline_stream_stream_method(implementation.stream_stream_inline))
elif implementation.style is style.Service.EVENT:
event_stream_in_stream_out_methods[name] = (
face_utilities.event_stream_stream_method(implementation.stream_stream_event))
return face_implementations.servicer(
pool,
inline_value_in_value_out_methods=inline_value_in_value_out_methods,
inline_value_in_stream_out_methods=inline_value_in_stream_out_methods,
inline_stream_in_value_out_methods=inline_stream_in_value_out_methods,
inline_stream_in_stream_out_methods=inline_stream_in_stream_out_methods,
event_value_in_value_out_methods=event_value_in_value_out_methods,
event_value_in_stream_out_methods=event_value_in_stream_out_methods,
event_stream_in_value_out_methods=event_stream_in_value_out_methods,
event_stream_in_stream_out_methods=event_stream_in_stream_out_methods)
class _ServiceAssembly(interfaces.Server):
def __init__(self, implementations, fore_link):
self._implementations = implementations
self._fore_link = fore_link
self._lock = threading.Lock()
self._pool = None
self._back = None
def _start(self):
with self._lock:
self._pool = logging_pool.pool(_THREAD_POOL_SIZE)
servicer = _servicer(self._implementations, self._pool)
self._back = tickets_implementations.back(
servicer, self._pool, self._pool, self._pool, _ONE_DAY_IN_SECONDS,
_ONE_DAY_IN_SECONDS)
self._fore_link.start()
self._fore_link.join_rear_link(self._back)
self._back.join_fore_link(self._fore_link)
def _stop(self):
with self._lock:
self._fore_link.stop()
base_utilities.wait_for_idle(self._back)
self._back = None
self._pool.shutdown(wait=True)
self._pool = None
def __enter__(self):
self._start()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self._stop()
return False
def start(self):
return self._start()
def stop(self):
self._stop()
def port(self):
with self._lock:
return self._fore_link.port()
def assemble_face_stub(activated_rear_link):
return _FaceStub(activated_rear_link)
def assemble_dynamic_inline_stub(implementations, activated_rear_link):
return _DynamicInlineStub(implementations, activated_rear_link)
def assemble_service(implementations, activated_fore_link):
return _ServiceAssembly(implementations, activated_fore_link)
| true | true |
f7166f854ffcad07870a5030cb9bfd7720c7b846 | 4,685 | py | Python | relationships/relationship.py | emre/relationships | 9452af1dd2897a6b102c4a391c95b499622c2f28 | [
"MIT"
] | 85 | 2015-08-05T06:13:28.000Z | 2021-05-07T13:56:30.000Z | relationships/relationship.py | emre/relationships | 9452af1dd2897a6b102c4a391c95b499622c2f28 | [
"MIT"
] | 3 | 2015-08-06T05:50:37.000Z | 2015-08-07T05:31:50.000Z | relationships/relationship.py | emre/relationships | 9452af1dd2897a6b102c4a391c95b499622c2f28 | [
"MIT"
] | 7 | 2015-08-06T01:34:14.000Z | 2018-12-21T01:17:33.000Z |
import redis
from keys import key_list as default_key_list
class Relationship(object):
def __init__(self, redis_connection=None, key_list=None, actor=None):
if key_list:
self.key_list = default_key_list.copy()
self.key_list.update(key_list)
else:
self.key_list = default_key_list
if redis_connection:
self.redis_connection = redis_connection
else:
self.redis_connection = redis.StrictRedis(
host='localhost',
port=6379,
db=0
)
self.actor = actor
def __call__(self, *args, **kwargs):
self.actor = args[0]
return self
def _action_call(self, command, from_id, to_id, operation_key):
command_values = ':'.join(('user', str(from_id), operation_key)), to_id
return getattr(self.redis_connection, command)(*command_values)
def _list_call(self, operation_key):
return self.redis_connection.smembers(
'user:{}:{}'.format(self._get_actor(), operation_key)
)
def _count_call(self, operation_key):
return self.redis_connection.scard(
'user:{}:{}'.format(
self._get_actor(),
operation_key
)
)
def _get_actor(self):
if hasattr(self, 'actor'):
return self.actor
raise ValueError("actor is not defined")
def block(self, to_id):
self._action_call('sadd', self._get_actor(), to_id, self.key_list["blocked"])
self._action_call('sadd', to_id, self._get_actor(), self.key_list["blocked_by"])
def unblock(self, to_id):
self._action_call('srem', self._get_actor(), to_id, self.key_list["blocked"])
self._action_call('srem', to_id, self._get_actor(), self.key_list["blocked_by"])
def follow(self, to_id):
self._action_call('sadd', self._get_actor(), to_id, self.key_list["following"])
self._action_call('sadd', to_id, self._get_actor(), self.key_list["followers"])
def unfollow(self, to_id):
self._action_call('srem', self._get_actor(), to_id, self.key_list["following"])
self._action_call('srem', to_id, self._get_actor(), self.key_list["followers"])
def friends(self):
return self.redis_connection.sinter(
"user:{}:{}".format(self._get_actor(), self.key_list["following"]),
"user:{}:{}".format(self._get_actor(), self.key_list["followers"]),
)
def mutual_friends(self, to_id):
actor_friends, to_id_friends = self(self._get_actor()).friends(), self(to_id).friends()
return actor_friends.intersection(to_id_friends)
def followers(self):
return self._list_call(self.key_list["followers"])
def following(self):
return self._list_call(self.key_list["following"])
def blocks(self):
return self._list_call(self.key_list["blocked"])
def blocked(self):
return self._list_call(self.key_list["blocked_by"])
def follower_count(self):
return self._count_call(self.key_list["followers"])
def following_count(self):
return self._count_call(self.key_list["following"])
def block_count(self):
return self._count_call(self.key_list["blocked"])
def blocked_count(self):
return self._count_call(self.key_list["blocked_by"])
def is_follower(self, follower_id):
return self._action_call('sismember', self._get_actor(), follower_id, self.key_list["followers"])
def is_following(self, following_id):
return self._action_call('sismember', self._get_actor(), following_id, self.key_list["following"])
def is_blocked(self, blocked_id):
return self._action_call('sismember', self._get_actor(), blocked_id, self.key_list["blocked"])
def is_blocked_by(self, blocked_by_id):
return self._action_call('sismember', self._get_actor(), blocked_by_id,self.key_list["blocked_by"])
def get_network(self, output):
user_id = self._get_actor()
try:
import pydot
except ImportError:
raise ImportError("You need pydot library to get network functionality.")
graph = pydot.Dot('network_of_user_{}'.format(user_id), graph_type='digraph')
target_node = pydot.Node(user_id)
for _id in self(user_id).following():
user_node = pydot.Node(_id)
graph.add_edge(pydot.Edge(target_node, user_node))
for _id in self(user_id).followers():
user_node = pydot.Node(_id)
graph.add_edge(pydot.Edge(user_node, target_node))
graph.write_png(output)
| 31.655405 | 108 | 0.639488 |
import redis
from keys import key_list as default_key_list
class Relationship(object):
def __init__(self, redis_connection=None, key_list=None, actor=None):
if key_list:
self.key_list = default_key_list.copy()
self.key_list.update(key_list)
else:
self.key_list = default_key_list
if redis_connection:
self.redis_connection = redis_connection
else:
self.redis_connection = redis.StrictRedis(
host='localhost',
port=6379,
db=0
)
self.actor = actor
def __call__(self, *args, **kwargs):
self.actor = args[0]
return self
def _action_call(self, command, from_id, to_id, operation_key):
command_values = ':'.join(('user', str(from_id), operation_key)), to_id
return getattr(self.redis_connection, command)(*command_values)
def _list_call(self, operation_key):
return self.redis_connection.smembers(
'user:{}:{}'.format(self._get_actor(), operation_key)
)
def _count_call(self, operation_key):
return self.redis_connection.scard(
'user:{}:{}'.format(
self._get_actor(),
operation_key
)
)
def _get_actor(self):
if hasattr(self, 'actor'):
return self.actor
raise ValueError("actor is not defined")
def block(self, to_id):
self._action_call('sadd', self._get_actor(), to_id, self.key_list["blocked"])
self._action_call('sadd', to_id, self._get_actor(), self.key_list["blocked_by"])
def unblock(self, to_id):
self._action_call('srem', self._get_actor(), to_id, self.key_list["blocked"])
self._action_call('srem', to_id, self._get_actor(), self.key_list["blocked_by"])
def follow(self, to_id):
self._action_call('sadd', self._get_actor(), to_id, self.key_list["following"])
self._action_call('sadd', to_id, self._get_actor(), self.key_list["followers"])
def unfollow(self, to_id):
self._action_call('srem', self._get_actor(), to_id, self.key_list["following"])
self._action_call('srem', to_id, self._get_actor(), self.key_list["followers"])
def friends(self):
return self.redis_connection.sinter(
"user:{}:{}".format(self._get_actor(), self.key_list["following"]),
"user:{}:{}".format(self._get_actor(), self.key_list["followers"]),
)
def mutual_friends(self, to_id):
actor_friends, to_id_friends = self(self._get_actor()).friends(), self(to_id).friends()
return actor_friends.intersection(to_id_friends)
def followers(self):
return self._list_call(self.key_list["followers"])
def following(self):
return self._list_call(self.key_list["following"])
def blocks(self):
return self._list_call(self.key_list["blocked"])
def blocked(self):
return self._list_call(self.key_list["blocked_by"])
def follower_count(self):
return self._count_call(self.key_list["followers"])
def following_count(self):
return self._count_call(self.key_list["following"])
def block_count(self):
return self._count_call(self.key_list["blocked"])
def blocked_count(self):
return self._count_call(self.key_list["blocked_by"])
def is_follower(self, follower_id):
return self._action_call('sismember', self._get_actor(), follower_id, self.key_list["followers"])
def is_following(self, following_id):
return self._action_call('sismember', self._get_actor(), following_id, self.key_list["following"])
def is_blocked(self, blocked_id):
return self._action_call('sismember', self._get_actor(), blocked_id, self.key_list["blocked"])
def is_blocked_by(self, blocked_by_id):
return self._action_call('sismember', self._get_actor(), blocked_by_id,self.key_list["blocked_by"])
def get_network(self, output):
user_id = self._get_actor()
try:
import pydot
except ImportError:
raise ImportError("You need pydot library to get network functionality.")
graph = pydot.Dot('network_of_user_{}'.format(user_id), graph_type='digraph')
target_node = pydot.Node(user_id)
for _id in self(user_id).following():
user_node = pydot.Node(_id)
graph.add_edge(pydot.Edge(target_node, user_node))
for _id in self(user_id).followers():
user_node = pydot.Node(_id)
graph.add_edge(pydot.Edge(user_node, target_node))
graph.write_png(output)
| true | true |
f71670077ff7bfc22a95558c4ef9773e2b4a8e07 | 4,867 | py | Python | deeplearning_examples/loaders/Churn.py | dileep-kishore/deeplearning-examples | 2b230ea17f366f602044d44cc8abcac419d4e521 | [
"MIT"
] | null | null | null | deeplearning_examples/loaders/Churn.py | dileep-kishore/deeplearning-examples | 2b230ea17f366f602044d44cc8abcac419d4e521 | [
"MIT"
] | 321 | 2017-11-23T20:37:03.000Z | 2020-12-28T13:06:15.000Z | deeplearning_examples/loaders/Churn.py | dileep-kishore/deeplearning-examples | 2b230ea17f366f602044d44cc8abcac419d4e521 | [
"MIT"
] | null | null | null | # @Author: dileep
# @Last Modified by: dileep
from collections import OrderedDict
import os
from typing import Tuple, Iterable, Sequence, Dict, Union
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.model_selection import train_test_split
from . import datapath
from ..preprocessing import Encoder
from ..sampling import hold_out
#TODO: Make this a subclass of torch.utils.data.Dataset
class Churn:
"""
Class for loading the `churn` dataset to predict whether customer `exited` or not
Parameters:
----------
features : Iterable[str]
List of features to be used in training and testing.
NOTE: Do not include the dependent variable
Options: {RowNumber,CustomerId,Surname,CreditScore,Geography,Gender,
Age,Tenure,Balance,NumOfProducts,HasCrCard,IsActiveMember,
EstimatedSalary}
Attributes:
----------
raw_data : pd.Series
Raw data returned in the form of a pandas dataframe
train_data : Tuple[np.ndarray, np.ndarray]
Tuple of (features, targets) where each is a numpy ndarray
test_data : Tuple[np.ndarray, np.ndarray]
Tuple of (features, targets) where each is a numpy ndarray
"""
_feature_dict = {
'multi-category': {'Geography'},
'binary-category': {'Gender', 'HasCrCard', 'IsActiveMember', 'Exited'},
'int': {'CreditScore', 'Age', 'Tenure', 'NumOfProducts'},
'float': {'Balance', 'EstimatedSalary'}
}
def __init__(self, features: Union[Iterable[str], str] = 'all') -> None:
churn_path = os.path.join(datapath(), 'churn/Churn_Modeling.csv')
self.raw_data = pd.read_csv(churn_path, index_col=0)
if features == 'all':
features = self.all_features
assert self._validate_features(features), "Invalid features given"
self._features = features + ['Exited']
def __call__(self):
raw_train, raw_test = hold_out(self.raw_data[self._features])
feat_meta = self._get_feat_meta(self._features)
data_encoder = Encoder(feat_meta)
return data_encoder.encode(raw_train, raw_test, 'Exited')
@property
def all_features(self) -> Iterable[str]:
"""
Returns all the possible features that can be used
Returns:
-------
Iterable[str]
A list of all possible features
"""
features = list(self.raw_data.columns)
return [f for f in features if f not in {'Exited', 'RowNumber', 'CustomerId', 'Surname'}]
def _validate_features(self, features: Iterable[str]) -> bool:
"""
Returns whether the input set of features are valid
Parameters:
----------
features : Iterable[str]
Features input to the class
Returns:
-------
bool
True/False based on validity
"""
all_features = set()
for f_set in self._feature_dict.values():
all_features.update(f_set)
return not any(filter(lambda f: f not in all_features, features))
def _get_feat_meta(self, features: Iterable[str]) -> Dict[str, str]:
"""
Returns the type for each feature
Parameters:
----------
features : Iterable[str]
A list of features that are to be used for classification
Returns:
-------
Dict[str, str]
Dictionary of features and their corresponding types
"""
invert_fdict = {frozenset(v): k for k, v in self._feature_dict.items()}
feat_meta: Dict[str, str] = OrderedDict()
for feat in features:
for feat_group, data_type in invert_fdict.items():
if feat in feat_group:
feat_meta[feat] = data_type
continue
return feat_meta
def encode_features(self, features: Iterable[str]) -> Tuple[np.ndarray, np.ndarray]:
cat_features = (self._feature_dict['binary-category'] or
self._feature_dict['multi-category'])
for feat in features:
if feat in cat_features:
self.pp
def split_data(self, features: Iterable[str]) -> Sequence[np.ndarray]:
"""
Splits the raw data into training and testing using the features as a filter
Parameters:
----------
features : Iterable[str]
Features that are to be used in the training and testing data
Returns:
-------
Sequence[np.ndarray]
Sequence of x_train, x_test, y_train, y_test
"""
pass
| 38.322835 | 97 | 0.589275 |
from collections import OrderedDict
import os
from typing import Tuple, Iterable, Sequence, Dict, Union
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.model_selection import train_test_split
from . import datapath
from ..preprocessing import Encoder
from ..sampling import hold_out
class Churn:
_feature_dict = {
'multi-category': {'Geography'},
'binary-category': {'Gender', 'HasCrCard', 'IsActiveMember', 'Exited'},
'int': {'CreditScore', 'Age', 'Tenure', 'NumOfProducts'},
'float': {'Balance', 'EstimatedSalary'}
}
def __init__(self, features: Union[Iterable[str], str] = 'all') -> None:
churn_path = os.path.join(datapath(), 'churn/Churn_Modeling.csv')
self.raw_data = pd.read_csv(churn_path, index_col=0)
if features == 'all':
features = self.all_features
assert self._validate_features(features), "Invalid features given"
self._features = features + ['Exited']
def __call__(self):
raw_train, raw_test = hold_out(self.raw_data[self._features])
feat_meta = self._get_feat_meta(self._features)
data_encoder = Encoder(feat_meta)
return data_encoder.encode(raw_train, raw_test, 'Exited')
@property
def all_features(self) -> Iterable[str]:
features = list(self.raw_data.columns)
return [f for f in features if f not in {'Exited', 'RowNumber', 'CustomerId', 'Surname'}]
def _validate_features(self, features: Iterable[str]) -> bool:
all_features = set()
for f_set in self._feature_dict.values():
all_features.update(f_set)
return not any(filter(lambda f: f not in all_features, features))
def _get_feat_meta(self, features: Iterable[str]) -> Dict[str, str]:
invert_fdict = {frozenset(v): k for k, v in self._feature_dict.items()}
feat_meta: Dict[str, str] = OrderedDict()
for feat in features:
for feat_group, data_type in invert_fdict.items():
if feat in feat_group:
feat_meta[feat] = data_type
continue
return feat_meta
def encode_features(self, features: Iterable[str]) -> Tuple[np.ndarray, np.ndarray]:
cat_features = (self._feature_dict['binary-category'] or
self._feature_dict['multi-category'])
for feat in features:
if feat in cat_features:
self.pp
def split_data(self, features: Iterable[str]) -> Sequence[np.ndarray]:
pass
| true | true |
f716709e2478d7522c2c591d1f65cf3807762b7e | 255 | py | Python | Project Euler/1_Multiples_of_3_and_5.py | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 36 | 2019-12-27T08:23:08.000Z | 2022-01-24T20:35:47.000Z | Project Euler/1_Multiples_of_3_and_5.py | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 10 | 2019-11-13T02:55:18.000Z | 2021-10-13T23:28:09.000Z | Project Euler/1_Multiples_of_3_and_5.py | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 53 | 2020-08-15T11:08:40.000Z | 2021-10-09T15:51:38.000Z | # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
print(sum( i for i in range(1000) if i % 3 == 0 or i % 5 == 0 )) | 63.75 | 131 | 0.670588 |
print(sum( i for i in range(1000) if i % 3 == 0 or i % 5 == 0 )) | true | true |
f71671890da4aa3c0e2138334e26e8ab78927add | 451 | py | Python | musicbotv2/plugins/loader.py | dabolink/MusicBot | 38ab851b2c533e5bc703c4a4b3bb4af07059139f | [
"MIT"
] | null | null | null | musicbotv2/plugins/loader.py | dabolink/MusicBot | 38ab851b2c533e5bc703c4a4b3bb4af07059139f | [
"MIT"
] | null | null | null | musicbotv2/plugins/loader.py | dabolink/MusicBot | 38ab851b2c533e5bc703c4a4b3bb4af07059139f | [
"MIT"
] | null | null | null | import importlib
from typing import List
class ModuleInterface:
@staticmethod
def register() -> None:
"""Init the command"""
def import_module(name: str) -> ModuleInterface:
return importlib.import_module(name) # type: ignore
def load_commands(commands: List[str]) -> None:
for command_name in commands:
print("loading command :: ", command_name)
cmd = import_module(command_name)
cmd.register()
| 22.55 | 56 | 0.678492 | import importlib
from typing import List
class ModuleInterface:
@staticmethod
def register() -> None:
def import_module(name: str) -> ModuleInterface:
return importlib.import_module(name)
def load_commands(commands: List[str]) -> None:
for command_name in commands:
print("loading command :: ", command_name)
cmd = import_module(command_name)
cmd.register()
| true | true |
f716730fc1f1eb3c334d8d580c59f6f1e1e87d19 | 793 | py | Python | setup.py | fginter/simstring-cuda | 7773bca1e3ecf6dd9eac8f7c007549d098539356 | [
"Apache-2.0"
] | 2 | 2022-02-02T13:47:32.000Z | 2022-02-10T04:30:38.000Z | setup.py | fginter/simstring-cuda | 7773bca1e3ecf6dd9eac8f7c007549d098539356 | [
"Apache-2.0"
] | 1 | 2022-02-10T04:40:00.000Z | 2022-02-10T04:40:00.000Z | setup.py | fginter/simstring-cuda | 7773bca1e3ecf6dd9eac8f7c007549d098539356 | [
"Apache-2.0"
] | null | null | null | from setuptools import setup, find_packages
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='SimString-cuda',
version='0.1.0',
url='https://github.com/fginter/simstring-cuda.git',
author='Filip Ginter',
author_email='filip.ginter@gmail.com',
description="A poor-man's version of simistring-like lookup. Can hold its ground if the DB is few million strings, a GPU is present, and queries are batched by about a hundred strings.",
long_description=long_description,
long_description_content_type='text/markdown',
packages=find_packages(),
install_requires=['sklearn', 'torch'],
scripts=['simscuda']
)
| 37.761905 | 190 | 0.725095 | from setuptools import setup, find_packages
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='SimString-cuda',
version='0.1.0',
url='https://github.com/fginter/simstring-cuda.git',
author='Filip Ginter',
author_email='filip.ginter@gmail.com',
description="A poor-man's version of simistring-like lookup. Can hold its ground if the DB is few million strings, a GPU is present, and queries are batched by about a hundred strings.",
long_description=long_description,
long_description_content_type='text/markdown',
packages=find_packages(),
install_requires=['sklearn', 'torch'],
scripts=['simscuda']
)
| true | true |
f716732d7832fd5fb2824492c9a76cc168282fea | 7,206 | bzl | Python | scala_proto/private/scalapb_aspect.bzl | majcherm-da/rules_scala | 78104d8014d4e4fc8f905cd34b91dfabd9a268c8 | [
"Apache-2.0"
] | null | null | null | scala_proto/private/scalapb_aspect.bzl | majcherm-da/rules_scala | 78104d8014d4e4fc8f905cd34b91dfabd9a268c8 | [
"Apache-2.0"
] | null | null | null | scala_proto/private/scalapb_aspect.bzl | majcherm-da/rules_scala | 78104d8014d4e4fc8f905cd34b91dfabd9a268c8 | [
"Apache-2.0"
] | null | null | null | load(
"//scala/private:common.bzl",
"write_manifest_file",
)
load("//scala/private:rule_impls.bzl", "compile_scala")
load("//scala_proto/private:proto_to_scala_src.bzl", "proto_to_scala_src")
ScalaPBAspectInfo = provider(fields = [
"proto_info",
"src_jars",
"output_files",
"java_info",
])
ScalaPBImport = provider(fields = [
"java_info",
"proto_info",
])
ScalaPBInfo = provider(fields = [
"aspect_info",
])
def merge_proto_infos(tis):
return struct(
transitive_sources = [t.transitive_sources for t in tis],
)
def merge_scalapb_aspect_info(scalapbs):
return ScalaPBAspectInfo(
src_jars = depset(transitive = [s.src_jars for s in scalapbs]),
output_files = depset(transitive = [s.output_files for s in scalapbs]),
proto_info = merge_proto_infos([s.proto_info for s in scalapbs]),
java_info = java_common.merge([s.java_info for s in scalapbs]),
)
def _compiled_jar_file(actions, scalapb_jar):
scalapb_jar_name = scalapb_jar.basename
# ends with .srcjar, so remove last 6 characters
without_suffix = scalapb_jar_name[0:len(scalapb_jar_name) - 6]
# this already ends with _scalapb because that is how scalapb_jar is named
compiled_jar = without_suffix + "jar"
return actions.declare_file(compiled_jar, sibling = scalapb_jar)
def _compile_scala(
ctx,
scalac,
label,
output,
scalapb_jar,
deps_java_info,
implicit_deps):
manifest = ctx.actions.declare_file(
label.name + "_MANIFEST.MF",
sibling = scalapb_jar,
)
write_manifest_file(ctx.actions, manifest, None)
statsfile = ctx.actions.declare_file(
label.name + "_scalac.statsfile",
sibling = scalapb_jar,
)
merged_deps = java_common.merge(deps_java_info + implicit_deps)
# this only compiles scala, not the ijar, but we don't
# want the ijar for generated code anyway: any change
# in the proto generally will change the interface and
# method bodies
compile_scala(
ctx,
Label("%s-fast" % (label)),
output,
manifest,
statsfile,
sources = [],
cjars = merged_deps.compile_jars,
all_srcjars = depset([scalapb_jar]),
transitive_compile_jars = merged_deps.transitive_compile_time_jars,
plugins = [],
resource_strip_prefix = "",
resources = [],
resource_jars = [],
labels = {},
in_scalacopts = [],
print_compile_time = False,
expect_java_output = False,
scalac_jvm_flags = [],
scalac = scalac,
)
return JavaInfo(
source_jar = scalapb_jar,
deps = deps_java_info + implicit_deps,
runtime_deps = deps_java_info + implicit_deps,
exports = deps_java_info + implicit_deps,
output_jar = output,
compile_jar = output,
)
def _empty_java_info(deps_java_info, implicit_deps):
return java_common.merge(deps_java_info + implicit_deps)
####
# This is applied to the DAG of proto_librarys reachable from a deps
# or a scalapb_scala_library. Each proto_library will be one scalapb
# invocation assuming it has some sources.
def _scalapb_aspect_impl(target, ctx):
deps = [d[ScalaPBAspectInfo].java_info for d in ctx.rule.attr.deps]
if ProtoInfo not in target:
# We allow some dependencies which are not protobuf, but instead
# are jvm deps. This is to enable cases of custom generators which
# add a needed jvm dependency.
java_info = target[JavaInfo]
src_jars = depset()
outs = depset()
transitive_ti = merge_proto_infos(
[
d[ScalaPBAspectInfo].proto_info
for d in ctx.rule.attr.deps
],
)
else:
target_ti = target[ProtoInfo]
transitive_ti = merge_proto_infos(
[
d[ScalaPBAspectInfo].proto_info
for d in ctx.rule.attr.deps
] + [target_ti],
)
# we sort so the inputs are always the same for caching
compile_protos = sorted(target_ti.direct_sources)
transitive_protos = sorted(target_ti.transitive_sources)
toolchain = ctx.toolchains["@io_bazel_rules_scala//scala_proto:toolchain_type"]
flags = []
imps = [j[JavaInfo] for j in toolchain.implicit_compile_deps]
if toolchain.with_grpc:
flags.append("grpc")
imps.extend([j[JavaInfo] for j in toolchain.grpc_deps])
if toolchain.with_flat_package:
flags.append("flat_package")
if toolchain.with_single_line_to_string:
flags.append("single_line_to_proto_string")
# This feels rather hacky and odd, but we can't compare the labels to ignore a target easily
# since the @ or // forms seem to not have good equality :( , so we aim to make them absolute
#
# the backlisted protos in the tool chain get made into to absolute paths
# so we make the local target we are looking at absolute too
target_absolute_label = target.label
if not str(target_absolute_label)[0] == "@":
target_absolute_label = Label("@%s//%s:%s" % (ctx.workspace_name, target.label.package, target.label.name))
for lbl in toolchain.blacklisted_protos:
if(lbl.label == target_absolute_label):
compile_protos = False
code_generator = toolchain.code_generator
if compile_protos:
scalapb_file = ctx.actions.declare_file(
target.label.name + "_scalapb.srcjar",
)
proto_to_scala_src(
ctx,
target.label,
code_generator,
compile_protos,
transitive_protos,
target_ti.transitive_proto_path.to_list(),
flags,
scalapb_file,
)
src_jars = depset([scalapb_file])
output = _compiled_jar_file(ctx.actions, scalapb_file)
outs = depset([output])
java_info = _compile_scala(
ctx,
toolchain.scalac,
target.label,
output,
scalapb_file,
deps,
imps,
)
else:
# this target is only an aggregation target
src_jars = depset()
outs = depset()
java_info = _empty_java_info(deps, imps)
return [
ScalaPBAspectInfo(
src_jars = src_jars,
output_files = outs,
proto_info = transitive_ti,
java_info = java_info,
),
]
scalapb_aspect = aspect(
implementation = _scalapb_aspect_impl,
attr_aspects = ["deps"],
required_aspect_providers = [
[ProtoInfo],
[ScalaPBImport],
],
attrs = {
"_protoc": attr.label(executable = True, cfg = "host", default = "@com_google_protobuf//:protoc"),
},
toolchains = [
"@io_bazel_rules_scala//scala:toolchain_type",
"@io_bazel_rules_scala//scala_proto:toolchain_type",
],
)
| 31.605263 | 119 | 0.614627 | load(
"//scala/private:common.bzl",
"write_manifest_file",
)
load("//scala/private:rule_impls.bzl", "compile_scala")
load("//scala_proto/private:proto_to_scala_src.bzl", "proto_to_scala_src")
ScalaPBAspectInfo = provider(fields = [
"proto_info",
"src_jars",
"output_files",
"java_info",
])
ScalaPBImport = provider(fields = [
"java_info",
"proto_info",
])
ScalaPBInfo = provider(fields = [
"aspect_info",
])
def merge_proto_infos(tis):
return struct(
transitive_sources = [t.transitive_sources for t in tis],
)
def merge_scalapb_aspect_info(scalapbs):
return ScalaPBAspectInfo(
src_jars = depset(transitive = [s.src_jars for s in scalapbs]),
output_files = depset(transitive = [s.output_files for s in scalapbs]),
proto_info = merge_proto_infos([s.proto_info for s in scalapbs]),
java_info = java_common.merge([s.java_info for s in scalapbs]),
)
def _compiled_jar_file(actions, scalapb_jar):
scalapb_jar_name = scalapb_jar.basename
without_suffix = scalapb_jar_name[0:len(scalapb_jar_name) - 6]
compiled_jar = without_suffix + "jar"
return actions.declare_file(compiled_jar, sibling = scalapb_jar)
def _compile_scala(
ctx,
scalac,
label,
output,
scalapb_jar,
deps_java_info,
implicit_deps):
manifest = ctx.actions.declare_file(
label.name + "_MANIFEST.MF",
sibling = scalapb_jar,
)
write_manifest_file(ctx.actions, manifest, None)
statsfile = ctx.actions.declare_file(
label.name + "_scalac.statsfile",
sibling = scalapb_jar,
)
merged_deps = java_common.merge(deps_java_info + implicit_deps)
# want the ijar for generated code anyway: any change
# in the proto generally will change the interface and
# method bodies
compile_scala(
ctx,
Label("%s-fast" % (label)),
output,
manifest,
statsfile,
sources = [],
cjars = merged_deps.compile_jars,
all_srcjars = depset([scalapb_jar]),
transitive_compile_jars = merged_deps.transitive_compile_time_jars,
plugins = [],
resource_strip_prefix = "",
resources = [],
resource_jars = [],
labels = {},
in_scalacopts = [],
print_compile_time = False,
expect_java_output = False,
scalac_jvm_flags = [],
scalac = scalac,
)
return JavaInfo(
source_jar = scalapb_jar,
deps = deps_java_info + implicit_deps,
runtime_deps = deps_java_info + implicit_deps,
exports = deps_java_info + implicit_deps,
output_jar = output,
compile_jar = output,
)
def _empty_java_info(deps_java_info, implicit_deps):
return java_common.merge(deps_java_info + implicit_deps)
####
# This is applied to the DAG of proto_librarys reachable from a deps
# or a scalapb_scala_library. Each proto_library will be one scalapb
# invocation assuming it has some sources.
def _scalapb_aspect_impl(target, ctx):
deps = [d[ScalaPBAspectInfo].java_info for d in ctx.rule.attr.deps]
if ProtoInfo not in target:
# We allow some dependencies which are not protobuf, but instead
# are jvm deps. This is to enable cases of custom generators which
# add a needed jvm dependency.
java_info = target[JavaInfo]
src_jars = depset()
outs = depset()
transitive_ti = merge_proto_infos(
[
d[ScalaPBAspectInfo].proto_info
for d in ctx.rule.attr.deps
],
)
else:
target_ti = target[ProtoInfo]
transitive_ti = merge_proto_infos(
[
d[ScalaPBAspectInfo].proto_info
for d in ctx.rule.attr.deps
] + [target_ti],
)
# we sort so the inputs are always the same for caching
compile_protos = sorted(target_ti.direct_sources)
transitive_protos = sorted(target_ti.transitive_sources)
toolchain = ctx.toolchains["@io_bazel_rules_scala//scala_proto:toolchain_type"]
flags = []
imps = [j[JavaInfo] for j in toolchain.implicit_compile_deps]
if toolchain.with_grpc:
flags.append("grpc")
imps.extend([j[JavaInfo] for j in toolchain.grpc_deps])
if toolchain.with_flat_package:
flags.append("flat_package")
if toolchain.with_single_line_to_string:
flags.append("single_line_to_proto_string")
# This feels rather hacky and odd, but we can't compare the labels to ignore a target easily
target_absolute_label = target.label
if not str(target_absolute_label)[0] == "@":
target_absolute_label = Label("@%s//%s:%s" % (ctx.workspace_name, target.label.package, target.label.name))
for lbl in toolchain.blacklisted_protos:
if(lbl.label == target_absolute_label):
compile_protos = False
code_generator = toolchain.code_generator
if compile_protos:
scalapb_file = ctx.actions.declare_file(
target.label.name + "_scalapb.srcjar",
)
proto_to_scala_src(
ctx,
target.label,
code_generator,
compile_protos,
transitive_protos,
target_ti.transitive_proto_path.to_list(),
flags,
scalapb_file,
)
src_jars = depset([scalapb_file])
output = _compiled_jar_file(ctx.actions, scalapb_file)
outs = depset([output])
java_info = _compile_scala(
ctx,
toolchain.scalac,
target.label,
output,
scalapb_file,
deps,
imps,
)
else:
src_jars = depset()
outs = depset()
java_info = _empty_java_info(deps, imps)
return [
ScalaPBAspectInfo(
src_jars = src_jars,
output_files = outs,
proto_info = transitive_ti,
java_info = java_info,
),
]
scalapb_aspect = aspect(
implementation = _scalapb_aspect_impl,
attr_aspects = ["deps"],
required_aspect_providers = [
[ProtoInfo],
[ScalaPBImport],
],
attrs = {
"_protoc": attr.label(executable = True, cfg = "host", default = "@com_google_protobuf//:protoc"),
},
toolchains = [
"@io_bazel_rules_scala//scala:toolchain_type",
"@io_bazel_rules_scala//scala_proto:toolchain_type",
],
)
| true | true |
f7167381295d7b56237bfdcc1b5bedebfca834ed | 477 | py | Python | mac/pyobjc-framework-Quartz/PyObjCTest/test_PDFAnnotationLine.py | albertz/music-player | d23586f5bf657cbaea8147223be7814d117ae73d | [
"BSD-2-Clause"
] | 132 | 2015-01-01T10:02:42.000Z | 2022-03-09T12:51:01.000Z | mac/pyobjc-framework-Quartz/PyObjCTest/test_PDFAnnotationLine.py | mba811/music-player | 7998986b34cfda2244ef622adefb839331b81a81 | [
"BSD-2-Clause"
] | 6 | 2015-01-06T08:23:19.000Z | 2019-03-14T12:22:06.000Z | mac/pyobjc-framework-Quartz/PyObjCTest/test_PDFAnnotationLine.py | mba811/music-player | 7998986b34cfda2244ef622adefb839331b81a81 | [
"BSD-2-Clause"
] | 27 | 2015-02-23T11:51:43.000Z | 2022-03-07T02:34:18.000Z |
from PyObjCTools.TestSupport import *
from Quartz.PDFKit import *
class TestPDFAnnotationLine (TestCase):
def testConstants(self):
self.assertEqual(kPDFLineStyleNone, 0)
self.assertEqual(kPDFLineStyleSquare, 1)
self.assertEqual(kPDFLineStyleCircle, 2)
self.assertEqual(kPDFLineStyleDiamond, 3)
self.assertEqual(kPDFLineStyleOpenArrow, 4)
self.assertEqual(kPDFLineStyleClosedArrow, 5)
if __name__ == "__main__":
main()
| 29.8125 | 53 | 0.727463 |
from PyObjCTools.TestSupport import *
from Quartz.PDFKit import *
class TestPDFAnnotationLine (TestCase):
def testConstants(self):
self.assertEqual(kPDFLineStyleNone, 0)
self.assertEqual(kPDFLineStyleSquare, 1)
self.assertEqual(kPDFLineStyleCircle, 2)
self.assertEqual(kPDFLineStyleDiamond, 3)
self.assertEqual(kPDFLineStyleOpenArrow, 4)
self.assertEqual(kPDFLineStyleClosedArrow, 5)
if __name__ == "__main__":
main()
| true | true |
f71673edb368999b65c6db4d94b46852b8198252 | 886 | py | Python | setup.py | olivier-m/django-graffle | e2049b048e0c7944022e99800ca8f241c7d849ba | [
"BSD-3-Clause"
] | 1 | 2015-10-21T21:09:39.000Z | 2015-10-21T21:09:39.000Z | setup.py | olivier-m/django-graffle | e2049b048e0c7944022e99800ca8f241c7d849ba | [
"BSD-3-Clause"
] | null | null | null | setup.py | olivier-m/django-graffle | e2049b048e0c7944022e99800ca8f241c7d849ba | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
#
# This file is part of Django graffle released under the BSD license.
# See the LICENSE for more information.
from setuptools import setup, find_packages
version = '0.5'
packages = ['django_graffle'] + ['django_graffle.%s' % x for x in find_packages('django_graffle',)]
setup(
name='django_graffle',
version=version,
description='Graph your django views with Omnigraffle.',
author='Olivier Meunier',
author_email='om@neokraft.net',
url='http://bitbucket.org/cedarlab/django-graffle/',
packages=packages,
classifiers=[
'Development Status :: %s' % version,
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'
],
)
| 30.551724 | 99 | 0.654628 |
from setuptools import setup, find_packages
version = '0.5'
packages = ['django_graffle'] + ['django_graffle.%s' % x for x in find_packages('django_graffle',)]
setup(
name='django_graffle',
version=version,
description='Graph your django views with Omnigraffle.',
author='Olivier Meunier',
author_email='om@neokraft.net',
url='http://bitbucket.org/cedarlab/django-graffle/',
packages=packages,
classifiers=[
'Development Status :: %s' % version,
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'
],
)
| true | true |
f716742ca70ffea5e8234ece3da288effc4a72ca | 5,631 | py | Python | tests/test_metrics/test_issue_metrics.py | Joshinn-io/augur | 6759204dbae2ebb992dcd8c1f05408b9206c4ba3 | [
"MIT"
] | 443 | 2018-09-19T00:30:36.000Z | 2022-03-31T11:39:13.000Z | tests/test_metrics/test_issue_metrics.py | Romelo-S/augur | e9410887f58af2b26c350edf08e3f70ff783bdc5 | [
"MIT"
] | 613 | 2018-09-19T18:31:13.000Z | 2022-03-31T05:41:16.000Z | tests/test_metrics/test_issue_metrics.py | Romelo-S/augur | e9410887f58af2b26c350edf08e3f70ff783bdc5 | [
"MIT"
] | 764 | 2018-10-17T01:08:10.000Z | 2022-03-31T05:25:01.000Z | #SPDX-License-Identifier: MIT
import pytest
import pandas as pd
def test_issues_new(metrics):
#repo_id
assert metrics.issues_new(1, 1 , period='year').iloc[0]['issues'] > 0
#repo_group_id
assert metrics.issues_new(10, period='year').iloc[1]['issues'] > 0
#begin_date & end_date
assert metrics.issues_new(10, 25430, period='week', begin_date='2017',
end_date='2017-10').iloc[1]['issues'] > 0
assert metrics.issues_new(10, period='month', begin_date='2017-05',
end_date='2018').iloc[2]['issues'] > 0
def test_issues_active(metrics):
# repo
assert metrics.issues_active(1, 1, period='year').iloc[0]['issues'] > 0
# repo_group
assert metrics.issues_active(10, period='year').iloc[0]['issues'] > 0
# begin_date & end_date
assert metrics.issues_active(10, 25430, period='month', begin_date='2020-02',
end_date='2020-03').iloc[0]['issues'] > 0
assert metrics.issues_active(10, period='week', begin_date='2020-01',
end_date='2020-03') .iloc[0]['issues'] > 0
def test_issues_closed(metrics):
# repo
assert metrics.issues_closed(10, 25430, period='year').iloc[0]['issues'] > 0
#repo_group
assert metrics.issues_closed(10, period='year').iloc[0]['issues'] > 0
# begin_date & end_date
assert metrics.issues_closed(10, 25430, period='week', begin_date='2019',
end_date='2020-02').iloc[0]['issues'] > 0
assert metrics.issues_closed(10, period='month', begin_date='2018-05',
end_date='2019-08-15').iloc[0]['issues'] > 0
def test_issue_duration(metrics):
# repo
assert metrics.issue_duration(10, 25430).iloc[0]['duration'] == '20 days 03:08:22.000000000'
# repo_group
assert metrics.issue_duration(10).iloc[0]['duration'] == '20 days 03:08:22.000000000'
def test_issue_participants(metrics):
# repo
assert metrics.issue_participants(10, 25430).iloc[0]['participants'] > 0
# repo_group
assert metrics.issue_participants(10).iloc[0]['participants'] > 0
def test_issue_throughput(metrics):
# repo
assert metrics.issue_throughput(10, 25430).iloc[0]['throughput'] >= 0
# repo_group
assert metrics.issue_throughput(10).iloc[0]['throughput'] >= 0
def test_issue_backlog(metrics):
#repo_id
assert metrics.issue_backlog(10, 25430).iloc[0]['issue_backlog'] > 0
#repo_group_id
assert metrics.issue_backlog(10).iloc[0]['issue_backlog'] > 0
def test_issues_first_time_closed(metrics):
# repo id
assert metrics.issues_first_time_closed(10, repo_id=25430, period='year').isin(
[pd.Timestamp('2019', tz='UTC')]).any().any()
# repo_group_id
assert metrics.issues_first_time_closed(10, period='year').isin(
[pd.Timestamp('2020', tz='UTC')]).any().any()
# begin_date and end_date
assert metrics.issues_first_time_closed(10, period='year', begin_date='2019-1-1 00:00:00',
end_date='2019-12-31 23:59:59').isin([pd.Timestamp('2019-01-01 00:00:00', tz='UTC')]).any().any()
assert metrics.issues_first_time_closed(10, repo_id=25430, period='year', begin_date='2019-1-1 00:00:00',
end_date='2019-12-31 23:59:59').isin([pd.Timestamp('2019-01-01 00:00:00', tz='UTC')]).any().any()
def test_open_issues_count(metrics):
# repo
assert metrics.open_issues_count(10, 25430).iloc[0]['open_count'] > 0
# repo_group
assert metrics.open_issues_count(10).iloc[0]['open_count'] > 0
def test_closed_issues_count(metrics):
# repo
assert metrics.closed_issues_count(10, 25430).iloc[0]['closed_count'] > 0
# repo_group
assert metrics.closed_issues_count(10).iloc[0]['closed_count'] > 0
def test_issues_open_age(metrics):
#repo group
assert metrics.issues_open_age(10).iloc[0]['open_date'] > 0
# repo
assert metrics.issues_open_age(10, 25430).iloc[0]['open_date'] > 0
def test_issues_closed_resolution_duration(metrics):
# repo group
assert metrics.issues_closed_resolution_duration(10).iloc[0]['diffdate'] >= 0
# repo
assert metrics.issues_closed_resolution_duration(10, 25430).iloc[0]['diffdate'] >= 0
def test_average_issue_resolution_time(metrics):
#repo
assert metrics.average_issue_resolution_time(10, 25430).isin(
['augur', '61 days 12:20:43.791667']).any().any()
# repo_group
assert metrics.average_issue_resolution_time(10).isin(
['grimoirelab', ' 67 days 22:41:55.260417']).any().any()
def test_issues_maintainer_response_duration(metrics):
assert metrics.issues_maintainer_response_duration(10, 25430).iloc[0].average_days_comment > 0
assert metrics.issues_maintainer_response_duration(10).iloc[0].average_days_comment > 0
assert metrics.issues_maintainer_response_duration(10, 25430).iloc[0].average_days_comment > 0
def test_issue_comments_mean(metrics):
assert metrics.issue_comments_mean(10).any().any()
assert metrics.issue_comments_mean(10, 25430).any().any()
assert metrics.issue_comments_mean(10, group_by='year').any().any()
assert metrics.issue_comments_mean(10, 25430, group_by='year').any().any()
def test_issue_comments_mean_std(metrics):
assert metrics.issue_comments_mean_std(10).any().any()
assert metrics.issue_comments_mean_std(10, 25430).any().any()
assert metrics.issue_comments_mean_std(10, group_by='year').any().any()
assert metrics.issue_comments_mean_std(10, 25430, group_by='year').any().any()
| 38.834483 | 142 | 0.672527 |
import pytest
import pandas as pd
def test_issues_new(metrics):
assert metrics.issues_new(1, 1 , period='year').iloc[0]['issues'] > 0
assert metrics.issues_new(10, period='year').iloc[1]['issues'] > 0
assert metrics.issues_new(10, 25430, period='week', begin_date='2017',
end_date='2017-10').iloc[1]['issues'] > 0
assert metrics.issues_new(10, period='month', begin_date='2017-05',
end_date='2018').iloc[2]['issues'] > 0
def test_issues_active(metrics):
assert metrics.issues_active(1, 1, period='year').iloc[0]['issues'] > 0
assert metrics.issues_active(10, period='year').iloc[0]['issues'] > 0
assert metrics.issues_active(10, 25430, period='month', begin_date='2020-02',
end_date='2020-03').iloc[0]['issues'] > 0
assert metrics.issues_active(10, period='week', begin_date='2020-01',
end_date='2020-03') .iloc[0]['issues'] > 0
def test_issues_closed(metrics):
assert metrics.issues_closed(10, 25430, period='year').iloc[0]['issues'] > 0
assert metrics.issues_closed(10, period='year').iloc[0]['issues'] > 0
assert metrics.issues_closed(10, 25430, period='week', begin_date='2019',
end_date='2020-02').iloc[0]['issues'] > 0
assert metrics.issues_closed(10, period='month', begin_date='2018-05',
end_date='2019-08-15').iloc[0]['issues'] > 0
def test_issue_duration(metrics):
assert metrics.issue_duration(10, 25430).iloc[0]['duration'] == '20 days 03:08:22.000000000'
assert metrics.issue_duration(10).iloc[0]['duration'] == '20 days 03:08:22.000000000'
def test_issue_participants(metrics):
assert metrics.issue_participants(10, 25430).iloc[0]['participants'] > 0
assert metrics.issue_participants(10).iloc[0]['participants'] > 0
def test_issue_throughput(metrics):
assert metrics.issue_throughput(10, 25430).iloc[0]['throughput'] >= 0
assert metrics.issue_throughput(10).iloc[0]['throughput'] >= 0
def test_issue_backlog(metrics):
assert metrics.issue_backlog(10, 25430).iloc[0]['issue_backlog'] > 0
assert metrics.issue_backlog(10).iloc[0]['issue_backlog'] > 0
def test_issues_first_time_closed(metrics):
assert metrics.issues_first_time_closed(10, repo_id=25430, period='year').isin(
[pd.Timestamp('2019', tz='UTC')]).any().any()
assert metrics.issues_first_time_closed(10, period='year').isin(
[pd.Timestamp('2020', tz='UTC')]).any().any()
assert metrics.issues_first_time_closed(10, period='year', begin_date='2019-1-1 00:00:00',
end_date='2019-12-31 23:59:59').isin([pd.Timestamp('2019-01-01 00:00:00', tz='UTC')]).any().any()
assert metrics.issues_first_time_closed(10, repo_id=25430, period='year', begin_date='2019-1-1 00:00:00',
end_date='2019-12-31 23:59:59').isin([pd.Timestamp('2019-01-01 00:00:00', tz='UTC')]).any().any()
def test_open_issues_count(metrics):
assert metrics.open_issues_count(10, 25430).iloc[0]['open_count'] > 0
assert metrics.open_issues_count(10).iloc[0]['open_count'] > 0
def test_closed_issues_count(metrics):
assert metrics.closed_issues_count(10, 25430).iloc[0]['closed_count'] > 0
assert metrics.closed_issues_count(10).iloc[0]['closed_count'] > 0
def test_issues_open_age(metrics):
assert metrics.issues_open_age(10).iloc[0]['open_date'] > 0
assert metrics.issues_open_age(10, 25430).iloc[0]['open_date'] > 0
def test_issues_closed_resolution_duration(metrics):
assert metrics.issues_closed_resolution_duration(10).iloc[0]['diffdate'] >= 0
assert metrics.issues_closed_resolution_duration(10, 25430).iloc[0]['diffdate'] >= 0
def test_average_issue_resolution_time(metrics):
assert metrics.average_issue_resolution_time(10, 25430).isin(
['augur', '61 days 12:20:43.791667']).any().any()
assert metrics.average_issue_resolution_time(10).isin(
['grimoirelab', ' 67 days 22:41:55.260417']).any().any()
def test_issues_maintainer_response_duration(metrics):
assert metrics.issues_maintainer_response_duration(10, 25430).iloc[0].average_days_comment > 0
assert metrics.issues_maintainer_response_duration(10).iloc[0].average_days_comment > 0
assert metrics.issues_maintainer_response_duration(10, 25430).iloc[0].average_days_comment > 0
def test_issue_comments_mean(metrics):
assert metrics.issue_comments_mean(10).any().any()
assert metrics.issue_comments_mean(10, 25430).any().any()
assert metrics.issue_comments_mean(10, group_by='year').any().any()
assert metrics.issue_comments_mean(10, 25430, group_by='year').any().any()
def test_issue_comments_mean_std(metrics):
assert metrics.issue_comments_mean_std(10).any().any()
assert metrics.issue_comments_mean_std(10, 25430).any().any()
assert metrics.issue_comments_mean_std(10, group_by='year').any().any()
assert metrics.issue_comments_mean_std(10, 25430, group_by='year').any().any()
| true | true |
f71676329ad1aa128a74b82803791f78a3149af3 | 1,831 | py | Python | pydescriptors/helpers.py | c-martinez/compactness | 679a1644e0cd3ded278e9917efe171b5e89fc780 | [
"Apache-2.0"
] | 9 | 2017-02-15T10:44:17.000Z | 2022-03-05T10:14:21.000Z | pydescriptors/helpers.py | c-martinez/compactness | 679a1644e0cd3ded278e9917efe171b5e89fc780 | [
"Apache-2.0"
] | 1 | 2021-11-22T02:31:37.000Z | 2021-11-22T10:33:39.000Z | pydescriptors/helpers.py | c-martinez/compactness | 679a1644e0cd3ded278e9917efe171b5e89fc780 | [
"Apache-2.0"
] | 4 | 2019-04-17T02:28:01.000Z | 2022-02-15T02:03:38.000Z | import numpy as _np
from .moments import immoment3D as _immoment3D
def getSphere(side):
"""Create a 3D volume of sideXsideXside, where voxels representing a
sphere are ones and background is zeros.
Keyword arguments:
side -- the number of voxels the 3D volume should have on each side.
Returns:
A (side,side,side) shaped matrix of zeros and ones.
"""
volume = _np.zeros((side, side, side))
r = side / 2
Xs, Ys = _np.meshgrid(_np.arange(-r, r), _np.arange(-r, r))
for k, z in enumerate(_np.arange(-r, r)):
volume[:, :, k] = _np.sqrt(Xs ** 2 + Ys ** 2 + z ** 2) < r
return volume
def rotate3D(X, Y, Z, rx, ry):
"""Rotates a 3D object along one ordinate axis at a time.
Keyword arguments:
X -- The X coordinate of the voxels to be rotated.
Y -- The Y coordinate of the voxels to be rotated.
Z -- The Z coordinate of the voxels to be rotated.
Returns:
X,Y,Z coordinates of the rotated voxels.
"""
R = _np.eye(3)
Rx = _np.array([[1, 0, 0],
[0, _np.cos(rx), -_np.sin(rx)],
[0, _np.sin(rx), _np.cos(rx)]])
Ry = _np.array([[_np.cos(ry), 0, _np.sin(ry)],
[0, 1, 0],
[-_np.sin(ry), 0, _np.cos(ry)]])
R = _np.dot(R, Rx)
R = _np.dot(R, Ry)
XYZ = _np.vstack([X, Y, Z])
XYZ_ = _np.dot(XYZ.T, R)
return XYZ_[:, 0], XYZ_[:, 1], XYZ_[:, 2]
def recenter(X, Y, Z):
# TODO: Document, write unit test
m000 = _immoment3D(X, Y, Z, 0, 0, 0)
m100 = _immoment3D(X, Y, Z, 1, 0, 0)
m010 = _immoment3D(X, Y, Z, 0, 1, 0)
m001 = _immoment3D(X, Y, Z, 0, 0, 1)
# Find centroid
cx = m100 / m000
cy = m010 / m000
cz = m001 / m000
# Recentering
X_ = X - cx
Y_ = Y - cy
Z_ = Z - cz
return X_, Y_, Z_
| 26.926471 | 72 | 0.550519 | import numpy as _np
from .moments import immoment3D as _immoment3D
def getSphere(side):
volume = _np.zeros((side, side, side))
r = side / 2
Xs, Ys = _np.meshgrid(_np.arange(-r, r), _np.arange(-r, r))
for k, z in enumerate(_np.arange(-r, r)):
volume[:, :, k] = _np.sqrt(Xs ** 2 + Ys ** 2 + z ** 2) < r
return volume
def rotate3D(X, Y, Z, rx, ry):
R = _np.eye(3)
Rx = _np.array([[1, 0, 0],
[0, _np.cos(rx), -_np.sin(rx)],
[0, _np.sin(rx), _np.cos(rx)]])
Ry = _np.array([[_np.cos(ry), 0, _np.sin(ry)],
[0, 1, 0],
[-_np.sin(ry), 0, _np.cos(ry)]])
R = _np.dot(R, Rx)
R = _np.dot(R, Ry)
XYZ = _np.vstack([X, Y, Z])
XYZ_ = _np.dot(XYZ.T, R)
return XYZ_[:, 0], XYZ_[:, 1], XYZ_[:, 2]
def recenter(X, Y, Z):
m000 = _immoment3D(X, Y, Z, 0, 0, 0)
m100 = _immoment3D(X, Y, Z, 1, 0, 0)
m010 = _immoment3D(X, Y, Z, 0, 1, 0)
m001 = _immoment3D(X, Y, Z, 0, 0, 1)
cx = m100 / m000
cy = m010 / m000
cz = m001 / m000
X_ = X - cx
Y_ = Y - cy
Z_ = Z - cz
return X_, Y_, Z_
| true | true |
f716766002a0b6aae9b9a89d8422883c38d8d8f9 | 19,179 | py | Python | tests/jobs/test_local_task_job.py | anitakar/airflow | fc32d36d44f9d36b30333ce0676f2f3a6b133619 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | null | null | null | tests/jobs/test_local_task_job.py | anitakar/airflow | fc32d36d44f9d36b30333ce0676f2f3a6b133619 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | null | null | null | tests/jobs/test_local_task_job.py | anitakar/airflow | fc32d36d44f9d36b30333ce0676f2f3a6b133619 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | null | null | null | #
# 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.
#
import multiprocessing
import os
import time
import unittest
import uuid
from multiprocessing import Lock, Value
from unittest import mock
from unittest.mock import patch
import pytest
from airflow import settings
from airflow.exceptions import AirflowException, AirflowFailException
from airflow.executors.sequential_executor import SequentialExecutor
from airflow.jobs.local_task_job import LocalTaskJob
from airflow.models.dag import DAG
from airflow.models.dagbag import DagBag
from airflow.models.taskinstance import TaskInstance
from airflow.operators.dummy import DummyOperator
from airflow.operators.python import PythonOperator
from airflow.task.task_runner.standard_task_runner import StandardTaskRunner
from airflow.utils import timezone
from airflow.utils.net import get_hostname
from airflow.utils.session import create_session
from airflow.utils.state import State
from airflow.utils.timeout import timeout
from tests.test_utils.asserts import assert_queries_count
from tests.test_utils.db import clear_db_jobs, clear_db_runs
from tests.test_utils.mock_executor import MockExecutor
DEFAULT_DATE = timezone.datetime(2016, 1, 1)
TEST_DAG_FOLDER = os.environ['AIRFLOW__CORE__DAGS_FOLDER']
class TestLocalTaskJob(unittest.TestCase):
def setUp(self):
clear_db_jobs()
clear_db_runs()
patcher = patch('airflow.jobs.base_job.sleep')
self.addCleanup(patcher.stop)
self.mock_base_job_sleep = patcher.start()
def tearDown(self) -> None:
clear_db_jobs()
clear_db_runs()
def test_localtaskjob_essential_attr(self):
"""
Check whether essential attributes
of LocalTaskJob can be assigned with
proper values without intervention
"""
dag = DAG(
'test_localtaskjob_essential_attr', start_date=DEFAULT_DATE, default_args={'owner': 'owner1'}
)
with dag:
op1 = DummyOperator(task_id='op1')
dag.clear()
dr = dag.create_dagrun(
run_id="test", state=State.SUCCESS, execution_date=DEFAULT_DATE, start_date=DEFAULT_DATE
)
ti = dr.get_task_instance(task_id=op1.task_id)
job1 = LocalTaskJob(task_instance=ti, ignore_ti_state=True, executor=SequentialExecutor())
essential_attr = ["dag_id", "job_type", "start_date", "hostname"]
check_result_1 = [hasattr(job1, attr) for attr in essential_attr]
assert all(check_result_1)
check_result_2 = [getattr(job1, attr) is not None for attr in essential_attr]
assert all(check_result_2)
@patch('os.getpid')
def test_localtaskjob_heartbeat(self, mock_pid):
session = settings.Session()
dag = DAG('test_localtaskjob_heartbeat', start_date=DEFAULT_DATE, default_args={'owner': 'owner1'})
with dag:
op1 = DummyOperator(task_id='op1')
dag.clear()
dr = dag.create_dagrun(
run_id="test",
state=State.SUCCESS,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session,
)
ti = dr.get_task_instance(task_id=op1.task_id, session=session)
ti.state = State.RUNNING
ti.hostname = "blablabla"
session.commit()
job1 = LocalTaskJob(task_instance=ti, ignore_ti_state=True, executor=SequentialExecutor())
with pytest.raises(AirflowException):
job1.heartbeat_callback() # pylint: disable=no-value-for-parameter
mock_pid.return_value = 1
ti.state = State.RUNNING
ti.hostname = get_hostname()
ti.pid = 1
session.merge(ti)
session.commit()
job1.heartbeat_callback(session=None)
mock_pid.return_value = 2
with pytest.raises(AirflowException):
job1.heartbeat_callback() # pylint: disable=no-value-for-parameter
def test_heartbeat_failed_fast(self):
"""
Test that task heartbeat will sleep when it fails fast
"""
self.mock_base_job_sleep.side_effect = time.sleep
with create_session() as session:
dagbag = DagBag(
dag_folder=TEST_DAG_FOLDER,
include_examples=False,
)
dag_id = 'test_heartbeat_failed_fast'
task_id = 'test_heartbeat_failed_fast_op'
dag = dagbag.get_dag(dag_id)
task = dag.get_task(task_id)
dag.create_dagrun(
run_id="test_heartbeat_failed_fast_run",
state=State.RUNNING,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session,
)
ti = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti.refresh_from_db()
ti.state = State.RUNNING
ti.hostname = get_hostname()
ti.pid = 1
session.commit()
job = LocalTaskJob(task_instance=ti, executor=MockExecutor(do_update=False))
job.heartrate = 2
heartbeat_records = []
job.heartbeat_callback = lambda session: heartbeat_records.append(job.latest_heartbeat)
job._execute()
assert len(heartbeat_records) > 2
for i in range(1, len(heartbeat_records)):
time1 = heartbeat_records[i - 1]
time2 = heartbeat_records[i]
# Assert that difference small enough
delta = (time2 - time1).total_seconds()
assert abs(delta - job.heartrate) < 0.05
@pytest.mark.quarantined
def test_mark_success_no_kill(self):
"""
Test that ensures that mark_success in the UI doesn't cause
the task to fail, and that the task exits
"""
dagbag = DagBag(
dag_folder=TEST_DAG_FOLDER,
include_examples=False,
)
dag = dagbag.dags.get('test_mark_success')
task = dag.get_task('task1')
session = settings.Session()
dag.clear()
dag.create_dagrun(
run_id="test",
state=State.RUNNING,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session,
)
ti = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti.refresh_from_db()
job1 = LocalTaskJob(task_instance=ti, ignore_ti_state=True)
process = multiprocessing.Process(target=job1.run)
process.start()
ti.refresh_from_db()
for _ in range(0, 50):
if ti.state == State.RUNNING:
break
time.sleep(0.1)
ti.refresh_from_db()
assert State.RUNNING == ti.state
ti.state = State.SUCCESS
session.merge(ti)
session.commit()
process.join(timeout=10)
assert not process.is_alive()
ti.refresh_from_db()
assert State.SUCCESS == ti.state
def test_localtaskjob_double_trigger(self):
dagbag = DagBag(
dag_folder=TEST_DAG_FOLDER,
include_examples=False,
)
dag = dagbag.dags.get('test_localtaskjob_double_trigger')
task = dag.get_task('test_localtaskjob_double_trigger_task')
session = settings.Session()
dag.clear()
dr = dag.create_dagrun(
run_id="test",
state=State.SUCCESS,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session,
)
ti = dr.get_task_instance(task_id=task.task_id, session=session)
ti.state = State.RUNNING
ti.hostname = get_hostname()
ti.pid = 1
session.merge(ti)
session.commit()
ti_run = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti_run.refresh_from_db()
job1 = LocalTaskJob(task_instance=ti_run, executor=SequentialExecutor())
with patch.object(StandardTaskRunner, 'start', return_value=None) as mock_method:
job1.run()
mock_method.assert_not_called()
ti = dr.get_task_instance(task_id=task.task_id, session=session)
assert ti.pid == 1
assert ti.state == State.RUNNING
session.close()
@pytest.mark.quarantined
def test_localtaskjob_maintain_heart_rate(self):
dagbag = DagBag(
dag_folder=TEST_DAG_FOLDER,
include_examples=False,
)
dag = dagbag.dags.get('test_localtaskjob_double_trigger')
task = dag.get_task('test_localtaskjob_double_trigger_task')
session = settings.Session()
dag.clear()
dag.create_dagrun(
run_id="test",
state=State.SUCCESS,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session,
)
ti_run = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti_run.refresh_from_db()
job1 = LocalTaskJob(task_instance=ti_run, executor=SequentialExecutor())
# this should make sure we only heartbeat once and exit at the second
# loop in _execute()
return_codes = [None, 0]
def multi_return_code():
return return_codes.pop(0)
time_start = time.time()
with patch.object(StandardTaskRunner, 'start', return_value=None) as mock_start:
with patch.object(StandardTaskRunner, 'return_code') as mock_ret_code:
mock_ret_code.side_effect = multi_return_code
job1.run()
assert mock_start.call_count == 1
assert mock_ret_code.call_count == 2
time_end = time.time()
assert self.mock_base_job_sleep.call_count == 1
assert job1.state == State.SUCCESS
# Consider we have patched sleep call, it should not be sleeping to
# keep up with the heart rate in other unpatched places
#
# We already make sure patched sleep call is only called once
assert time_end - time_start < job1.heartrate
session.close()
def test_mark_failure_on_failure_callback(self):
"""
Test that ensures that mark_failure in the UI fails
the task, and executes on_failure_callback
"""
# use shared memory value so we can properly track value change even if
# it's been updated across processes.
failure_callback_called = Value('i', 0)
task_terminated_externally = Value('i', 1)
def check_failure(context):
with failure_callback_called.get_lock():
failure_callback_called.value += 1
assert context['dag_run'].dag_id == 'test_mark_failure'
assert context['exception'] == "task marked as failed externally"
def task_function(ti):
with create_session() as session:
assert State.RUNNING == ti.state
ti.log.info("Marking TI as failed 'externally'")
ti.state = State.FAILED
session.merge(ti)
session.commit()
time.sleep(10)
# This should not happen -- the state change should be noticed and the task should get killed
with task_terminated_externally.get_lock():
task_terminated_externally.value = 0
with DAG(dag_id='test_mark_failure', start_date=DEFAULT_DATE) as dag:
task = PythonOperator(
task_id='test_state_succeeded1',
python_callable=task_function,
on_failure_callback=check_failure,
)
dag.clear()
with create_session() as session:
dag.create_dagrun(
run_id="test",
state=State.RUNNING,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session,
)
ti = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti.refresh_from_db()
job1 = LocalTaskJob(task_instance=ti, ignore_ti_state=True, executor=SequentialExecutor())
with timeout(30):
# This should be _much_ shorter to run.
# If you change this limit, make the timeout in the callable above bigger
job1.run()
ti.refresh_from_db()
assert ti.state == State.FAILED
assert failure_callback_called.value == 1
assert task_terminated_externally.value == 1
@patch('airflow.utils.process_utils.subprocess.check_call')
@patch.object(StandardTaskRunner, 'return_code')
def test_failure_callback_only_called_once(self, mock_return_code, _check_call):
"""
Test that ensures that when a task exits with failure by itself,
failure callback is only called once
"""
# use shared memory value so we can properly track value change even if
# it's been updated across processes.
failure_callback_called = Value('i', 0)
callback_count_lock = Lock()
def failure_callback(context):
with callback_count_lock:
failure_callback_called.value += 1
assert context['dag_run'].dag_id == 'test_failure_callback_race'
assert isinstance(context['exception'], AirflowFailException)
def task_function(ti):
raise AirflowFailException()
dag = DAG(dag_id='test_failure_callback_race', start_date=DEFAULT_DATE)
task = PythonOperator(
task_id='test_exit_on_failure',
python_callable=task_function,
on_failure_callback=failure_callback,
dag=dag,
)
dag.clear()
with create_session() as session:
dag.create_dagrun(
run_id="test",
state=State.RUNNING,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session,
)
ti = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti.refresh_from_db()
job1 = LocalTaskJob(task_instance=ti, ignore_ti_state=True, executor=SequentialExecutor())
# Simulate race condition where job1 heartbeat ran right after task
# state got set to failed by ti.handle_failure but before task process
# fully exits. See _execute loop in airflow/jobs/local_task_job.py.
# In this case, we have:
# * task_runner.return_code() is None
# * ti.state == State.Failed
#
# We also need to set return_code to a valid int after job1.terminating
# is set to True so _execute loop won't loop forever.
def dummy_return_code(*args, **kwargs):
return None if not job1.terminating else -9
mock_return_code.side_effect = dummy_return_code
with timeout(10):
# This should be _much_ shorter to run.
# If you change this limit, make the timeout in the callable above bigger
job1.run()
ti.refresh_from_db()
assert ti.state == State.FAILED # task exits with failure state
assert failure_callback_called.value == 1
def test_mark_success_on_success_callback(self):
"""
Test that ensures that where a task is marked success in the UI
on_success_callback gets executed
"""
# use shared memory value so we can properly track value change even if
# it's been updated across processes.
success_callback_called = Value('i', 0)
task_terminated_externally = Value('i', 1)
shared_mem_lock = Lock()
def success_callback(context):
with shared_mem_lock:
success_callback_called.value += 1
assert context['dag_run'].dag_id == 'test_mark_success'
dag = DAG(dag_id='test_mark_success', start_date=DEFAULT_DATE, default_args={'owner': 'owner1'})
def task_function(ti):
# pylint: disable=unused-argument
time.sleep(60)
# This should not happen -- the state change should be noticed and the task should get killed
with shared_mem_lock:
task_terminated_externally.value = 0
task = PythonOperator(
task_id='test_state_succeeded1',
python_callable=task_function,
on_success_callback=success_callback,
dag=dag,
)
session = settings.Session()
dag.clear()
dag.create_dagrun(
run_id="test",
state=State.RUNNING,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session,
)
ti = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti.refresh_from_db()
job1 = LocalTaskJob(task_instance=ti, ignore_ti_state=True, executor=SequentialExecutor())
job1.task_runner = StandardTaskRunner(job1)
settings.engine.dispose()
process = multiprocessing.Process(target=job1.run)
process.start()
for _ in range(0, 25):
ti.refresh_from_db()
if ti.state == State.RUNNING:
break
time.sleep(0.2)
assert ti.state == State.RUNNING
ti.state = State.SUCCESS
session.merge(ti)
session.commit()
process.join(timeout=10)
assert success_callback_called.value == 1
assert task_terminated_externally.value == 1
assert not process.is_alive()
@pytest.fixture()
def clean_db_helper():
yield
clear_db_jobs()
clear_db_runs()
@pytest.mark.usefixtures("clean_db_helper")
class TestLocalTaskJobPerformance:
@pytest.mark.parametrize("return_codes", [[0], 9 * [None] + [0]]) # type: ignore
@mock.patch("airflow.jobs.local_task_job.get_task_runner")
def test_number_of_queries_single_loop(self, mock_get_task_runner, return_codes):
unique_prefix = str(uuid.uuid4())
dag = DAG(dag_id=f'{unique_prefix}_test_number_of_queries', start_date=DEFAULT_DATE)
task = DummyOperator(task_id='test_state_succeeded1', dag=dag)
dag.clear()
dag.create_dagrun(run_id=unique_prefix, state=State.NONE)
ti = TaskInstance(task=task, execution_date=DEFAULT_DATE)
mock_get_task_runner.return_value.return_code.side_effects = return_codes
job = LocalTaskJob(task_instance=ti, executor=MockExecutor())
with assert_queries_count(13):
job.run()
| 36.531429 | 107 | 0.640388 |
import multiprocessing
import os
import time
import unittest
import uuid
from multiprocessing import Lock, Value
from unittest import mock
from unittest.mock import patch
import pytest
from airflow import settings
from airflow.exceptions import AirflowException, AirflowFailException
from airflow.executors.sequential_executor import SequentialExecutor
from airflow.jobs.local_task_job import LocalTaskJob
from airflow.models.dag import DAG
from airflow.models.dagbag import DagBag
from airflow.models.taskinstance import TaskInstance
from airflow.operators.dummy import DummyOperator
from airflow.operators.python import PythonOperator
from airflow.task.task_runner.standard_task_runner import StandardTaskRunner
from airflow.utils import timezone
from airflow.utils.net import get_hostname
from airflow.utils.session import create_session
from airflow.utils.state import State
from airflow.utils.timeout import timeout
from tests.test_utils.asserts import assert_queries_count
from tests.test_utils.db import clear_db_jobs, clear_db_runs
from tests.test_utils.mock_executor import MockExecutor
DEFAULT_DATE = timezone.datetime(2016, 1, 1)
TEST_DAG_FOLDER = os.environ['AIRFLOW__CORE__DAGS_FOLDER']
class TestLocalTaskJob(unittest.TestCase):
def setUp(self):
clear_db_jobs()
clear_db_runs()
patcher = patch('airflow.jobs.base_job.sleep')
self.addCleanup(patcher.stop)
self.mock_base_job_sleep = patcher.start()
def tearDown(self) -> None:
clear_db_jobs()
clear_db_runs()
def test_localtaskjob_essential_attr(self):
dag = DAG(
'test_localtaskjob_essential_attr', start_date=DEFAULT_DATE, default_args={'owner': 'owner1'}
)
with dag:
op1 = DummyOperator(task_id='op1')
dag.clear()
dr = dag.create_dagrun(
run_id="test", state=State.SUCCESS, execution_date=DEFAULT_DATE, start_date=DEFAULT_DATE
)
ti = dr.get_task_instance(task_id=op1.task_id)
job1 = LocalTaskJob(task_instance=ti, ignore_ti_state=True, executor=SequentialExecutor())
essential_attr = ["dag_id", "job_type", "start_date", "hostname"]
check_result_1 = [hasattr(job1, attr) for attr in essential_attr]
assert all(check_result_1)
check_result_2 = [getattr(job1, attr) is not None for attr in essential_attr]
assert all(check_result_2)
@patch('os.getpid')
def test_localtaskjob_heartbeat(self, mock_pid):
session = settings.Session()
dag = DAG('test_localtaskjob_heartbeat', start_date=DEFAULT_DATE, default_args={'owner': 'owner1'})
with dag:
op1 = DummyOperator(task_id='op1')
dag.clear()
dr = dag.create_dagrun(
run_id="test",
state=State.SUCCESS,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session,
)
ti = dr.get_task_instance(task_id=op1.task_id, session=session)
ti.state = State.RUNNING
ti.hostname = "blablabla"
session.commit()
job1 = LocalTaskJob(task_instance=ti, ignore_ti_state=True, executor=SequentialExecutor())
with pytest.raises(AirflowException):
job1.heartbeat_callback()
mock_pid.return_value = 1
ti.state = State.RUNNING
ti.hostname = get_hostname()
ti.pid = 1
session.merge(ti)
session.commit()
job1.heartbeat_callback(session=None)
mock_pid.return_value = 2
with pytest.raises(AirflowException):
job1.heartbeat_callback()
def test_heartbeat_failed_fast(self):
self.mock_base_job_sleep.side_effect = time.sleep
with create_session() as session:
dagbag = DagBag(
dag_folder=TEST_DAG_FOLDER,
include_examples=False,
)
dag_id = 'test_heartbeat_failed_fast'
task_id = 'test_heartbeat_failed_fast_op'
dag = dagbag.get_dag(dag_id)
task = dag.get_task(task_id)
dag.create_dagrun(
run_id="test_heartbeat_failed_fast_run",
state=State.RUNNING,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session,
)
ti = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti.refresh_from_db()
ti.state = State.RUNNING
ti.hostname = get_hostname()
ti.pid = 1
session.commit()
job = LocalTaskJob(task_instance=ti, executor=MockExecutor(do_update=False))
job.heartrate = 2
heartbeat_records = []
job.heartbeat_callback = lambda session: heartbeat_records.append(job.latest_heartbeat)
job._execute()
assert len(heartbeat_records) > 2
for i in range(1, len(heartbeat_records)):
time1 = heartbeat_records[i - 1]
time2 = heartbeat_records[i]
delta = (time2 - time1).total_seconds()
assert abs(delta - job.heartrate) < 0.05
@pytest.mark.quarantined
def test_mark_success_no_kill(self):
dagbag = DagBag(
dag_folder=TEST_DAG_FOLDER,
include_examples=False,
)
dag = dagbag.dags.get('test_mark_success')
task = dag.get_task('task1')
session = settings.Session()
dag.clear()
dag.create_dagrun(
run_id="test",
state=State.RUNNING,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session,
)
ti = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti.refresh_from_db()
job1 = LocalTaskJob(task_instance=ti, ignore_ti_state=True)
process = multiprocessing.Process(target=job1.run)
process.start()
ti.refresh_from_db()
for _ in range(0, 50):
if ti.state == State.RUNNING:
break
time.sleep(0.1)
ti.refresh_from_db()
assert State.RUNNING == ti.state
ti.state = State.SUCCESS
session.merge(ti)
session.commit()
process.join(timeout=10)
assert not process.is_alive()
ti.refresh_from_db()
assert State.SUCCESS == ti.state
def test_localtaskjob_double_trigger(self):
dagbag = DagBag(
dag_folder=TEST_DAG_FOLDER,
include_examples=False,
)
dag = dagbag.dags.get('test_localtaskjob_double_trigger')
task = dag.get_task('test_localtaskjob_double_trigger_task')
session = settings.Session()
dag.clear()
dr = dag.create_dagrun(
run_id="test",
state=State.SUCCESS,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session,
)
ti = dr.get_task_instance(task_id=task.task_id, session=session)
ti.state = State.RUNNING
ti.hostname = get_hostname()
ti.pid = 1
session.merge(ti)
session.commit()
ti_run = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti_run.refresh_from_db()
job1 = LocalTaskJob(task_instance=ti_run, executor=SequentialExecutor())
with patch.object(StandardTaskRunner, 'start', return_value=None) as mock_method:
job1.run()
mock_method.assert_not_called()
ti = dr.get_task_instance(task_id=task.task_id, session=session)
assert ti.pid == 1
assert ti.state == State.RUNNING
session.close()
@pytest.mark.quarantined
def test_localtaskjob_maintain_heart_rate(self):
dagbag = DagBag(
dag_folder=TEST_DAG_FOLDER,
include_examples=False,
)
dag = dagbag.dags.get('test_localtaskjob_double_trigger')
task = dag.get_task('test_localtaskjob_double_trigger_task')
session = settings.Session()
dag.clear()
dag.create_dagrun(
run_id="test",
state=State.SUCCESS,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session,
)
ti_run = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti_run.refresh_from_db()
job1 = LocalTaskJob(task_instance=ti_run, executor=SequentialExecutor())
return_codes = [None, 0]
def multi_return_code():
return return_codes.pop(0)
time_start = time.time()
with patch.object(StandardTaskRunner, 'start', return_value=None) as mock_start:
with patch.object(StandardTaskRunner, 'return_code') as mock_ret_code:
mock_ret_code.side_effect = multi_return_code
job1.run()
assert mock_start.call_count == 1
assert mock_ret_code.call_count == 2
time_end = time.time()
assert self.mock_base_job_sleep.call_count == 1
assert job1.state == State.SUCCESS
assert time_end - time_start < job1.heartrate
session.close()
def test_mark_failure_on_failure_callback(self):
failure_callback_called = Value('i', 0)
task_terminated_externally = Value('i', 1)
def check_failure(context):
with failure_callback_called.get_lock():
failure_callback_called.value += 1
assert context['dag_run'].dag_id == 'test_mark_failure'
assert context['exception'] == "task marked as failed externally"
def task_function(ti):
with create_session() as session:
assert State.RUNNING == ti.state
ti.log.info("Marking TI as failed 'externally'")
ti.state = State.FAILED
session.merge(ti)
session.commit()
time.sleep(10)
# This should not happen -- the state change should be noticed and the task should get killed
with task_terminated_externally.get_lock():
task_terminated_externally.value = 0
with DAG(dag_id='test_mark_failure', start_date=DEFAULT_DATE) as dag:
task = PythonOperator(
task_id='test_state_succeeded1',
python_callable=task_function,
on_failure_callback=check_failure,
)
dag.clear()
with create_session() as session:
dag.create_dagrun(
run_id="test",
state=State.RUNNING,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session,
)
ti = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti.refresh_from_db()
job1 = LocalTaskJob(task_instance=ti, ignore_ti_state=True, executor=SequentialExecutor())
with timeout(30):
# This should be _much_ shorter to run.
# If you change this limit, make the timeout in the callable above bigger
job1.run()
ti.refresh_from_db()
assert ti.state == State.FAILED
assert failure_callback_called.value == 1
assert task_terminated_externally.value == 1
@patch('airflow.utils.process_utils.subprocess.check_call')
@patch.object(StandardTaskRunner, 'return_code')
def test_failure_callback_only_called_once(self, mock_return_code, _check_call):
# use shared memory value so we can properly track value change even if
# it's been updated across processes.
failure_callback_called = Value('i', 0)
callback_count_lock = Lock()
def failure_callback(context):
with callback_count_lock:
failure_callback_called.value += 1
assert context['dag_run'].dag_id == 'test_failure_callback_race'
assert isinstance(context['exception'], AirflowFailException)
def task_function(ti):
raise AirflowFailException()
dag = DAG(dag_id='test_failure_callback_race', start_date=DEFAULT_DATE)
task = PythonOperator(
task_id='test_exit_on_failure',
python_callable=task_function,
on_failure_callback=failure_callback,
dag=dag,
)
dag.clear()
with create_session() as session:
dag.create_dagrun(
run_id="test",
state=State.RUNNING,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session,
)
ti = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti.refresh_from_db()
job1 = LocalTaskJob(task_instance=ti, ignore_ti_state=True, executor=SequentialExecutor())
def dummy_return_code(*args, **kwargs):
return None if not job1.terminating else -9
mock_return_code.side_effect = dummy_return_code
with timeout(10):
# This should be _much_ shorter to run.
# If you change this limit, make the timeout in the callable above bigger
job1.run()
ti.refresh_from_db()
assert ti.state == State.FAILED # task exits with failure state
assert failure_callback_called.value == 1
def test_mark_success_on_success_callback(self):
# use shared memory value so we can properly track value change even if
# it's been updated across processes.
success_callback_called = Value('i', 0)
task_terminated_externally = Value('i', 1)
shared_mem_lock = Lock()
def success_callback(context):
with shared_mem_lock:
success_callback_called.value += 1
assert context['dag_run'].dag_id == 'test_mark_success'
dag = DAG(dag_id='test_mark_success', start_date=DEFAULT_DATE, default_args={'owner': 'owner1'})
def task_function(ti):
time.sleep(60)
with shared_mem_lock:
task_terminated_externally.value = 0
task = PythonOperator(
task_id='test_state_succeeded1',
python_callable=task_function,
on_success_callback=success_callback,
dag=dag,
)
session = settings.Session()
dag.clear()
dag.create_dagrun(
run_id="test",
state=State.RUNNING,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session,
)
ti = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti.refresh_from_db()
job1 = LocalTaskJob(task_instance=ti, ignore_ti_state=True, executor=SequentialExecutor())
job1.task_runner = StandardTaskRunner(job1)
settings.engine.dispose()
process = multiprocessing.Process(target=job1.run)
process.start()
for _ in range(0, 25):
ti.refresh_from_db()
if ti.state == State.RUNNING:
break
time.sleep(0.2)
assert ti.state == State.RUNNING
ti.state = State.SUCCESS
session.merge(ti)
session.commit()
process.join(timeout=10)
assert success_callback_called.value == 1
assert task_terminated_externally.value == 1
assert not process.is_alive()
@pytest.fixture()
def clean_db_helper():
yield
clear_db_jobs()
clear_db_runs()
@pytest.mark.usefixtures("clean_db_helper")
class TestLocalTaskJobPerformance:
@pytest.mark.parametrize("return_codes", [[0], 9 * [None] + [0]])
@mock.patch("airflow.jobs.local_task_job.get_task_runner")
def test_number_of_queries_single_loop(self, mock_get_task_runner, return_codes):
unique_prefix = str(uuid.uuid4())
dag = DAG(dag_id=f'{unique_prefix}_test_number_of_queries', start_date=DEFAULT_DATE)
task = DummyOperator(task_id='test_state_succeeded1', dag=dag)
dag.clear()
dag.create_dagrun(run_id=unique_prefix, state=State.NONE)
ti = TaskInstance(task=task, execution_date=DEFAULT_DATE)
mock_get_task_runner.return_value.return_code.side_effects = return_codes
job = LocalTaskJob(task_instance=ti, executor=MockExecutor())
with assert_queries_count(13):
job.run()
| true | true |
f71676683a6637366c41785b4c0e85fe9f8fcaf2 | 2,554 | py | Python | tests/test_submission.py | Uchimura85/wswp | 54b7e59390721cbd1e3ce0d7ed255af3c2b4511e | [
"MIT"
] | 4 | 2020-12-27T00:31:49.000Z | 2021-08-03T22:33:41.000Z | tests/test_submission.py | Uchimura85/wswp | 54b7e59390721cbd1e3ce0d7ed255af3c2b4511e | [
"MIT"
] | 1 | 2021-04-08T02:59:31.000Z | 2021-04-08T02:59:31.000Z | tests/test_submission.py | Uchimura85/wswp | 54b7e59390721cbd1e3ce0d7ed255af3c2b4511e | [
"MIT"
] | 1 | 2021-08-03T22:33:42.000Z | 2021-08-03T22:33:42.000Z | """Tests for submission functionality-- primarily if a submission
form is validated properly and passed to the backend.
"""
import pytest
import pathlib, json
from src.model import Activity, Submission
# Load in sample submissions and their expected status codes if they were submitted:
with open(pathlib.Path(__file__).parent.absolute()/'data'/'sample_submissions_base.json') as samples:
json_data = json.load(samples)
sample_submissions = [pytest.param(x['submission'], x['status_code'], x.get('broken_field'), id=x['id']) for x in json_data['sample_submissions']]
@pytest.mark.parametrize("submission, expected_code, problematic_field", sample_submissions)
def test_submissions(app, client, submission, expected_code, problematic_field):
"""Tests some typical submissions to make sure the error code raised
is the one expected (422 in a validation error) and that any validation
errors raised correspond to the right field that failed validation.
"""
rv = client.post('/v1/games/suggest', json=submission)
response_json = rv.get_json()
assert rv.status_code == expected_code
# In the response, validation issues are given in the 'issues' object, like:
# .. 'issues': { 'url': ['Field may not be null'] }
# So, we check to see if the issues object contains the field we expected
# to trigger a validation error.
if 'issues' in response_json and problematic_field:
assert problematic_field in response_json['issues']
# If we expected a 200, was the submission actually added?
if expected_code == 200:
with app.app_context():
game = Submission.query.filter_by(name=submission['name']).first()
assert game is not None
@pytest.mark.parametrize("max_players", [0, None])
def test_blank_max_players(app, client, max_players):
"""Leaving the max number of players blank (or 0) should result
in a NULL value going to the database.
"""
submission = {
"name": "TestMaxPlayersBlank",
"url": "https://google.ca",
"description": "test desc",
"min_players": 4,
"max_players": max_players,
"paid": False,
"submitted_by": "Matt"
}
rv = client.post('/v1/games/suggest', json=submission)
assert rv.status_code == 200
with app.app_context():
# Physically go into the submissions table and ensure the created
# record has NULL max_players
game = Submission.query.filter_by(name="TestMaxPlayersBlank").first()
assert game.max_players is None
| 43.288136 | 150 | 0.698904 |
import pytest
import pathlib, json
from src.model import Activity, Submission
with open(pathlib.Path(__file__).parent.absolute()/'data'/'sample_submissions_base.json') as samples:
json_data = json.load(samples)
sample_submissions = [pytest.param(x['submission'], x['status_code'], x.get('broken_field'), id=x['id']) for x in json_data['sample_submissions']]
@pytest.mark.parametrize("submission, expected_code, problematic_field", sample_submissions)
def test_submissions(app, client, submission, expected_code, problematic_field):
rv = client.post('/v1/games/suggest', json=submission)
response_json = rv.get_json()
assert rv.status_code == expected_code
if 'issues' in response_json and problematic_field:
assert problematic_field in response_json['issues']
if expected_code == 200:
with app.app_context():
game = Submission.query.filter_by(name=submission['name']).first()
assert game is not None
@pytest.mark.parametrize("max_players", [0, None])
def test_blank_max_players(app, client, max_players):
submission = {
"name": "TestMaxPlayersBlank",
"url": "https://google.ca",
"description": "test desc",
"min_players": 4,
"max_players": max_players,
"paid": False,
"submitted_by": "Matt"
}
rv = client.post('/v1/games/suggest', json=submission)
assert rv.status_code == 200
with app.app_context():
game = Submission.query.filter_by(name="TestMaxPlayersBlank").first()
assert game.max_players is None
| true | true |
f71678195657d243066d4e9b9ea9b1e9901b4130 | 4,061 | py | Python | scripts/Emdometrial/Statistics/mut_analysis.py | yaront/MutSig | 456dc793ab2dbd955b5cef098fd14539d428de0b | [
"Apache-2.0"
] | null | null | null | scripts/Emdometrial/Statistics/mut_analysis.py | yaront/MutSig | 456dc793ab2dbd955b5cef098fd14539d428de0b | [
"Apache-2.0"
] | null | null | null | scripts/Emdometrial/Statistics/mut_analysis.py | yaront/MutSig | 456dc793ab2dbd955b5cef098fd14539d428de0b | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 26 20:42:43 2018
@author: tomer
"""
#%%
# =================================================
# # Mutation per gene
# =================================================
import numpy as np
import pandas as pd
#%%
#tumor = sys.argv[1]
#tumor = tumor.split('/')[-1].split('.')[0]
#print tumor
tumor = 'UCEC'
#%% Reading data
print("Starting: " + tumor)
mut_data = pd.read_table('./../../../databases/Endometrial/TCGA_MAFs/' + tumor + '.maf', sep = '\t')
bmi_data = pd.read_table('./../../../databases/Endometrial/information/TCGA_bmi_data.txt', sep = '\t')
pat_bmi = bmi_data[bmi_data['bmi'] != '--']
pat_bmi = pat_bmi[(18.5 < pd.to_numeric(pat_bmi['bmi'])) & (pd.to_numeric(pat_bmi['bmi']) < 90)]
patients = list(set(np.unique(['-'.join(x.split('-')[0:3]) for x in mut_data['Tumor_Sample_Barcode']])).intersection(list(pat_bmi['submitter_id'].values)))
pat_bmi = pat_bmi[[(x in patients) for x in pat_bmi['submitter_id'].values]].sort_values(by = ['bmi'])
pat_mut = mut_data[[(x in patients) for x in ['-'.join(x.split('-')[0:3]) for x in mut_data['Tumor_Sample_Barcode']]]]
pat_mut = pat_mut[pat_mut['Variant_Classification'].isin(['Frame_Shift_Del', 'Frame_Shift_Ins', 'In_Frame_Del', 'In_Frame_Ins', 'Missense_Mutation', 'Nonsense_Mutation', 'Nonstop_Mutation', 'Translation_Start_Site'])]
#%% Creating table of mutations per BMI and mutation burden per patient
gene_bmi_mut = pd.DataFrame(0, columns = ['BMI','Total_Mutations'] + list(np.unique(pat_mut['Hugo_Symbol'])), index = np.sort(pat_bmi[['submitter_id','bmi']])[:,1])
gene_bmi_mut['BMI'] = np.sort(pat_bmi[['submitter_id','bmi']])[:,0]
pat_name_mut = ['-'.join(x.split('-')[0:3]) for x in pat_mut['Tumor_Sample_Barcode']]
for pat in gene_bmi_mut.index:
gene_bmi_mut.loc[pat,'Total_Mutations'] = pat_name_mut.count(pat)
gene_bmi_mut = gene_bmi_mut[gene_bmi_mut['Total_Mutations'] < 3000]
#%% Assigning mutations per gene per patient
print("Calculating mutations for " + tumor)
for g in np.unique(pat_mut['Hugo_Symbol']):
gene_mut = pat_mut[pat_mut['Hugo_Symbol'] == g]
gene_pat = ['-'.join(x.split('-')[0:3]) for x in gene_mut['Tumor_Sample_Barcode']]
for p in np.unique(gene_pat):
gene_bmi_mut.loc[p,g] = gene_pat.count(p)
gene_bmi_mut = gene_bmi_mut.transpose()
norm_gene_bmi_mut = []
#%% Finding the slope
print("Calculating slope for " + tumor)
inds = {bmi: ind for ind,bmi in enumerate(set(pd.to_numeric(gene_bmi_mut.loc['BMI',:])))}
bmi_ind = [inds[bmi] for bmi in pd.to_numeric(gene_bmi_mut.loc['BMI',:])]
slope = []
for i,j in gene_bmi_mut.iloc[2:,:].iterrows():
norm_mut = pd.to_numeric(j) / pd.to_numeric(gene_bmi_mut.loc['Total_Mutations'])
norm_gene_bmi_mut.append(norm_mut)
weight_mut = np.bincount(np.array(bmi_ind),weights=list(map(float,norm_mut.values))) / np.bincount(np.array(bmi_ind))
slope.append(np.polyfit(list(range(len(weight_mut))), weight_mut,1)[0])
norm_gene_bmi_mut = pd.DataFrame(norm_gene_bmi_mut)
norm_gene_bmi_mut = pd.concat([gene_bmi_mut.loc[['BMI','Total_Mutations'],:],norm_gene_bmi_mut])
norm_gene_bmi_mut.index = gene_bmi_mut.index
gene_bmi_mut['Slope'] = [-np.inf,-np.inf] + slope
gene_bmi_mut = gene_bmi_mut.sort_values(by = ['Slope'])
gene_bmi_mut.loc[['BMI','Total_Mutations'],'Slope'] = '-'
norm_gene_bmi_mut['Slope'] = [-np.inf,-np.inf] + slope
norm_gene_bmi_mut = norm_gene_bmi_mut.sort_values(by = ['Slope'])
norm_gene_bmi_mut.loc[['BMI','Total_Mutations'],'Slope'] = '-'
#%% Writing the data
print("Writing " + tumor)
gene_bmi_mut.to_csv('./../output/' + tumor + '_bmi_gene_mut.txt', header = True, index = True, sep = '\t')
norm_gene_bmi_mut.to_csv('./../output/' + tumor + '_bmi_gene_mut_norm.txt', header = True, index = True, sep = '\t')
writer = pd.ExcelWriter('./../output/' + tumor + '_bmi_gene_mut_slope.xlsx', engine='xlsxwriter')
gene_bmi_mut.to_excel(writer, sheet_name = tumor + '_binary')
norm_gene_bmi_mut.to_excel(writer, sheet_name = tumor + '_norm')
writer.save()
print("Done: " + tumor)
| 35.622807 | 217 | 0.676927 |
np
import pandas as pd
tumor = 'UCEC'
print("Starting: " + tumor)
mut_data = pd.read_table('./../../../databases/Endometrial/TCGA_MAFs/' + tumor + '.maf', sep = '\t')
bmi_data = pd.read_table('./../../../databases/Endometrial/information/TCGA_bmi_data.txt', sep = '\t')
pat_bmi = bmi_data[bmi_data['bmi'] != '--']
pat_bmi = pat_bmi[(18.5 < pd.to_numeric(pat_bmi['bmi'])) & (pd.to_numeric(pat_bmi['bmi']) < 90)]
patients = list(set(np.unique(['-'.join(x.split('-')[0:3]) for x in mut_data['Tumor_Sample_Barcode']])).intersection(list(pat_bmi['submitter_id'].values)))
pat_bmi = pat_bmi[[(x in patients) for x in pat_bmi['submitter_id'].values]].sort_values(by = ['bmi'])
pat_mut = mut_data[[(x in patients) for x in ['-'.join(x.split('-')[0:3]) for x in mut_data['Tumor_Sample_Barcode']]]]
pat_mut = pat_mut[pat_mut['Variant_Classification'].isin(['Frame_Shift_Del', 'Frame_Shift_Ins', 'In_Frame_Del', 'In_Frame_Ins', 'Missense_Mutation', 'Nonsense_Mutation', 'Nonstop_Mutation', 'Translation_Start_Site'])]
gene_bmi_mut = pd.DataFrame(0, columns = ['BMI','Total_Mutations'] + list(np.unique(pat_mut['Hugo_Symbol'])), index = np.sort(pat_bmi[['submitter_id','bmi']])[:,1])
gene_bmi_mut['BMI'] = np.sort(pat_bmi[['submitter_id','bmi']])[:,0]
pat_name_mut = ['-'.join(x.split('-')[0:3]) for x in pat_mut['Tumor_Sample_Barcode']]
for pat in gene_bmi_mut.index:
gene_bmi_mut.loc[pat,'Total_Mutations'] = pat_name_mut.count(pat)
gene_bmi_mut = gene_bmi_mut[gene_bmi_mut['Total_Mutations'] < 3000]
print("Calculating mutations for " + tumor)
for g in np.unique(pat_mut['Hugo_Symbol']):
gene_mut = pat_mut[pat_mut['Hugo_Symbol'] == g]
gene_pat = ['-'.join(x.split('-')[0:3]) for x in gene_mut['Tumor_Sample_Barcode']]
for p in np.unique(gene_pat):
gene_bmi_mut.loc[p,g] = gene_pat.count(p)
gene_bmi_mut = gene_bmi_mut.transpose()
norm_gene_bmi_mut = []
print("Calculating slope for " + tumor)
inds = {bmi: ind for ind,bmi in enumerate(set(pd.to_numeric(gene_bmi_mut.loc['BMI',:])))}
bmi_ind = [inds[bmi] for bmi in pd.to_numeric(gene_bmi_mut.loc['BMI',:])]
slope = []
for i,j in gene_bmi_mut.iloc[2:,:].iterrows():
norm_mut = pd.to_numeric(j) / pd.to_numeric(gene_bmi_mut.loc['Total_Mutations'])
norm_gene_bmi_mut.append(norm_mut)
weight_mut = np.bincount(np.array(bmi_ind),weights=list(map(float,norm_mut.values))) / np.bincount(np.array(bmi_ind))
slope.append(np.polyfit(list(range(len(weight_mut))), weight_mut,1)[0])
norm_gene_bmi_mut = pd.DataFrame(norm_gene_bmi_mut)
norm_gene_bmi_mut = pd.concat([gene_bmi_mut.loc[['BMI','Total_Mutations'],:],norm_gene_bmi_mut])
norm_gene_bmi_mut.index = gene_bmi_mut.index
gene_bmi_mut['Slope'] = [-np.inf,-np.inf] + slope
gene_bmi_mut = gene_bmi_mut.sort_values(by = ['Slope'])
gene_bmi_mut.loc[['BMI','Total_Mutations'],'Slope'] = '-'
norm_gene_bmi_mut['Slope'] = [-np.inf,-np.inf] + slope
norm_gene_bmi_mut = norm_gene_bmi_mut.sort_values(by = ['Slope'])
norm_gene_bmi_mut.loc[['BMI','Total_Mutations'],'Slope'] = '-'
print("Writing " + tumor)
gene_bmi_mut.to_csv('./../output/' + tumor + '_bmi_gene_mut.txt', header = True, index = True, sep = '\t')
norm_gene_bmi_mut.to_csv('./../output/' + tumor + '_bmi_gene_mut_norm.txt', header = True, index = True, sep = '\t')
writer = pd.ExcelWriter('./../output/' + tumor + '_bmi_gene_mut_slope.xlsx', engine='xlsxwriter')
gene_bmi_mut.to_excel(writer, sheet_name = tumor + '_binary')
norm_gene_bmi_mut.to_excel(writer, sheet_name = tumor + '_norm')
writer.save()
print("Done: " + tumor)
| true | true |
f71678545058b774df26f6e4aec31a97d2933afd | 406 | py | Python | zerver/migrations/0062_default_timezone.py | TylerPham2000/zulip | 2e7aaba0dde5517b4a55cb0bd782f009be45e3ba | [
"Apache-2.0"
] | 17,004 | 2015-09-25T18:27:24.000Z | 2022-03-31T22:02:32.000Z | zerver/migrations/0062_default_timezone.py | TylerPham2000/zulip | 2e7aaba0dde5517b4a55cb0bd782f009be45e3ba | [
"Apache-2.0"
] | 20,344 | 2015-09-25T19:02:42.000Z | 2022-03-31T23:54:40.000Z | zerver/migrations/0062_default_timezone.py | TylerPham2000/zulip | 2e7aaba0dde5517b4a55cb0bd782f009be45e3ba | [
"Apache-2.0"
] | 7,271 | 2015-09-25T18:48:39.000Z | 2022-03-31T21:06:11.000Z | # Generated by Django 1.10.5 on 2017-03-16 12:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("zerver", "0061_userprofile_timezone"),
]
operations = [
migrations.AlterField(
model_name="userprofile",
name="timezone",
field=models.CharField(default="", max_length=40),
),
]
| 22.555556 | 62 | 0.608374 |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("zerver", "0061_userprofile_timezone"),
]
operations = [
migrations.AlterField(
model_name="userprofile",
name="timezone",
field=models.CharField(default="", max_length=40),
),
]
| true | true |
f7167876873bfd4fe4f89c9dbfccf3393adb7076 | 1,589 | py | Python | expmgmt/utils/structures.py | wbrandenburger/ExpMgmt | bc2383bb360d8d7e876d503c1570c2d9188f8e39 | [
"MIT"
] | null | null | null | expmgmt/utils/structures.py | wbrandenburger/ExpMgmt | bc2383bb360d8d7e876d503c1570c2d9188f8e39 | [
"MIT"
] | null | null | null | expmgmt/utils/structures.py | wbrandenburger/ExpMgmt | bc2383bb360d8d7e876d503c1570c2d9188f8e39 | [
"MIT"
] | null | null | null | # ===========================================================================
# dictionary.py -----------------------------------------------------------
# ===========================================================================
# function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def update_dict(a, b):
# @todo[comment]:
if a and b and isinstance(a, dict):
a.update(b)
return a
# function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_dict_element(dict_list, field, query):
# @todo[comment]:
for item in dict_list:
if item[field] == query:
return item
return dict()
# function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_dict_elements(dict_list, field, query, update=False):
# @todo[comment]:
if not isinstance(field, list) and isinstance(query, list):
field = [field] * len(query)
result = list() if not update else dict()
if isinstance(field, list) and isinstance(query, list):
for field_item, query_item in zip(field, query):
item = get_dict_element(dict_list, field_item, query_item)
if item:
if not update:
result.append(item)
else:
result.update(item)
return result
| 38.756098 | 77 | 0.349276 |
def update_dict(a, b):
if a and b and isinstance(a, dict):
a.update(b)
return a
def get_dict_element(dict_list, field, query):
for item in dict_list:
if item[field] == query:
return item
return dict()
def get_dict_elements(dict_list, field, query, update=False):
if not isinstance(field, list) and isinstance(query, list):
field = [field] * len(query)
result = list() if not update else dict()
if isinstance(field, list) and isinstance(query, list):
for field_item, query_item in zip(field, query):
item = get_dict_element(dict_list, field_item, query_item)
if item:
if not update:
result.append(item)
else:
result.update(item)
return result
| true | true |
f71678a61c98b95204ecbdc16742b5edb4c3e82f | 458 | py | Python | dataset_results.py | polikutinevgeny/FrontsCNN | a9f48d5afcdd7e0fe561840d94af36c0fedf1c15 | [
"MIT"
] | 1 | 2019-12-28T08:40:44.000Z | 2019-12-28T08:40:44.000Z | dataset_results.py | polikutinevgeny/FrontsCNN | a9f48d5afcdd7e0fe561840d94af36c0fedf1c15 | [
"MIT"
] | null | null | null | dataset_results.py | polikutinevgeny/FrontsCNN | a9f48d5afcdd7e0fe561840d94af36c0fedf1c15 | [
"MIT"
] | null | null | null | import gc
import numpy as np
def dataset_results(dataset, model, binary=False):
x = np.array([dataset[i][0][0] for i in range(len(dataset))])
y_true = np.array([dataset[i][1][0] for i in range(len(dataset))])
y_pred = model.predict(x, batch_size=1, verbose=0).flatten()
if binary:
y_true = y_true[..., 0].flatten()
else:
y_true = np.argmax(y_true, axis=-1).flatten()
del x
gc.collect()
return y_true, y_pred
| 28.625 | 70 | 0.626638 | import gc
import numpy as np
def dataset_results(dataset, model, binary=False):
x = np.array([dataset[i][0][0] for i in range(len(dataset))])
y_true = np.array([dataset[i][1][0] for i in range(len(dataset))])
y_pred = model.predict(x, batch_size=1, verbose=0).flatten()
if binary:
y_true = y_true[..., 0].flatten()
else:
y_true = np.argmax(y_true, axis=-1).flatten()
del x
gc.collect()
return y_true, y_pred
| true | true |
f716792771771c2a540c7c03471ad8050e7db370 | 6,984 | py | Python | mbrl/env/pets_reacher.py | MaxSobolMark/mbrl-lib | bc8ccfe8a56b58d3ce5bae2c4ccdadd82ecdb594 | [
"MIT"
] | null | null | null | mbrl/env/pets_reacher.py | MaxSobolMark/mbrl-lib | bc8ccfe8a56b58d3ce5bae2c4ccdadd82ecdb594 | [
"MIT"
] | null | null | null | mbrl/env/pets_reacher.py | MaxSobolMark/mbrl-lib | bc8ccfe8a56b58d3ce5bae2c4ccdadd82ecdb594 | [
"MIT"
] | null | null | null | import os
from typing import Tuple
import numpy as np
from numpy.random import MT19937, RandomState, SeedSequence
import torch
from gym import utils
from gym.envs.mujoco import mujoco_env
class Reacher3DEnv(mujoco_env.MujocoEnv, utils.EzPickle):
def __init__(self, task_id=None, hide_goal=False):
self.viewer = None
utils.EzPickle.__init__(self)
dir_path = os.path.dirname(os.path.realpath(__file__))
self.goal = np.zeros(3)
self._hide_goal = hide_goal
mujoco_env.MujocoEnv.__init__(
self, os.path.join(dir_path, "assets/reacher3d.xml"), 2)
self._task_id = task_id
if task_id is not None:
self._rng = RandomState(MT19937(SeedSequence(task_id)))
self.goal = self._rng.normal(loc=0, scale=0.1, size=[3])
def step(self, a):
self.do_simulation(a, self.frame_skip)
ob = self._get_obs()
# print('[pets_reacher:22] ob[7:10]: ', ob[7:10])
reward = -np.sum(
np.square(Reacher3DEnv.get_EE_pos(ob[None]) - self.goal))
reward -= 0.01 * np.square(a).sum()
done = False
return ob, reward, done, dict(reward_dist=0, reward_ctrl=0)
def viewer_setup(self):
self.viewer.cam.trackbodyid = 1
self.viewer.cam.distance = 2.5
self.viewer.cam.elevation = -30
self.viewer.cam.azimuth = 270
def reset_model(self):
qpos, qvel = np.copy(self.init_qpos), np.copy(self.init_qvel)
if self._task_id is not None:
qpos[-3:] += self.goal
else:
qpos[-3:] += np.random.normal(loc=0, scale=0.1, size=[3])
self.goal = qpos[-3:]
qvel[-3:] = 0
self.set_state(qpos, qvel)
return self._get_obs()
def _get_obs(self):
if not self._hide_goal:
return np.concatenate([
self.data.qpos.flat,
self.data.qvel.flat[:-3],
])
return np.concatenate([
self.data.qpos.flat[:-3],
self.data.qvel.flat[:-3],
])
@staticmethod
def get_EE_pos(states, are_tensors=False):
theta1, theta2, theta3, theta4, theta5, theta6, _ = (
states[:, :1],
states[:, 1:2],
states[:, 2:3],
states[:, 3:4],
states[:, 4:5],
states[:, 5:6],
states[:, 6:],
)
if not are_tensors:
rot_axis = np.concatenate(
[
np.cos(theta2) * np.cos(theta1),
np.cos(theta2) * np.sin(theta1),
-np.sin(theta2),
],
axis=1,
)
rot_perp_axis = np.concatenate(
[-np.sin(theta1),
np.cos(theta1),
np.zeros(theta1.shape)],
axis=1)
cur_end = np.concatenate(
[
0.1 * np.cos(theta1) +
0.4 * np.cos(theta1) * np.cos(theta2),
0.1 * np.sin(theta1) +
0.4 * np.sin(theta1) * np.cos(theta2) - 0.188,
-0.4 * np.sin(theta2),
],
axis=1,
)
for length, hinge, roll in [(0.321, theta4, theta3),
(0.16828, theta6, theta5)]:
perp_all_axis = np.cross(rot_axis, rot_perp_axis)
x = np.cos(hinge) * rot_axis
y = np.sin(hinge) * np.sin(roll) * rot_perp_axis
z = -np.sin(hinge) * np.cos(roll) * perp_all_axis
new_rot_axis = x + y + z
new_rot_perp_axis = np.cross(new_rot_axis, rot_axis)
new_rot_perp_axis[np.linalg.norm(
new_rot_perp_axis, axis=1) < 1e-30] = rot_perp_axis[
np.linalg.norm(new_rot_perp_axis, axis=1) < 1e-30]
new_rot_perp_axis /= np.linalg.norm(new_rot_perp_axis,
axis=1,
keepdims=True)
rot_axis, rot_perp_axis, cur_end = (
new_rot_axis,
new_rot_perp_axis,
cur_end + length * new_rot_axis,
)
return cur_end
else:
rot_axis = torch.cat(
[
torch.cos(theta2) * torch.cos(theta1),
torch.cos(theta2) * torch.sin(theta1),
-torch.sin(theta2),
],
dim=1,
)
rot_perp_axis = torch.cat([
-torch.sin(theta1),
torch.cos(theta1),
torch.zeros_like(theta1)
],
dim=1)
cur_end = torch.cat(
[
0.1 * torch.cos(theta1) +
0.4 * torch.cos(theta1) * torch.cos(theta2),
0.1 * torch.sin(theta1) +
0.4 * torch.sin(theta1) * torch.cos(theta2) - 0.188,
-0.4 * torch.sin(theta2),
],
dim=1,
)
for length, hinge, roll in [(0.321, theta4, theta3),
(0.16828, theta6, theta5)]:
perp_all_axis = torch.cross(rot_axis, rot_perp_axis)
x = torch.cos(hinge) * rot_axis
y = torch.sin(hinge) * torch.sin(roll) * rot_perp_axis
z = -torch.sin(hinge) * torch.cos(roll) * perp_all_axis
new_rot_axis = x + y + z
new_rot_perp_axis = torch.cross(new_rot_axis, rot_axis)
new_rot_perp_axis[torch.linalg.norm(
new_rot_perp_axis, dim=1) < 1e-30] = rot_perp_axis[
torch.linalg.norm(new_rot_perp_axis, dim=1) < 1e-30]
new_rot_perp_axis /= torch.linalg.norm(new_rot_perp_axis,
dim=1,
keepdims=True)
rot_axis, rot_perp_axis, cur_end = (
new_rot_axis,
new_rot_perp_axis,
cur_end + length * new_rot_axis,
)
return cur_end
@staticmethod
def get_reward(ob, action):
# This is a bit tricky to implement, implement when needed
print('NOT SUPPOSED TO RUN THIS!')
raise NotImplementedError
def forward_postprocess_fn(
self, inputs: torch.Tensor, mean: torch.Tensor, logvar: torch.Tensor,
min_logvar: torch.nn.parameter.Parameter
) -> Tuple[torch.Tensor, torch.Tensor]:
if not self._hide_goal:
mean[..., 7:10] = inputs[..., 7:10]
logvar[..., 7:10] = torch.full(logvar[..., 7:10].shape,
-float('inf'))
return mean, logvar
| 37.751351 | 77 | 0.477663 | import os
from typing import Tuple
import numpy as np
from numpy.random import MT19937, RandomState, SeedSequence
import torch
from gym import utils
from gym.envs.mujoco import mujoco_env
class Reacher3DEnv(mujoco_env.MujocoEnv, utils.EzPickle):
def __init__(self, task_id=None, hide_goal=False):
self.viewer = None
utils.EzPickle.__init__(self)
dir_path = os.path.dirname(os.path.realpath(__file__))
self.goal = np.zeros(3)
self._hide_goal = hide_goal
mujoco_env.MujocoEnv.__init__(
self, os.path.join(dir_path, "assets/reacher3d.xml"), 2)
self._task_id = task_id
if task_id is not None:
self._rng = RandomState(MT19937(SeedSequence(task_id)))
self.goal = self._rng.normal(loc=0, scale=0.1, size=[3])
def step(self, a):
self.do_simulation(a, self.frame_skip)
ob = self._get_obs()
reward = -np.sum(
np.square(Reacher3DEnv.get_EE_pos(ob[None]) - self.goal))
reward -= 0.01 * np.square(a).sum()
done = False
return ob, reward, done, dict(reward_dist=0, reward_ctrl=0)
def viewer_setup(self):
self.viewer.cam.trackbodyid = 1
self.viewer.cam.distance = 2.5
self.viewer.cam.elevation = -30
self.viewer.cam.azimuth = 270
def reset_model(self):
qpos, qvel = np.copy(self.init_qpos), np.copy(self.init_qvel)
if self._task_id is not None:
qpos[-3:] += self.goal
else:
qpos[-3:] += np.random.normal(loc=0, scale=0.1, size=[3])
self.goal = qpos[-3:]
qvel[-3:] = 0
self.set_state(qpos, qvel)
return self._get_obs()
def _get_obs(self):
if not self._hide_goal:
return np.concatenate([
self.data.qpos.flat,
self.data.qvel.flat[:-3],
])
return np.concatenate([
self.data.qpos.flat[:-3],
self.data.qvel.flat[:-3],
])
@staticmethod
def get_EE_pos(states, are_tensors=False):
theta1, theta2, theta3, theta4, theta5, theta6, _ = (
states[:, :1],
states[:, 1:2],
states[:, 2:3],
states[:, 3:4],
states[:, 4:5],
states[:, 5:6],
states[:, 6:],
)
if not are_tensors:
rot_axis = np.concatenate(
[
np.cos(theta2) * np.cos(theta1),
np.cos(theta2) * np.sin(theta1),
-np.sin(theta2),
],
axis=1,
)
rot_perp_axis = np.concatenate(
[-np.sin(theta1),
np.cos(theta1),
np.zeros(theta1.shape)],
axis=1)
cur_end = np.concatenate(
[
0.1 * np.cos(theta1) +
0.4 * np.cos(theta1) * np.cos(theta2),
0.1 * np.sin(theta1) +
0.4 * np.sin(theta1) * np.cos(theta2) - 0.188,
-0.4 * np.sin(theta2),
],
axis=1,
)
for length, hinge, roll in [(0.321, theta4, theta3),
(0.16828, theta6, theta5)]:
perp_all_axis = np.cross(rot_axis, rot_perp_axis)
x = np.cos(hinge) * rot_axis
y = np.sin(hinge) * np.sin(roll) * rot_perp_axis
z = -np.sin(hinge) * np.cos(roll) * perp_all_axis
new_rot_axis = x + y + z
new_rot_perp_axis = np.cross(new_rot_axis, rot_axis)
new_rot_perp_axis[np.linalg.norm(
new_rot_perp_axis, axis=1) < 1e-30] = rot_perp_axis[
np.linalg.norm(new_rot_perp_axis, axis=1) < 1e-30]
new_rot_perp_axis /= np.linalg.norm(new_rot_perp_axis,
axis=1,
keepdims=True)
rot_axis, rot_perp_axis, cur_end = (
new_rot_axis,
new_rot_perp_axis,
cur_end + length * new_rot_axis,
)
return cur_end
else:
rot_axis = torch.cat(
[
torch.cos(theta2) * torch.cos(theta1),
torch.cos(theta2) * torch.sin(theta1),
-torch.sin(theta2),
],
dim=1,
)
rot_perp_axis = torch.cat([
-torch.sin(theta1),
torch.cos(theta1),
torch.zeros_like(theta1)
],
dim=1)
cur_end = torch.cat(
[
0.1 * torch.cos(theta1) +
0.4 * torch.cos(theta1) * torch.cos(theta2),
0.1 * torch.sin(theta1) +
0.4 * torch.sin(theta1) * torch.cos(theta2) - 0.188,
-0.4 * torch.sin(theta2),
],
dim=1,
)
for length, hinge, roll in [(0.321, theta4, theta3),
(0.16828, theta6, theta5)]:
perp_all_axis = torch.cross(rot_axis, rot_perp_axis)
x = torch.cos(hinge) * rot_axis
y = torch.sin(hinge) * torch.sin(roll) * rot_perp_axis
z = -torch.sin(hinge) * torch.cos(roll) * perp_all_axis
new_rot_axis = x + y + z
new_rot_perp_axis = torch.cross(new_rot_axis, rot_axis)
new_rot_perp_axis[torch.linalg.norm(
new_rot_perp_axis, dim=1) < 1e-30] = rot_perp_axis[
torch.linalg.norm(new_rot_perp_axis, dim=1) < 1e-30]
new_rot_perp_axis /= torch.linalg.norm(new_rot_perp_axis,
dim=1,
keepdims=True)
rot_axis, rot_perp_axis, cur_end = (
new_rot_axis,
new_rot_perp_axis,
cur_end + length * new_rot_axis,
)
return cur_end
@staticmethod
def get_reward(ob, action):
print('NOT SUPPOSED TO RUN THIS!')
raise NotImplementedError
def forward_postprocess_fn(
self, inputs: torch.Tensor, mean: torch.Tensor, logvar: torch.Tensor,
min_logvar: torch.nn.parameter.Parameter
) -> Tuple[torch.Tensor, torch.Tensor]:
if not self._hide_goal:
mean[..., 7:10] = inputs[..., 7:10]
logvar[..., 7:10] = torch.full(logvar[..., 7:10].shape,
-float('inf'))
return mean, logvar
| true | true |
f716795d8f15462f698be1ecce4ae982839d72ed | 2,091 | py | Python | src/front-door/azext_front_door/vendored_sdks/models/managed_rule_override.py | michimune/azure-cli-extensions | 697e2c674e5c0825d44c72d714542fe01331e107 | [
"MIT"
] | 1 | 2022-03-22T15:02:32.000Z | 2022-03-22T15:02:32.000Z | src/front-door/azext_front_door/vendored_sdks/models/managed_rule_override.py | michimune/azure-cli-extensions | 697e2c674e5c0825d44c72d714542fe01331e107 | [
"MIT"
] | 1 | 2021-02-10T22:04:59.000Z | 2021-02-10T22:04:59.000Z | src/front-door/azext_front_door/vendored_sdks/models/managed_rule_override.py | michimune/azure-cli-extensions | 697e2c674e5c0825d44c72d714542fe01331e107 | [
"MIT"
] | 1 | 2021-06-03T19:31:10.000Z | 2021-06-03T19:31:10.000Z | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class ManagedRuleOverride(Model):
"""Defines a managed rule group override setting.
All required parameters must be populated in order to send to Azure.
:param rule_id: Required. Identifier for the managed rule.
:type rule_id: str
:param enabled_state: Describes if the managed rule is in enabled or
disabled state. Defaults to Disabled if not specified. Possible values
include: 'Disabled', 'Enabled'
:type enabled_state: str or
~azure.mgmt.frontdoor.models.ManagedRuleEnabledState
:param action: Describes the override action to be applied when rule
matches. Possible values include: 'Allow', 'Block', 'Log', 'Redirect'
:type action: str or ~azure.mgmt.frontdoor.models.ActionType
:param exclusions: Describes the exclusions that are applied to this
specific rule.
:type exclusions: list[~azure.mgmt.frontdoor.models.ManagedRuleExclusion]
"""
_validation = {
'rule_id': {'required': True},
}
_attribute_map = {
'rule_id': {'key': 'ruleId', 'type': 'str'},
'enabled_state': {'key': 'enabledState', 'type': 'str'},
'action': {'key': 'action', 'type': 'str'},
'exclusions': {'key': 'exclusions', 'type': '[ManagedRuleExclusion]'},
}
def __init__(self, **kwargs):
super(ManagedRuleOverride, self).__init__(**kwargs)
self.rule_id = kwargs.get('rule_id', None)
self.enabled_state = kwargs.get('enabled_state', None)
self.action = kwargs.get('action', None)
self.exclusions = kwargs.get('exclusions', None)
| 40.211538 | 78 | 0.636059 |
from msrest.serialization import Model
class ManagedRuleOverride(Model):
_validation = {
'rule_id': {'required': True},
}
_attribute_map = {
'rule_id': {'key': 'ruleId', 'type': 'str'},
'enabled_state': {'key': 'enabledState', 'type': 'str'},
'action': {'key': 'action', 'type': 'str'},
'exclusions': {'key': 'exclusions', 'type': '[ManagedRuleExclusion]'},
}
def __init__(self, **kwargs):
super(ManagedRuleOverride, self).__init__(**kwargs)
self.rule_id = kwargs.get('rule_id', None)
self.enabled_state = kwargs.get('enabled_state', None)
self.action = kwargs.get('action', None)
self.exclusions = kwargs.get('exclusions', None)
| true | true |
f71679d226b40ff0d00a91dabe615ef3a5c5b9e5 | 1,354 | py | Python | Asyncio/asyncio_queue.py | xlui/PythonExamples | 0389efb84e01dc1310bb2bab7aa2433c0e1b45c4 | [
"MIT"
] | null | null | null | Asyncio/asyncio_queue.py | xlui/PythonExamples | 0389efb84e01dc1310bb2bab7aa2433c0e1b45c4 | [
"MIT"
] | null | null | null | Asyncio/asyncio_queue.py | xlui/PythonExamples | 0389efb84e01dc1310bb2bab7aa2433c0e1b45c4 | [
"MIT"
] | null | null | null | # asyncio_queue.py
import asyncio
async def consumer(n, _queue):
""":type _queue asyncio.Queue"""
# print('consumer {}: waiting for item'.format(n))
while True:
print('consumer {}: waiting for item'.format(n))
item = await _queue.get()
print('consumer {}: has item {}'.format(n, item))
if item is None:
_queue.task_done()
break
else:
await asyncio.sleep(.01 * item)
_queue.task_done()
print('consumer {}: ending'.format(n))
async def producer(_queue, workers):
""":type _queue asyncio.Queue"""
print('producer: starting')
for i in range(workers * 3):
await _queue.put(i)
print('producer: add task {} to queue'.format(i))
print('producer: adding stop signals to the queue')
for i in range(workers):
await _queue.put(None)
print('producer: waiting for queue to empty')
await _queue.join()
print('producer: ending')
async def main(loop, _consumers):
queue = asyncio.Queue(maxsize=_consumers)
consumers = [loop.create_task(consumer(i, queue)) for i in range(_consumers)]
prod = loop.create_task(producer(queue, _consumers))
await asyncio.wait(consumers + [prod])
event_loop = asyncio.get_event_loop()
event_loop.run_until_complete(main(event_loop, 2))
event_loop.close()
| 28.208333 | 81 | 0.637371 |
import asyncio
async def consumer(n, _queue):
while True:
print('consumer {}: waiting for item'.format(n))
item = await _queue.get()
print('consumer {}: has item {}'.format(n, item))
if item is None:
_queue.task_done()
break
else:
await asyncio.sleep(.01 * item)
_queue.task_done()
print('consumer {}: ending'.format(n))
async def producer(_queue, workers):
print('producer: starting')
for i in range(workers * 3):
await _queue.put(i)
print('producer: add task {} to queue'.format(i))
print('producer: adding stop signals to the queue')
for i in range(workers):
await _queue.put(None)
print('producer: waiting for queue to empty')
await _queue.join()
print('producer: ending')
async def main(loop, _consumers):
queue = asyncio.Queue(maxsize=_consumers)
consumers = [loop.create_task(consumer(i, queue)) for i in range(_consumers)]
prod = loop.create_task(producer(queue, _consumers))
await asyncio.wait(consumers + [prod])
event_loop = asyncio.get_event_loop()
event_loop.run_until_complete(main(event_loop, 2))
event_loop.close()
| true | true |
f71679e9a79db28502e7b077981e0b0b7bee67f6 | 37,770 | py | Python | apprise_api/api/views.py | adamus1red/apprise-api | 757adce17642a3dfaa2b2e3244e147911386dabb | [
"MIT"
] | 160 | 2019-10-27T19:39:01.000Z | 2022-03-30T21:43:16.000Z | apprise_api/api/views.py | adamus1red/apprise-api | 757adce17642a3dfaa2b2e3244e147911386dabb | [
"MIT"
] | 51 | 2019-12-25T12:28:11.000Z | 2022-03-31T23:57:30.000Z | apprise_api/api/views.py | adamus1red/apprise-api | 757adce17642a3dfaa2b2e3244e147911386dabb | [
"MIT"
] | 26 | 2020-01-10T14:58:01.000Z | 2022-02-19T03:02:28.000Z | # -*- coding: utf-8 -*-
#
# Copyright (C) 2019 Chris Caron <lead2gold@gmail.com>
# All rights reserved.
#
# This code is licensed under the MIT License.
#
# 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.
from django.shortcuts import render
from django.http import HttpResponse
from django.http import JsonResponse
from django.views import View
from django.conf import settings
from django.utils.html import escape
from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache
from django.views.decorators.gzip import gzip_page
from django.utils.translation import gettext_lazy as _
from django.core.serializers.json import DjangoJSONEncoder
from .utils import ConfigCache
from .forms import AddByUrlForm
from .forms import AddByConfigForm
from .forms import NotifyForm
from .forms import NotifyByUrlForm
from .forms import CONFIG_FORMATS
from .forms import AUTO_DETECT_CONFIG_KEYWORD
import apprise
import json
import re
# import the logging library
import logging
# Get an instance of a logger
logger = logging.getLogger('django')
# Content-Type Parsing
# application/x-www-form-urlencoded
# application/x-www-form-urlencoded
# multipart/form-data
MIME_IS_FORM = re.compile(
r'(multipart|application)/(x-www-)?form-(data|urlencoded)', re.I)
# Support JSON formats
# text/json
# text/x-json
# application/json
# application/x-json
MIME_IS_JSON = re.compile(
r'(text|application)/(x-)?json', re.I)
class JSONEncoder(DjangoJSONEncoder):
"""
A wrapper to the DjangoJSONEncoder to support
sets() (converting them to lists).
"""
def default(self, obj):
if isinstance(obj, set):
return list(obj)
return super().default(obj)
class ResponseCode(object):
"""
These codes are based on those provided by the requests object
"""
okay = 200
no_content = 204
bad_request = 400
no_access = 403
not_found = 404
method_not_allowed = 405
method_not_accepted = 406
failed_dependency = 424
internal_server_error = 500
class WelcomeView(View):
"""
A simple welcome/index page
"""
template_name = 'welcome.html'
def get(self, request):
return render(request, self.template_name, {})
@method_decorator(never_cache, name='dispatch')
class ConfigView(View):
"""
A Django view used to manage configuration
"""
template_name = 'config.html'
def get(self, request, key):
"""
Handle a GET request
"""
return render(request, self.template_name, {
'key': key,
'form_url': AddByUrlForm(),
'form_cfg': AddByConfigForm(),
'form_notify': NotifyForm(),
})
@method_decorator(never_cache, name='dispatch')
class AddView(View):
"""
A Django view used to store Apprise configuration
"""
def post(self, request, key):
"""
Handle a POST request
"""
# Detect the format our response should be in
json_response = MIME_IS_JSON.match(request.content_type) is not None
if settings.APPRISE_CONFIG_LOCK:
# General Access Control
msg = _('The site has been configured to deny this request.')
status = ResponseCode.no_access
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
# our content
content = {}
if MIME_IS_FORM.match(request.content_type):
content = {}
form = AddByConfigForm(request.POST)
if form.is_valid():
content.update(form.cleaned_data)
form = AddByUrlForm(request.POST)
if form.is_valid():
content.update(form.cleaned_data)
elif json_response:
# Prepare our default response
try:
# load our JSON content
content = json.loads(request.body.decode('utf-8'))
except (AttributeError, ValueError):
# could not parse JSON response...
return JsonResponse({
'error': _('Invalid JSON specified.'),
},
encoder=JSONEncoder,
safe=False,
status=ResponseCode.bad_request,
)
if not content:
# No information was posted
msg = _('The message format is not supported.')
status = ResponseCode.bad_request
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
# Create ourselves an apprise object to work with
a_obj = apprise.Apprise()
if 'urls' in content:
# Load our content
a_obj.add(content['urls'])
if not len(a_obj):
# No URLs were loaded
msg = _('No valid URLs were found.')
status = ResponseCode.bad_request
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
if not ConfigCache.put(
key, '\r\n'.join([s.url() for s in a_obj]),
apprise.ConfigFormat.TEXT):
msg = _('The configuration could not be saved.')
status = ResponseCode.internal_server_error
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
elif 'config' in content:
fmt = content.get('format', '').lower()
if fmt not in [i[0] for i in CONFIG_FORMATS]:
# Format must be one supported by apprise
msg = _('The format specified is invalid.')
status = ResponseCode.bad_request
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
# prepare our apprise config object
ac_obj = apprise.AppriseConfig()
if fmt == AUTO_DETECT_CONFIG_KEYWORD:
# By setting format to None, it is automatically detected from
# within the add_config() call
fmt = None
# Load our configuration
if not ac_obj.add_config(content['config'], format=fmt):
# The format could not be detected
msg = _('The configuration format could not be detected.')
status = ResponseCode.bad_request
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
# Add our configuration
a_obj.add(ac_obj)
if not len(a_obj):
# No specified URL(s) were loaded due to
# mis-configuration on the caller's part
msg = _('No valid URL(s) were specified.')
status = ResponseCode.bad_request
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
if not ConfigCache.put(
key, content['config'], fmt=ac_obj[0].config_format):
# Something went very wrong; return 500
msg = _('An error occured saving configuration.')
status = ResponseCode.internal_server_error
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
else:
# No configuration specified; we're done
msg = _('No configuration specified.')
status = ResponseCode.bad_request
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
# If we reach here; we successfully loaded the configuration so we can
# go ahead and write it to disk and alert our caller of the success.
return HttpResponse(
_('Successfully saved configuration.'),
status=ResponseCode.okay,
)
@method_decorator(never_cache, name='dispatch')
class DelView(View):
"""
A Django view for removing content associated with a key
"""
def post(self, request, key):
"""
Handle a POST request
"""
# Detect the format our response should be in
json_response = MIME_IS_JSON.match(request.content_type) is not None
if settings.APPRISE_CONFIG_LOCK:
# General Access Control
msg = _('The site has been configured to deny this request.')
status = ResponseCode.no_access
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
# Clear the key
result = ConfigCache.clear(key)
if result is None:
msg = _('There was no configuration to remove.')
status = ResponseCode.no_content
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
elif result is False:
# There was a failure at the os level
msg = _('The configuration could not be removed.')
status = ResponseCode.internal_server_error
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
# Removed content
return HttpResponse(
_('Successfully removed configuration.'),
status=ResponseCode.okay,
)
@method_decorator((gzip_page, never_cache), name='dispatch')
class GetView(View):
"""
A Django view used to retrieve previously stored Apprise configuration
"""
def post(self, request, key):
"""
Handle a POST request
"""
# Detect the format our response should be in
json_response = MIME_IS_JSON.match(request.content_type) is not None
if settings.APPRISE_CONFIG_LOCK:
# General Access Control
return HttpResponse(
_('The site has been configured to deny this request.'),
status=ResponseCode.no_access,
) if not json_response else JsonResponse({
'error':
_('The site has been configured to deny this request.')
},
encoder=JSONEncoder,
safe=False,
status=ResponseCode.no_access,
)
config, format = ConfigCache.get(key)
if config is None:
# The returned value of config and format tell a rather cryptic
# story; this portion could probably be updated in the future.
# but for now it reads like this:
# config == None and format == None: We had an internal error
# config == None and format != None: we simply have no data
# config != None: we simply have no data
if format is not None:
# no content to return
return HttpResponse(
_('There was no configuration found.'),
status=ResponseCode.no_content,
) if not json_response else JsonResponse({
'error': _('There was no configuration found.')
},
encoder=JSONEncoder,
safe=False,
status=ResponseCode.no_content,
)
# Something went very wrong; return 500
msg = _('An error occured accessing configuration.')
status = ResponseCode.internal_server_error
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
# Our configuration was retrieved; now our response varies on whether
# we are a YAML configuration or a TEXT based one. This allows us to
# be compatible with those using the AppriseConfig() library or the
# reference to it through the --config (-c) option in the CLI.
content_type = 'text/yaml; charset=utf-8' \
if format == apprise.ConfigFormat.YAML \
else 'text/html; charset=utf-8'
# Return our retrieved content
return HttpResponse(
config,
content_type=content_type,
status=ResponseCode.okay,
) if not json_response else JsonResponse({
'format': format,
'config': config,
},
encoder=JSONEncoder,
safe=False,
status=ResponseCode.okay,
)
@method_decorator((gzip_page, never_cache), name='dispatch')
class NotifyView(View):
"""
A Django view for sending a notification
"""
def post(self, request, key):
"""
Handle a POST request
"""
# Detect the format our response should be in
json_response = MIME_IS_JSON.match(request.content_type) is not None
# our content
content = {}
if MIME_IS_FORM.match(request.content_type):
content = {}
form = NotifyForm(request.POST)
if form.is_valid():
content.update(form.cleaned_data)
elif json_response:
# Prepare our default response
try:
# load our JSON content
content = json.loads(request.body.decode('utf-8'))
except (AttributeError, ValueError):
# could not parse JSON response...
return JsonResponse(
_('Invalid JSON specified.'),
encoder=JSONEncoder,
safe=False,
status=ResponseCode.bad_request)
if not content:
# We could not handle the Content-Type
msg = _('The message format is not supported.')
status = ResponseCode.bad_request
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
# Some basic error checking
if not content.get('body') or \
content.get('type', apprise.NotifyType.INFO) \
not in apprise.NOTIFY_TYPES:
msg = _('An invalid payload was specified.')
status = ResponseCode.bad_request
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
# Acquire our body format (if identified)
body_format = content.get('format', apprise.NotifyFormat.TEXT)
if body_format and body_format not in apprise.NOTIFY_FORMATS:
msg = _('An invalid body input format was specified.')
status = ResponseCode.bad_request
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
# If we get here, we have enough information to generate a notification
# with.
config, format = ConfigCache.get(key)
if config is None:
# The returned value of config and format tell a rather cryptic
# story; this portion could probably be updated in the future.
# but for now it reads like this:
# config == None and format == None: We had an internal error
# config == None and format != None: we simply have no data
# config != None: we simply have no data
if format is not None:
# no content to return
msg = _('There was no configuration found.')
status = ResponseCode.no_content
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
# Something went very wrong; return 500
msg = _('An error occured accessing configuration.')
status = ResponseCode.internal_server_error
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
#
# Apply Any Global Filters (if identified)
#
if settings.APPRISE_ALLOW_SERVICES:
alphanum_re = re.compile(
r'^(?P<name>[a-z][a-z0-9]+)', re.IGNORECASE)
entries = \
[alphanum_re.match(x).group('name').lower()
for x in re.split(r'[ ,]+', settings.APPRISE_ALLOW_SERVICES)
if alphanum_re.match(x)]
for plugin in set(apprise.plugins.SCHEMA_MAP.values()):
if entries:
# Get a list of the current schema's associated with
# a given plugin
schemas = set(apprise.plugins.details(plugin)
['tokens']['schema']['values'])
# Check what was defined and see if there is a hit
for entry in entries:
if entry in schemas:
# We had a hit; we're done
break
if entry in schemas:
entries.remove(entry)
# We can keep this plugin enabled and move along to the
# next one...
continue
# if we reach here, we have to block our plugin
plugin.enabled = False
for entry in entries:
# Generate some noise for those who have bad configurations
logger.warning(
'APPRISE_ALLOW_SERVICES plugin %s:// was not found - '
'ignoring.', entry)
elif settings.APPRISE_DENY_SERVICES:
alphanum_re = re.compile(
r'^(?P<name>[a-z][a-z0-9]+)', re.IGNORECASE)
entries = \
[alphanum_re.match(x).group('name').lower()
for x in re.split(r'[ ,]+', settings.APPRISE_DENY_SERVICES)
if alphanum_re.match(x)]
for name in entries:
try:
# Force plugin to be disabled
apprise.plugins.SCHEMA_MAP[name].enabled = False
except KeyError:
logger.warning(
'APPRISE_DENY_SERVICES plugin %s:// was not found -'
' ignoring.', name)
# Prepare our keyword arguments (to be passed into an AppriseAsset
# object)
kwargs = {}
if body_format:
# Store our defined body format
kwargs['body_format'] = body_format
# Acquire our recursion count (if defined)
try:
recursion = \
int(request.headers.get('X-Apprise-Recursion-Count', 0))
if recursion < 0:
# We do not accept negative numbers
raise TypeError("Invalid Recursion Value")
if recursion > settings.APPRISE_RECURSION_MAX:
return HttpResponse(
_('The recursion limit has been reached.'),
status=ResponseCode.method_not_accepted)
# Store our recursion value for our AppriseAsset() initialization
kwargs['_recursion'] = recursion
except (TypeError, ValueError):
return HttpResponse(
_('An invalid recursion value was specified.'),
status=ResponseCode.bad_request)
# Acquire our unique identifier (if defined)
uid = request.headers.get('X-Apprise-ID', '').strip()
if uid:
kwargs['_uid'] = uid
# Prepare ourselves a default Asset
asset = None if not body_format else \
apprise.AppriseAsset(body_format=body_format)
# Prepare our apprise object
a_obj = apprise.Apprise(asset=asset)
# Create an apprise config object
ac_obj = apprise.AppriseConfig()
# Load our configuration
ac_obj.add_config(config, format=format)
# Add our configuration
a_obj.add(ac_obj)
# Our return content type can be controlled by the Accept keyword
# If it includes /* or /html somewhere then we return html, otherwise
# we return the logs as they're processed in their text format.
# The HTML response type has a bit of overhead where as it's not
# the case with text/plain
content_type = \
'text/html' if re.search(r'text\/(\*|html)',
request.headers.get('Accept', ''),
re.IGNORECASE) \
else 'text/plain'
# Acquire our log level from headers if defined, otherwise use
# the global one set in the settings
level = request.headers.get(
'X-Apprise-Log-Level',
settings.LOGGING['loggers']['apprise']['level']).upper()
# Initialize our response object
response = None
if level in ('CRITICAL', 'ERROR' 'WARNING', 'INFO', 'DEBUG'):
level = getattr(apprise.logging, level)
esc = '<!!-!ESC!-!!>'
fmt = '<li class="log_%(levelname)s">' \
'<div class="log_time">%(asctime)s</div>' \
'<div class="log_level">%(levelname)s</div>' \
f'<div class="log_msg">{esc}%(message)s{esc}</div></li>' \
if content_type == 'text/html' else \
settings.LOGGING['formatters']['standard']['format']
# Now specify our format (and over-ride the default):
with apprise.LogCapture(level=level, fmt=fmt) as logs:
# Perform our notification at this point
result = a_obj.notify(
content.get('body'),
title=content.get('title', ''),
notify_type=content.get('type', apprise.NotifyType.INFO),
tag=content.get('tag'),
)
if content_type == 'text/html':
# Iterate over our entries so that we can prepare to escape
# things to be presented as HTML
esc = re.escape(esc)
entries = re.findall(
r'(?P<head><li .+?){}(?P<to_escape>.*?)'
r'{}(?P<tail>.+li>$)(?=$|<li .+{})'.format(
esc, esc, esc), logs.getvalue(),
re.DOTALL)
# Wrap logs in `<ul>` tag and escape our message body:
response = '<ul class="logs">{}</ul>'.format(
''.join([e[0] + escape(e[1]) + e[2] for e in entries]))
else: # content_type == 'text/plain'
response = logs.getvalue()
else:
# Perform our notification at this point without logging
result = a_obj.notify(
content.get('body'),
title=content.get('title', ''),
notify_type=content.get('type', apprise.NotifyType.INFO),
tag=content.get('tag'),
)
if not result:
# If at least one notification couldn't be sent; change up
# the response to a 424 error code
msg = _('One or more notification could not be sent.')
status = ResponseCode.failed_dependency
return HttpResponse(response if response else msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
# Return our retrieved content
return HttpResponse(
response if response is not None else
_('Notification(s) sent.'),
content_type=content_type,
status=ResponseCode.okay,
)
@method_decorator((gzip_page, never_cache), name='dispatch')
class StatelessNotifyView(View):
"""
A Django view for sending a stateless notification
"""
def post(self, request):
"""
Handle a POST request
"""
# our content
content = {}
if MIME_IS_FORM.match(request.content_type):
content = {}
form = NotifyByUrlForm(request.POST)
if form.is_valid():
content.update(form.cleaned_data)
elif MIME_IS_JSON.match(request.content_type):
# Prepare our default response
try:
# load our JSON content
content = json.loads(request.body.decode('utf-8'))
except (AttributeError, ValueError):
# could not parse JSON response...
return HttpResponse(
_('Invalid JSON specified.'),
status=ResponseCode.bad_request)
if not content:
# We could not handle the Content-Type
return HttpResponse(
_('The message format is not supported.'),
status=ResponseCode.bad_request)
if not content.get('urls') and settings.APPRISE_STATELESS_URLS:
# fallback to settings.APPRISE_STATELESS_URLS if no urls were
# defined
content['urls'] = settings.APPRISE_STATELESS_URLS
# Some basic error checking
if not content.get('body') or \
content.get('type', apprise.NotifyType.INFO) \
not in apprise.NOTIFY_TYPES:
return HttpResponse(
_('An invalid payload was specified.'),
status=ResponseCode.bad_request)
# Acquire our body format (if identified)
body_format = content.get('format', apprise.NotifyFormat.TEXT)
if body_format and body_format not in apprise.NOTIFY_FORMATS:
return HttpResponse(
_('An invalid (body) format was specified.'),
status=ResponseCode.bad_request)
# Prepare our keyword arguments (to be passed into an AppriseAsset
# object)
kwargs = {}
if body_format:
# Store our defined body format
kwargs['body_format'] = body_format
# Acquire our recursion count (if defined)
try:
recursion = \
int(request.headers.get('X-Apprise-Recursion-Count', 0))
if recursion < 0:
# We do not accept negative numbers
raise TypeError("Invalid Recursion Value")
if recursion > settings.APPRISE_RECURSION_MAX:
return HttpResponse(
_('The recursion limit has been reached.'),
status=ResponseCode.method_not_accepted)
# Store our recursion value for our AppriseAsset() initialization
kwargs['_recursion'] = recursion
except (TypeError, ValueError):
return HttpResponse(
_('An invalid recursion value was specified.'),
status=ResponseCode.bad_request)
# Acquire our unique identifier (if defined)
uid = request.headers.get('X-Apprise-ID', '').strip()
if uid:
kwargs['_uid'] = uid
# Prepare ourselves a default Asset
asset = None if not body_format else \
apprise.AppriseAsset(body_format=body_format)
#
# Apply Any Global Filters (if identified)
#
if settings.APPRISE_ALLOW_SERVICES:
alphanum_re = re.compile(
r'^(?P<name>[a-z][a-z0-9]+)', re.IGNORECASE)
entries = \
[alphanum_re.match(x).group('name').lower()
for x in re.split(r'[ ,]+', settings.APPRISE_ALLOW_SERVICES)
if alphanum_re.match(x)]
for plugin in set(apprise.plugins.SCHEMA_MAP.values()):
if entries:
# Get a list of the current schema's associated with
# a given plugin
schemas = set(apprise.plugins.details(plugin)
['tokens']['schema']['values'])
# Check what was defined and see if there is a hit
for entry in entries:
if entry in schemas:
# We had a hit; we're done
break
if entry in schemas:
entries.remove(entry)
# We can keep this plugin enabled and move along to the
# next one...
continue
# if we reach here, we have to block our plugin
plugin.enabled = False
for entry in entries:
# Generate some noise for those who have bad configurations
logger.warning(
'APPRISE_ALLOW_SERVICES plugin %s:// was not found - '
'ignoring.', entry)
elif settings.APPRISE_DENY_SERVICES:
alphanum_re = re.compile(
r'^(?P<name>[a-z][a-z0-9]+)', re.IGNORECASE)
entries = \
[alphanum_re.match(x).group('name').lower()
for x in re.split(r'[ ,]+', settings.APPRISE_DENY_SERVICES)
if alphanum_re.match(x)]
for name in entries:
try:
# Force plugin to be disabled
apprise.plugins.SCHEMA_MAP[name].enabled = False
except KeyError:
logger.warning(
'APPRISE_DENY_SERVICES plugin %s:// was not found -'
' ignoring.', name)
# Prepare our apprise object
a_obj = apprise.Apprise(asset=asset)
# Add URLs
a_obj.add(content.get('urls'))
if not len(a_obj):
return HttpResponse(
_('There was no services to notify.'),
status=ResponseCode.no_content,
)
# Perform our notification at this point
result = a_obj.notify(
content.get('body'),
title=content.get('title', ''),
notify_type=content.get('type', apprise.NotifyType.INFO),
tag='all',
)
if not result:
# If at least one notification couldn't be sent; change up the
# response to a 424 error code
return HttpResponse(
_('One or more notification could not be sent.'),
status=ResponseCode.failed_dependency)
# Return our retrieved content
return HttpResponse(
_('Notification(s) sent.'),
status=ResponseCode.okay,
)
@method_decorator((gzip_page, never_cache), name='dispatch')
class JsonUrlView(View):
"""
A Django view that lists all loaded tags and URLs for a given key
"""
def get(self, request, key):
"""
Handle a POST request
"""
# Now build our tag response that identifies all of the tags
# and the URL's they're associated with
# {
# "tags": ["tag1', "tag2", "tag3"],
# "urls": [
# {
# "url": "windows://",
# "tags": [],
# },
# {
# "url": "mailto://user:pass@gmail.com"
# "tags": ["tag1", "tag2", "tag3"]
# }
# ]
# }
response = {
'tags': set(),
'urls': [],
}
# Privacy flag
# Support 'yes', '1', 'true', 'enable', 'active', and +
privacy = settings.APPRISE_CONFIG_LOCK or \
request.GET.get('privacy', 'no')[0] in (
'a', 'y', '1', 't', 'e', '+')
# Optionally filter on tags. Use comma to identify more then one
tag = request.GET.get('tag', 'all')
config, format = ConfigCache.get(key)
if config is None:
# The returned value of config and format tell a rather cryptic
# story; this portion could probably be updated in the future.
# but for now it reads like this:
# config == None and format == None: We had an internal error
# config == None and format != None: we simply have no data
# config != None: we simply have no data
if format is not None:
# no content to return
return JsonResponse(
response,
encoder=JSONEncoder,
safe=False,
status=ResponseCode.no_content,
)
# Something went very wrong; return 500
response['error'] = _('There was no configuration found.')
return JsonResponse(
response,
encoder=JSONEncoder,
safe=False,
status=ResponseCode.internal_server_error,
)
# Prepare our apprise object
a_obj = apprise.Apprise()
# Create an apprise config object
ac_obj = apprise.AppriseConfig()
# Load our configuration
ac_obj.add_config(config, format=format)
# Add our configuration
a_obj.add(ac_obj)
for notification in a_obj.find(tag):
# Set Notification
response['urls'].append({
'url': notification.url(privacy=privacy),
'tags': notification.tags,
})
# Store Tags
response['tags'] |= notification.tags
# Return our retrieved content
return JsonResponse(
response,
encoder=JSONEncoder,
safe=False,
status=ResponseCode.okay
)
| 36.074499 | 79 | 0.533625 |
from django.shortcuts import render
from django.http import HttpResponse
from django.http import JsonResponse
from django.views import View
from django.conf import settings
from django.utils.html import escape
from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache
from django.views.decorators.gzip import gzip_page
from django.utils.translation import gettext_lazy as _
from django.core.serializers.json import DjangoJSONEncoder
from .utils import ConfigCache
from .forms import AddByUrlForm
from .forms import AddByConfigForm
from .forms import NotifyForm
from .forms import NotifyByUrlForm
from .forms import CONFIG_FORMATS
from .forms import AUTO_DETECT_CONFIG_KEYWORD
import apprise
import json
import re
import logging
logger = logging.getLogger('django')
MIME_IS_FORM = re.compile(
r'(multipart|application)/(x-www-)?form-(data|urlencoded)', re.I)
MIME_IS_JSON = re.compile(
r'(text|application)/(x-)?json', re.I)
class JSONEncoder(DjangoJSONEncoder):
def default(self, obj):
if isinstance(obj, set):
return list(obj)
return super().default(obj)
class ResponseCode(object):
okay = 200
no_content = 204
bad_request = 400
no_access = 403
not_found = 404
method_not_allowed = 405
method_not_accepted = 406
failed_dependency = 424
internal_server_error = 500
class WelcomeView(View):
template_name = 'welcome.html'
def get(self, request):
return render(request, self.template_name, {})
@method_decorator(never_cache, name='dispatch')
class ConfigView(View):
template_name = 'config.html'
def get(self, request, key):
return render(request, self.template_name, {
'key': key,
'form_url': AddByUrlForm(),
'form_cfg': AddByConfigForm(),
'form_notify': NotifyForm(),
})
@method_decorator(never_cache, name='dispatch')
class AddView(View):
def post(self, request, key):
json_response = MIME_IS_JSON.match(request.content_type) is not None
if settings.APPRISE_CONFIG_LOCK:
msg = _('The site has been configured to deny this request.')
status = ResponseCode.no_access
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
content = {}
if MIME_IS_FORM.match(request.content_type):
content = {}
form = AddByConfigForm(request.POST)
if form.is_valid():
content.update(form.cleaned_data)
form = AddByUrlForm(request.POST)
if form.is_valid():
content.update(form.cleaned_data)
elif json_response:
try:
content = json.loads(request.body.decode('utf-8'))
except (AttributeError, ValueError):
return JsonResponse({
'error': _('Invalid JSON specified.'),
},
encoder=JSONEncoder,
safe=False,
status=ResponseCode.bad_request,
)
if not content:
msg = _('The message format is not supported.')
status = ResponseCode.bad_request
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
a_obj = apprise.Apprise()
if 'urls' in content:
a_obj.add(content['urls'])
if not len(a_obj):
msg = _('No valid URLs were found.')
status = ResponseCode.bad_request
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
if not ConfigCache.put(
key, '\r\n'.join([s.url() for s in a_obj]),
apprise.ConfigFormat.TEXT):
msg = _('The configuration could not be saved.')
status = ResponseCode.internal_server_error
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
elif 'config' in content:
fmt = content.get('format', '').lower()
if fmt not in [i[0] for i in CONFIG_FORMATS]:
msg = _('The format specified is invalid.')
status = ResponseCode.bad_request
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
ac_obj = apprise.AppriseConfig()
if fmt == AUTO_DETECT_CONFIG_KEYWORD:
fmt = None
if not ac_obj.add_config(content['config'], format=fmt):
msg = _('The configuration format could not be detected.')
status = ResponseCode.bad_request
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
a_obj.add(ac_obj)
if not len(a_obj):
msg = _('No valid URL(s) were specified.')
status = ResponseCode.bad_request
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
if not ConfigCache.put(
key, content['config'], fmt=ac_obj[0].config_format):
# Something went very wrong; return 500
msg = _('An error occured saving configuration.')
status = ResponseCode.internal_server_error
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
else:
# No configuration specified; we're done
msg = _('No configuration specified.')
status = ResponseCode.bad_request
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
return HttpResponse(
_('Successfully saved configuration.'),
status=ResponseCode.okay,
)
@method_decorator(never_cache, name='dispatch')
class DelView(View):
def post(self, request, key):
json_response = MIME_IS_JSON.match(request.content_type) is not None
if settings.APPRISE_CONFIG_LOCK:
msg = _('The site has been configured to deny this request.')
status = ResponseCode.no_access
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
result = ConfigCache.clear(key)
if result is None:
msg = _('There was no configuration to remove.')
status = ResponseCode.no_content
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
elif result is False:
msg = _('The configuration could not be removed.')
status = ResponseCode.internal_server_error
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
return HttpResponse(
_('Successfully removed configuration.'),
status=ResponseCode.okay,
)
@method_decorator((gzip_page, never_cache), name='dispatch')
class GetView(View):
def post(self, request, key):
json_response = MIME_IS_JSON.match(request.content_type) is not None
if settings.APPRISE_CONFIG_LOCK:
return HttpResponse(
_('The site has been configured to deny this request.'),
status=ResponseCode.no_access,
) if not json_response else JsonResponse({
'error':
_('The site has been configured to deny this request.')
},
encoder=JSONEncoder,
safe=False,
status=ResponseCode.no_access,
)
config, format = ConfigCache.get(key)
if config is None:
if format is not None:
return HttpResponse(
_('There was no configuration found.'),
status=ResponseCode.no_content,
) if not json_response else JsonResponse({
'error': _('There was no configuration found.')
},
encoder=JSONEncoder,
safe=False,
status=ResponseCode.no_content,
)
msg = _('An error occured accessing configuration.')
status = ResponseCode.internal_server_error
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
content_type = 'text/yaml; charset=utf-8' \
if format == apprise.ConfigFormat.YAML \
else 'text/html; charset=utf-8'
return HttpResponse(
config,
content_type=content_type,
status=ResponseCode.okay,
) if not json_response else JsonResponse({
'format': format,
'config': config,
},
encoder=JSONEncoder,
safe=False,
status=ResponseCode.okay,
)
@method_decorator((gzip_page, never_cache), name='dispatch')
class NotifyView(View):
def post(self, request, key):
json_response = MIME_IS_JSON.match(request.content_type) is not None
content = {}
if MIME_IS_FORM.match(request.content_type):
content = {}
form = NotifyForm(request.POST)
if form.is_valid():
content.update(form.cleaned_data)
elif json_response:
try:
content = json.loads(request.body.decode('utf-8'))
except (AttributeError, ValueError):
return JsonResponse(
_('Invalid JSON specified.'),
encoder=JSONEncoder,
safe=False,
status=ResponseCode.bad_request)
if not content:
msg = _('The message format is not supported.')
status = ResponseCode.bad_request
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
if not content.get('body') or \
content.get('type', apprise.NotifyType.INFO) \
not in apprise.NOTIFY_TYPES:
msg = _('An invalid payload was specified.')
status = ResponseCode.bad_request
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
body_format = content.get('format', apprise.NotifyFormat.TEXT)
if body_format and body_format not in apprise.NOTIFY_FORMATS:
msg = _('An invalid body input format was specified.')
status = ResponseCode.bad_request
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
config, format = ConfigCache.get(key)
if config is None:
if format is not None:
msg = _('There was no configuration found.')
status = ResponseCode.no_content
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
msg = _('An error occured accessing configuration.')
status = ResponseCode.internal_server_error
return HttpResponse(msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
if settings.APPRISE_ALLOW_SERVICES:
alphanum_re = re.compile(
r'^(?P<name>[a-z][a-z0-9]+)', re.IGNORECASE)
entries = \
[alphanum_re.match(x).group('name').lower()
for x in re.split(r'[ ,]+', settings.APPRISE_ALLOW_SERVICES)
if alphanum_re.match(x)]
for plugin in set(apprise.plugins.SCHEMA_MAP.values()):
if entries:
# a given plugin
schemas = set(apprise.plugins.details(plugin)
['tokens']['schema']['values'])
# Check what was defined and see if there is a hit
for entry in entries:
if entry in schemas:
# We had a hit; we're done
break
if entry in schemas:
entries.remove(entry)
continue
plugin.enabled = False
for entry in entries:
logger.warning(
'APPRISE_ALLOW_SERVICES plugin %s:// was not found - '
'ignoring.', entry)
elif settings.APPRISE_DENY_SERVICES:
alphanum_re = re.compile(
r'^(?P<name>[a-z][a-z0-9]+)', re.IGNORECASE)
entries = \
[alphanum_re.match(x).group('name').lower()
for x in re.split(r'[ ,]+', settings.APPRISE_DENY_SERVICES)
if alphanum_re.match(x)]
for name in entries:
try:
apprise.plugins.SCHEMA_MAP[name].enabled = False
except KeyError:
logger.warning(
'APPRISE_DENY_SERVICES plugin %s:// was not found -'
' ignoring.', name)
kwargs = {}
if body_format:
kwargs['body_format'] = body_format
try:
recursion = \
int(request.headers.get('X-Apprise-Recursion-Count', 0))
if recursion < 0:
raise TypeError("Invalid Recursion Value")
if recursion > settings.APPRISE_RECURSION_MAX:
return HttpResponse(
_('The recursion limit has been reached.'),
status=ResponseCode.method_not_accepted)
kwargs['_recursion'] = recursion
except (TypeError, ValueError):
return HttpResponse(
_('An invalid recursion value was specified.'),
status=ResponseCode.bad_request)
uid = request.headers.get('X-Apprise-ID', '').strip()
if uid:
kwargs['_uid'] = uid
asset = None if not body_format else \
apprise.AppriseAsset(body_format=body_format)
a_obj = apprise.Apprise(asset=asset)
ac_obj = apprise.AppriseConfig()
ac_obj.add_config(config, format=format)
a_obj.add(ac_obj)
# The HTML response type has a bit of overhead where as it's not
content_type = \
'text/html' if re.search(r'text\/(\*|html)',
request.headers.get('Accept', ''),
re.IGNORECASE) \
else 'text/plain'
level = request.headers.get(
'X-Apprise-Log-Level',
settings.LOGGING['loggers']['apprise']['level']).upper()
response = None
if level in ('CRITICAL', 'ERROR' 'WARNING', 'INFO', 'DEBUG'):
level = getattr(apprise.logging, level)
esc = '<!!-!ESC!-!!>'
fmt = '<li class="log_%(levelname)s">' \
'<div class="log_time">%(asctime)s</div>' \
'<div class="log_level">%(levelname)s</div>' \
f'<div class="log_msg">{esc}%(message)s{esc}</div></li>' \
if content_type == 'text/html' else \
settings.LOGGING['formatters']['standard']['format']
with apprise.LogCapture(level=level, fmt=fmt) as logs:
result = a_obj.notify(
content.get('body'),
title=content.get('title', ''),
notify_type=content.get('type', apprise.NotifyType.INFO),
tag=content.get('tag'),
)
if content_type == 'text/html':
esc = re.escape(esc)
entries = re.findall(
r'(?P<head><li .+?){}(?P<to_escape>.*?)'
r'{}(?P<tail>.+li>$)(?=$|<li .+{})'.format(
esc, esc, esc), logs.getvalue(),
re.DOTALL)
response = '<ul class="logs">{}</ul>'.format(
''.join([e[0] + escape(e[1]) + e[2] for e in entries]))
else:
response = logs.getvalue()
else:
result = a_obj.notify(
content.get('body'),
title=content.get('title', ''),
notify_type=content.get('type', apprise.NotifyType.INFO),
tag=content.get('tag'),
)
if not result:
# the response to a 424 error code
msg = _('One or more notification could not be sent.')
status = ResponseCode.failed_dependency
return HttpResponse(response if response else msg, status=status) \
if not json_response else JsonResponse({
'error': msg,
},
encoder=JSONEncoder,
safe=False,
status=status,
)
# Return our retrieved content
return HttpResponse(
response if response is not None else
_('Notification(s) sent.'),
content_type=content_type,
status=ResponseCode.okay,
)
@method_decorator((gzip_page, never_cache), name='dispatch')
class StatelessNotifyView(View):
def post(self, request):
# our content
content = {}
if MIME_IS_FORM.match(request.content_type):
content = {}
form = NotifyByUrlForm(request.POST)
if form.is_valid():
content.update(form.cleaned_data)
elif MIME_IS_JSON.match(request.content_type):
# Prepare our default response
try:
# load our JSON content
content = json.loads(request.body.decode('utf-8'))
except (AttributeError, ValueError):
# could not parse JSON response...
return HttpResponse(
_('Invalid JSON specified.'),
status=ResponseCode.bad_request)
if not content:
# We could not handle the Content-Type
return HttpResponse(
_('The message format is not supported.'),
status=ResponseCode.bad_request)
if not content.get('urls') and settings.APPRISE_STATELESS_URLS:
# fallback to settings.APPRISE_STATELESS_URLS if no urls were
# defined
content['urls'] = settings.APPRISE_STATELESS_URLS
# Some basic error checking
if not content.get('body') or \
content.get('type', apprise.NotifyType.INFO) \
not in apprise.NOTIFY_TYPES:
return HttpResponse(
_('An invalid payload was specified.'),
status=ResponseCode.bad_request)
# Acquire our body format (if identified)
body_format = content.get('format', apprise.NotifyFormat.TEXT)
if body_format and body_format not in apprise.NOTIFY_FORMATS:
return HttpResponse(
_('An invalid (body) format was specified.'),
status=ResponseCode.bad_request)
# Prepare our keyword arguments (to be passed into an AppriseAsset
# object)
kwargs = {}
if body_format:
# Store our defined body format
kwargs['body_format'] = body_format
# Acquire our recursion count (if defined)
try:
recursion = \
int(request.headers.get('X-Apprise-Recursion-Count', 0))
if recursion < 0:
# We do not accept negative numbers
raise TypeError("Invalid Recursion Value")
if recursion > settings.APPRISE_RECURSION_MAX:
return HttpResponse(
_('The recursion limit has been reached.'),
status=ResponseCode.method_not_accepted)
# Store our recursion value for our AppriseAsset() initialization
kwargs['_recursion'] = recursion
except (TypeError, ValueError):
return HttpResponse(
_('An invalid recursion value was specified.'),
status=ResponseCode.bad_request)
# Acquire our unique identifier (if defined)
uid = request.headers.get('X-Apprise-ID', '').strip()
if uid:
kwargs['_uid'] = uid
# Prepare ourselves a default Asset
asset = None if not body_format else \
apprise.AppriseAsset(body_format=body_format)
#
# Apply Any Global Filters (if identified)
#
if settings.APPRISE_ALLOW_SERVICES:
alphanum_re = re.compile(
r'^(?P<name>[a-z][a-z0-9]+)', re.IGNORECASE)
entries = \
[alphanum_re.match(x).group('name').lower()
for x in re.split(r'[ ,]+', settings.APPRISE_ALLOW_SERVICES)
if alphanum_re.match(x)]
for plugin in set(apprise.plugins.SCHEMA_MAP.values()):
if entries:
# Get a list of the current schema's associated with
schemas = set(apprise.plugins.details(plugin)
['tokens']['schema']['values'])
for entry in entries:
if entry in schemas:
break
if entry in schemas:
entries.remove(entry)
# We can keep this plugin enabled and move along to the
# next one...
continue
# if we reach here, we have to block our plugin
plugin.enabled = False
for entry in entries:
# Generate some noise for those who have bad configurations
logger.warning(
'APPRISE_ALLOW_SERVICES plugin %s:// was not found - '
'ignoring.', entry)
elif settings.APPRISE_DENY_SERVICES:
alphanum_re = re.compile(
r'^(?P<name>[a-z][a-z0-9]+)', re.IGNORECASE)
entries = \
[alphanum_re.match(x).group('name').lower()
for x in re.split(r'[ ,]+', settings.APPRISE_DENY_SERVICES)
if alphanum_re.match(x)]
for name in entries:
try:
# Force plugin to be disabled
apprise.plugins.SCHEMA_MAP[name].enabled = False
except KeyError:
logger.warning(
'APPRISE_DENY_SERVICES plugin %s:// was not found -'
' ignoring.', name)
# Prepare our apprise object
a_obj = apprise.Apprise(asset=asset)
# Add URLs
a_obj.add(content.get('urls'))
if not len(a_obj):
return HttpResponse(
_('There was no services to notify.'),
status=ResponseCode.no_content,
)
# Perform our notification at this point
result = a_obj.notify(
content.get('body'),
title=content.get('title', ''),
notify_type=content.get('type', apprise.NotifyType.INFO),
tag='all',
)
if not result:
# If at least one notification couldn't be sent; change up the
return HttpResponse(
_('One or more notification could not be sent.'),
status=ResponseCode.failed_dependency)
return HttpResponse(
_('Notification(s) sent.'),
status=ResponseCode.okay,
)
@method_decorator((gzip_page, never_cache), name='dispatch')
class JsonUrlView(View):
def get(self, request, key):
# "urls": [
# {
# "url": "windows://",
# "tags": [],
# },
# {
# "url": "mailto://user:pass@gmail.com"
# "tags": ["tag1", "tag2", "tag3"]
# }
# ]
# }
response = {
'tags': set(),
'urls': [],
}
# Privacy flag
# Support 'yes', '1', 'true', 'enable', 'active', and +
privacy = settings.APPRISE_CONFIG_LOCK or \
request.GET.get('privacy', 'no')[0] in (
'a', 'y', '1', 't', 'e', '+')
# Optionally filter on tags. Use comma to identify more then one
tag = request.GET.get('tag', 'all')
config, format = ConfigCache.get(key)
if config is None:
# The returned value of config and format tell a rather cryptic
# story; this portion could probably be updated in the future.
# but for now it reads like this:
# config == None and format == None: We had an internal error
# config == None and format != None: we simply have no data
# config != None: we simply have no data
if format is not None:
# no content to return
return JsonResponse(
response,
encoder=JSONEncoder,
safe=False,
status=ResponseCode.no_content,
)
# Something went very wrong; return 500
response['error'] = _('There was no configuration found.')
return JsonResponse(
response,
encoder=JSONEncoder,
safe=False,
status=ResponseCode.internal_server_error,
)
# Prepare our apprise object
a_obj = apprise.Apprise()
# Create an apprise config object
ac_obj = apprise.AppriseConfig()
# Load our configuration
ac_obj.add_config(config, format=format)
# Add our configuration
a_obj.add(ac_obj)
for notification in a_obj.find(tag):
# Set Notification
response['urls'].append({
'url': notification.url(privacy=privacy),
'tags': notification.tags,
})
# Store Tags
response['tags'] |= notification.tags
# Return our retrieved content
return JsonResponse(
response,
encoder=JSONEncoder,
safe=False,
status=ResponseCode.okay
)
| true | true |
f7167dafa438abb972d4d287944bf016ae2c3bf7 | 15,655 | py | Python | MuJoCo/modules/utils.py | mosesnah-shared/whip-project-targeting | 7f47598635f027e2cb05ad33b66ed67627d20329 | [
"BSD-3-Clause"
] | null | null | null | MuJoCo/modules/utils.py | mosesnah-shared/whip-project-targeting | 7f47598635f027e2cb05ad33b66ed67627d20329 | [
"BSD-3-Clause"
] | null | null | null | MuJoCo/modules/utils.py | mosesnah-shared/whip-project-targeting | 7f47598635f027e2cb05ad33b66ed67627d20329 | [
"BSD-3-Clause"
] | null | null | null | # [Built-in modules]
import os
import re
import sys
import shutil
import time, datetime
import math as myMath
import glob
# [3rd party modules]
import cv2
import numpy as np
import xml.etree.ElementTree as ET
import sympy as sp
from sympy.utilities.lambdify import lambdify, implemented_function
from scipy.special import lambertw
from scipy.integrate import quad
from scipy.spatial.transform import Rotation as R
# [Local modules]
from modules.constants import Constants
class MyVideo:
"""
Description
----------
Arguments
---------
Returns
-------
"""
def __init__( self, vid_dir = None, height = 1440, width = 850, fps = 60 ):
# self.height = height
# self.width = width
self.height = 2880
self.width = 1800
self.vid_dir = vid_dir if not None else "."
self.fps = fps
fourcc = cv2.VideoWriter_fourcc( *'MP4V' ) # 4-character code of codec used to compress the frames.
# For example, VideoWriter::fourcc('P','I','M','1') is a MPEG-1 codec,
# VideoWriter::fourcc('M','J','P','G') is a motion-jpeg codec etc.
# List of codes can be obtained at Video Codecs by FOURCC page.
# self.outVideo = cv2.VideoWriter( self.vid_dir + "/video.mp4", fourcc, fps, ( self.height, self.width ) )
self.outVideo = cv2.VideoWriter( self.vid_dir + "/video.mp4", fourcc, fps, ( self.height//2, self.width//2 ) )
def write( self, myViewer ):
data = myViewer.read_pixels( self.height, self.width, depth = False ) # Get the pixel from the render screen
data = cv2.cvtColor( data, cv2.COLOR_BGR2RGB )
# data = cv2.resize( data,( self.height, self.width ) )
data = cv2.resize( data,( self.height//2, self.width//2 ) )
self.outVideo.write( np.flip( data, axis = 0 ) )
def release( self ):
self.outVideo.release()
def length_elem2elem( mjModel, mjData, elem_name1, elem_name2 ):
type1 = get_elem_type( mjModel, elem_name1 )
type2 = get_elem_type( mjModel, elem_name2 )
# The euclidean distance between two elements, calling using "get_geom_xpos" or "get_site_xpos" or "get_body_xpos" methods
return np.linalg.norm( getattr( mjData, "get_" + type1 + "_" + "xpos" )( elem_name1 )
- getattr( mjData, "get_" + type2 + "_" + "xpos" )( elem_name2 ) , ord = 2 )
def get_elem_type( mjModel, elem_name ):
"""
The naming convention of our mujoco simulation is "{elem}_name", where elem = [geom, site, body]
The string before the first underbar '_' describes the elem(ent) of the model.
This function parses the string and returns the first string (i.e., the element of the model)
"""
return elem_name.split( '_' )[ 0 ] # Parse and get the first string before "_"
def get_property( mjModel, elem_name, prop_name ):
# Get the property of the name
# The name of the elements start with "XXXX_", hence getting the string before the underbar.
type = get_elem_type( mjModel, elem_name )
for idx, s in enumerate( getattr( mjModel, type + "_" + "names" ) ): # run through the list of "geom_names" or "body_names"
if elem_name == s:
tmp = getattr( mjModel, type + "_" + prop_name )
return tmp[ idx ]
# If couldn't match in list, raise error
raise NameError( 'Cannot find geom_name with {0} in list, please check'.format( elem_name ) )
def snake2camel( s ):
"""
Switch string s from snake_form_naming to CamelCase
"""
return ''.join( word.title() for word in s.split( '_' ) )
def camel2snake( s ):
"""
Switch string s from CamelCase to snake_form_naming
[REF] https://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-snake-case
"""
re.sub( r'(?<!^)(?=[A-Z])', '_', s ).lower()
def clear_dir( dir ):
""" Cleaning up the contents in the directory """
def args_cleanup( args, s ):
"""
Description
-----------
Clean-up the substring s for keys in args
Arguments
---------
args: The dictionary to be parsed
s : Substring to be discarded. e.g. s = '--', then "--record" --> "record"
"""
if not isinstance( args, dict ) or not isinstance( s, str ):
raise ValueError( "Wrong input type. args should be type dict and s should be type str. {0:} and {1:} are rather given".format(
type( args ), type( str ) ) )
for old_key in list( args ) :
new_key = old_key.replace( s, '' )
args[ new_key ] = args.pop( old_key )
return args
def rot2quat( rot ):
# Taking the SO(3) matrix as an input and return the quaternion
return quat
def euler2quaternion( euler_angs ):
"""
Description
-----------
This code is directly from the following reference
[REF] https://computergraphics.stackexchange.com/questions/8195/how-to-convert-euler-angles-to-quaternions-and-get-the-same-euler-angles-back-fr
Converting a R4 quaternion vector (w, x, y, z) to Euler Angle (Roll, Pitch, Yaw)
Arguments
---------
[NAME] [TYPE] [DESCRIPTION]
(1) yaw, pitch, roll The euler angles of the given quaternion vector.
[OUTPUTS]
-----------
[NAME] [TYPE] [DESCRIPTION]
(1) quatVec List The quaternion vector, ordered in w, x, y and z
"""
yaw, pitch, roll = euler_angs[ : ]
cy = np.cos( yaw * 0.5 )
sy = np.sin( yaw * 0.5 )
cp = np.cos( pitch * 0.5 )
sp = np.sin( pitch * 0.5 )
cr = np.cos( roll * 0.5 )
sr = np.sin( roll * 0.5 )
w = cr * cp * cy + sr * sp * sy;
x = sr * cp * cy - cr * sp * sy;
y = cr * sp * cy + sr * cp * sy;
z = cr * cp * sy - sr * sp * cy;
return w,x,y,z
def quaternion2euler( quatVec ): # Inputting quaternion matrix and outputing the yaw, pitch, roll of the euler angle.
"""
Description
-----------
Converting a R4 quaternion vector (w, x, y, z) to Euler Angle (Roll, Pitch, Yaw)
This code is directly from the following reference
[REF] https://computergraphics.stackexchange.com/questions/8195/how-to-convert-euler-angles-to-quaternions-and-get-the-same-euler-angles-back-fr
Arguments
---------
[NAME] [TYPE] [DESCRIPTION]
(1) quatVec List The quaternion vector, ordered in w, x, y and z
Outputs
--------
[NAME] [TYPE] [DESCRIPTION]
(1) yaw, pitch, roll The euler angles of the given quaternion vector.
"""
if len( quatVec ) != 4:
raise ValueError( "Wrong size of input argument. Given size is [{0:d}] while it should be 4".format(
len( quatVec ) ) )
w, x, y ,z = quatVec[:]
t0 = + 2.0 * ( w * x + y * z )
t1 = + 1.0 - 2.0 * ( x * x + y * y )
roll = myMath.atan2( t0, t1 )
t2 = + 2.0 * ( w * y - z * x )
t2 = + 1.0 if t2 > +1.0 else t2
t2 = - 1.0 if t2 < -1.0 else t2
pitch = myMath.asin( t2 )
t3 = + 2.0 * ( w * z + x * y )
t4 = + 1.0 - 2.0 * ( y * y + z * z )
yaw = myMath.atan2( t3, t4 )
return yaw, pitch, roll
def str2bool( s ):
"""
Description:
----------
Converting an input string to a boolean
Arguments:
----------
[NAME] [TYPE] [DESCRIPTION]
(1) s dict, str The string which
Returns:
----------
True/False depending on the given input strin gv
"""
if isinstance( s, dict ):
for key, _ in s.items():
s[ key ] = str2bool( s[ key ] )
else:
return v.lower() in ( "yes", "true", "t", "1" )
def str2float( s ):
"""
Description:
----------
Converting an input string to a float arraay
Arguments:
----------
[NAME] [TYPE] [DESCRIPTION]
(1) s str The string which will be parsed to float array
Returns:
----------
The parsed float array
"""
if not isinstance( s, str ):
raise ValueError( "Input argument should be string, but {} is given".format( type( s ) ) )
return [ float( i ) for i in re.findall( r"[-+]?\d*\.\d+|[-+]?\d+", s ) ]
def my_mkdir( ):
dir = Constants.TMP_DIR # Temporarily saving at tmp
dir += datetime.datetime.now().strftime( "%Y%m%d_%H%M%S/" ) # Appending the date when this directory is called.
if not os.path.exists( dir ): # If directory not exist
os.makedirs( dir, exist_ok = True ) # mkdir -p functionality via exist_ok
return dir
def my_mvdir( from_dir, to_dir ):
shutil.move( from_dir , to_dir )
def my_rmdir( dir ):
if not isinstance( dir, str ):
raise ValueError( "Input directory should be a str, {} is given".format( type ( dir ) ) )
try:
shutil.rmtree( dir )
except:
print( "{0:s} Doesn't exist, hence cannot remove the directory".format( dir ) )
print( "Erasing Directory [{0:s}]".format( dir ) )
def my_print( **kwargs ):
"""
Description:
----------
** double asterisk means giving the argument as dictionary
By using double asterisk "kwargs" as input argument,
Arguments:
----------
Returns:
----------
"""
prec = kwargs[ "prec" ] if "prec" in kwargs else 5
f = kwargs[ "file" ] if "file" in kwargs else sys.stdout # If there is a keyword called "file" then use that as our standard output
tmpMaxLen = len( max( kwargs.keys( ), key = len ) ) # Getting the maximum length of a string list
for args in kwargs:
if 'file' == args.lower( ):
# Ignore the file's value, since it should not be added to the "output.txt" log file.
continue
print( "[{1:{0}s}]:".format( tmpMaxLen, args ), end = ' ', file = f ) # Printing out the name of the array
# {1:{0}s} Enables to set a variable as format length.
tmpData = kwargs[ args ]
if isinstance( tmpData, ( float, int ) ):
tmpPrint = "{2:{1}.{0}f}".format( prec, prec + 2, tmpData )
elif isinstance( tmpData, list ):
tmpPrint = np.array2string( np.array( tmpData ).flatten(), precision = prec, separator = ',' )
elif isinstance( tmpData, np.ndarray ):
tmpPrint = np.array2string( tmpData.flatten() , precision = prec, separator = ',' )
elif isinstance( tmpData, str ):
tmpPrint = tmpData
elif tmpData is None:
tmpPrint = "None"
else:
raise ValueError( "CHECK INPUT")
print( tmpPrint, file = f )
def solve_eq_posture( q0 ):
q1_0 = q0[ 0 ]
q2_0 = q0[ 1 ]
q3_0 = q0[ 2 ]
q4_0 = q0[ 3 ]
q1 = sp.Symbol( 'q1' )
q2 = sp.Symbol( 'q2' )
q3 = sp.Symbol( 'q3' )
q4 = sp.Symbol( 'q4' )
eqn1 = 0.52444712807465876380774716380984*sp.cos(q2)*sp.sin(q1) - 0.12721953522735995889547666592989*sp.cos(q1)*sp.sin(q2) - 0.05501625493258266441642945210333*sp.sin(q4)*(sp.sin(q1)*sp.sin(q3) + sp.cos(q1)*sp.cos(q3)*sp.sin(q2)) - 0.063807174539763700238381716189906*sp.cos(q1)*sp.cos(q2)*sp.sin(q4) - 0.042749427781976545581699156173272*sp.cos(q1)*sp.cos(q4)*sp.sin(q2) + 0.1762293392050615636890142923221*sp.cos(q2)*sp.cos(q4)*sp.sin(q1) + 0.1762293392050615636890142923221*sp.cos(q1)*sp.cos(q3)*sp.sin(q4) - 0.063807174539763700238381716189906*sp.cos(q3)*sp.cos(q4)*sp.sin(q1) + 0.042749427781976545581699156173272*sp.cos(q1)*sp.cos(q2)*sp.sin(q3)*sp.sin(q4) + 0.063807174539763700238381716189906*sp.cos(q1)*sp.cos(q4)*sp.sin(q2)*sp.sin(q3) + 0.1762293392050615636890142923221*sp.sin(q1)*sp.sin(q2)*sp.sin(q3)*sp.sin(q4) + q1 - q1_0
eqn2 = 0.1966778910733553153988850681344*sp.cos(q1)*sp.sin(q2) - 0.12721953522735995889547666592989*sp.cos(q2)*sp.sin(q1) + 0.020788410744410568131712579997838*sp.sin(q4)*(sp.sin(q1)*sp.sin(q3) + sp.cos(q1)*sp.cos(q3)*sp.sin(q2)) + 0.015478241093474287559672575298464*sp.cos(q1)*sp.cos(q2)*sp.sin(q4) + 0.066089435759419945526360606891103*sp.cos(q1)*sp.cos(q4)*sp.sin(q2) - 0.042749427781976545581699156173272*sp.cos(q2)*sp.cos(q4)*sp.sin(q1) - 0.042749427781976545581699156173272*sp.cos(q1)*sp.cos(q3)*sp.sin(q4) + 0.015478241093474287559672575298464*sp.cos(q3)*sp.cos(q4)*sp.sin(q1) - 0.066089435759419945526360606891103*sp.cos(q1)*sp.cos(q2)*sp.sin(q3)*sp.sin(q4) - 0.015478241093474287559672575298464*sp.cos(q1)*sp.cos(q4)*sp.sin(q2)*sp.sin(q3) - 0.042749427781976545581699156173272*sp.sin(q1)*sp.sin(q2)*sp.sin(q3)*sp.sin(q4) + q2 - q2_0
eqn3 = 0.1637248203220158515591720060911*sp.cos(q2)*sp.sin(q1) - 0.061864967327922570916598488111049*sp.cos(q1)*sp.sin(q2) - 0.083555731966853175052278857037891*sp.sin(q4)*(sp.sin(q1)*sp.sin(q3) + sp.cos(q1)*sp.cos(q3)*sp.sin(q2)) - 0.019919678510073035582195188908372*sp.cos(q1)*sp.cos(q2)*sp.sin(q4) - 0.020788410744410568131712579997838*sp.cos(q1)*sp.cos(q4)*sp.sin(q2) + 0.05501625493258266441642945210333*sp.cos(q2)*sp.cos(q4)*sp.sin(q1) + 0.05501625493258266441642945210333*sp.cos(q1)*sp.cos(q3)*sp.sin(q4) - 0.019919678510073035582195188908372*sp.cos(q3)*sp.cos(q4)*sp.sin(q1) + 0.020788410744410568131712579997838*sp.cos(q1)*sp.cos(q2)*sp.sin(q3)*sp.sin(q4) + 0.019919678510073035582195188908372*sp.cos(q1)*sp.cos(q4)*sp.sin(q2)*sp.sin(q3) + 0.05501625493258266441642945210333*sp.sin(q1)*sp.sin(q2)*sp.sin(q3)*sp.sin(q4) + q3 - q3_0
eqn4 = 0.046062245513354471704303705337225*sp.cos(q1)*sp.sin(q2) - 0.18988602913048024944941971625667*sp.cos(q2)*sp.sin(q1) + 0.019919678510073035582195188908372*sp.sin(q4)*(sp.sin(q1)*sp.sin(q3) + sp.cos(q1)*sp.cos(q3)*sp.sin(q2)) + 0.10117159250577656415259752975544*sp.cos(q1)*sp.cos(q2)*sp.sin(q4) + 0.015478241093474287559672575298464*sp.cos(q1)*sp.cos(q4)*sp.sin(q2) - 0.063807174539763700238381716189906*sp.cos(q2)*sp.cos(q4)*sp.sin(q1) - 0.063807174539763700238381716189906*sp.cos(q1)*sp.cos(q3)*sp.sin(q4) + 0.10117159250577656415259752975544*sp.cos(q3)*sp.cos(q4)*sp.sin(q1) - 0.015478241093474287559672575298464*sp.cos(q1)*sp.cos(q2)*sp.sin(q3)*sp.sin(q4) - 0.10117159250577656415259752975544*sp.cos(q1)*sp.cos(q4)*sp.sin(q2)*sp.sin(q3) - 0.063807174539763700238381716189906*sp.sin(q1)*sp.sin(q2)*sp.sin(q3)*sp.sin(q4) + q4 - q4_0
sol = sp.solvers.nsolve( ( eqn1, eqn2, eqn3, eqn4 ), ( q1, q2, q3, q4 ), q0 )
sol = np.array( sol )
return np.array( [ sol[ 0 ][ 0 ], sol[ 1 ][ 0 ], sol[ 2 ][ 0 ], sol[ 3 ][ 0 ] ] )
if __name__ == '__main__':
pass
| 42.196765 | 846 | 0.570808 |
import os
import re
import sys
import shutil
import time, datetime
import math as myMath
import glob
import cv2
import numpy as np
import xml.etree.ElementTree as ET
import sympy as sp
from sympy.utilities.lambdify import lambdify, implemented_function
from scipy.special import lambertw
from scipy.integrate import quad
from scipy.spatial.transform import Rotation as R
from modules.constants import Constants
class MyVideo:
def __init__( self, vid_dir = None, height = 1440, width = 850, fps = 60 ):
self.height = 2880
self.width = 1800
self.vid_dir = vid_dir if not None else "."
self.fps = fps
fourcc = cv2.VideoWriter_fourcc( *'MP4V' )
self.outVideo = cv2.VideoWriter( self.vid_dir + "/video.mp4", fourcc, fps, ( self.height//2, self.width//2 ) )
def write( self, myViewer ):
data = myViewer.read_pixels( self.height, self.width, depth = False )
data = cv2.cvtColor( data, cv2.COLOR_BGR2RGB )
data = cv2.resize( data,( self.height//2, self.width//2 ) )
self.outVideo.write( np.flip( data, axis = 0 ) )
def release( self ):
self.outVideo.release()
def length_elem2elem( mjModel, mjData, elem_name1, elem_name2 ):
type1 = get_elem_type( mjModel, elem_name1 )
type2 = get_elem_type( mjModel, elem_name2 )
return np.linalg.norm( getattr( mjData, "get_" + type1 + "_" + "xpos" )( elem_name1 )
- getattr( mjData, "get_" + type2 + "_" + "xpos" )( elem_name2 ) , ord = 2 )
def get_elem_type( mjModel, elem_name ):
return elem_name.split( '_' )[ 0 ]
def get_property( mjModel, elem_name, prop_name ):
type = get_elem_type( mjModel, elem_name )
for idx, s in enumerate( getattr( mjModel, type + "_" + "names" ) ):
if elem_name == s:
tmp = getattr( mjModel, type + "_" + prop_name )
return tmp[ idx ]
raise NameError( 'Cannot find geom_name with {0} in list, please check'.format( elem_name ) )
def snake2camel( s ):
return ''.join( word.title() for word in s.split( '_' ) )
def camel2snake( s ):
re.sub( r'(?<!^)(?=[A-Z])', '_', s ).lower()
def clear_dir( dir ):
def args_cleanup( args, s ):
if not isinstance( args, dict ) or not isinstance( s, str ):
raise ValueError( "Wrong input type. args should be type dict and s should be type str. {0:} and {1:} are rather given".format(
type( args ), type( str ) ) )
for old_key in list( args ) :
new_key = old_key.replace( s, '' )
args[ new_key ] = args.pop( old_key )
return args
def rot2quat( rot ):
# Taking the SO(3) matrix as an input and return the quaternion
return quat
def euler2quaternion( euler_angs ):
yaw, pitch, roll = euler_angs[ : ]
cy = np.cos( yaw * 0.5 )
sy = np.sin( yaw * 0.5 )
cp = np.cos( pitch * 0.5 )
sp = np.sin( pitch * 0.5 )
cr = np.cos( roll * 0.5 )
sr = np.sin( roll * 0.5 )
w = cr * cp * cy + sr * sp * sy;
x = sr * cp * cy - cr * sp * sy;
y = cr * sp * cy + sr * cp * sy;
z = cr * cp * sy - sr * sp * cy;
return w,x,y,z
def quaternion2euler( quatVec ): # Inputting quaternion matrix and outputing the yaw, pitch, roll of the euler angle.
if len( quatVec ) != 4:
raise ValueError( "Wrong size of input argument. Given size is [{0:d}] while it should be 4".format(
len( quatVec ) ) )
w, x, y ,z = quatVec[:]
t0 = + 2.0 * ( w * x + y * z )
t1 = + 1.0 - 2.0 * ( x * x + y * y )
roll = myMath.atan2( t0, t1 )
t2 = + 2.0 * ( w * y - z * x )
t2 = + 1.0 if t2 > +1.0 else t2
t2 = - 1.0 if t2 < -1.0 else t2
pitch = myMath.asin( t2 )
t3 = + 2.0 * ( w * z + x * y )
t4 = + 1.0 - 2.0 * ( y * y + z * z )
yaw = myMath.atan2( t3, t4 )
return yaw, pitch, roll
def str2bool( s ):
if isinstance( s, dict ):
for key, _ in s.items():
s[ key ] = str2bool( s[ key ] )
else:
return v.lower() in ( "yes", "true", "t", "1" )
def str2float( s ):
if not isinstance( s, str ):
raise ValueError( "Input argument should be string, but {} is given".format( type( s ) ) )
return [ float( i ) for i in re.findall( r"[-+]?\d*\.\d+|[-+]?\d+", s ) ]
def my_mkdir( ):
dir = Constants.TMP_DIR # Temporarily saving at tmp
dir += datetime.datetime.now().strftime( "%Y%m%d_%H%M%S/" ) # Appending the date when this directory is called.
if not os.path.exists( dir ): # If directory not exist
os.makedirs( dir, exist_ok = True ) # mkdir -p functionality via exist_ok
return dir
def my_mvdir( from_dir, to_dir ):
shutil.move( from_dir , to_dir )
def my_rmdir( dir ):
if not isinstance( dir, str ):
raise ValueError( "Input directory should be a str, {} is given".format( type ( dir ) ) )
try:
shutil.rmtree( dir )
except:
print( "{0:s} Doesn't exist, hence cannot remove the directory".format( dir ) )
print( "Erasing Directory [{0:s}]".format( dir ) )
def my_print( **kwargs ):
prec = kwargs[ "prec" ] if "prec" in kwargs else 5
f = kwargs[ "file" ] if "file" in kwargs else sys.stdout
tmpMaxLen = len( max( kwargs.keys( ), key = len ) )
for args in kwargs:
if 'file' == args.lower( ):
continue
print( "[{1:{0}s}]:".format( tmpMaxLen, args ), end = ' ', file = f ) # Printing out the name of the array
# {1:{0}s} Enables to set a variable as format length.
tmpData = kwargs[ args ]
if isinstance( tmpData, ( float, int ) ):
tmpPrint = "{2:{1}.{0}f}".format( prec, prec + 2, tmpData )
elif isinstance( tmpData, list ):
tmpPrint = np.array2string( np.array( tmpData ).flatten(), precision = prec, separator = ',' )
elif isinstance( tmpData, np.ndarray ):
tmpPrint = np.array2string( tmpData.flatten() , precision = prec, separator = ',' )
elif isinstance( tmpData, str ):
tmpPrint = tmpData
elif tmpData is None:
tmpPrint = "None"
else:
raise ValueError( "CHECK INPUT")
print( tmpPrint, file = f )
def solve_eq_posture( q0 ):
q1_0 = q0[ 0 ]
q2_0 = q0[ 1 ]
q3_0 = q0[ 2 ]
q4_0 = q0[ 3 ]
q1 = sp.Symbol( 'q1' )
q2 = sp.Symbol( 'q2' )
q3 = sp.Symbol( 'q3' )
q4 = sp.Symbol( 'q4' )
eqn1 = 0.52444712807465876380774716380984*sp.cos(q2)*sp.sin(q1) - 0.12721953522735995889547666592989*sp.cos(q1)*sp.sin(q2) - 0.05501625493258266441642945210333*sp.sin(q4)*(sp.sin(q1)*sp.sin(q3) + sp.cos(q1)*sp.cos(q3)*sp.sin(q2)) - 0.063807174539763700238381716189906*sp.cos(q1)*sp.cos(q2)*sp.sin(q4) - 0.042749427781976545581699156173272*sp.cos(q1)*sp.cos(q4)*sp.sin(q2) + 0.1762293392050615636890142923221*sp.cos(q2)*sp.cos(q4)*sp.sin(q1) + 0.1762293392050615636890142923221*sp.cos(q1)*sp.cos(q3)*sp.sin(q4) - 0.063807174539763700238381716189906*sp.cos(q3)*sp.cos(q4)*sp.sin(q1) + 0.042749427781976545581699156173272*sp.cos(q1)*sp.cos(q2)*sp.sin(q3)*sp.sin(q4) + 0.063807174539763700238381716189906*sp.cos(q1)*sp.cos(q4)*sp.sin(q2)*sp.sin(q3) + 0.1762293392050615636890142923221*sp.sin(q1)*sp.sin(q2)*sp.sin(q3)*sp.sin(q4) + q1 - q1_0
eqn2 = 0.1966778910733553153988850681344*sp.cos(q1)*sp.sin(q2) - 0.12721953522735995889547666592989*sp.cos(q2)*sp.sin(q1) + 0.020788410744410568131712579997838*sp.sin(q4)*(sp.sin(q1)*sp.sin(q3) + sp.cos(q1)*sp.cos(q3)*sp.sin(q2)) + 0.015478241093474287559672575298464*sp.cos(q1)*sp.cos(q2)*sp.sin(q4) + 0.066089435759419945526360606891103*sp.cos(q1)*sp.cos(q4)*sp.sin(q2) - 0.042749427781976545581699156173272*sp.cos(q2)*sp.cos(q4)*sp.sin(q1) - 0.042749427781976545581699156173272*sp.cos(q1)*sp.cos(q3)*sp.sin(q4) + 0.015478241093474287559672575298464*sp.cos(q3)*sp.cos(q4)*sp.sin(q1) - 0.066089435759419945526360606891103*sp.cos(q1)*sp.cos(q2)*sp.sin(q3)*sp.sin(q4) - 0.015478241093474287559672575298464*sp.cos(q1)*sp.cos(q4)*sp.sin(q2)*sp.sin(q3) - 0.042749427781976545581699156173272*sp.sin(q1)*sp.sin(q2)*sp.sin(q3)*sp.sin(q4) + q2 - q2_0
eqn3 = 0.1637248203220158515591720060911*sp.cos(q2)*sp.sin(q1) - 0.061864967327922570916598488111049*sp.cos(q1)*sp.sin(q2) - 0.083555731966853175052278857037891*sp.sin(q4)*(sp.sin(q1)*sp.sin(q3) + sp.cos(q1)*sp.cos(q3)*sp.sin(q2)) - 0.019919678510073035582195188908372*sp.cos(q1)*sp.cos(q2)*sp.sin(q4) - 0.020788410744410568131712579997838*sp.cos(q1)*sp.cos(q4)*sp.sin(q2) + 0.05501625493258266441642945210333*sp.cos(q2)*sp.cos(q4)*sp.sin(q1) + 0.05501625493258266441642945210333*sp.cos(q1)*sp.cos(q3)*sp.sin(q4) - 0.019919678510073035582195188908372*sp.cos(q3)*sp.cos(q4)*sp.sin(q1) + 0.020788410744410568131712579997838*sp.cos(q1)*sp.cos(q2)*sp.sin(q3)*sp.sin(q4) + 0.019919678510073035582195188908372*sp.cos(q1)*sp.cos(q4)*sp.sin(q2)*sp.sin(q3) + 0.05501625493258266441642945210333*sp.sin(q1)*sp.sin(q2)*sp.sin(q3)*sp.sin(q4) + q3 - q3_0
eqn4 = 0.046062245513354471704303705337225*sp.cos(q1)*sp.sin(q2) - 0.18988602913048024944941971625667*sp.cos(q2)*sp.sin(q1) + 0.019919678510073035582195188908372*sp.sin(q4)*(sp.sin(q1)*sp.sin(q3) + sp.cos(q1)*sp.cos(q3)*sp.sin(q2)) + 0.10117159250577656415259752975544*sp.cos(q1)*sp.cos(q2)*sp.sin(q4) + 0.015478241093474287559672575298464*sp.cos(q1)*sp.cos(q4)*sp.sin(q2) - 0.063807174539763700238381716189906*sp.cos(q2)*sp.cos(q4)*sp.sin(q1) - 0.063807174539763700238381716189906*sp.cos(q1)*sp.cos(q3)*sp.sin(q4) + 0.10117159250577656415259752975544*sp.cos(q3)*sp.cos(q4)*sp.sin(q1) - 0.015478241093474287559672575298464*sp.cos(q1)*sp.cos(q2)*sp.sin(q3)*sp.sin(q4) - 0.10117159250577656415259752975544*sp.cos(q1)*sp.cos(q4)*sp.sin(q2)*sp.sin(q3) - 0.063807174539763700238381716189906*sp.sin(q1)*sp.sin(q2)*sp.sin(q3)*sp.sin(q4) + q4 - q4_0
sol = sp.solvers.nsolve( ( eqn1, eqn2, eqn3, eqn4 ), ( q1, q2, q3, q4 ), q0 )
sol = np.array( sol )
return np.array( [ sol[ 0 ][ 0 ], sol[ 1 ][ 0 ], sol[ 2 ][ 0 ], sol[ 3 ][ 0 ] ] )
if __name__ == '__main__':
pass
| true | true |
f7167e61cefc29e05e76cf5f35782284b46a20aa | 4,682 | py | Python | sdk/netapp/azure-mgmt-netapp/azure/mgmt/netapp/aio/operations/_operations.py | ankitarorabit/azure-sdk-for-python | dd90281cbad9400f8080754a5ef2f56791a5a88f | [
"MIT"
] | 3 | 2020-06-23T02:25:27.000Z | 2021-09-07T18:48:11.000Z | sdk/netapp/azure-mgmt-netapp/azure/mgmt/netapp/aio/operations/_operations.py | ankitarorabit/azure-sdk-for-python | dd90281cbad9400f8080754a5ef2f56791a5a88f | [
"MIT"
] | 510 | 2019-07-17T16:11:19.000Z | 2021-08-02T08:38:32.000Z | sdk/netapp/azure-mgmt-netapp/azure/mgmt/netapp/aio/operations/_operations.py | ankitarorabit/azure-sdk-for-python | dd90281cbad9400f8080754a5ef2f56791a5a88f | [
"MIT"
] | 5 | 2019-09-04T12:51:37.000Z | 2020-09-16T07:28:40.000Z | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class Operations:
"""Operations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.netapp.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def list(
self,
**kwargs: Any
) -> AsyncIterable["_models.OperationListResult"]:
"""Describes the Resource Provider.
Lists all of the available Microsoft.NetApp Rest API operations.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either OperationListResult or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.netapp.models.OperationListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2021-02-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list.metadata['url'] # type: ignore
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('OperationListResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/providers/Microsoft.NetApp/operations'} # type: ignore
| 43.757009 | 133 | 0.65912 |
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class Operations:
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def list(
self,
**kwargs: Any
) -> AsyncIterable["_models.OperationListResult"]:
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2021-02-01"
accept = "application/json"
def prepare_request(next_link=None):
header_parameters = {}
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
url = self.list.metadata['url']
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {}
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('OperationListResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/providers/Microsoft.NetApp/operations'}
| true | true |
f7167ea0d6c0f9e11b4a88a19c5af9d2c9a92a69 | 17,093 | py | Python | intersight/model/niatelemetry_supervisor_module_details.py | CiscoDevNet/intersight-python | 04b721f37c3044646a91c185c7259edfb991557a | [
"Apache-2.0"
] | 5 | 2021-12-16T15:13:32.000Z | 2022-03-29T16:09:54.000Z | intersight/model/niatelemetry_supervisor_module_details.py | CiscoDevNet/intersight-python | 04b721f37c3044646a91c185c7259edfb991557a | [
"Apache-2.0"
] | 4 | 2022-01-25T19:05:51.000Z | 2022-03-29T20:18:37.000Z | intersight/model/niatelemetry_supervisor_module_details.py | CiscoDevNet/intersight-python | 04b721f37c3044646a91c185c7259edfb991557a | [
"Apache-2.0"
] | 2 | 2020-07-07T15:01:08.000Z | 2022-01-31T04:27:35.000Z | """
Cisco Intersight
Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environments in more advanced ways than the prior generations of tools. Cisco Intersight provides an integrated and intuitive management experience for resources in the traditional data center as well as at the edge. With flexible deployment options to address complex security needs, getting started with Intersight is quick and easy. Cisco Intersight has deep integration with Cisco UCS and HyperFlex systems allowing for remote deployment, configuration, and ongoing maintenance. The model-based deployment works for a single system in a remote location or hundreds of systems in a data center and enables rapid, standardized configuration and deployment. It also streamlines maintaining those systems whether you are working with small or very large configurations. The Intersight OpenAPI document defines the complete set of properties that are returned in the HTTP response. From that perspective, a client can expect that no additional properties are returned, unless these properties are explicitly defined in the OpenAPI document. However, when a client uses an older version of the Intersight OpenAPI document, the server may send additional properties because the software is more recent than the client. In that case, the client may receive properties that it does not know about. Some generated SDKs perform a strict validation of the HTTP response body against the OpenAPI document. # noqa: E501
The version of the OpenAPI document: 1.0.9-4950
Contact: intersight@cisco.com
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from intersight.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 intersight.model.asset_device_registration_relationship import AssetDeviceRegistrationRelationship
from intersight.model.display_names import DisplayNames
from intersight.model.mo_base_mo import MoBaseMo
from intersight.model.mo_base_mo_relationship import MoBaseMoRelationship
from intersight.model.mo_tag import MoTag
from intersight.model.mo_version_context import MoVersionContext
from intersight.model.niatelemetry_supervisor_module_details_all_of import NiatelemetrySupervisorModuleDetailsAllOf
globals()['AssetDeviceRegistrationRelationship'] = AssetDeviceRegistrationRelationship
globals()['DisplayNames'] = DisplayNames
globals()['MoBaseMo'] = MoBaseMo
globals()['MoBaseMoRelationship'] = MoBaseMoRelationship
globals()['MoTag'] = MoTag
globals()['MoVersionContext'] = MoVersionContext
globals()['NiatelemetrySupervisorModuleDetailsAllOf'] = NiatelemetrySupervisorModuleDetailsAllOf
class NiatelemetrySupervisorModuleDetails(ModelComposed):
"""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 = {
('class_id',): {
'NIATELEMETRY.SUPERVISORMODULEDETAILS': "niatelemetry.SupervisorModuleDetails",
},
('object_type',): {
'NIATELEMETRY.SUPERVISORMODULEDETAILS': "niatelemetry.SupervisorModuleDetails",
},
}
validations = {
}
@cached_property
def additional_properties_type():
"""
This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
"""
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501
_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 {
'class_id': (str,), # noqa: E501
'object_type': (str,), # noqa: E501
'dn': (str,), # noqa: E501
'hw_ver': (str,), # noqa: E501
'model': (str,), # noqa: E501
'record_type': (str,), # noqa: E501
'record_version': (str,), # noqa: E501
'serial': (str,), # noqa: E501
'site_name': (str,), # noqa: E501
'registered_device': (AssetDeviceRegistrationRelationship,), # noqa: E501
'account_moid': (str,), # noqa: E501
'create_time': (datetime,), # noqa: E501
'domain_group_moid': (str,), # noqa: E501
'mod_time': (datetime,), # noqa: E501
'moid': (str,), # noqa: E501
'owners': ([str], none_type,), # noqa: E501
'shared_scope': (str,), # noqa: E501
'tags': ([MoTag], none_type,), # noqa: E501
'version_context': (MoVersionContext,), # noqa: E501
'ancestors': ([MoBaseMoRelationship], none_type,), # noqa: E501
'parent': (MoBaseMoRelationship,), # noqa: E501
'permission_resources': ([MoBaseMoRelationship], none_type,), # noqa: E501
'display_names': (DisplayNames,), # noqa: E501
}
@cached_property
def discriminator():
val = {
}
if not val:
return None
return {'class_id': val}
attribute_map = {
'class_id': 'ClassId', # noqa: E501
'object_type': 'ObjectType', # noqa: E501
'dn': 'Dn', # noqa: E501
'hw_ver': 'HwVer', # noqa: E501
'model': 'Model', # noqa: E501
'record_type': 'RecordType', # noqa: E501
'record_version': 'RecordVersion', # noqa: E501
'serial': 'Serial', # noqa: E501
'site_name': 'SiteName', # noqa: E501
'registered_device': 'RegisteredDevice', # noqa: E501
'account_moid': 'AccountMoid', # noqa: E501
'create_time': 'CreateTime', # noqa: E501
'domain_group_moid': 'DomainGroupMoid', # noqa: E501
'mod_time': 'ModTime', # noqa: E501
'moid': 'Moid', # noqa: E501
'owners': 'Owners', # noqa: E501
'shared_scope': 'SharedScope', # noqa: E501
'tags': 'Tags', # noqa: E501
'version_context': 'VersionContext', # noqa: E501
'ancestors': 'Ancestors', # noqa: E501
'parent': 'Parent', # noqa: E501
'permission_resources': 'PermissionResources', # noqa: E501
'display_names': 'DisplayNames', # noqa: E501
}
required_properties = set([
'_data_store',
'_check_type',
'_spec_property_naming',
'_path_to_item',
'_configuration',
'_visited_composed_classes',
'_composed_instances',
'_var_name_to_model_instances',
'_additional_properties_model_instances',
])
@convert_js_args_to_python_args
def __init__(self, *args, **kwargs): # noqa: E501
"""NiatelemetrySupervisorModuleDetails - a model defined in OpenAPI
Args:
Keyword Args:
class_id (str): The fully-qualified name of the instantiated, concrete type. This property is used as a discriminator to identify the type of the payload when marshaling and unmarshaling data.. defaults to "niatelemetry.SupervisorModuleDetails", must be one of ["niatelemetry.SupervisorModuleDetails", ] # noqa: E501
object_type (str): The fully-qualified name of the instantiated, concrete type. The value should be the same as the 'ClassId' property.. defaults to "niatelemetry.SupervisorModuleDetails", must be one of ["niatelemetry.SupervisorModuleDetails", ] # noqa: E501
_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,)
dn (str): Dn of the supervisor module in APIC.. [optional] # noqa: E501
hw_ver (str): Hardware version of supervisor module.. [optional] # noqa: E501
model (str): Model of the supervisor module.. [optional] # noqa: E501
record_type (str): Type of record DCNM / APIC / SE. This determines the type of platform where inventory was collected.. [optional] # noqa: E501
record_version (str): Version of record being pushed. This determines what was the API version for data available from the device.. [optional] # noqa: E501
serial (str): Serial number of the supervisor module.. [optional] # noqa: E501
site_name (str): Name of the APIC site from which this data is being collected.. [optional] # noqa: E501
registered_device (AssetDeviceRegistrationRelationship): [optional] # noqa: E501
account_moid (str): The Account ID for this managed object.. [optional] # noqa: E501
create_time (datetime): The time when this managed object was created.. [optional] # noqa: E501
domain_group_moid (str): The DomainGroup ID for this managed object.. [optional] # noqa: E501
mod_time (datetime): The time when this managed object was last modified.. [optional] # noqa: E501
moid (str): The unique identifier of this Managed Object instance.. [optional] # noqa: E501
owners ([str], none_type): [optional] # noqa: E501
shared_scope (str): Intersight provides pre-built workflows, tasks and policies to end users through global catalogs. Objects that are made available through global catalogs are said to have a 'shared' ownership. Shared objects are either made globally available to all end users or restricted to end users based on their license entitlement. Users can use this property to differentiate the scope (global or a specific license tier) to which a shared MO belongs.. [optional] # noqa: E501
tags ([MoTag], none_type): [optional] # noqa: E501
version_context (MoVersionContext): [optional] # noqa: E501
ancestors ([MoBaseMoRelationship], none_type): An array of relationships to moBaseMo resources.. [optional] # noqa: E501
parent (MoBaseMoRelationship): [optional] # noqa: E501
permission_resources ([MoBaseMoRelationship], none_type): An array of relationships to moBaseMo resources.. [optional] # noqa: E501
display_names (DisplayNames): [optional] # noqa: E501
"""
class_id = kwargs.get('class_id', "niatelemetry.SupervisorModuleDetails")
object_type = kwargs.get('object_type', "niatelemetry.SupervisorModuleDetails")
_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__,)
constant_args = {
'_check_type': _check_type,
'_path_to_item': _path_to_item,
'_spec_property_naming': _spec_property_naming,
'_configuration': _configuration,
'_visited_composed_classes': self._visited_composed_classes,
}
required_args = {
'class_id': class_id,
'object_type': object_type,
}
model_args = {}
model_args.update(required_args)
model_args.update(kwargs)
composed_info = validate_get_composed_info(
constant_args, model_args, self)
self._composed_instances = composed_info[0]
self._var_name_to_model_instances = composed_info[1]
self._additional_properties_model_instances = composed_info[2]
unused_args = composed_info[3]
for var_name, var_value in required_args.items():
setattr(self, var_name, var_value)
for var_name, var_value in kwargs.items():
if var_name in unused_args and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
not self._additional_properties_model_instances:
# discard variable.
continue
setattr(self, var_name, var_value)
@cached_property
def _composed_schemas():
# we need this here to make our import statements work
# we must store _composed_schemas in here so the code is only run
# when we invoke this method. If we kept this at the class
# level we would get an error beause the class level
# code would be run when this module is imported, and these composed
# classes don't exist yet because their module has not finished
# loading
lazy_import()
return {
'anyOf': [
],
'allOf': [
MoBaseMo,
NiatelemetrySupervisorModuleDetailsAllOf,
],
'oneOf': [
],
}
| 54.091772 | 1,678 | 0.639677 |
import re
import sys
from intersight.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 intersight.model.asset_device_registration_relationship import AssetDeviceRegistrationRelationship
from intersight.model.display_names import DisplayNames
from intersight.model.mo_base_mo import MoBaseMo
from intersight.model.mo_base_mo_relationship import MoBaseMoRelationship
from intersight.model.mo_tag import MoTag
from intersight.model.mo_version_context import MoVersionContext
from intersight.model.niatelemetry_supervisor_module_details_all_of import NiatelemetrySupervisorModuleDetailsAllOf
globals()['AssetDeviceRegistrationRelationship'] = AssetDeviceRegistrationRelationship
globals()['DisplayNames'] = DisplayNames
globals()['MoBaseMo'] = MoBaseMo
globals()['MoBaseMoRelationship'] = MoBaseMoRelationship
globals()['MoTag'] = MoTag
globals()['MoVersionContext'] = MoVersionContext
globals()['NiatelemetrySupervisorModuleDetailsAllOf'] = NiatelemetrySupervisorModuleDetailsAllOf
class NiatelemetrySupervisorModuleDetails(ModelComposed):
allowed_values = {
('class_id',): {
'NIATELEMETRY.SUPERVISORMODULEDETAILS': "niatelemetry.SupervisorModuleDetails",
},
('object_type',): {
'NIATELEMETRY.SUPERVISORMODULEDETAILS': "niatelemetry.SupervisorModuleDetails",
},
}
validations = {
}
@cached_property
def additional_properties_type():
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type,)
_nullable = False
@cached_property
def openapi_types():
lazy_import()
return {
'class_id': (str,),
'object_type': (str,),
'dn': (str,),
'hw_ver': (str,),
'model': (str,),
'record_type': (str,),
'record_version': (str,),
'serial': (str,),
'site_name': (str,),
'registered_device': (AssetDeviceRegistrationRelationship,),
'account_moid': (str,),
'create_time': (datetime,),
'domain_group_moid': (str,),
'mod_time': (datetime,),
'moid': (str,),
'owners': ([str], none_type,),
'shared_scope': (str,),
'tags': ([MoTag], none_type,),
'version_context': (MoVersionContext,),
'ancestors': ([MoBaseMoRelationship], none_type,),
'parent': (MoBaseMoRelationship,),
'permission_resources': ([MoBaseMoRelationship], none_type,),
'display_names': (DisplayNames,),
}
@cached_property
def discriminator():
val = {
}
if not val:
return None
return {'class_id': val}
attribute_map = {
'class_id': 'ClassId',
'object_type': 'ObjectType',
'dn': 'Dn',
'hw_ver': 'HwVer',
'model': 'Model',
'record_type': 'RecordType',
'record_version': 'RecordVersion',
'serial': 'Serial',
'site_name': 'SiteName',
'registered_device': 'RegisteredDevice',
'account_moid': 'AccountMoid',
'create_time': 'CreateTime',
'domain_group_moid': 'DomainGroupMoid',
'mod_time': 'ModTime',
'moid': 'Moid',
'owners': 'Owners',
'shared_scope': 'SharedScope',
'tags': 'Tags',
'version_context': 'VersionContext',
'ancestors': 'Ancestors',
'parent': 'Parent',
'permission_resources': 'PermissionResources',
'display_names': 'DisplayNames',
}
required_properties = set([
'_data_store',
'_check_type',
'_spec_property_naming',
'_path_to_item',
'_configuration',
'_visited_composed_classes',
'_composed_instances',
'_var_name_to_model_instances',
'_additional_properties_model_instances',
])
@convert_js_args_to_python_args
def __init__(self, *args, **kwargs):
class_id = kwargs.get('class_id', "niatelemetry.SupervisorModuleDetails")
object_type = kwargs.get('object_type', "niatelemetry.SupervisorModuleDetails")
_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__,)
constant_args = {
'_check_type': _check_type,
'_path_to_item': _path_to_item,
'_spec_property_naming': _spec_property_naming,
'_configuration': _configuration,
'_visited_composed_classes': self._visited_composed_classes,
}
required_args = {
'class_id': class_id,
'object_type': object_type,
}
model_args = {}
model_args.update(required_args)
model_args.update(kwargs)
composed_info = validate_get_composed_info(
constant_args, model_args, self)
self._composed_instances = composed_info[0]
self._var_name_to_model_instances = composed_info[1]
self._additional_properties_model_instances = composed_info[2]
unused_args = composed_info[3]
for var_name, var_value in required_args.items():
setattr(self, var_name, var_value)
for var_name, var_value in kwargs.items():
if var_name in unused_args and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
not self._additional_properties_model_instances:
continue
setattr(self, var_name, var_value)
@cached_property
def _composed_schemas():
# loading
lazy_import()
return {
'anyOf': [
],
'allOf': [
MoBaseMo,
NiatelemetrySupervisorModuleDetailsAllOf,
],
'oneOf': [
],
}
| true | true |
f7167ec21a6a129bda61142db392f78aae4d6960 | 271 | py | Python | tests/database.py | tophat/ormar-postgres-extensions | 88fcab5a73bc89090739c38f063191d8473957a5 | [
"Apache-2.0"
] | 6 | 2021-08-02T22:24:34.000Z | 2022-03-21T08:59:22.000Z | tests/database.py | tophat/ormar-postgres-extensions | 88fcab5a73bc89090739c38f063191d8473957a5 | [
"Apache-2.0"
] | 14 | 2021-08-03T00:03:55.000Z | 2022-02-17T02:10:08.000Z | tests/database.py | tophat/ormar-postgres-extensions | 88fcab5a73bc89090739c38f063191d8473957a5 | [
"Apache-2.0"
] | 2 | 2022-01-28T20:10:12.000Z | 2022-02-09T16:49:01.000Z | import databases
import sqlalchemy
DB_HOST = "localhost"
DB_NAME = "TEST_DATABASE"
DATABASE_URL = databases.DatabaseURL(
f"postgres://DEV_USER:DEV_PASSWORD@{DB_HOST}:5432/{DB_NAME}"
)
database = databases.Database(str(DATABASE_URL))
metadata = sqlalchemy.MetaData()
| 24.636364 | 64 | 0.782288 | import databases
import sqlalchemy
DB_HOST = "localhost"
DB_NAME = "TEST_DATABASE"
DATABASE_URL = databases.DatabaseURL(
f"postgres://DEV_USER:DEV_PASSWORD@{DB_HOST}:5432/{DB_NAME}"
)
database = databases.Database(str(DATABASE_URL))
metadata = sqlalchemy.MetaData()
| true | true |
f71680e22b485ad498455c52808137f6caab7e0c | 910 | py | Python | gammapy/stats/tests/test_significance.py | qpiel/gammapy | cfb976909e63f4d5d578e1495245c0baad69482b | [
"BSD-3-Clause"
] | null | null | null | gammapy/stats/tests/test_significance.py | qpiel/gammapy | cfb976909e63f4d5d578e1495245c0baad69482b | [
"BSD-3-Clause"
] | 1 | 2020-10-29T19:55:46.000Z | 2020-10-29T19:55:46.000Z | gammapy/stats/tests/test_significance.py | qpiel/gammapy | cfb976909e63f4d5d578e1495245c0baad69482b | [
"BSD-3-Clause"
] | null | null | null | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import absolute_import, division, print_function, unicode_literals
from numpy.testing import assert_allclose
from ...stats import (
significance_to_probability_normal,
probability_to_significance_normal,
probability_to_significance_normal_limit,
significance_to_probability_normal_limit,
)
def test_significance_to_probability_normal():
significance = 5
p = significance_to_probability_normal(significance)
assert_allclose(p, 2.8665157187919328e-07)
s = probability_to_significance_normal(p)
assert_allclose(s, significance)
def test_significance_to_probability_normal_limit():
significance = 5
p = significance_to_probability_normal_limit(significance)
assert_allclose(p, 2.792513e-07)
s = probability_to_significance_normal_limit(p)
assert_allclose(s, significance)
| 32.5 | 82 | 0.806593 |
from __future__ import absolute_import, division, print_function, unicode_literals
from numpy.testing import assert_allclose
from ...stats import (
significance_to_probability_normal,
probability_to_significance_normal,
probability_to_significance_normal_limit,
significance_to_probability_normal_limit,
)
def test_significance_to_probability_normal():
significance = 5
p = significance_to_probability_normal(significance)
assert_allclose(p, 2.8665157187919328e-07)
s = probability_to_significance_normal(p)
assert_allclose(s, significance)
def test_significance_to_probability_normal_limit():
significance = 5
p = significance_to_probability_normal_limit(significance)
assert_allclose(p, 2.792513e-07)
s = probability_to_significance_normal_limit(p)
assert_allclose(s, significance)
| true | true |
f716815fb86995f906bd4284b72bbcf1851ecedc | 9,243 | py | Python | ros_pkg/dock/scripts/dock_generator.py | introlab/securbot | 0652ddf3e2dbcf0bb6ffcf76898749b67e443327 | [
"Apache-2.0"
] | 20 | 2019-03-13T13:37:51.000Z | 2022-01-25T16:56:35.000Z | ros_pkg/dock/scripts/dock_generator.py | introlab/securbot | 0652ddf3e2dbcf0bb6ffcf76898749b67e443327 | [
"Apache-2.0"
] | 15 | 2019-02-27T20:29:34.000Z | 2020-08-24T19:44:20.000Z | ros_pkg/dock/scripts/dock_generator.py | introlab/securbot | 0652ddf3e2dbcf0bb6ffcf76898749b67e443327 | [
"Apache-2.0"
] | 13 | 2019-07-31T00:47:49.000Z | 2021-04-15T01:33:02.000Z | #!/usr/bin/env python
"""Provide docking motivation layer node."""
import rospy
import json
import math
from enum import Enum
from threading import Lock
import tf
from tf.transformations import euler_from_quaternion
from std_msgs.msg import Bool
from std_msgs.msg import Empty
from geometry_msgs.msg import PoseStamped
from sensor_msgs.msg import BatteryState
from hbba_msgs.msg import Desire
from hbba_msgs.msg import Intention
from hbba_msgs.srv import AddDesires
from hbba_msgs.srv import RemoveDesires
class DockState(Enum):
"""Define dockig process states."""
idle = 0 # No dock required
approaching = 1 # Driving to dock approach goal
docking = 2 # Docking to station
docked = 3 # Docked at station and dock required
class DockGenerator:
"""Generate dock desires according to robot and dock state."""
def force_callback(self, msg):
"""Receive force docking command from electron."""
self.lock.acquire()
self.force_docking = msg.data
self.last_force = rospy.Time.now()
self.lock.release()
def battery_callback(self, msg):
"""Receive battery level from battery board."""
self.lock.acquire()
if msg.percentage < self.min_percent:
self.low_battery = True
if msg.percentage > self.charge_percent:
self.low_battery = False
self.lock.release()
def collision_callback(self, msg):
"""Receive collision events from collision detector."""
self.lock.acquire()
if self.state == DockState.docking:
self.finish_docking()
self.lock.release()
def intention_callback(self, msg):
"""Monitor current robot intention from hbba."""
self.lock.acquire()
self.approach_active = self.approach_desire.id in msg.desires
if self.state == DockState.docking:
if self.loiter_desire.id in msg.desires:
self.state = DockState.docked
elif self.dock_desire.id not in msg.desires:
self.restart_docking()
if self.state == DockState.docked:
if self.loiter_desire.id not in msg.desires:
self.stop_docking()
self.lock.release()
def approach_callback(self, msg):
"""Set approach goal."""
self.lock.acquire()
self.approach_goal['frame_id'] = msg.header.frame_id
self.approach_goal['x'] = msg.pose.position.x
self.approach_goal['y'] = msg.pose.position.y
quat = (
msg.pose.orientation.w,
msg.pose.orientation.x,
msg.pose.orientation.y,
msg.pose.orientation.z
)
euler = euler_from_quaternion(quat)
self.approach_goal['t'] = euler[2]
self.lock.release()
def start_docking(self):
"""Initialize docking sequence."""
self.add_desire([self.dock_desire])
self.restart_docking()
def restart_docking(self):
"""Restart approach after interuption."""
self.approach_desire.params = json.dumps(self.approach_goal)
self.add_desire([self.approach_desire])
self.state = DockState.approaching
def finish_approach(self):
"""End approach phase."""
self.rem_desire([self.approach_desire.id])
self.state = DockState.docking
def finish_docking(self):
"""End docking phase."""
self.add_desire([self.loiter_desire])
self.rem_desire([self.dock_desire.id])
def stop_docking(self):
"""Cancel docking process."""
if self.state == DockState.approaching:
# both dock and approach must be removed
self.rem_desire([
self.dock_desire.id,
self.approach_desire.id
])
elif self.state == DockState.docking:
# only dock desire must be removed
self.rem_desire([self.dock_desire.id])
elif self.state == DockState.docked:
# loiter desire must be removed
self.rem_desire([self.loiter_desire.id])
self.state = DockState.idle
def run(self):
"""Update desires and check if robot reached approach goal."""
rospy.Subscriber('force_docking', Bool, self.force_callback)
rospy.Subscriber('collision', Empty, self.collision_callback)
rospy.Subscriber('battery_state', BatteryState, self.battery_callback)
rospy.Subscriber('approach_goal', PoseStamped, self.approach_callback)
rospy.Subscriber('hbba/intention', Intention, self.intention_callback)
tf_listener = tf.TransformListener()
rate = rospy.Rate(1)
while not rospy.is_shutdown():
rate.sleep()
self.lock.acquire()
# Check if force is expired
now = rospy.Time.now()
timeout = rospy.Duration(self.force_timeout)
if now - self.last_force > timeout:
self.force_docking = False
# Check if we need to start docking
if (self.force_docking or self.low_battery)\
and self.state == DockState.idle:
self.start_docking()
self.lock.release()
continue
# Check if we need to stop docking
if not self.force_docking\
and not self.low_battery\
and self.state != DockState.idle:
self.stop_docking()
self.lock.release()
continue
# We are not approaching we cancel tf lookup
if self.state != DockState.approaching or not self.approach_active:
self.lock.release()
continue
# Lookup robot pose in map
try:
pos, quat = tf_listener.lookupTransform(
self.map_frame,
self.robot_frame,
rospy.Time())
except (tf.Exception):
self.lock.release()
continue
# Check if we reached our approach goal
dx = pos[0] - self.approach_goal['x']
dy = pos[1] - self.approach_goal['y']
lin_dst = math.sqrt(dx*dx + dy*dy)
angles = euler_from_quaternion(quat)
yaw_dst = angles[2] - self.approach_goal['t']
if lin_dst < self.appr_lin_tol and abs(yaw_dst) < self.appr_yaw_tol:
self.finish_approach()
self.lock.release()
def __init__(self):
"""Initialize dock generator node."""
self.lock = Lock()
self.low_battery = False
self.force_docking = False
self.approach_active = False
self.state = DockState.idle
self.last_force = rospy.Time()
rospy.init_node('dock_generator')
rospy.loginfo('waiting for add desire to be availble')
rospy.wait_for_service('/hbba/add_desires')
self.add_desire = rospy.ServiceProxy(
'/hbba/add_desires',
AddDesires)
rospy.loginfo('add desire registered')
rospy.loginfo('waiting for remove desire to be availbe')
rospy.wait_for_service('/hbba/remove_desires')
self.rem_desire = rospy.ServiceProxy(
'/hbba/remove_desires',
RemoveDesires)
rospy.loginfo('remove desire registered')
self.map_frame = rospy.get_param('~map_frame', 'map')
self.robot_frame = rospy.get_param('~robot_frame', 'base_footprint')
self.appr_lin_tol = rospy.get_param('~appr_lin_tol', 0.40)
self.appr_yaw_tol = rospy.get_param('~appr_yaw_tol', 0.1)
self.min_percent = rospy.get_param('~min_percent', 30)
self.charge_percent = rospy.get_param('~charge_percent', 80)
self.undock_time = rospy.get_param('~undock_time', 4.0)
self.force_timeout = rospy.get_param('~force_timeout', 10.0)
self.approach_goal = dict()
self.approach_goal['x'] = rospy.get_param('approach/x', 0.0)
self.approach_goal['y'] = rospy.get_param('approach/y', 0.0)
self.approach_goal['t'] = rospy.get_param('approach/t', 0.0)
self.approach_goal['frame_id'] = self.map_frame
self.approach_desire = Desire()
self.approach_desire.id = 'dock_approach'
self.approach_desire.type = 'GoTo'
self.approach_desire.intensity = 1
self.approach_desire.utility = 1
self.approach_desire.security = False
self.dock_desire = Desire()
self.dock_desire.id = 'dock_dock'
self.dock_desire.type = 'Dock'
self.dock_desire.intensity = 1
self.dock_desire.utility = 1
self.dock_desire.security = False
self.loiter_desire = Desire()
self.loiter_desire.id = 'dock_charge'
self.loiter_desire.type = 'Loiter'
self.loiter_desire.intensity = 1
self.loiter_desire.utility = 1
self.loiter_desire.security = False
params = dict()
params['t'] = self.undock_time
self.loiter_desire.params = json.dumps(params)
def node():
"""Run the docking motivation node."""
generator_node = DockGenerator()
generator_node.run()
if __name__ == '__main__':
node()
| 33.48913 | 80 | 0.612896 |
import rospy
import json
import math
from enum import Enum
from threading import Lock
import tf
from tf.transformations import euler_from_quaternion
from std_msgs.msg import Bool
from std_msgs.msg import Empty
from geometry_msgs.msg import PoseStamped
from sensor_msgs.msg import BatteryState
from hbba_msgs.msg import Desire
from hbba_msgs.msg import Intention
from hbba_msgs.srv import AddDesires
from hbba_msgs.srv import RemoveDesires
class DockState(Enum):
idle = 0
approaching = 1
docking = 2
docked = 3
class DockGenerator:
def force_callback(self, msg):
self.lock.acquire()
self.force_docking = msg.data
self.last_force = rospy.Time.now()
self.lock.release()
def battery_callback(self, msg):
self.lock.acquire()
if msg.percentage < self.min_percent:
self.low_battery = True
if msg.percentage > self.charge_percent:
self.low_battery = False
self.lock.release()
def collision_callback(self, msg):
self.lock.acquire()
if self.state == DockState.docking:
self.finish_docking()
self.lock.release()
def intention_callback(self, msg):
self.lock.acquire()
self.approach_active = self.approach_desire.id in msg.desires
if self.state == DockState.docking:
if self.loiter_desire.id in msg.desires:
self.state = DockState.docked
elif self.dock_desire.id not in msg.desires:
self.restart_docking()
if self.state == DockState.docked:
if self.loiter_desire.id not in msg.desires:
self.stop_docking()
self.lock.release()
def approach_callback(self, msg):
self.lock.acquire()
self.approach_goal['frame_id'] = msg.header.frame_id
self.approach_goal['x'] = msg.pose.position.x
self.approach_goal['y'] = msg.pose.position.y
quat = (
msg.pose.orientation.w,
msg.pose.orientation.x,
msg.pose.orientation.y,
msg.pose.orientation.z
)
euler = euler_from_quaternion(quat)
self.approach_goal['t'] = euler[2]
self.lock.release()
def start_docking(self):
self.add_desire([self.dock_desire])
self.restart_docking()
def restart_docking(self):
self.approach_desire.params = json.dumps(self.approach_goal)
self.add_desire([self.approach_desire])
self.state = DockState.approaching
def finish_approach(self):
self.rem_desire([self.approach_desire.id])
self.state = DockState.docking
def finish_docking(self):
self.add_desire([self.loiter_desire])
self.rem_desire([self.dock_desire.id])
def stop_docking(self):
if self.state == DockState.approaching:
self.rem_desire([
self.dock_desire.id,
self.approach_desire.id
])
elif self.state == DockState.docking:
self.rem_desire([self.dock_desire.id])
elif self.state == DockState.docked:
self.rem_desire([self.loiter_desire.id])
self.state = DockState.idle
def run(self):
rospy.Subscriber('force_docking', Bool, self.force_callback)
rospy.Subscriber('collision', Empty, self.collision_callback)
rospy.Subscriber('battery_state', BatteryState, self.battery_callback)
rospy.Subscriber('approach_goal', PoseStamped, self.approach_callback)
rospy.Subscriber('hbba/intention', Intention, self.intention_callback)
tf_listener = tf.TransformListener()
rate = rospy.Rate(1)
while not rospy.is_shutdown():
rate.sleep()
self.lock.acquire()
now = rospy.Time.now()
timeout = rospy.Duration(self.force_timeout)
if now - self.last_force > timeout:
self.force_docking = False
if (self.force_docking or self.low_battery)\
and self.state == DockState.idle:
self.start_docking()
self.lock.release()
continue
if not self.force_docking\
and not self.low_battery\
and self.state != DockState.idle:
self.stop_docking()
self.lock.release()
continue
if self.state != DockState.approaching or not self.approach_active:
self.lock.release()
continue
try:
pos, quat = tf_listener.lookupTransform(
self.map_frame,
self.robot_frame,
rospy.Time())
except (tf.Exception):
self.lock.release()
continue
dx = pos[0] - self.approach_goal['x']
dy = pos[1] - self.approach_goal['y']
lin_dst = math.sqrt(dx*dx + dy*dy)
angles = euler_from_quaternion(quat)
yaw_dst = angles[2] - self.approach_goal['t']
if lin_dst < self.appr_lin_tol and abs(yaw_dst) < self.appr_yaw_tol:
self.finish_approach()
self.lock.release()
def __init__(self):
self.lock = Lock()
self.low_battery = False
self.force_docking = False
self.approach_active = False
self.state = DockState.idle
self.last_force = rospy.Time()
rospy.init_node('dock_generator')
rospy.loginfo('waiting for add desire to be availble')
rospy.wait_for_service('/hbba/add_desires')
self.add_desire = rospy.ServiceProxy(
'/hbba/add_desires',
AddDesires)
rospy.loginfo('add desire registered')
rospy.loginfo('waiting for remove desire to be availbe')
rospy.wait_for_service('/hbba/remove_desires')
self.rem_desire = rospy.ServiceProxy(
'/hbba/remove_desires',
RemoveDesires)
rospy.loginfo('remove desire registered')
self.map_frame = rospy.get_param('~map_frame', 'map')
self.robot_frame = rospy.get_param('~robot_frame', 'base_footprint')
self.appr_lin_tol = rospy.get_param('~appr_lin_tol', 0.40)
self.appr_yaw_tol = rospy.get_param('~appr_yaw_tol', 0.1)
self.min_percent = rospy.get_param('~min_percent', 30)
self.charge_percent = rospy.get_param('~charge_percent', 80)
self.undock_time = rospy.get_param('~undock_time', 4.0)
self.force_timeout = rospy.get_param('~force_timeout', 10.0)
self.approach_goal = dict()
self.approach_goal['x'] = rospy.get_param('approach/x', 0.0)
self.approach_goal['y'] = rospy.get_param('approach/y', 0.0)
self.approach_goal['t'] = rospy.get_param('approach/t', 0.0)
self.approach_goal['frame_id'] = self.map_frame
self.approach_desire = Desire()
self.approach_desire.id = 'dock_approach'
self.approach_desire.type = 'GoTo'
self.approach_desire.intensity = 1
self.approach_desire.utility = 1
self.approach_desire.security = False
self.dock_desire = Desire()
self.dock_desire.id = 'dock_dock'
self.dock_desire.type = 'Dock'
self.dock_desire.intensity = 1
self.dock_desire.utility = 1
self.dock_desire.security = False
self.loiter_desire = Desire()
self.loiter_desire.id = 'dock_charge'
self.loiter_desire.type = 'Loiter'
self.loiter_desire.intensity = 1
self.loiter_desire.utility = 1
self.loiter_desire.security = False
params = dict()
params['t'] = self.undock_time
self.loiter_desire.params = json.dumps(params)
def node():
generator_node = DockGenerator()
generator_node.run()
if __name__ == '__main__':
node()
| true | true |
f716825448eb20eaa87e600968288d77efb47ddf | 14,659 | py | Python | dataReader.py | tsfw/yolov3 | bf6d03d9a84a0ac1e94bcc4f9a026f7d32dfbdab | [
"Apache-2.0"
] | null | null | null | dataReader.py | tsfw/yolov3 | bf6d03d9a84a0ac1e94bcc4f9a026f7d32dfbdab | [
"Apache-2.0"
] | null | null | null | dataReader.py | tsfw/yolov3 | bf6d03d9a84a0ac1e94bcc4f9a026f7d32dfbdab | [
"Apache-2.0"
] | null | null | null | import os
import config
import json
import tensorflow as tf
import numpy as np
from collections import defaultdict
class Reader:
def __init__(self, mode, data_dir, anchors_path, num_classes, tfrecord_num = 12, input_shape = 416, max_boxes = 20):
"""
Introduction
------------
构造函数
Parameters
----------
data_dir: 文件路径
mode: 数据集模式
anchors: 数据集聚类得到的anchor
num_classes: 数据集图片类别数量
input_shape: 图像输入模型的大小
max_boxes: 每张图片最大的box数量
jitter: 随机长宽比系数
hue: 调整hsv颜色空间系数
sat: 调整饱和度系数
cont: 调整对比度系数
bri: 调整亮度系数
"""
self.data_dir = data_dir
self.input_shape = input_shape
self.max_boxes = max_boxes
self.mode = mode
self.annotations_file = {'train' : config.train_annotations_file, 'val' : config.val_annotations_file}
self.data_file = {'train': config.train_data_file, 'val': config.val_data_file}
self.anchors_path = anchors_path
self.anchors = self._get_anchors()
self.num_classes = num_classes
file_pattern = self.data_dir + "/*" + self.mode + '.tfrecords'
self.TfrecordFile = tf.gfile.Glob(file_pattern)
self.class_names = self._get_class(config.classes_path)
if len(self.TfrecordFile) == 0:
self.convert_to_tfrecord(self.data_dir, tfrecord_num)
def _get_anchors(self):
"""
Introduction
------------
获取anchors
Returns
-------
anchors: anchor数组
"""
anchors_path = os.path.expanduser(self.anchors_path)
with open(anchors_path) as f:
anchors = f.readline()
anchors = [float(x) for x in anchors.split(',')]
return np.array(anchors).reshape(-1, 2)
def _get_class(self, classes_path):
"""
Introduction
------------
获取类别名字
Returns
-------
class_names: coco数据集类别对应的名字
"""
classes_path = os.path.expanduser(classes_path)
with open(classes_path) as f:
class_names = f.readlines()
class_names = [c.strip() for c in class_names]
return class_names
def Preprocess_true_boxes(self, true_boxes):
"""
Introduction
------------
对训练数据的ground truth box进行预处理
Parameters
----------
true_boxes: ground truth box 形状为[boxes, 5], x_min, y_min, x_max, y_max, class_id
"""
num_layers = len(self.anchors) // 3
anchor_mask = [[6, 7, 8], [3, 4, 5], [0, 1, 2]]
true_boxes = np.array(true_boxes, dtype='float32')
input_shape = np.array([self.input_shape, self.input_shape], dtype='int32')
boxes_xy = (true_boxes[..., 0:2] + true_boxes[..., 2:4]) // 2.
boxes_wh = true_boxes[..., 2:4] - true_boxes[..., 0:2]
true_boxes[..., 0:2] = boxes_xy / input_shape[::-1]
true_boxes[..., 2:4] = boxes_wh / input_shape[::-1]
grid_shapes = [input_shape // 32, input_shape // 16, input_shape // 8]
y_true = [np.zeros((grid_shapes[l][0], grid_shapes[l][1], len(anchor_mask[l]), 5 + self.num_classes), dtype='float32') for l in range(num_layers)]
# 这里扩充维度是为了后面应用广播计算每个图中所有box的anchor互相之间的iou
anchors = np.expand_dims(self.anchors, 0)
anchors_max = anchors / 2.
anchors_min = -anchors_max
# 因为之前对box做了padding, 因此需要去除全0行
valid_mask = boxes_wh[..., 0] > 0
wh = boxes_wh[valid_mask]
# 为了应用广播扩充维度
wh = np.expand_dims(wh, -2)
# wh 的shape为[box_num, 1, 2]
boxes_max = wh / 2.
boxes_min = -boxes_max
intersect_min = np.maximum(boxes_min, anchors_min)
intersect_max = np.minimum(boxes_max, anchors_max)
intersect_wh = np.maximum(intersect_max - intersect_min, 0.)
intersect_area = intersect_wh[..., 0] * intersect_wh[..., 1]
box_area = wh[..., 0] * wh[..., 1]
anchor_area = anchors[..., 0] * anchors[..., 1]
iou = intersect_area / (box_area + anchor_area - intersect_area)
# 找出和ground truth box的iou最大的anchor box, 然后将对应不同比例的负责该ground turth box 的位置置为ground truth box坐标
best_anchor = np.argmax(iou, axis = -1)
for t, n in enumerate(best_anchor):
for l in range(num_layers):
if n in anchor_mask[l]:
i = np.floor(true_boxes[t, 0] * grid_shapes[l][1]).astype('int32')
j = np.floor(true_boxes[t, 1] * grid_shapes[l][0]).astype('int32')
k = anchor_mask[l].index(n)
c = true_boxes[t, 4].astype('int32')
y_true[l][j, i, k, 0:4] = true_boxes[t, 0:4]
y_true[l][j, i, k, 4] = 1.
y_true[l][j, i, k, 5 + c] = 1.
return y_true[0], y_true[1], y_true[2]
def read_annotations(self):
"""
Introduction
------------
读取COCO数据集图片路径和对应的标注
Parameters
----------
data_file: 文件路径
"""
image_data = []
boxes_data = []
name_box_id = defaultdict(list)
with open(self.annotations_file[self.mode], encoding='utf-8') as file:
data = json.load(file)
annotations = data['annotations']
for ant in annotations:
id = ant['image_id']
name = os.path.join(self.data_file[self.mode], '%012d.jpg' % id)
cat = ant['category_id']
if cat >= 1 and cat <= 11:
cat = cat - 1
elif cat >= 13 and cat <= 25:
cat = cat - 2
elif cat >= 27 and cat <= 28:
cat = cat - 3
elif cat >= 31 and cat <= 44:
cat = cat - 5
elif cat >= 46 and cat <= 65:
cat = cat - 6
elif cat == 67:
cat = cat - 7
elif cat == 70:
cat = cat - 9
elif cat >= 72 and cat <= 82:
cat = cat - 10
elif cat >= 84 and cat <= 90:
cat = cat - 11
name_box_id[name].append([ant['bbox'], cat])
for key in name_box_id.keys():
boxes = []
image_data.append(key)
box_infos = name_box_id[key]
for info in box_infos:
x_min = info[0][0]
y_min = info[0][1]
x_max = x_min + info[0][2]
y_max = y_min + info[0][3]
boxes.append(np.array([x_min, y_min, x_max, y_max, info[1]]))
boxes_data.append(np.array(boxes))
return image_data, boxes_data
def convert_to_tfrecord(self, tfrecord_path, num_tfrecords):
"""
Introduction
------------
将图片和boxes数据存储为tfRecord
Parameters
----------
tfrecord_path: tfrecord文件存储路径
num_tfrecords: 分成多少个tfrecord
"""
image_data, boxes_data = self.read_annotations()
images_num = int(len(image_data) / num_tfrecords)
for index_records in range(num_tfrecords):
output_file = os.path.join(tfrecord_path, str(index_records) + '_' + self.mode + '.tfrecords')
with tf.python_io.TFRecordWriter(output_file) as record_writer:
for index in range(index_records * images_num, (index_records + 1) * images_num):
with tf.gfile.FastGFile(image_data[index], 'rb') as file:
image = file.read()
xmin, xmax, ymin, ymax, label = [], [], [], [], []
for box in boxes_data[index]:
xmin.append(box[0])
ymin.append(box[1])
xmax.append(box[2])
ymax.append(box[3])
label.append(box[4])
example = tf.train.Example(features = tf.train.Features(
feature = {
'image/encoded' : tf.train.Feature(bytes_list = tf.train.BytesList(value = [image])),
'image/object/bbox/xmin' : tf.train.Feature(float_list = tf.train.FloatList(value = xmin)),
'image/object/bbox/xmax': tf.train.Feature(float_list = tf.train.FloatList(value = xmax)),
'image/object/bbox/ymin': tf.train.Feature(float_list = tf.train.FloatList(value = ymin)),
'image/object/bbox/ymax': tf.train.Feature(float_list = tf.train.FloatList(value = ymax)),
'image/object/bbox/label': tf.train.Feature(float_list = tf.train.FloatList(value = label)),
}
))
record_writer.write(example.SerializeToString())
if index % 1000 == 0:
print('Processed {} of {} images'.format(index + 1, len(image_data)))
def parser(self, serialized_example):
"""
Introduction
------------
解析tfRecord数据
Parameters
----------
serialized_example: 序列化的每条数据
"""
features = tf.parse_single_example(
serialized_example,
features = {
'image/encoded' : tf.FixedLenFeature([], dtype = tf.string),
'image/object/bbox/xmin' : tf.VarLenFeature(dtype = tf.float32),
'image/object/bbox/xmax': tf.VarLenFeature(dtype = tf.float32),
'image/object/bbox/ymin': tf.VarLenFeature(dtype = tf.float32),
'image/object/bbox/ymax': tf.VarLenFeature(dtype = tf.float32),
'image/object/bbox/label': tf.VarLenFeature(dtype = tf.float32)
}
)
image = tf.image.decode_jpeg(features['image/encoded'], channels = 3)
image = tf.image.convert_image_dtype(image, tf.uint8)
xmin = tf.expand_dims(features['image/object/bbox/xmin'].values, axis = 0)
ymin = tf.expand_dims(features['image/object/bbox/ymin'].values, axis = 0)
xmax = tf.expand_dims(features['image/object/bbox/xmax'].values, axis = 0)
ymax = tf.expand_dims(features['image/object/bbox/ymax'].values, axis = 0)
label = tf.expand_dims(features['image/object/bbox/label'].values, axis = 0)
bbox = tf.concat(axis = 0, values = [xmin, ymin, xmax, ymax, label])
bbox = tf.transpose(bbox, [1, 0])
image, bbox = self.Preprocess(image, bbox)
bbox_true_13, bbox_true_26, bbox_true_52 = tf.py_func(self.Preprocess_true_boxes, [bbox], [tf.float32, tf.float32, tf.float32])
return image, bbox, bbox_true_13, bbox_true_26, bbox_true_52
def Preprocess(self, image, bbox):
"""
Introduction
------------
对图片进行预处理,增强数据集
Parameters
----------
image: tensorflow解析的图片
bbox: 图片中对应的box坐标
"""
image_width, image_high = tf.cast(tf.shape(image)[1], tf.float32), tf.cast(tf.shape(image)[0], tf.float32)
input_width = tf.cast(self.input_shape, tf.float32)
input_high = tf.cast(self.input_shape, tf.float32)
new_high = image_high * tf.minimum(input_width / image_width, input_high / image_high)
new_width = image_width * tf.minimum(input_width / image_width, input_high / image_high)
# 将图片按照固定长宽比进行padding缩放
dx = (input_width - new_width) / 2
dy = (input_high - new_high) / 2
image = tf.image.resize_images(image, [tf.cast(new_high, tf.int32), tf.cast(new_width, tf.int32)], method = tf.image.ResizeMethod.BICUBIC)
new_image = tf.image.pad_to_bounding_box(image, tf.cast(dy, tf.int32), tf.cast(dx, tf.int32), tf.cast(input_high, tf.int32), tf.cast(input_width, tf.int32))
image_ones = tf.ones_like(image)
image_ones_padded = tf.image.pad_to_bounding_box(image_ones, tf.cast(dy, tf.int32), tf.cast(dx, tf.int32), tf.cast(input_high, tf.int32), tf.cast(input_width, tf.int32))
image_color_padded = (1 - image_ones_padded) * 128
image = image_color_padded + new_image
# 矫正bbox坐标
xmin, ymin, xmax, ymax, label = tf.split(value = bbox, num_or_size_splits=5, axis = 1)
xmin = xmin * new_width / image_width + dx
xmax = xmax * new_width / image_width + dx
ymin = ymin * new_high / image_high + dy
ymax = ymax * new_high / image_high + dy
bbox = tf.concat([xmin, ymin, xmax, ymax, label], 1)
if self.mode == 'train':
# 随机左右翻转图片
def _flip_left_right_boxes(boxes):
xmin, ymin, xmax, ymax, label = tf.split(value = boxes, num_or_size_splits = 5, axis = 1)
flipped_xmin = tf.subtract(input_width, xmax)
flipped_xmax = tf.subtract(input_width, xmin)
flipped_boxes = tf.concat([flipped_xmin, ymin, flipped_xmax, ymax, label], 1)
return flipped_boxes
flip_left_right = tf.greater(tf.random_uniform([], dtype = tf.float32, minval = 0, maxval = 1), 0.5)
image = tf.cond(flip_left_right, lambda : tf.image.flip_left_right(image), lambda : image)
bbox = tf.cond(flip_left_right, lambda: _flip_left_right_boxes(bbox), lambda: bbox)
# 将图片归一化到0和1之间
image = image / 255.
image = tf.clip_by_value(image, clip_value_min = 0.0, clip_value_max = 1.0)
bbox = tf.clip_by_value(bbox, clip_value_min = 0, clip_value_max = input_width - 1)
bbox = tf.cond(tf.greater(tf.shape(bbox)[0], config.max_boxes), lambda: bbox[:config.max_boxes], lambda: tf.pad(bbox, paddings = [[0, config.max_boxes - tf.shape(bbox)[0]], [0, 0]], mode = 'CONSTANT'))
return image, bbox
def build_dataset(self, batch_size):
"""
Introduction
------------
建立数据集dataset
Parameters
----------
batch_size: batch大小
Return
------
dataset: 返回tensorflow的dataset
"""
dataset = tf.data.TFRecordDataset(filenames = self.TfrecordFile)
dataset = dataset.map(self.parser, num_parallel_calls = 10)
if self.mode == 'train':
dataset = dataset.repeat().shuffle(9000).batch(batch_size).prefetch(batch_size)
else:
dataset = dataset.repeat().batch(batch_size).prefetch(batch_size)
return dataset
| 44.966258 | 209 | 0.548469 | import os
import config
import json
import tensorflow as tf
import numpy as np
from collections import defaultdict
class Reader:
def __init__(self, mode, data_dir, anchors_path, num_classes, tfrecord_num = 12, input_shape = 416, max_boxes = 20):
self.data_dir = data_dir
self.input_shape = input_shape
self.max_boxes = max_boxes
self.mode = mode
self.annotations_file = {'train' : config.train_annotations_file, 'val' : config.val_annotations_file}
self.data_file = {'train': config.train_data_file, 'val': config.val_data_file}
self.anchors_path = anchors_path
self.anchors = self._get_anchors()
self.num_classes = num_classes
file_pattern = self.data_dir + "/*" + self.mode + '.tfrecords'
self.TfrecordFile = tf.gfile.Glob(file_pattern)
self.class_names = self._get_class(config.classes_path)
if len(self.TfrecordFile) == 0:
self.convert_to_tfrecord(self.data_dir, tfrecord_num)
def _get_anchors(self):
anchors_path = os.path.expanduser(self.anchors_path)
with open(anchors_path) as f:
anchors = f.readline()
anchors = [float(x) for x in anchors.split(',')]
return np.array(anchors).reshape(-1, 2)
def _get_class(self, classes_path):
classes_path = os.path.expanduser(classes_path)
with open(classes_path) as f:
class_names = f.readlines()
class_names = [c.strip() for c in class_names]
return class_names
def Preprocess_true_boxes(self, true_boxes):
num_layers = len(self.anchors) // 3
anchor_mask = [[6, 7, 8], [3, 4, 5], [0, 1, 2]]
true_boxes = np.array(true_boxes, dtype='float32')
input_shape = np.array([self.input_shape, self.input_shape], dtype='int32')
boxes_xy = (true_boxes[..., 0:2] + true_boxes[..., 2:4]) // 2.
boxes_wh = true_boxes[..., 2:4] - true_boxes[..., 0:2]
true_boxes[..., 0:2] = boxes_xy / input_shape[::-1]
true_boxes[..., 2:4] = boxes_wh / input_shape[::-1]
grid_shapes = [input_shape // 32, input_shape // 16, input_shape // 8]
y_true = [np.zeros((grid_shapes[l][0], grid_shapes[l][1], len(anchor_mask[l]), 5 + self.num_classes), dtype='float32') for l in range(num_layers)]
anchors = np.expand_dims(self.anchors, 0)
anchors_max = anchors / 2.
anchors_min = -anchors_max
valid_mask = boxes_wh[..., 0] > 0
wh = boxes_wh[valid_mask]
wh = np.expand_dims(wh, -2)
boxes_max = wh / 2.
boxes_min = -boxes_max
intersect_min = np.maximum(boxes_min, anchors_min)
intersect_max = np.minimum(boxes_max, anchors_max)
intersect_wh = np.maximum(intersect_max - intersect_min, 0.)
intersect_area = intersect_wh[..., 0] * intersect_wh[..., 1]
box_area = wh[..., 0] * wh[..., 1]
anchor_area = anchors[..., 0] * anchors[..., 1]
iou = intersect_area / (box_area + anchor_area - intersect_area)
best_anchor = np.argmax(iou, axis = -1)
for t, n in enumerate(best_anchor):
for l in range(num_layers):
if n in anchor_mask[l]:
i = np.floor(true_boxes[t, 0] * grid_shapes[l][1]).astype('int32')
j = np.floor(true_boxes[t, 1] * grid_shapes[l][0]).astype('int32')
k = anchor_mask[l].index(n)
c = true_boxes[t, 4].astype('int32')
y_true[l][j, i, k, 0:4] = true_boxes[t, 0:4]
y_true[l][j, i, k, 4] = 1.
y_true[l][j, i, k, 5 + c] = 1.
return y_true[0], y_true[1], y_true[2]
def read_annotations(self):
image_data = []
boxes_data = []
name_box_id = defaultdict(list)
with open(self.annotations_file[self.mode], encoding='utf-8') as file:
data = json.load(file)
annotations = data['annotations']
for ant in annotations:
id = ant['image_id']
name = os.path.join(self.data_file[self.mode], '%012d.jpg' % id)
cat = ant['category_id']
if cat >= 1 and cat <= 11:
cat = cat - 1
elif cat >= 13 and cat <= 25:
cat = cat - 2
elif cat >= 27 and cat <= 28:
cat = cat - 3
elif cat >= 31 and cat <= 44:
cat = cat - 5
elif cat >= 46 and cat <= 65:
cat = cat - 6
elif cat == 67:
cat = cat - 7
elif cat == 70:
cat = cat - 9
elif cat >= 72 and cat <= 82:
cat = cat - 10
elif cat >= 84 and cat <= 90:
cat = cat - 11
name_box_id[name].append([ant['bbox'], cat])
for key in name_box_id.keys():
boxes = []
image_data.append(key)
box_infos = name_box_id[key]
for info in box_infos:
x_min = info[0][0]
y_min = info[0][1]
x_max = x_min + info[0][2]
y_max = y_min + info[0][3]
boxes.append(np.array([x_min, y_min, x_max, y_max, info[1]]))
boxes_data.append(np.array(boxes))
return image_data, boxes_data
def convert_to_tfrecord(self, tfrecord_path, num_tfrecords):
image_data, boxes_data = self.read_annotations()
images_num = int(len(image_data) / num_tfrecords)
for index_records in range(num_tfrecords):
output_file = os.path.join(tfrecord_path, str(index_records) + '_' + self.mode + '.tfrecords')
with tf.python_io.TFRecordWriter(output_file) as record_writer:
for index in range(index_records * images_num, (index_records + 1) * images_num):
with tf.gfile.FastGFile(image_data[index], 'rb') as file:
image = file.read()
xmin, xmax, ymin, ymax, label = [], [], [], [], []
for box in boxes_data[index]:
xmin.append(box[0])
ymin.append(box[1])
xmax.append(box[2])
ymax.append(box[3])
label.append(box[4])
example = tf.train.Example(features = tf.train.Features(
feature = {
'image/encoded' : tf.train.Feature(bytes_list = tf.train.BytesList(value = [image])),
'image/object/bbox/xmin' : tf.train.Feature(float_list = tf.train.FloatList(value = xmin)),
'image/object/bbox/xmax': tf.train.Feature(float_list = tf.train.FloatList(value = xmax)),
'image/object/bbox/ymin': tf.train.Feature(float_list = tf.train.FloatList(value = ymin)),
'image/object/bbox/ymax': tf.train.Feature(float_list = tf.train.FloatList(value = ymax)),
'image/object/bbox/label': tf.train.Feature(float_list = tf.train.FloatList(value = label)),
}
))
record_writer.write(example.SerializeToString())
if index % 1000 == 0:
print('Processed {} of {} images'.format(index + 1, len(image_data)))
def parser(self, serialized_example):
features = tf.parse_single_example(
serialized_example,
features = {
'image/encoded' : tf.FixedLenFeature([], dtype = tf.string),
'image/object/bbox/xmin' : tf.VarLenFeature(dtype = tf.float32),
'image/object/bbox/xmax': tf.VarLenFeature(dtype = tf.float32),
'image/object/bbox/ymin': tf.VarLenFeature(dtype = tf.float32),
'image/object/bbox/ymax': tf.VarLenFeature(dtype = tf.float32),
'image/object/bbox/label': tf.VarLenFeature(dtype = tf.float32)
}
)
image = tf.image.decode_jpeg(features['image/encoded'], channels = 3)
image = tf.image.convert_image_dtype(image, tf.uint8)
xmin = tf.expand_dims(features['image/object/bbox/xmin'].values, axis = 0)
ymin = tf.expand_dims(features['image/object/bbox/ymin'].values, axis = 0)
xmax = tf.expand_dims(features['image/object/bbox/xmax'].values, axis = 0)
ymax = tf.expand_dims(features['image/object/bbox/ymax'].values, axis = 0)
label = tf.expand_dims(features['image/object/bbox/label'].values, axis = 0)
bbox = tf.concat(axis = 0, values = [xmin, ymin, xmax, ymax, label])
bbox = tf.transpose(bbox, [1, 0])
image, bbox = self.Preprocess(image, bbox)
bbox_true_13, bbox_true_26, bbox_true_52 = tf.py_func(self.Preprocess_true_boxes, [bbox], [tf.float32, tf.float32, tf.float32])
return image, bbox, bbox_true_13, bbox_true_26, bbox_true_52
def Preprocess(self, image, bbox):
image_width, image_high = tf.cast(tf.shape(image)[1], tf.float32), tf.cast(tf.shape(image)[0], tf.float32)
input_width = tf.cast(self.input_shape, tf.float32)
input_high = tf.cast(self.input_shape, tf.float32)
new_high = image_high * tf.minimum(input_width / image_width, input_high / image_high)
new_width = image_width * tf.minimum(input_width / image_width, input_high / image_high)
dx = (input_width - new_width) / 2
dy = (input_high - new_high) / 2
image = tf.image.resize_images(image, [tf.cast(new_high, tf.int32), tf.cast(new_width, tf.int32)], method = tf.image.ResizeMethod.BICUBIC)
new_image = tf.image.pad_to_bounding_box(image, tf.cast(dy, tf.int32), tf.cast(dx, tf.int32), tf.cast(input_high, tf.int32), tf.cast(input_width, tf.int32))
image_ones = tf.ones_like(image)
image_ones_padded = tf.image.pad_to_bounding_box(image_ones, tf.cast(dy, tf.int32), tf.cast(dx, tf.int32), tf.cast(input_high, tf.int32), tf.cast(input_width, tf.int32))
image_color_padded = (1 - image_ones_padded) * 128
image = image_color_padded + new_image
xmin, ymin, xmax, ymax, label = tf.split(value = bbox, num_or_size_splits=5, axis = 1)
xmin = xmin * new_width / image_width + dx
xmax = xmax * new_width / image_width + dx
ymin = ymin * new_high / image_high + dy
ymax = ymax * new_high / image_high + dy
bbox = tf.concat([xmin, ymin, xmax, ymax, label], 1)
if self.mode == 'train':
def _flip_left_right_boxes(boxes):
xmin, ymin, xmax, ymax, label = tf.split(value = boxes, num_or_size_splits = 5, axis = 1)
flipped_xmin = tf.subtract(input_width, xmax)
flipped_xmax = tf.subtract(input_width, xmin)
flipped_boxes = tf.concat([flipped_xmin, ymin, flipped_xmax, ymax, label], 1)
return flipped_boxes
flip_left_right = tf.greater(tf.random_uniform([], dtype = tf.float32, minval = 0, maxval = 1), 0.5)
image = tf.cond(flip_left_right, lambda : tf.image.flip_left_right(image), lambda : image)
bbox = tf.cond(flip_left_right, lambda: _flip_left_right_boxes(bbox), lambda: bbox)
image = image / 255.
image = tf.clip_by_value(image, clip_value_min = 0.0, clip_value_max = 1.0)
bbox = tf.clip_by_value(bbox, clip_value_min = 0, clip_value_max = input_width - 1)
bbox = tf.cond(tf.greater(tf.shape(bbox)[0], config.max_boxes), lambda: bbox[:config.max_boxes], lambda: tf.pad(bbox, paddings = [[0, config.max_boxes - tf.shape(bbox)[0]], [0, 0]], mode = 'CONSTANT'))
return image, bbox
def build_dataset(self, batch_size):
dataset = tf.data.TFRecordDataset(filenames = self.TfrecordFile)
dataset = dataset.map(self.parser, num_parallel_calls = 10)
if self.mode == 'train':
dataset = dataset.repeat().shuffle(9000).batch(batch_size).prefetch(batch_size)
else:
dataset = dataset.repeat().batch(batch_size).prefetch(batch_size)
return dataset
| true | true |
f71684275afc20018793ca67d49712a2693a0850 | 10,212 | py | Python | a3c_master_sewak.py | sebtac/MLxE | 93baa6b7c9fd14e54abd7199e868fb828e9a7c52 | [
"Apache-2.0"
] | 1 | 2020-12-15T17:19:33.000Z | 2020-12-15T17:19:33.000Z | a3c_master_sewak.py | sebtac/MLxE | 93baa6b7c9fd14e54abd7199e868fb828e9a7c52 | [
"Apache-2.0"
] | null | null | null | a3c_master_sewak.py | sebtac/MLxE | 93baa6b7c9fd14e54abd7199e868fb828e9a7c52 | [
"Apache-2.0"
] | null | null | null | """ A3C in Code - Centralized/ Gobal Network Parameter Server/ Controller
Based On:
A3C Code as in the book Deep Reinforcement Learning, Chapter 12.
Runtime: Python 3.6.5
Dependencies: numpy, matplotlib, tensorflow (/ tensorflow-gpu), gym
DocStrings: GoogleStyle
Author : Mohit Sewak (p20150023@goa-bits-pilani.ac.in)
Inspired from: A3C implementation on TensorFLow official github repository (Tensorflow/models/research)
**********************************************************************
Adjusted by Seabstian Taciak as part of develeopment of MLxE Architecture
@author: sebtac
@contact: https://www.linkedin.com/in/sebastian-taciak-5893861/
"""
# SET BEFORE RUNNIG
# AGENT TYPE
# 0 - Sewak Base Agent (Fixed)
# 1 - Sewak DNN Adjusted
# 2 - Sewak "Task" Modified
# 3 - Sewak ISTB (Iterative, Synchronous Thread Based)
Agent_Type = 3
learning_rate = 0.0001
import multiprocessing
cores = multiprocessing.cpu_count() # DEFAULT SETTING
#cores = 1 # FOR DEBUGGING
# GENERAL IMPORTS
import sys
sys.path.append(r'C:\Users\surface\Documents\Python\RL\MLxE\Mohit Sewak RL\Mohit12_A3C')
import time
import winsound
import logging
import os
import numpy as np
import matplotlib.pyplot as plt
logging.basicConfig()
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# DEEP LEARING and ENVIRONEMENT RELATER IMPORTS
import tensorflow as tf
import tensorflow_addons as tfa # ST for DNN Adjustment
import gym
# CUSTOM SEWAK's MODULES with OPTIONAL SEBTAC ADJUSTMENTS
from experience_replay_sewak import SimpleListBasedMemory
if Agent_Type == 0:
from actorcritic_model_sewak import ActorCriticModel as ACModel # For Sewak Fixed version
from a3c_worker_sewak_base import A3C_Worker # the intial Sewak's implementation with fixes of the Policy_Loss Calcultion
elif Agent_Type == 1:
from actorcritic_model_sewak import ActorCriticModel_Dimond as ACModel
from a3c_worker_sewak_DNN_Adjusted import A3C_Worker
elif Agent_Type == 2:
from actorcritic_model_sewak import ActorCriticModel_Dimond as ACModel
from a3c_worker_sewak_Task_Modifications import A3C_Worker
elif Agent_Type == 3:
from actorcritic_model_sewak import ActorCriticModel_DoubleDimond as ACModel
from a3c_worker_sewak_ISTB import A3C_Worker
# SEWAK's Implementation Fix
"""
- Policy Loss Calcualtion
- Using actual play in example generation (was random)
"""
# DNN Adjustments
"""
- Adding monotonic decrease in Learing Rate relative to the number of episodes run with:
self.alpha_power = 0.998
self.alpha_limit = 0.000001
- Modifying the Model to: common_network_size=[128,256,128], policy_network_size=[64,128,64], value_network_size=[64,128,64]
- Changing the Optimizer to RectifiedAdam -- requaires tensorflow_addons
- Changing Gamma coeffcient to 0.97
"""
# Task Specific Modifications
"""
- Modified state representation with addition of 5th parameter representing the squared distance of the cart from the center of the plane
- Adverse Initial Position
- Negative Reward: -10.0 (originally 0.0)
- Monotonically Decreasing Discount Factor (Gamma Coefficent)
- Goal Specific Reward for cart being close to center of the pland and the pole being close to vertical
"""
class A3C_Master():
"""A3C Master
Centralized Master class of A3C used for hosting the global network parameters and spawning the agents.
Args:
env_name (str): Name of a valid gym environment
model_dir (str): Directory for saving the model during training, and loading the same while playing
learning_rate (float): The learning rate (alpha) for the optimizer
Examples:
agent = A3C_Master()
agent.train()
agent.play()
"""
def __init__(self, Agent_Type=Agent_Type, env_name='CartPole-v0', model_dir="models", learning_rate=learning_rate): #ST 0.001 for Fixed, 0.0001 otherwise
self.env_name = env_name
self.model_dir = model_dir
self.alpha = learning_rate
if not os.path.exists(model_dir):
os.makedirs(model_dir)
self.env = gym.make(self.env_name)
self.action_size = self.env.action_space.n
if Agent_Type <= 1:
self.state_size = self.env.observation_space.shape[0] # For None TaH imlementations
elif Agent_Type == 2:
self.state_size = self.env.observation_space.shape[0] + 1 # ST for TaH implementation
elif Agent_Type == 3:
self.state_size = self.env.observation_space.shape[0] + 1 # ST for TaH implementation
if Agent_Type == 0:
self.optimizer = tf.keras.optimizers.Adam(self.alpha)
else:
self.optimizer = tfa.optimizers.RectifiedAdam(self.alpha) # ST DNN Adjustment
logger.debug("StateSize:{}, ActionSize:{}".format(self.state_size, self.action_size))
self.master_model = ACModel(self.action_size)
self.master_model(tf.convert_to_tensor(np.random.random((1, self.state_size)), dtype=tf.float32))
def train(self, cores):
"""Train the A3C agent
Main function to train the A3C agent after instantiation.
This method uses the number of processor cores to spawns as many Workers. The workers are spawned as
multiple parallel threads instead of multiple parallel processes. Being a threaded execution, the workers
share memory and hence can write directly into the shared global variables.
A more optimal, completely asynchronous implementation could be to spawn the workers as different processes
using a task queue or multiprocessing. In case if this is adopted, then the shared variables need to made
accessible in the distributed environment.
"""
a3c_workers = [A3C_Worker(self.master_model,
self.optimizer,
i,
self.env_name,
self.model_dir,
workers_num = cores,
learning_rate = learning_rate)
for i in range(cores)]
for i, worker in enumerate(a3c_workers):
logger.info("Starting worker {}".format(i))
worker.start()
[worker.join() for worker in a3c_workers]
self.plot_training_statistics()
def play(self):
"""Play the environment using a trained agent
This function opens a (graphical) window that will play a trained agent. The function will try to retrieve
the model saved in the model_dir with filename formatted to contain the associated env_name.
If the model is not found, then the function will first call the train function to start the training.
"""
env = self.env.unwrapped
state = env.reset()
model = self.master_model
model_path = os.path.join(self.model_dir, 'model_{}.h5'.format(self.env_name))
if not os.path.exists(model_path):
logger.info('A3CMaster: No model found at {}, starting fresh training before playing!'.format(model_path))
self.train()
logger.info('A3CMaster: Playing env, Loading model from: {}'.format(model_path))
print("Model Path:", model_path)
#model.load_weights(model_path)
done = False
step_counter = 0
reward_sum = 0
try:
while not done:
env.render(mode='rgb_array')
policy, value = model(tf.convert_to_tensor(state[None, :], dtype=tf.float32))
policy = tf.nn.softmax(policy)
action = np.argmax(policy)
state, reward, done, _ = env.step(action)
reward_sum += reward
logger.info("{}. Reward: {}, action: {}".format(step_counter, reward_sum, action))
step_counter += 1
except KeyboardInterrupt:
print("Received Keyboard Interrupt. Shutting down.")
finally:
env.close()
def plot_training_statistics(self, training_statistics=None):
"""Plot training statistics
This function plot the training statistics like the steps, rewards, discounted_rewards, and loss in each
of the training episode.
"""
training_statistics = A3C_Worker.global_shared_training_stats if training_statistics is None \
else training_statistics
all_episodes = []
all_steps = []
all_rewards = []
all_discounted_rewards = []
all_losses = []
for stats in training_statistics:
worker, episode, steps, reward, discounted_rewards, loss = stats
all_episodes.append(episode)
all_steps.append(steps)
all_rewards.append(reward)
all_discounted_rewards.append(discounted_rewards)
all_losses.append(loss)
self._make_double_axis_plot(all_episodes, all_steps, all_rewards)
self._make_double_axis_plot(all_episodes,all_discounted_rewards,all_losses, label_y1="Discounted Reward",
label_y2="Loss", color_y1="cyan", color_y2="black")
np.savetxt('run.csv', all_steps, delimiter=',', fmt='%d')
@staticmethod
def _make_double_axis_plot(data_x, data_y1, data_y2, x_label='Episodes (e)', label_y1='Steps To Episode Completion',
label_y2='Reward in each Episode', color_y1="red", color_y2="blue"):
"""Internal helper function for plotting dual axis plots
"""
fig, ax1 = plt.subplots()
ax1.set_xlabel(x_label)
ax1.set_ylabel(label_y1, color=color_y1)
ax1.plot(data_x, data_y1, color=color_y1)
ax2 = ax1.twinx()
ax2.set_ylabel(label_y2, color=color_y2)
ax2.plot(data_x, data_y2, color=color_y2)
fig.tight_layout()
plt.show()
if __name__ == "__main__":
"""Main function for testing the A3C Master code's implementation
"""
agent = A3C_Master(Agent_Type=Agent_Type)
agent.train(cores)
#agent.play()
for i in range(10):
winsound.Beep(500,500)
| 39.890625 | 158 | 0.665785 |
Agent_Type = 3
learning_rate = 0.0001
import multiprocessing
cores = multiprocessing.cpu_count()
ys.path.append(r'C:\Users\surface\Documents\Python\RL\MLxE\Mohit Sewak RL\Mohit12_A3C')
import time
import winsound
import logging
import os
import numpy as np
import matplotlib.pyplot as plt
logging.basicConfig()
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
import tensorflow as tf
import tensorflow_addons as tfa
import gym
from experience_replay_sewak import SimpleListBasedMemory
if Agent_Type == 0:
from actorcritic_model_sewak import ActorCriticModel as ACModel # For Sewak Fixed version
from a3c_worker_sewak_base import A3C_Worker # the intial Sewak's implementation with fixes of the Policy_Loss Calcultion
elif Agent_Type == 1:
from actorcritic_model_sewak import ActorCriticModel_Dimond as ACModel
from a3c_worker_sewak_DNN_Adjusted import A3C_Worker
elif Agent_Type == 2:
from actorcritic_model_sewak import ActorCriticModel_Dimond as ACModel
from a3c_worker_sewak_Task_Modifications import A3C_Worker
elif Agent_Type == 3:
from actorcritic_model_sewak import ActorCriticModel_DoubleDimond as ACModel
from a3c_worker_sewak_ISTB import A3C_Worker
# DNN Adjustments
# Task Specific Modifications
class A3C_Master():
def __init__(self, Agent_Type=Agent_Type, env_name='CartPole-v0', model_dir="models", learning_rate=learning_rate): #ST 0.001 for Fixed, 0.0001 otherwise
self.env_name = env_name
self.model_dir = model_dir
self.alpha = learning_rate
if not os.path.exists(model_dir):
os.makedirs(model_dir)
self.env = gym.make(self.env_name)
self.action_size = self.env.action_space.n
if Agent_Type <= 1:
self.state_size = self.env.observation_space.shape[0] # For None TaH imlementations
elif Agent_Type == 2:
self.state_size = self.env.observation_space.shape[0] + 1 # ST for TaH implementation
elif Agent_Type == 3:
self.state_size = self.env.observation_space.shape[0] + 1 # ST for TaH implementation
if Agent_Type == 0:
self.optimizer = tf.keras.optimizers.Adam(self.alpha)
else:
self.optimizer = tfa.optimizers.RectifiedAdam(self.alpha) # ST DNN Adjustment
logger.debug("StateSize:{}, ActionSize:{}".format(self.state_size, self.action_size))
self.master_model = ACModel(self.action_size)
self.master_model(tf.convert_to_tensor(np.random.random((1, self.state_size)), dtype=tf.float32))
def train(self, cores):
a3c_workers = [A3C_Worker(self.master_model,
self.optimizer,
i,
self.env_name,
self.model_dir,
workers_num = cores,
learning_rate = learning_rate)
for i in range(cores)]
for i, worker in enumerate(a3c_workers):
logger.info("Starting worker {}".format(i))
worker.start()
[worker.join() for worker in a3c_workers]
self.plot_training_statistics()
def play(self):
env = self.env.unwrapped
state = env.reset()
model = self.master_model
model_path = os.path.join(self.model_dir, 'model_{}.h5'.format(self.env_name))
if not os.path.exists(model_path):
logger.info('A3CMaster: No model found at {}, starting fresh training before playing!'.format(model_path))
self.train()
logger.info('A3CMaster: Playing env, Loading model from: {}'.format(model_path))
print("Model Path:", model_path)
#model.load_weights(model_path)
done = False
step_counter = 0
reward_sum = 0
try:
while not done:
env.render(mode='rgb_array')
policy, value = model(tf.convert_to_tensor(state[None, :], dtype=tf.float32))
policy = tf.nn.softmax(policy)
action = np.argmax(policy)
state, reward, done, _ = env.step(action)
reward_sum += reward
logger.info("{}. Reward: {}, action: {}".format(step_counter, reward_sum, action))
step_counter += 1
except KeyboardInterrupt:
print("Received Keyboard Interrupt. Shutting down.")
finally:
env.close()
def plot_training_statistics(self, training_statistics=None):
training_statistics = A3C_Worker.global_shared_training_stats if training_statistics is None \
else training_statistics
all_episodes = []
all_steps = []
all_rewards = []
all_discounted_rewards = []
all_losses = []
for stats in training_statistics:
worker, episode, steps, reward, discounted_rewards, loss = stats
all_episodes.append(episode)
all_steps.append(steps)
all_rewards.append(reward)
all_discounted_rewards.append(discounted_rewards)
all_losses.append(loss)
self._make_double_axis_plot(all_episodes, all_steps, all_rewards)
self._make_double_axis_plot(all_episodes,all_discounted_rewards,all_losses, label_y1="Discounted Reward",
label_y2="Loss", color_y1="cyan", color_y2="black")
np.savetxt('run.csv', all_steps, delimiter=',', fmt='%d')
@staticmethod
def _make_double_axis_plot(data_x, data_y1, data_y2, x_label='Episodes (e)', label_y1='Steps To Episode Completion',
label_y2='Reward in each Episode', color_y1="red", color_y2="blue"):
fig, ax1 = plt.subplots()
ax1.set_xlabel(x_label)
ax1.set_ylabel(label_y1, color=color_y1)
ax1.plot(data_x, data_y1, color=color_y1)
ax2 = ax1.twinx()
ax2.set_ylabel(label_y2, color=color_y2)
ax2.plot(data_x, data_y2, color=color_y2)
fig.tight_layout()
plt.show()
if __name__ == "__main__":
agent = A3C_Master(Agent_Type=Agent_Type)
agent.train(cores)
#agent.play()
for i in range(10):
winsound.Beep(500,500)
| true | true |
f716847b7e7f2b74e68a21c9fff18732128dc20b | 1,196 | py | Python | examples/cdv/plttraj.py | geflaspohler/deep-OTD | 0daec276669776952b5142149007175b8a3c4d87 | [
"MIT"
] | 1 | 2020-07-18T02:00:50.000Z | 2020-07-18T02:00:50.000Z | examples/cdv/plttraj.py | geflaspohler/deep-OTD | 0daec276669776952b5142149007175b8a3c4d87 | [
"MIT"
] | null | null | null | examples/cdv/plttraj.py | geflaspohler/deep-OTD | 0daec276669776952b5142149007175b8a3c4d87 | [
"MIT"
] | 3 | 2019-11-28T04:15:59.000Z | 2020-03-27T16:15:36.000Z | import numpy as np
import matplotlib
from matplotlib import pyplot as plt
matplotlib.rcParams['mathtext.fontset'] = 'stix'
matplotlib.rcParams['font.size'] = 9
ndim = 6
data = np.genfromtxt('dOTD_tst1.out')
xticks = [900, 1100, 1300]
yticks = [[0.7, 0.8, 0.9, 1],
[-0.2, 0, 0.2, 0.4],
[-0.5, 0, 0.5],
[-1, -0.5, 0],
[-0.5, 0, 0.5],
[-0.5, 0, 0.5, 1]]
def latexify(ticklabels):
"""Manually set LaTeX format for tick labels."""
return [r"$" + str(label) + "$" for label in ticklabels]
for ii in range(ndim):
fig = plt.figure(figsize=(2.2,1.3), constrained_layout=True)
fig.set_constrained_layout_pads(w_pad=0, h_pad=0)
ax = plt.axes()
plt.plot(data[:,0], data[:,ii+1], 'k-', linewidth=0.75)
plt.xlabel('$t$')
plt.ylabel('$z_{' + str(ii+1) + '}$')
plt.xlim(xticks[0], xticks[-1])
plt.ylim(yticks[ii][0], yticks[ii][-1])
ax.set_xticks(xticks)
ax.set_yticks(yticks[ii])
ax.set_xticklabels(latexify(xticks))
ax.set_yticklabels(latexify(yticks[ii]))
ax.yaxis.set_label_coords(-0.2, 0.5)
ax.tick_params(direction='in', length=2)
plt.savefig('traj' + str(ii+1) + '.pdf')
| 29.170732 | 64 | 0.591137 | import numpy as np
import matplotlib
from matplotlib import pyplot as plt
matplotlib.rcParams['mathtext.fontset'] = 'stix'
matplotlib.rcParams['font.size'] = 9
ndim = 6
data = np.genfromtxt('dOTD_tst1.out')
xticks = [900, 1100, 1300]
yticks = [[0.7, 0.8, 0.9, 1],
[-0.2, 0, 0.2, 0.4],
[-0.5, 0, 0.5],
[-1, -0.5, 0],
[-0.5, 0, 0.5],
[-0.5, 0, 0.5, 1]]
def latexify(ticklabels):
return [r"$" + str(label) + "$" for label in ticklabels]
for ii in range(ndim):
fig = plt.figure(figsize=(2.2,1.3), constrained_layout=True)
fig.set_constrained_layout_pads(w_pad=0, h_pad=0)
ax = plt.axes()
plt.plot(data[:,0], data[:,ii+1], 'k-', linewidth=0.75)
plt.xlabel('$t$')
plt.ylabel('$z_{' + str(ii+1) + '}$')
plt.xlim(xticks[0], xticks[-1])
plt.ylim(yticks[ii][0], yticks[ii][-1])
ax.set_xticks(xticks)
ax.set_yticks(yticks[ii])
ax.set_xticklabels(latexify(xticks))
ax.set_yticklabels(latexify(yticks[ii]))
ax.yaxis.set_label_coords(-0.2, 0.5)
ax.tick_params(direction='in', length=2)
plt.savefig('traj' + str(ii+1) + '.pdf')
| true | true |
f7168651a64c6d1d8e833e8659ea210c7750b724 | 662 | py | Python | exercicio55Corrigido.py | adrianomdantas/Exercicios-Python | ef5025a186615258aec0cf35ed839fe49577d983 | [
"MIT"
] | null | null | null | exercicio55Corrigido.py | adrianomdantas/Exercicios-Python | ef5025a186615258aec0cf35ed839fe49577d983 | [
"MIT"
] | null | null | null | exercicio55Corrigido.py | adrianomdantas/Exercicios-Python | ef5025a186615258aec0cf35ed839fe49577d983 | [
"MIT"
] | null | null | null | '''maior = 0
menor = 0
for p in range(1, 6):
peso = float(input('digite o {}o peso '.format(p)))
if p == 1:
menor = peso
maior = peso
else:
if peso >= maior:
maior = peso
if peso < menor:
menor = peso
print('O maior peso registrado foi {:.1f}kg \nO menor peso registrado foi {:.1f}kg'.format(maior, menor))
'''
lst=[] #lista vazia
for c in range(1, 6):
peso=float(input('Peso da {}ª pessoa: '.format(c)))
lst+=[peso] #adc os valores de peso na lista
print('')
print('O Maior peso foi:', max(lst)) #maximo valor da lista
print('O Menor peso foi:', min(lst)) #minimo valor da lista
| 28.782609 | 105 | 0.575529 |
lst=[]
for c in range(1, 6):
peso=float(input('Peso da {}ª pessoa: '.format(c)))
lst+=[peso]
print('')
print('O Maior peso foi:', max(lst))
print('O Menor peso foi:', min(lst))
| true | true |
f71686608991387d6cf7844d049a4fbe7531d303 | 1,071 | py | Python | learning/set-background-image-v2.py | CrtomirJuren/pyfirmata-arduino | 020873972d119955e80387f44bcc193ad0b460a6 | [
"MIT"
] | null | null | null | learning/set-background-image-v2.py | CrtomirJuren/pyfirmata-arduino | 020873972d119955e80387f44bcc193ad0b460a6 | [
"MIT"
] | null | null | null | learning/set-background-image-v2.py | CrtomirJuren/pyfirmata-arduino | 020873972d119955e80387f44bcc193ad0b460a6 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 25 15:21:34 2021
@author: crtjur
"""
import tkinter as tk
from PIL import Image, ImageTk
root = tk.Tk()
root.title("Title")
root.geometry("280x350")
root.configure(background="black")
class Example(tk.Frame):
def __init__(self, master, *pargs):
tk.Frame.__init__(self, master, *pargs)
self.image = Image.open("diagram-v2.png")
self.img_copy= self.image.copy()
self.background_image = ImageTk.PhotoImage(self.image)
self.background = tk.Label(self, image=self.background_image)
self.background.pack(fill= tk.BOTH, expand=True) #,
self.background.bind('<Configure>', self._resize_image)
def _resize_image(self,event):
new_width = event.width
new_height = event.height
self.image = self.img_copy.resize((new_width, new_height))
self.background_image = ImageTk.PhotoImage(self.image)
self.background.configure(image = self.background_image)
e = Example(root)
e.pack(fill=tk.BOTH, expand=True)
root.mainloop() | 24.340909 | 69 | 0.674136 |
import tkinter as tk
from PIL import Image, ImageTk
root = tk.Tk()
root.title("Title")
root.geometry("280x350")
root.configure(background="black")
class Example(tk.Frame):
def __init__(self, master, *pargs):
tk.Frame.__init__(self, master, *pargs)
self.image = Image.open("diagram-v2.png")
self.img_copy= self.image.copy()
self.background_image = ImageTk.PhotoImage(self.image)
self.background = tk.Label(self, image=self.background_image)
self.background.pack(fill= tk.BOTH, expand=True)
self.background.bind('<Configure>', self._resize_image)
def _resize_image(self,event):
new_width = event.width
new_height = event.height
self.image = self.img_copy.resize((new_width, new_height))
self.background_image = ImageTk.PhotoImage(self.image)
self.background.configure(image = self.background_image)
e = Example(root)
e.pack(fill=tk.BOTH, expand=True)
root.mainloop() | true | true |
f716868e337d9c56b7761e3167f53df728c5c6c1 | 4,185 | py | Python | tools/train.py | nikhilrayaprolu/food-version2 | 5fe558ba96be34e52e48ee60bdde2298245a769e | [
"Apache-2.0"
] | null | null | null | tools/train.py | nikhilrayaprolu/food-version2 | 5fe558ba96be34e52e48ee60bdde2298245a769e | [
"Apache-2.0"
] | null | null | null | tools/train.py | nikhilrayaprolu/food-version2 | 5fe558ba96be34e52e48ee60bdde2298245a769e | [
"Apache-2.0"
] | 1 | 2020-12-22T08:38:56.000Z | 2020-12-22T08:38:56.000Z | from __future__ import division
import argparse
import os
import os.path as osp
import time
import mmcv
import torch
from mmcv import Config
from mmcv.runner import init_dist
from mmdet import __version__
from mmdet.apis import set_random_seed, train_detector
from mmdet.datasets import build_dataset
from mmdet.models import build_detector
from mmdet.utils import get_root_logger
import warnings
warnings.filterwarnings("ignore")
def parse_args():
parser = argparse.ArgumentParser(description='Train a detector')
parser.add_argument('config', help='train config file path')
parser.add_argument('--work_dir', help='the dir to save logs and models')
parser.add_argument(
'--resume_from', help='the checkpoint file to resume from')
parser.add_argument(
'--validate',
action='store_true',
help='whether to evaluate the checkpoint during training')
parser.add_argument(
'--gpus',
type=int,
default=1,
help='number of gpus to use '
'(only applicable to non-distributed training)')
parser.add_argument('--seed', type=int, default=None, help='random seed')
parser.add_argument(
'--deterministic',
action='store_true',
help='whether to set deterministic options for CUDNN backend.')
parser.add_argument(
'--launcher',
choices=['none', 'pytorch', 'slurm', 'mpi'],
default='none',
help='job launcher')
parser.add_argument('--local_rank', type=int, default=0)
parser.add_argument(
'--autoscale-lr',
action='store_true',
help='automatically scale lr with the number of gpus')
args = parser.parse_args()
if 'LOCAL_RANK' not in os.environ:
os.environ['LOCAL_RANK'] = str(args.local_rank)
return args
def main():
args = parse_args()
cfg = Config.fromfile(args.config)
# set cudnn_benchmark
if cfg.get('cudnn_benchmark', False):
torch.backends.cudnn.benchmark = True
# update configs according to CLI args
if args.work_dir is not None:
cfg.work_dir = args.work_dir
if args.resume_from is not None:
cfg.resume_from = args.resume_from
cfg.gpus = args.gpus
if args.autoscale_lr:
# apply the linear scaling rule (https://arxiv.org/abs/1706.02677)
cfg.optimizer['lr'] = cfg.optimizer['lr'] * cfg.gpus / 8
# init distributed env first, since logger depends on the dist info.
if args.launcher == 'none':
distributed = False
else:
distributed = True
init_dist(args.launcher, **cfg.dist_params)
# create work_dir
mmcv.mkdir_or_exist(osp.abspath(cfg.work_dir))
# init the logger before other steps
timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime())
log_file = osp.join(cfg.work_dir, '{}.log'.format(timestamp))
logger = get_root_logger(log_file=log_file, log_level=cfg.log_level)
# log some basic info
logger.info('Distributed training: {}'.format(distributed))
logger.info('MMDetection Version: {}'.format(__version__))
logger.info('Config:\n{}'.format(cfg.text))
# set random seeds
if args.seed is not None:
logger.info('Set random seed to {}, deterministic: {}'.format(
args.seed, args.deterministic))
set_random_seed(args.seed, deterministic=args.deterministic)
model = build_detector(
cfg.model, train_cfg=cfg.train_cfg, test_cfg=cfg.test_cfg)
datasets = [build_dataset(cfg.data.train)]
if len(cfg.workflow) == 2:
datasets.append(build_dataset(cfg.data.val))
if cfg.checkpoint_config is not None:
# save mmdet version, config file content and class names in
# checkpoints as meta data
cfg.checkpoint_config.meta = dict(
mmdet_version=__version__,
config=cfg.text,
CLASSES=datasets[0].CLASSES)
# add an attribute for visualization convenience
model.CLASSES = datasets[0].CLASSES
train_detector(
model,
datasets,
cfg,
distributed=distributed,
validate=args.validate,
timestamp=timestamp)
if __name__ == '__main__':
main()
| 32.952756 | 77 | 0.6681 | from __future__ import division
import argparse
import os
import os.path as osp
import time
import mmcv
import torch
from mmcv import Config
from mmcv.runner import init_dist
from mmdet import __version__
from mmdet.apis import set_random_seed, train_detector
from mmdet.datasets import build_dataset
from mmdet.models import build_detector
from mmdet.utils import get_root_logger
import warnings
warnings.filterwarnings("ignore")
def parse_args():
parser = argparse.ArgumentParser(description='Train a detector')
parser.add_argument('config', help='train config file path')
parser.add_argument('--work_dir', help='the dir to save logs and models')
parser.add_argument(
'--resume_from', help='the checkpoint file to resume from')
parser.add_argument(
'--validate',
action='store_true',
help='whether to evaluate the checkpoint during training')
parser.add_argument(
'--gpus',
type=int,
default=1,
help='number of gpus to use '
'(only applicable to non-distributed training)')
parser.add_argument('--seed', type=int, default=None, help='random seed')
parser.add_argument(
'--deterministic',
action='store_true',
help='whether to set deterministic options for CUDNN backend.')
parser.add_argument(
'--launcher',
choices=['none', 'pytorch', 'slurm', 'mpi'],
default='none',
help='job launcher')
parser.add_argument('--local_rank', type=int, default=0)
parser.add_argument(
'--autoscale-lr',
action='store_true',
help='automatically scale lr with the number of gpus')
args = parser.parse_args()
if 'LOCAL_RANK' not in os.environ:
os.environ['LOCAL_RANK'] = str(args.local_rank)
return args
def main():
args = parse_args()
cfg = Config.fromfile(args.config)
if cfg.get('cudnn_benchmark', False):
torch.backends.cudnn.benchmark = True
if args.work_dir is not None:
cfg.work_dir = args.work_dir
if args.resume_from is not None:
cfg.resume_from = args.resume_from
cfg.gpus = args.gpus
if args.autoscale_lr:
cfg.optimizer['lr'] = cfg.optimizer['lr'] * cfg.gpus / 8
if args.launcher == 'none':
distributed = False
else:
distributed = True
init_dist(args.launcher, **cfg.dist_params)
mmcv.mkdir_or_exist(osp.abspath(cfg.work_dir))
timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime())
log_file = osp.join(cfg.work_dir, '{}.log'.format(timestamp))
logger = get_root_logger(log_file=log_file, log_level=cfg.log_level)
logger.info('Distributed training: {}'.format(distributed))
logger.info('MMDetection Version: {}'.format(__version__))
logger.info('Config:\n{}'.format(cfg.text))
if args.seed is not None:
logger.info('Set random seed to {}, deterministic: {}'.format(
args.seed, args.deterministic))
set_random_seed(args.seed, deterministic=args.deterministic)
model = build_detector(
cfg.model, train_cfg=cfg.train_cfg, test_cfg=cfg.test_cfg)
datasets = [build_dataset(cfg.data.train)]
if len(cfg.workflow) == 2:
datasets.append(build_dataset(cfg.data.val))
if cfg.checkpoint_config is not None:
cfg.checkpoint_config.meta = dict(
mmdet_version=__version__,
config=cfg.text,
CLASSES=datasets[0].CLASSES)
model.CLASSES = datasets[0].CLASSES
train_detector(
model,
datasets,
cfg,
distributed=distributed,
validate=args.validate,
timestamp=timestamp)
if __name__ == '__main__':
main()
| true | true |
f71687e21d8ea9780570ef161a23f33fdc061d2f | 2,837 | py | Python | samples/basic/executor/models/cisco-ios-xr/Cisco-IOS-XR-snmp-test-trap-act/nc-execute-xr-snmp-test-trap-act-115-ydk.py | maccioni/ydk-py-samples | d1758694bef97327c5477e65649326c7595ce499 | [
"Apache-2.0"
] | 1 | 2021-07-08T14:02:12.000Z | 2021-07-08T14:02:12.000Z | samples/basic/executor/models/cisco-ios-xr/Cisco-IOS-XR-snmp-test-trap-act/nc-execute-xr-snmp-test-trap-act-115-ydk.py | maccioni/ydk-py-samples | d1758694bef97327c5477e65649326c7595ce499 | [
"Apache-2.0"
] | null | null | null | samples/basic/executor/models/cisco-ios-xr/Cisco-IOS-XR-snmp-test-trap-act/nc-execute-xr-snmp-test-trap-act-115-ydk.py | maccioni/ydk-py-samples | d1758694bef97327c5477e65649326c7595ce499 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
#
# Copyright 2016 Cisco Systems, 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.
#
"""
Execute RPC for model Cisco-IOS-XR-snmp-test-trap-act.
usage: nc-execute-xr-snmp-test-trap-act-115-ydk.py [-h] [-v] device
positional arguments:
device NETCONF device (ssh://user:password@host:port)
optional arguments:
-h, --help show this help message and exit
-v, --verbose print debugging messages
"""
from argparse import ArgumentParser
from urlparse import urlparse
from ydk.services import ExecutorService
from ydk.providers import NetconfServiceProvider
from ydk.models.cisco_ios_xr import Cisco_IOS_XR_snmp_test_trap_act \
as xr_snmp_test_trap_act
import logging
def prepare_sonet_line_status_rpc(sonet_line_status_rpc):
"""Add RPC input data to sonet_line_status_rpc object."""
pass
if __name__ == "__main__":
"""Execute main program."""
parser = ArgumentParser()
parser.add_argument("-v", "--verbose", help="print debugging messages",
action="store_true")
parser.add_argument("device",
help="NETCONF device (ssh://user:password@host:port)")
args = parser.parse_args()
device = urlparse(args.device)
# log debug messages if verbose argument specified
if args.verbose:
logger = logging.getLogger("ydk")
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
formatter = logging.Formatter(("%(asctime)s - %(name)s - "
"%(levelname)s - %(message)s"))
handler.setFormatter(formatter)
logger.addHandler(handler)
# create NETCONF provider
provider = NetconfServiceProvider(address=device.hostname,
port=device.port,
username=device.username,
password=device.password,
protocol=device.scheme)
# create executor service
executor = ExecutorService()
sonet_line_status_rpc = xr_snmp_test_trap_act.SonetLineStatusRpc() # create object
prepare_sonet_line_status_rpc(sonet_line_status_rpc) # add RPC input
# execute RPC on NETCONF device
# executor.execute_rpc(provider, sonet_line_status_rpc)
exit()
# End of script
| 34.180723 | 87 | 0.673599 |
from argparse import ArgumentParser
from urlparse import urlparse
from ydk.services import ExecutorService
from ydk.providers import NetconfServiceProvider
from ydk.models.cisco_ios_xr import Cisco_IOS_XR_snmp_test_trap_act \
as xr_snmp_test_trap_act
import logging
def prepare_sonet_line_status_rpc(sonet_line_status_rpc):
pass
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument("-v", "--verbose", help="print debugging messages",
action="store_true")
parser.add_argument("device",
help="NETCONF device (ssh://user:password@host:port)")
args = parser.parse_args()
device = urlparse(args.device)
if args.verbose:
logger = logging.getLogger("ydk")
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
formatter = logging.Formatter(("%(asctime)s - %(name)s - "
"%(levelname)s - %(message)s"))
handler.setFormatter(formatter)
logger.addHandler(handler)
provider = NetconfServiceProvider(address=device.hostname,
port=device.port,
username=device.username,
password=device.password,
protocol=device.scheme)
executor = ExecutorService()
sonet_line_status_rpc = xr_snmp_test_trap_act.SonetLineStatusRpc()
prepare_sonet_line_status_rpc(sonet_line_status_rpc)
exit()
| true | true |
f7168881dda3037f1831c4695a51ad6b12964680 | 963 | py | Python | membership/forms.py | carpentries/membershipdb | 9f6270cea7251c490686926f041e21a929218e6c | [
"MIT"
] | 3 | 2018-05-31T16:09:52.000Z | 2018-09-30T21:35:06.000Z | membership/forms.py | carpentries/membershipdb | 9f6270cea7251c490686926f041e21a929218e6c | [
"MIT"
] | 5 | 2018-06-19T21:51:16.000Z | 2020-01-19T20:18:48.000Z | membership/forms.py | carpentries/membershipdb | 9f6270cea7251c490686926f041e21a929218e6c | [
"MIT"
] | 1 | 2020-07-07T03:23:34.000Z | 2020-07-07T03:23:34.000Z | """Membership forms module
"""
from django.forms import ModelForm
from .models import Note, Term, Organization, Contact, Membership
class NoteForm(ModelForm):
"""Note Form
"""
class Meta:
model = Note
fields = ['title', 'content', 'date_time']
class TermForm(ModelForm):
"""Term Form
"""
class Meta:
model = Term
fields = ['mem_type', 'n_workshops',
'n_instructors', 'reserve',
'inh_trainer', 'local_train',
'publicize', 'recruit',
'coordinate']
class OrganizationForm(ModelForm):
"""Organization Form
"""
class Meta:
model = Organization
fields = []
class ContactForm(ModelForm):
"""Contact Form
"""
class Meta:
model = Contact
fields = []
class MembershipForm(ModelForm):
"""Membership Form
"""
class Meta:
model = Membership
fields = []
| 19.26 | 65 | 0.553479 | from django.forms import ModelForm
from .models import Note, Term, Organization, Contact, Membership
class NoteForm(ModelForm):
class Meta:
model = Note
fields = ['title', 'content', 'date_time']
class TermForm(ModelForm):
class Meta:
model = Term
fields = ['mem_type', 'n_workshops',
'n_instructors', 'reserve',
'inh_trainer', 'local_train',
'publicize', 'recruit',
'coordinate']
class OrganizationForm(ModelForm):
class Meta:
model = Organization
fields = []
class ContactForm(ModelForm):
class Meta:
model = Contact
fields = []
class MembershipForm(ModelForm):
class Meta:
model = Membership
fields = []
| true | true |
f71688edd94f6768ac57dec0eba3a526f1529856 | 28,910 | py | Python | sdk/python/pulumi_azure_native/insights/v20150501/component.py | polivbr/pulumi-azure-native | 09571f3bf6bdc4f3621aabefd1ba6c0d4ecfb0e7 | [
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_azure_native/insights/v20150501/component.py | polivbr/pulumi-azure-native | 09571f3bf6bdc4f3621aabefd1ba6c0d4ecfb0e7 | [
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_azure_native/insights/v20150501/component.py | polivbr/pulumi-azure-native | 09571f3bf6bdc4f3621aabefd1ba6c0d4ecfb0e7 | [
"Apache-2.0"
] | null | null | null | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from . import outputs
from ._enums import *
__all__ = ['ComponentArgs', 'Component']
@pulumi.input_type
class ComponentArgs:
def __init__(__self__, *,
application_type: pulumi.Input[Union[str, 'ApplicationType']],
kind: pulumi.Input[str],
resource_group_name: pulumi.Input[str],
disable_ip_masking: Optional[pulumi.Input[bool]] = None,
flow_type: Optional[pulumi.Input[Union[str, 'FlowType']]] = None,
hockey_app_id: Optional[pulumi.Input[str]] = None,
immediate_purge_data_on30_days: Optional[pulumi.Input[bool]] = None,
ingestion_mode: Optional[pulumi.Input[Union[str, 'IngestionMode']]] = None,
location: Optional[pulumi.Input[str]] = None,
request_source: Optional[pulumi.Input[Union[str, 'RequestSource']]] = None,
resource_name: Optional[pulumi.Input[str]] = None,
retention_in_days: Optional[pulumi.Input[int]] = None,
sampling_percentage: Optional[pulumi.Input[float]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None):
"""
The set of arguments for constructing a Component resource.
:param pulumi.Input[Union[str, 'ApplicationType']] application_type: Type of application being monitored.
:param pulumi.Input[str] kind: The kind of application that this component refers to, used to customize UI. This value is a freeform string, values should typically be one of the following: web, ios, other, store, java, phone.
:param pulumi.Input[str] resource_group_name: The name of the resource group. The name is case insensitive.
:param pulumi.Input[bool] disable_ip_masking: Disable IP masking.
:param pulumi.Input[Union[str, 'FlowType']] flow_type: Used by the Application Insights system to determine what kind of flow this component was created by. This is to be set to 'Bluefield' when creating/updating a component via the REST API.
:param pulumi.Input[str] hockey_app_id: The unique application ID created when a new application is added to HockeyApp, used for communications with HockeyApp.
:param pulumi.Input[bool] immediate_purge_data_on30_days: Purge data immediately after 30 days.
:param pulumi.Input[Union[str, 'IngestionMode']] ingestion_mode: Indicates the flow of the ingestion.
:param pulumi.Input[str] location: Resource location
:param pulumi.Input[Union[str, 'RequestSource']] request_source: Describes what tool created this Application Insights component. Customers using this API should set this to the default 'rest'.
:param pulumi.Input[str] resource_name: The name of the Application Insights component resource.
:param pulumi.Input[int] retention_in_days: Retention period in days.
:param pulumi.Input[float] sampling_percentage: Percentage of the data produced by the application being monitored that is being sampled for Application Insights telemetry.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Resource tags
"""
if application_type is None:
application_type = 'web'
pulumi.set(__self__, "application_type", application_type)
pulumi.set(__self__, "kind", kind)
pulumi.set(__self__, "resource_group_name", resource_group_name)
if disable_ip_masking is not None:
pulumi.set(__self__, "disable_ip_masking", disable_ip_masking)
if flow_type is None:
flow_type = 'Bluefield'
if flow_type is not None:
pulumi.set(__self__, "flow_type", flow_type)
if hockey_app_id is not None:
pulumi.set(__self__, "hockey_app_id", hockey_app_id)
if immediate_purge_data_on30_days is not None:
pulumi.set(__self__, "immediate_purge_data_on30_days", immediate_purge_data_on30_days)
if ingestion_mode is None:
ingestion_mode = 'ApplicationInsights'
if ingestion_mode is not None:
pulumi.set(__self__, "ingestion_mode", ingestion_mode)
if location is not None:
pulumi.set(__self__, "location", location)
if request_source is None:
request_source = 'rest'
if request_source is not None:
pulumi.set(__self__, "request_source", request_source)
if resource_name is not None:
pulumi.set(__self__, "resource_name", resource_name)
if retention_in_days is None:
retention_in_days = 90
if retention_in_days is not None:
pulumi.set(__self__, "retention_in_days", retention_in_days)
if sampling_percentage is not None:
pulumi.set(__self__, "sampling_percentage", sampling_percentage)
if tags is not None:
pulumi.set(__self__, "tags", tags)
@property
@pulumi.getter(name="applicationType")
def application_type(self) -> pulumi.Input[Union[str, 'ApplicationType']]:
"""
Type of application being monitored.
"""
return pulumi.get(self, "application_type")
@application_type.setter
def application_type(self, value: pulumi.Input[Union[str, 'ApplicationType']]):
pulumi.set(self, "application_type", value)
@property
@pulumi.getter
def kind(self) -> pulumi.Input[str]:
"""
The kind of application that this component refers to, used to customize UI. This value is a freeform string, values should typically be one of the following: web, ios, other, store, java, phone.
"""
return pulumi.get(self, "kind")
@kind.setter
def kind(self, value: pulumi.Input[str]):
pulumi.set(self, "kind", value)
@property
@pulumi.getter(name="resourceGroupName")
def resource_group_name(self) -> pulumi.Input[str]:
"""
The name of the resource group. The name is case insensitive.
"""
return pulumi.get(self, "resource_group_name")
@resource_group_name.setter
def resource_group_name(self, value: pulumi.Input[str]):
pulumi.set(self, "resource_group_name", value)
@property
@pulumi.getter(name="disableIpMasking")
def disable_ip_masking(self) -> Optional[pulumi.Input[bool]]:
"""
Disable IP masking.
"""
return pulumi.get(self, "disable_ip_masking")
@disable_ip_masking.setter
def disable_ip_masking(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "disable_ip_masking", value)
@property
@pulumi.getter(name="flowType")
def flow_type(self) -> Optional[pulumi.Input[Union[str, 'FlowType']]]:
"""
Used by the Application Insights system to determine what kind of flow this component was created by. This is to be set to 'Bluefield' when creating/updating a component via the REST API.
"""
return pulumi.get(self, "flow_type")
@flow_type.setter
def flow_type(self, value: Optional[pulumi.Input[Union[str, 'FlowType']]]):
pulumi.set(self, "flow_type", value)
@property
@pulumi.getter(name="hockeyAppId")
def hockey_app_id(self) -> Optional[pulumi.Input[str]]:
"""
The unique application ID created when a new application is added to HockeyApp, used for communications with HockeyApp.
"""
return pulumi.get(self, "hockey_app_id")
@hockey_app_id.setter
def hockey_app_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "hockey_app_id", value)
@property
@pulumi.getter(name="immediatePurgeDataOn30Days")
def immediate_purge_data_on30_days(self) -> Optional[pulumi.Input[bool]]:
"""
Purge data immediately after 30 days.
"""
return pulumi.get(self, "immediate_purge_data_on30_days")
@immediate_purge_data_on30_days.setter
def immediate_purge_data_on30_days(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "immediate_purge_data_on30_days", value)
@property
@pulumi.getter(name="ingestionMode")
def ingestion_mode(self) -> Optional[pulumi.Input[Union[str, 'IngestionMode']]]:
"""
Indicates the flow of the ingestion.
"""
return pulumi.get(self, "ingestion_mode")
@ingestion_mode.setter
def ingestion_mode(self, value: Optional[pulumi.Input[Union[str, 'IngestionMode']]]):
pulumi.set(self, "ingestion_mode", value)
@property
@pulumi.getter
def location(self) -> Optional[pulumi.Input[str]]:
"""
Resource location
"""
return pulumi.get(self, "location")
@location.setter
def location(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "location", value)
@property
@pulumi.getter(name="requestSource")
def request_source(self) -> Optional[pulumi.Input[Union[str, 'RequestSource']]]:
"""
Describes what tool created this Application Insights component. Customers using this API should set this to the default 'rest'.
"""
return pulumi.get(self, "request_source")
@request_source.setter
def request_source(self, value: Optional[pulumi.Input[Union[str, 'RequestSource']]]):
pulumi.set(self, "request_source", value)
@property
@pulumi.getter(name="resourceName")
def resource_name(self) -> Optional[pulumi.Input[str]]:
"""
The name of the Application Insights component resource.
"""
return pulumi.get(self, "resource_name")
@resource_name.setter
def resource_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "resource_name", value)
@property
@pulumi.getter(name="retentionInDays")
def retention_in_days(self) -> Optional[pulumi.Input[int]]:
"""
Retention period in days.
"""
return pulumi.get(self, "retention_in_days")
@retention_in_days.setter
def retention_in_days(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "retention_in_days", value)
@property
@pulumi.getter(name="samplingPercentage")
def sampling_percentage(self) -> Optional[pulumi.Input[float]]:
"""
Percentage of the data produced by the application being monitored that is being sampled for Application Insights telemetry.
"""
return pulumi.get(self, "sampling_percentage")
@sampling_percentage.setter
def sampling_percentage(self, value: Optional[pulumi.Input[float]]):
pulumi.set(self, "sampling_percentage", value)
@property
@pulumi.getter
def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]:
"""
Resource tags
"""
return pulumi.get(self, "tags")
@tags.setter
def tags(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]):
pulumi.set(self, "tags", value)
class Component(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
application_type: Optional[pulumi.Input[Union[str, 'ApplicationType']]] = None,
disable_ip_masking: Optional[pulumi.Input[bool]] = None,
flow_type: Optional[pulumi.Input[Union[str, 'FlowType']]] = None,
hockey_app_id: Optional[pulumi.Input[str]] = None,
immediate_purge_data_on30_days: Optional[pulumi.Input[bool]] = None,
ingestion_mode: Optional[pulumi.Input[Union[str, 'IngestionMode']]] = None,
kind: Optional[pulumi.Input[str]] = None,
location: Optional[pulumi.Input[str]] = None,
request_source: Optional[pulumi.Input[Union[str, 'RequestSource']]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
resource_name_: Optional[pulumi.Input[str]] = None,
retention_in_days: Optional[pulumi.Input[int]] = None,
sampling_percentage: Optional[pulumi.Input[float]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
__props__=None):
"""
An Application Insights component definition.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[Union[str, 'ApplicationType']] application_type: Type of application being monitored.
:param pulumi.Input[bool] disable_ip_masking: Disable IP masking.
:param pulumi.Input[Union[str, 'FlowType']] flow_type: Used by the Application Insights system to determine what kind of flow this component was created by. This is to be set to 'Bluefield' when creating/updating a component via the REST API.
:param pulumi.Input[str] hockey_app_id: The unique application ID created when a new application is added to HockeyApp, used for communications with HockeyApp.
:param pulumi.Input[bool] immediate_purge_data_on30_days: Purge data immediately after 30 days.
:param pulumi.Input[Union[str, 'IngestionMode']] ingestion_mode: Indicates the flow of the ingestion.
:param pulumi.Input[str] kind: The kind of application that this component refers to, used to customize UI. This value is a freeform string, values should typically be one of the following: web, ios, other, store, java, phone.
:param pulumi.Input[str] location: Resource location
:param pulumi.Input[Union[str, 'RequestSource']] request_source: Describes what tool created this Application Insights component. Customers using this API should set this to the default 'rest'.
:param pulumi.Input[str] resource_group_name: The name of the resource group. The name is case insensitive.
:param pulumi.Input[str] resource_name_: The name of the Application Insights component resource.
:param pulumi.Input[int] retention_in_days: Retention period in days.
:param pulumi.Input[float] sampling_percentage: Percentage of the data produced by the application being monitored that is being sampled for Application Insights telemetry.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Resource tags
"""
...
@overload
def __init__(__self__,
resource_name: str,
args: ComponentArgs,
opts: Optional[pulumi.ResourceOptions] = None):
"""
An Application Insights component definition.
:param str resource_name: The name of the resource.
:param ComponentArgs args: The arguments to use to populate this resource's properties.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(ComponentArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
application_type: Optional[pulumi.Input[Union[str, 'ApplicationType']]] = None,
disable_ip_masking: Optional[pulumi.Input[bool]] = None,
flow_type: Optional[pulumi.Input[Union[str, 'FlowType']]] = None,
hockey_app_id: Optional[pulumi.Input[str]] = None,
immediate_purge_data_on30_days: Optional[pulumi.Input[bool]] = None,
ingestion_mode: Optional[pulumi.Input[Union[str, 'IngestionMode']]] = None,
kind: Optional[pulumi.Input[str]] = None,
location: Optional[pulumi.Input[str]] = None,
request_source: Optional[pulumi.Input[Union[str, 'RequestSource']]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
resource_name_: Optional[pulumi.Input[str]] = None,
retention_in_days: Optional[pulumi.Input[int]] = None,
sampling_percentage: Optional[pulumi.Input[float]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = ComponentArgs.__new__(ComponentArgs)
if application_type is None:
application_type = 'web'
if application_type is None and not opts.urn:
raise TypeError("Missing required property 'application_type'")
__props__.__dict__["application_type"] = application_type
__props__.__dict__["disable_ip_masking"] = disable_ip_masking
if flow_type is None:
flow_type = 'Bluefield'
__props__.__dict__["flow_type"] = flow_type
__props__.__dict__["hockey_app_id"] = hockey_app_id
__props__.__dict__["immediate_purge_data_on30_days"] = immediate_purge_data_on30_days
if ingestion_mode is None:
ingestion_mode = 'ApplicationInsights'
__props__.__dict__["ingestion_mode"] = ingestion_mode
if kind is None and not opts.urn:
raise TypeError("Missing required property 'kind'")
__props__.__dict__["kind"] = kind
__props__.__dict__["location"] = location
if request_source is None:
request_source = 'rest'
__props__.__dict__["request_source"] = request_source
if resource_group_name is None and not opts.urn:
raise TypeError("Missing required property 'resource_group_name'")
__props__.__dict__["resource_group_name"] = resource_group_name
__props__.__dict__["resource_name"] = resource_name_
if retention_in_days is None:
retention_in_days = 90
__props__.__dict__["retention_in_days"] = retention_in_days
__props__.__dict__["sampling_percentage"] = sampling_percentage
__props__.__dict__["tags"] = tags
__props__.__dict__["app_id"] = None
__props__.__dict__["application_id"] = None
__props__.__dict__["connection_string"] = None
__props__.__dict__["creation_date"] = None
__props__.__dict__["hockey_app_token"] = None
__props__.__dict__["instrumentation_key"] = None
__props__.__dict__["name"] = None
__props__.__dict__["private_link_scoped_resources"] = None
__props__.__dict__["provisioning_state"] = None
__props__.__dict__["tenant_id"] = None
__props__.__dict__["type"] = None
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:insights/v20150501:Component"), pulumi.Alias(type_="azure-native:insights:Component"), pulumi.Alias(type_="azure-nextgen:insights:Component"), pulumi.Alias(type_="azure-native:insights/v20180501preview:Component"), pulumi.Alias(type_="azure-nextgen:insights/v20180501preview:Component"), pulumi.Alias(type_="azure-native:insights/v20200202:Component"), pulumi.Alias(type_="azure-nextgen:insights/v20200202:Component"), pulumi.Alias(type_="azure-native:insights/v20200202preview:Component"), pulumi.Alias(type_="azure-nextgen:insights/v20200202preview:Component")])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(Component, __self__).__init__(
'azure-native:insights/v20150501:Component',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'Component':
"""
Get an existing Component resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = ComponentArgs.__new__(ComponentArgs)
__props__.__dict__["app_id"] = None
__props__.__dict__["application_id"] = None
__props__.__dict__["application_type"] = None
__props__.__dict__["connection_string"] = None
__props__.__dict__["creation_date"] = None
__props__.__dict__["disable_ip_masking"] = None
__props__.__dict__["flow_type"] = None
__props__.__dict__["hockey_app_id"] = None
__props__.__dict__["hockey_app_token"] = None
__props__.__dict__["immediate_purge_data_on30_days"] = None
__props__.__dict__["ingestion_mode"] = None
__props__.__dict__["instrumentation_key"] = None
__props__.__dict__["kind"] = None
__props__.__dict__["location"] = None
__props__.__dict__["name"] = None
__props__.__dict__["private_link_scoped_resources"] = None
__props__.__dict__["provisioning_state"] = None
__props__.__dict__["request_source"] = None
__props__.__dict__["retention_in_days"] = None
__props__.__dict__["sampling_percentage"] = None
__props__.__dict__["tags"] = None
__props__.__dict__["tenant_id"] = None
__props__.__dict__["type"] = None
return Component(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter(name="appId")
def app_id(self) -> pulumi.Output[str]:
"""
Application Insights Unique ID for your Application.
"""
return pulumi.get(self, "app_id")
@property
@pulumi.getter(name="applicationId")
def application_id(self) -> pulumi.Output[str]:
"""
The unique ID of your application. This field mirrors the 'Name' field and cannot be changed.
"""
return pulumi.get(self, "application_id")
@property
@pulumi.getter(name="applicationType")
def application_type(self) -> pulumi.Output[str]:
"""
Type of application being monitored.
"""
return pulumi.get(self, "application_type")
@property
@pulumi.getter(name="connectionString")
def connection_string(self) -> pulumi.Output[str]:
"""
Application Insights component connection string.
"""
return pulumi.get(self, "connection_string")
@property
@pulumi.getter(name="creationDate")
def creation_date(self) -> pulumi.Output[str]:
"""
Creation Date for the Application Insights component, in ISO 8601 format.
"""
return pulumi.get(self, "creation_date")
@property
@pulumi.getter(name="disableIpMasking")
def disable_ip_masking(self) -> pulumi.Output[Optional[bool]]:
"""
Disable IP masking.
"""
return pulumi.get(self, "disable_ip_masking")
@property
@pulumi.getter(name="flowType")
def flow_type(self) -> pulumi.Output[Optional[str]]:
"""
Used by the Application Insights system to determine what kind of flow this component was created by. This is to be set to 'Bluefield' when creating/updating a component via the REST API.
"""
return pulumi.get(self, "flow_type")
@property
@pulumi.getter(name="hockeyAppId")
def hockey_app_id(self) -> pulumi.Output[Optional[str]]:
"""
The unique application ID created when a new application is added to HockeyApp, used for communications with HockeyApp.
"""
return pulumi.get(self, "hockey_app_id")
@property
@pulumi.getter(name="hockeyAppToken")
def hockey_app_token(self) -> pulumi.Output[str]:
"""
Token used to authenticate communications with between Application Insights and HockeyApp.
"""
return pulumi.get(self, "hockey_app_token")
@property
@pulumi.getter(name="immediatePurgeDataOn30Days")
def immediate_purge_data_on30_days(self) -> pulumi.Output[Optional[bool]]:
"""
Purge data immediately after 30 days.
"""
return pulumi.get(self, "immediate_purge_data_on30_days")
@property
@pulumi.getter(name="ingestionMode")
def ingestion_mode(self) -> pulumi.Output[Optional[str]]:
"""
Indicates the flow of the ingestion.
"""
return pulumi.get(self, "ingestion_mode")
@property
@pulumi.getter(name="instrumentationKey")
def instrumentation_key(self) -> pulumi.Output[str]:
"""
Application Insights Instrumentation key. A read-only value that applications can use to identify the destination for all telemetry sent to Azure Application Insights. This value will be supplied upon construction of each new Application Insights component.
"""
return pulumi.get(self, "instrumentation_key")
@property
@pulumi.getter
def kind(self) -> pulumi.Output[str]:
"""
The kind of application that this component refers to, used to customize UI. This value is a freeform string, values should typically be one of the following: web, ios, other, store, java, phone.
"""
return pulumi.get(self, "kind")
@property
@pulumi.getter
def location(self) -> pulumi.Output[str]:
"""
Resource location
"""
return pulumi.get(self, "location")
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
"""
Azure resource name
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="privateLinkScopedResources")
def private_link_scoped_resources(self) -> pulumi.Output[Sequence['outputs.PrivateLinkScopedResourceResponse']]:
"""
List of linked private link scope resources.
"""
return pulumi.get(self, "private_link_scoped_resources")
@property
@pulumi.getter(name="provisioningState")
def provisioning_state(self) -> pulumi.Output[str]:
"""
Current state of this component: whether or not is has been provisioned within the resource group it is defined. Users cannot change this value but are able to read from it. Values will include Succeeded, Deploying, Canceled, and Failed.
"""
return pulumi.get(self, "provisioning_state")
@property
@pulumi.getter(name="requestSource")
def request_source(self) -> pulumi.Output[Optional[str]]:
"""
Describes what tool created this Application Insights component. Customers using this API should set this to the default 'rest'.
"""
return pulumi.get(self, "request_source")
@property
@pulumi.getter(name="retentionInDays")
def retention_in_days(self) -> pulumi.Output[Optional[int]]:
"""
Retention period in days.
"""
return pulumi.get(self, "retention_in_days")
@property
@pulumi.getter(name="samplingPercentage")
def sampling_percentage(self) -> pulumi.Output[Optional[float]]:
"""
Percentage of the data produced by the application being monitored that is being sampled for Application Insights telemetry.
"""
return pulumi.get(self, "sampling_percentage")
@property
@pulumi.getter
def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]:
"""
Resource tags
"""
return pulumi.get(self, "tags")
@property
@pulumi.getter(name="tenantId")
def tenant_id(self) -> pulumi.Output[str]:
"""
Azure Tenant Id.
"""
return pulumi.get(self, "tenant_id")
@property
@pulumi.getter
def type(self) -> pulumi.Output[str]:
"""
Azure resource type
"""
return pulumi.get(self, "type")
| 46.779935 | 651 | 0.661397 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from . import outputs
from ._enums import *
__all__ = ['ComponentArgs', 'Component']
@pulumi.input_type
class ComponentArgs:
def __init__(__self__, *,
application_type: pulumi.Input[Union[str, 'ApplicationType']],
kind: pulumi.Input[str],
resource_group_name: pulumi.Input[str],
disable_ip_masking: Optional[pulumi.Input[bool]] = None,
flow_type: Optional[pulumi.Input[Union[str, 'FlowType']]] = None,
hockey_app_id: Optional[pulumi.Input[str]] = None,
immediate_purge_data_on30_days: Optional[pulumi.Input[bool]] = None,
ingestion_mode: Optional[pulumi.Input[Union[str, 'IngestionMode']]] = None,
location: Optional[pulumi.Input[str]] = None,
request_source: Optional[pulumi.Input[Union[str, 'RequestSource']]] = None,
resource_name: Optional[pulumi.Input[str]] = None,
retention_in_days: Optional[pulumi.Input[int]] = None,
sampling_percentage: Optional[pulumi.Input[float]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None):
if application_type is None:
application_type = 'web'
pulumi.set(__self__, "application_type", application_type)
pulumi.set(__self__, "kind", kind)
pulumi.set(__self__, "resource_group_name", resource_group_name)
if disable_ip_masking is not None:
pulumi.set(__self__, "disable_ip_masking", disable_ip_masking)
if flow_type is None:
flow_type = 'Bluefield'
if flow_type is not None:
pulumi.set(__self__, "flow_type", flow_type)
if hockey_app_id is not None:
pulumi.set(__self__, "hockey_app_id", hockey_app_id)
if immediate_purge_data_on30_days is not None:
pulumi.set(__self__, "immediate_purge_data_on30_days", immediate_purge_data_on30_days)
if ingestion_mode is None:
ingestion_mode = 'ApplicationInsights'
if ingestion_mode is not None:
pulumi.set(__self__, "ingestion_mode", ingestion_mode)
if location is not None:
pulumi.set(__self__, "location", location)
if request_source is None:
request_source = 'rest'
if request_source is not None:
pulumi.set(__self__, "request_source", request_source)
if resource_name is not None:
pulumi.set(__self__, "resource_name", resource_name)
if retention_in_days is None:
retention_in_days = 90
if retention_in_days is not None:
pulumi.set(__self__, "retention_in_days", retention_in_days)
if sampling_percentage is not None:
pulumi.set(__self__, "sampling_percentage", sampling_percentage)
if tags is not None:
pulumi.set(__self__, "tags", tags)
@property
@pulumi.getter(name="applicationType")
def application_type(self) -> pulumi.Input[Union[str, 'ApplicationType']]:
return pulumi.get(self, "application_type")
@application_type.setter
def application_type(self, value: pulumi.Input[Union[str, 'ApplicationType']]):
pulumi.set(self, "application_type", value)
@property
@pulumi.getter
def kind(self) -> pulumi.Input[str]:
return pulumi.get(self, "kind")
@kind.setter
def kind(self, value: pulumi.Input[str]):
pulumi.set(self, "kind", value)
@property
@pulumi.getter(name="resourceGroupName")
def resource_group_name(self) -> pulumi.Input[str]:
return pulumi.get(self, "resource_group_name")
@resource_group_name.setter
def resource_group_name(self, value: pulumi.Input[str]):
pulumi.set(self, "resource_group_name", value)
@property
@pulumi.getter(name="disableIpMasking")
def disable_ip_masking(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "disable_ip_masking")
@disable_ip_masking.setter
def disable_ip_masking(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "disable_ip_masking", value)
@property
@pulumi.getter(name="flowType")
def flow_type(self) -> Optional[pulumi.Input[Union[str, 'FlowType']]]:
return pulumi.get(self, "flow_type")
@flow_type.setter
def flow_type(self, value: Optional[pulumi.Input[Union[str, 'FlowType']]]):
pulumi.set(self, "flow_type", value)
@property
@pulumi.getter(name="hockeyAppId")
def hockey_app_id(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "hockey_app_id")
@hockey_app_id.setter
def hockey_app_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "hockey_app_id", value)
@property
@pulumi.getter(name="immediatePurgeDataOn30Days")
def immediate_purge_data_on30_days(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "immediate_purge_data_on30_days")
@immediate_purge_data_on30_days.setter
def immediate_purge_data_on30_days(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "immediate_purge_data_on30_days", value)
@property
@pulumi.getter(name="ingestionMode")
def ingestion_mode(self) -> Optional[pulumi.Input[Union[str, 'IngestionMode']]]:
return pulumi.get(self, "ingestion_mode")
@ingestion_mode.setter
def ingestion_mode(self, value: Optional[pulumi.Input[Union[str, 'IngestionMode']]]):
pulumi.set(self, "ingestion_mode", value)
@property
@pulumi.getter
def location(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "location")
@location.setter
def location(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "location", value)
@property
@pulumi.getter(name="requestSource")
def request_source(self) -> Optional[pulumi.Input[Union[str, 'RequestSource']]]:
return pulumi.get(self, "request_source")
@request_source.setter
def request_source(self, value: Optional[pulumi.Input[Union[str, 'RequestSource']]]):
pulumi.set(self, "request_source", value)
@property
@pulumi.getter(name="resourceName")
def resource_name(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "resource_name")
@resource_name.setter
def resource_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "resource_name", value)
@property
@pulumi.getter(name="retentionInDays")
def retention_in_days(self) -> Optional[pulumi.Input[int]]:
return pulumi.get(self, "retention_in_days")
@retention_in_days.setter
def retention_in_days(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "retention_in_days", value)
@property
@pulumi.getter(name="samplingPercentage")
def sampling_percentage(self) -> Optional[pulumi.Input[float]]:
return pulumi.get(self, "sampling_percentage")
@sampling_percentage.setter
def sampling_percentage(self, value: Optional[pulumi.Input[float]]):
pulumi.set(self, "sampling_percentage", value)
@property
@pulumi.getter
def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]:
return pulumi.get(self, "tags")
@tags.setter
def tags(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]):
pulumi.set(self, "tags", value)
class Component(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
application_type: Optional[pulumi.Input[Union[str, 'ApplicationType']]] = None,
disable_ip_masking: Optional[pulumi.Input[bool]] = None,
flow_type: Optional[pulumi.Input[Union[str, 'FlowType']]] = None,
hockey_app_id: Optional[pulumi.Input[str]] = None,
immediate_purge_data_on30_days: Optional[pulumi.Input[bool]] = None,
ingestion_mode: Optional[pulumi.Input[Union[str, 'IngestionMode']]] = None,
kind: Optional[pulumi.Input[str]] = None,
location: Optional[pulumi.Input[str]] = None,
request_source: Optional[pulumi.Input[Union[str, 'RequestSource']]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
resource_name_: Optional[pulumi.Input[str]] = None,
retention_in_days: Optional[pulumi.Input[int]] = None,
sampling_percentage: Optional[pulumi.Input[float]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
__props__=None):
...
@overload
def __init__(__self__,
resource_name: str,
args: ComponentArgs,
opts: Optional[pulumi.ResourceOptions] = None):
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(ComponentArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
application_type: Optional[pulumi.Input[Union[str, 'ApplicationType']]] = None,
disable_ip_masking: Optional[pulumi.Input[bool]] = None,
flow_type: Optional[pulumi.Input[Union[str, 'FlowType']]] = None,
hockey_app_id: Optional[pulumi.Input[str]] = None,
immediate_purge_data_on30_days: Optional[pulumi.Input[bool]] = None,
ingestion_mode: Optional[pulumi.Input[Union[str, 'IngestionMode']]] = None,
kind: Optional[pulumi.Input[str]] = None,
location: Optional[pulumi.Input[str]] = None,
request_source: Optional[pulumi.Input[Union[str, 'RequestSource']]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
resource_name_: Optional[pulumi.Input[str]] = None,
retention_in_days: Optional[pulumi.Input[int]] = None,
sampling_percentage: Optional[pulumi.Input[float]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = ComponentArgs.__new__(ComponentArgs)
if application_type is None:
application_type = 'web'
if application_type is None and not opts.urn:
raise TypeError("Missing required property 'application_type'")
__props__.__dict__["application_type"] = application_type
__props__.__dict__["disable_ip_masking"] = disable_ip_masking
if flow_type is None:
flow_type = 'Bluefield'
__props__.__dict__["flow_type"] = flow_type
__props__.__dict__["hockey_app_id"] = hockey_app_id
__props__.__dict__["immediate_purge_data_on30_days"] = immediate_purge_data_on30_days
if ingestion_mode is None:
ingestion_mode = 'ApplicationInsights'
__props__.__dict__["ingestion_mode"] = ingestion_mode
if kind is None and not opts.urn:
raise TypeError("Missing required property 'kind'")
__props__.__dict__["kind"] = kind
__props__.__dict__["location"] = location
if request_source is None:
request_source = 'rest'
__props__.__dict__["request_source"] = request_source
if resource_group_name is None and not opts.urn:
raise TypeError("Missing required property 'resource_group_name'")
__props__.__dict__["resource_group_name"] = resource_group_name
__props__.__dict__["resource_name"] = resource_name_
if retention_in_days is None:
retention_in_days = 90
__props__.__dict__["retention_in_days"] = retention_in_days
__props__.__dict__["sampling_percentage"] = sampling_percentage
__props__.__dict__["tags"] = tags
__props__.__dict__["app_id"] = None
__props__.__dict__["application_id"] = None
__props__.__dict__["connection_string"] = None
__props__.__dict__["creation_date"] = None
__props__.__dict__["hockey_app_token"] = None
__props__.__dict__["instrumentation_key"] = None
__props__.__dict__["name"] = None
__props__.__dict__["private_link_scoped_resources"] = None
__props__.__dict__["provisioning_state"] = None
__props__.__dict__["tenant_id"] = None
__props__.__dict__["type"] = None
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:insights/v20150501:Component"), pulumi.Alias(type_="azure-native:insights:Component"), pulumi.Alias(type_="azure-nextgen:insights:Component"), pulumi.Alias(type_="azure-native:insights/v20180501preview:Component"), pulumi.Alias(type_="azure-nextgen:insights/v20180501preview:Component"), pulumi.Alias(type_="azure-native:insights/v20200202:Component"), pulumi.Alias(type_="azure-nextgen:insights/v20200202:Component"), pulumi.Alias(type_="azure-native:insights/v20200202preview:Component"), pulumi.Alias(type_="azure-nextgen:insights/v20200202preview:Component")])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(Component, __self__).__init__(
'azure-native:insights/v20150501:Component',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'Component':
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = ComponentArgs.__new__(ComponentArgs)
__props__.__dict__["app_id"] = None
__props__.__dict__["application_id"] = None
__props__.__dict__["application_type"] = None
__props__.__dict__["connection_string"] = None
__props__.__dict__["creation_date"] = None
__props__.__dict__["disable_ip_masking"] = None
__props__.__dict__["flow_type"] = None
__props__.__dict__["hockey_app_id"] = None
__props__.__dict__["hockey_app_token"] = None
__props__.__dict__["immediate_purge_data_on30_days"] = None
__props__.__dict__["ingestion_mode"] = None
__props__.__dict__["instrumentation_key"] = None
__props__.__dict__["kind"] = None
__props__.__dict__["location"] = None
__props__.__dict__["name"] = None
__props__.__dict__["private_link_scoped_resources"] = None
__props__.__dict__["provisioning_state"] = None
__props__.__dict__["request_source"] = None
__props__.__dict__["retention_in_days"] = None
__props__.__dict__["sampling_percentage"] = None
__props__.__dict__["tags"] = None
__props__.__dict__["tenant_id"] = None
__props__.__dict__["type"] = None
return Component(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter(name="appId")
def app_id(self) -> pulumi.Output[str]:
return pulumi.get(self, "app_id")
@property
@pulumi.getter(name="applicationId")
def application_id(self) -> pulumi.Output[str]:
return pulumi.get(self, "application_id")
@property
@pulumi.getter(name="applicationType")
def application_type(self) -> pulumi.Output[str]:
return pulumi.get(self, "application_type")
@property
@pulumi.getter(name="connectionString")
def connection_string(self) -> pulumi.Output[str]:
return pulumi.get(self, "connection_string")
@property
@pulumi.getter(name="creationDate")
def creation_date(self) -> pulumi.Output[str]:
return pulumi.get(self, "creation_date")
@property
@pulumi.getter(name="disableIpMasking")
def disable_ip_masking(self) -> pulumi.Output[Optional[bool]]:
return pulumi.get(self, "disable_ip_masking")
@property
@pulumi.getter(name="flowType")
def flow_type(self) -> pulumi.Output[Optional[str]]:
return pulumi.get(self, "flow_type")
@property
@pulumi.getter(name="hockeyAppId")
def hockey_app_id(self) -> pulumi.Output[Optional[str]]:
return pulumi.get(self, "hockey_app_id")
@property
@pulumi.getter(name="hockeyAppToken")
def hockey_app_token(self) -> pulumi.Output[str]:
return pulumi.get(self, "hockey_app_token")
@property
@pulumi.getter(name="immediatePurgeDataOn30Days")
def immediate_purge_data_on30_days(self) -> pulumi.Output[Optional[bool]]:
return pulumi.get(self, "immediate_purge_data_on30_days")
@property
@pulumi.getter(name="ingestionMode")
def ingestion_mode(self) -> pulumi.Output[Optional[str]]:
return pulumi.get(self, "ingestion_mode")
@property
@pulumi.getter(name="instrumentationKey")
def instrumentation_key(self) -> pulumi.Output[str]:
return pulumi.get(self, "instrumentation_key")
@property
@pulumi.getter
def kind(self) -> pulumi.Output[str]:
return pulumi.get(self, "kind")
@property
@pulumi.getter
def location(self) -> pulumi.Output[str]:
return pulumi.get(self, "location")
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
return pulumi.get(self, "name")
@property
@pulumi.getter(name="privateLinkScopedResources")
def private_link_scoped_resources(self) -> pulumi.Output[Sequence['outputs.PrivateLinkScopedResourceResponse']]:
return pulumi.get(self, "private_link_scoped_resources")
@property
@pulumi.getter(name="provisioningState")
def provisioning_state(self) -> pulumi.Output[str]:
return pulumi.get(self, "provisioning_state")
@property
@pulumi.getter(name="requestSource")
def request_source(self) -> pulumi.Output[Optional[str]]:
return pulumi.get(self, "request_source")
@property
@pulumi.getter(name="retentionInDays")
def retention_in_days(self) -> pulumi.Output[Optional[int]]:
return pulumi.get(self, "retention_in_days")
@property
@pulumi.getter(name="samplingPercentage")
def sampling_percentage(self) -> pulumi.Output[Optional[float]]:
return pulumi.get(self, "sampling_percentage")
@property
@pulumi.getter
def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]:
return pulumi.get(self, "tags")
@property
@pulumi.getter(name="tenantId")
def tenant_id(self) -> pulumi.Output[str]:
return pulumi.get(self, "tenant_id")
@property
@pulumi.getter
def type(self) -> pulumi.Output[str]:
return pulumi.get(self, "type")
| true | true |
f7168a4422b050f7d1300a0db6bbaf4282e7bd75 | 1,953 | py | Python | jungle/code/sorting.py | nate-russell/Jungle | 114d744ed66fec11b8d5e62444253892a7ffa5cd | [
"MIT"
] | null | null | null | jungle/code/sorting.py | nate-russell/Jungle | 114d744ed66fec11b8d5e62444253892a7ffa5cd | [
"MIT"
] | 4 | 2017-12-28T02:07:33.000Z | 2018-01-04T06:38:43.000Z | jungle/code/sorting.py | nate-russell/Jungle | 114d744ed66fec11b8d5e62444253892a7ffa5cd | [
"MIT"
] | null | null | null | '''
Sorting Examples for showcasing and developing Jungle features
'''
import inspect
from jungle import JungleExperiment, JungleProfiler
import numpy as np
print('Finished Loading Modules')
class Sorting_Prototype:
print('\n---Test Sort N---')
@JungleExperiment(reps=1, n=[100, 500])
def test_sort_n(self, n=100, seed=1234):
''' Test sorting an iterable of size n with a random distribution '''
# make data to sort with random distribution
np.random.seed(seed)
list_2_sort = list(np.random.randn(n))
@JungleProfiler()
def sort_n(l):
sorted_list = self.sort(l)
return sorted_list
# Sort and check sort status
sorted_list, _ = sort_n(list_2_sort)
sort_status = all(sorted_list[i] <= sorted_list[i + 1] for i in range(len(sorted_list) - 1))
return sort_status
print('\n---Test Block Sort---')
@JungleExperiment(reps=1, n_blocks=[2, 4], block_size=[50, 100])
@JungleProfiler()
def test_block_random_sort(self, n_blocks=4, block_size=100):
print('n_blocks: %s' % n_blocks)
print('block_size: %s' % block_size)
return 'something'
class NP_QuickSort(Sorting_Prototype):
def sort(self, l):
return np.sort(l, kind='quicksort')
class NP_MergeSort(Sorting_Prototype):
def sort(self, l):
return np.sort(l, kind='mergesort')
class NP_HeapSort(Sorting_Prototype):
def sort(self, l):
return np.sort(l, kind='heapsort')
if __name__ == '__main__':
print('\n__main__\n')
print('\n---Starting Call #1---')
m1 = NP_QuickSort()
jc1 = m1.test_sort_n()
print('\n---Starting Call #2---')
m2 = NP_MergeSort()
jc2 = m2.test_sort_n()
print('\n---Starting Call #3---')
m1 = NP_QuickSort()
jc1 = m1.test_block_random_sort()
print('\n---Starting Call #4---')
m2 = NP_MergeSort()
jc2 = m2.test_block_random_sort()
| 24.721519 | 100 | 0.63236 | import inspect
from jungle import JungleExperiment, JungleProfiler
import numpy as np
print('Finished Loading Modules')
class Sorting_Prototype:
print('\n---Test Sort N---')
@JungleExperiment(reps=1, n=[100, 500])
def test_sort_n(self, n=100, seed=1234):
np.random.seed(seed)
list_2_sort = list(np.random.randn(n))
@JungleProfiler()
def sort_n(l):
sorted_list = self.sort(l)
return sorted_list
sorted_list, _ = sort_n(list_2_sort)
sort_status = all(sorted_list[i] <= sorted_list[i + 1] for i in range(len(sorted_list) - 1))
return sort_status
print('\n---Test Block Sort---')
@JungleExperiment(reps=1, n_blocks=[2, 4], block_size=[50, 100])
@JungleProfiler()
def test_block_random_sort(self, n_blocks=4, block_size=100):
print('n_blocks: %s' % n_blocks)
print('block_size: %s' % block_size)
return 'something'
class NP_QuickSort(Sorting_Prototype):
def sort(self, l):
return np.sort(l, kind='quicksort')
class NP_MergeSort(Sorting_Prototype):
def sort(self, l):
return np.sort(l, kind='mergesort')
class NP_HeapSort(Sorting_Prototype):
def sort(self, l):
return np.sort(l, kind='heapsort')
if __name__ == '__main__':
print('\n__main__\n')
print('\n---Starting Call #1---')
m1 = NP_QuickSort()
jc1 = m1.test_sort_n()
print('\n---Starting Call #2---')
m2 = NP_MergeSort()
jc2 = m2.test_sort_n()
print('\n---Starting Call #3---')
m1 = NP_QuickSort()
jc1 = m1.test_block_random_sort()
print('\n---Starting Call #4---')
m2 = NP_MergeSort()
jc2 = m2.test_block_random_sort()
| true | true |
f7168a45d1129bfe9f7ee66ee3c14b06f2b75b19 | 432 | py | Python | exercicios/ex052.py | MaikolSantos/curso-em-video-python3 | 3a1ab2761b8a0f98e128083a7b0e50b19a75b7bf | [
"MIT"
] | null | null | null | exercicios/ex052.py | MaikolSantos/curso-em-video-python3 | 3a1ab2761b8a0f98e128083a7b0e50b19a75b7bf | [
"MIT"
] | null | null | null | exercicios/ex052.py | MaikolSantos/curso-em-video-python3 | 3a1ab2761b8a0f98e128083a7b0e50b19a75b7bf | [
"MIT"
] | null | null | null | n = int(input('Digite um número inteiro: '))
cont = 0
for c in range(1, n + 1):
if n % c == 0:
print('\033[034m{}\033[m'.format(c), end=' ')
cont += 1
else:
print('\033[031m{}\033[m'.format(c), end=' ')
print('\nO número {} foi divisível {} vezes '.format(n, cont))
if cont == 2:
print('Portanto, o número {} é PRIMO'.format(n))
else:
print('Portanto, o número {} NÃO é PRIMO'.format(n))
| 24 | 62 | 0.546296 | n = int(input('Digite um número inteiro: '))
cont = 0
for c in range(1, n + 1):
if n % c == 0:
print('\033[034m{}\033[m'.format(c), end=' ')
cont += 1
else:
print('\033[031m{}\033[m'.format(c), end=' ')
print('\nO número {} foi divisível {} vezes '.format(n, cont))
if cont == 2:
print('Portanto, o número {} é PRIMO'.format(n))
else:
print('Portanto, o número {} NÃO é PRIMO'.format(n))
| true | true |
f7168a487b6bc455015981782fb336330a0490cd | 26,905 | py | Python | src/sage/rings/polynomial/flatten.py | nikmihale/sage | e2dcdeeabb578c37bcf0361c0be3079315e9252c | [
"BSL-1.0"
] | null | null | null | src/sage/rings/polynomial/flatten.py | nikmihale/sage | e2dcdeeabb578c37bcf0361c0be3079315e9252c | [
"BSL-1.0"
] | null | null | null | src/sage/rings/polynomial/flatten.py | nikmihale/sage | e2dcdeeabb578c37bcf0361c0be3079315e9252c | [
"BSL-1.0"
] | null | null | null | # -*- coding: utf-8 -*-
r"""
Class to flatten polynomial rings over polynomial ring
For example ``QQ['a','b'],['x','y']`` flattens to ``QQ['a','b','x','y']``.
EXAMPLES::
sage: R = QQ['x']['y']['s','t']['X']
sage: from sage.rings.polynomial.flatten import FlatteningMorphism
sage: phi = FlatteningMorphism(R); phi
Flattening morphism:
From: Univariate Polynomial Ring in X over Multivariate Polynomial Ring in s, t over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
To: Multivariate Polynomial Ring in x, y, s, t, X over Rational Field
sage: phi('x*y*s + t*X').parent()
Multivariate Polynomial Ring in x, y, s, t, X over Rational Field
Authors:
Vincent Delecroix, Ben Hutz (July 2016): initial implementation
"""
# ****************************************************************************
# Copyright (C) 2016
#
# 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.
# https://www.gnu.org/licenses/
# ****************************************************************************
from __future__ import absolute_import, print_function
import itertools
from sage.categories.homset import Homset
from sage.categories.morphism import Morphism
from sage.misc.cachefunc import cached_method
from .polynomial_ring_constructor import PolynomialRing
from .polynomial_ring import is_PolynomialRing
from .multi_polynomial_ring_base import is_MPolynomialRing
from sage.rings.fraction_field import is_FractionField
from sage.rings.fraction_field_element import FractionFieldElement
from sage.rings.polynomial.polydict import ETuple
class FlatteningMorphism(Morphism):
r"""
EXAMPLES::
sage: R = QQ['a','b']['x','y','z']['t1','t2']
sage: from sage.rings.polynomial.flatten import FlatteningMorphism
sage: f = FlatteningMorphism(R)
sage: f.codomain()
Multivariate Polynomial Ring in a, b, x, y, z, t1, t2 over Rational Field
sage: p = R('(a+b)*x + (a^2-b)*t2*(z+y)')
sage: p
((a^2 - b)*y + (a^2 - b)*z)*t2 + (a + b)*x
sage: f(p)
a^2*y*t2 + a^2*z*t2 - b*y*t2 - b*z*t2 + a*x + b*x
sage: f(p).parent()
Multivariate Polynomial Ring in a, b, x, y, z, t1, t2 over Rational Field
Also works when univariate polynomial ring are involved::
sage: R = QQ['x']['y']['s','t']['X']
sage: from sage.rings.polynomial.flatten import FlatteningMorphism
sage: f = FlatteningMorphism(R)
sage: f.codomain()
Multivariate Polynomial Ring in x, y, s, t, X over Rational Field
sage: p = R('((x^2 + 1) + (x+2)*y + x*y^3)*(s+t) + x*y*X')
sage: p
x*y*X + (x*y^3 + (x + 2)*y + x^2 + 1)*s + (x*y^3 + (x + 2)*y + x^2 + 1)*t
sage: f(p)
x*y^3*s + x*y^3*t + x^2*s + x*y*s + x^2*t + x*y*t + x*y*X + 2*y*s + 2*y*t + s + t
sage: f(p).parent()
Multivariate Polynomial Ring in x, y, s, t, X over Rational Field
"""
def __init__(self, domain):
"""
The Python constructor
EXAMPLES::
sage: R = ZZ['a', 'b', 'c']['x', 'y', 'z']
sage: from sage.rings.polynomial.flatten import FlatteningMorphism
sage: FlatteningMorphism(R)
Flattening morphism:
From: Multivariate Polynomial Ring in x, y, z over Multivariate Polynomial Ring in a, b, c over Integer Ring
To: Multivariate Polynomial Ring in a, b, c, x, y, z over Integer Ring
::
sage: R = ZZ['a']['b']['c']
sage: from sage.rings.polynomial.flatten import FlatteningMorphism
sage: FlatteningMorphism(R)
Flattening morphism:
From: Univariate Polynomial Ring in c over Univariate Polynomial Ring in b over Univariate Polynomial Ring in a over Integer Ring
To: Multivariate Polynomial Ring in a, b, c over Integer Ring
::
sage: R = ZZ['a']['a','b']
sage: from sage.rings.polynomial.flatten import FlatteningMorphism
sage: FlatteningMorphism(R)
Flattening morphism:
From: Multivariate Polynomial Ring in a, b over Univariate Polynomial Ring in a over Integer Ring
To: Multivariate Polynomial Ring in a, a0, b over Integer Ring
::
sage: K.<v> = NumberField(x^3 - 2)
sage: R = K['x','y']['a','b']
sage: from sage.rings.polynomial.flatten import FlatteningMorphism
sage: f = FlatteningMorphism(R)
sage: f(R('v*a*x^2 + b^2 + 1/v*y'))
(v)*x^2*a + b^2 + (1/2*v^2)*y
::
sage: R = QQbar['x','y']['a','b']
sage: from sage.rings.polynomial.flatten import FlatteningMorphism
sage: f = FlatteningMorphism(R)
sage: f(R('QQbar(sqrt(2))*a*x^2 + b^2 + QQbar(I)*y'))
1.414213562373095?*x^2*a + b^2 + I*y
::
sage: R.<z> = PolynomialRing(QQbar,1)
sage: from sage.rings.polynomial.flatten import FlatteningMorphism
sage: f = FlatteningMorphism(R)
sage: f.domain(), f.codomain()
(Multivariate Polynomial Ring in z over Algebraic Field,
Multivariate Polynomial Ring in z over Algebraic Field)
::
sage: R.<z> = PolynomialRing(QQbar)
sage: from sage.rings.polynomial.flatten import FlatteningMorphism
sage: f = FlatteningMorphism(R)
sage: f.domain(), f.codomain()
(Univariate Polynomial Ring in z over Algebraic Field,
Univariate Polynomial Ring in z over Algebraic Field)
TESTS::
sage: Pol = QQ['x']['x0']['x']
sage: fl = FlatteningMorphism(Pol)
sage: fl
Flattening morphism:
From: Univariate Polynomial Ring in x over Univariate Polynomial Ring in x0 over Univariate Polynomial Ring in x over Rational Field
To: Multivariate Polynomial Ring in x, x0, x1 over Rational Field
sage: p = Pol([[[1,2],[3,4]],[[5,6],[7,8]]])
sage: fl.section()(fl(p)) == p
True
"""
if not is_PolynomialRing(domain) and not is_MPolynomialRing(domain):
raise ValueError("domain should be a polynomial ring")
ring = domain
variables = []
intermediate_rings = []
while is_PolynomialRing(ring) or is_MPolynomialRing(ring):
intermediate_rings.append(ring)
v = ring.variable_names()
variables.extend(reversed(v))
ring = ring.base_ring()
self._intermediate_rings = intermediate_rings
variables.reverse()
for i, a in enumerate(variables):
if a in variables[:i]:
for index in itertools.count():
b = a + str(index)
if b not in variables: # not just variables[:i]!
break
variables[i] = b
if is_MPolynomialRing(domain):
codomain = PolynomialRing(ring, variables, len(variables))
else:
codomain = PolynomialRing(ring, variables)
hom = Homset(domain, codomain, base=ring, check=False)
Morphism.__init__(self, hom)
self._repr_type_str = 'Flattening'
def _call_(self, p):
r"""
Evaluate a flattening morphism.
EXAMPLES::
sage: R = QQ['a','b','c']['x','y','z']
sage: from sage.rings.polynomial.flatten import FlatteningMorphism
sage: h = FlatteningMorphism(R)('2*a*x + b*z'); h
2*a*x + b*z
sage: h.parent()
Multivariate Polynomial Ring in a, b, c, x, y, z over Rational Field
TESTS::
sage: R = QQ['x']['y']['s','t']
sage: p = R('s*x + y*t + x^2*s + 1 + t')
sage: from sage.rings.polynomial.flatten import FlatteningMorphism
sage: f = FlatteningMorphism(R)
sage: f._call_(p)
x^2*s + x*s + y*t + t + 1
"""
# If we are just specializing a univariate polynomial, then
# the flattening morphism is the identity
if self.codomain().ngens() == 1:
return p
p = {(): p}
for ring in self._intermediate_rings:
new_p = {}
if is_PolynomialRing(ring):
for mon, pp in p.items():
assert pp.parent() is ring
for i, j in pp.dict().items():
new_p[(i,)+(mon)] = j
elif is_MPolynomialRing(ring):
for mon, pp in p.items():
assert pp.parent() is ring
for mmon, q in pp.dict().items():
new_p[tuple(mmon)+mon] = q
else:
raise RuntimeError
p = new_p
return self.codomain()(p, check=False)
@cached_method
def section(self):
"""
Inverse of this flattening morphism.
EXAMPLES::
sage: R = QQ['a','b','c']['x','y','z']
sage: from sage.rings.polynomial.flatten import FlatteningMorphism
sage: h = FlatteningMorphism(R)
sage: h.section()
Unflattening morphism:
From: Multivariate Polynomial Ring in a, b, c, x, y, z over Rational Field
To: Multivariate Polynomial Ring in x, y, z over Multivariate Polynomial Ring in a, b, c over Rational Field
::
sage: R = ZZ['a']['b']['c']
sage: from sage.rings.polynomial.flatten import FlatteningMorphism
sage: FlatteningMorphism(R).section()
Unflattening morphism:
From: Multivariate Polynomial Ring in a, b, c over Integer Ring
To: Univariate Polynomial Ring in c over Univariate Polynomial Ring in b over Univariate Polynomial Ring in a over Integer Ring
"""
return UnflatteningMorphism(self.codomain(), self.domain())
class UnflatteningMorphism(Morphism):
r"""
Inverses for :class:`FlatteningMorphism`
EXAMPLES::
sage: R = QQ['c','x','y','z']
sage: S = QQ['c']['x','y','z']
sage: from sage.rings.polynomial.flatten import UnflatteningMorphism
sage: f = UnflatteningMorphism(R, S)
sage: g = f(R('x^2 + c*y^2 - z^2'));g
x^2 + c*y^2 - z^2
sage: g.parent()
Multivariate Polynomial Ring in x, y, z over Univariate Polynomial Ring in c over Rational Field
::
sage: R = QQ['a','b', 'x','y']
sage: S = QQ['a','b']['x','y']
sage: from sage.rings.polynomial.flatten import UnflatteningMorphism
sage: UnflatteningMorphism(R, S)
Unflattening morphism:
From: Multivariate Polynomial Ring in a, b, x, y over Rational Field
To: Multivariate Polynomial Ring in x, y over Multivariate Polynomial Ring in a, b over Rational Field
"""
def __init__(self, domain, codomain):
"""
The Python constructor
EXAMPLES::
sage: R = QQ['x']['y']['s','t']['X']
sage: p = R.random_element()
sage: from sage.rings.polynomial.flatten import FlatteningMorphism
sage: f = FlatteningMorphism(R)
sage: g = f.section()
sage: g(f(p)) == p
True
::
sage: R = QQ['a','b','x','y']
sage: S = ZZ['a','b']['x','z']
sage: from sage.rings.polynomial.flatten import UnflatteningMorphism
sage: UnflatteningMorphism(R, S)
Traceback (most recent call last):
...
ValueError: rings must have same base ring
::
sage: R = QQ['a','b','x','y']
sage: S = QQ['a','b']['x','z','w']
sage: from sage.rings.polynomial.flatten import UnflatteningMorphism
sage: UnflatteningMorphism(R, S)
Traceback (most recent call last):
...
ValueError: rings must have the same number of variables
"""
if not is_MPolynomialRing(domain):
raise ValueError("domain should be a multivariate polynomial ring")
if not is_PolynomialRing(codomain) and not is_MPolynomialRing(codomain):
raise ValueError("codomain should be a polynomial ring")
ring = codomain
intermediate_rings = []
while True:
is_polynomial_ring = is_PolynomialRing(ring)
if not (is_polynomial_ring or is_MPolynomialRing(ring)):
break
intermediate_rings.append((ring, is_polynomial_ring))
ring = ring.base_ring()
if domain.base_ring() != intermediate_rings[-1][0].base_ring():
raise ValueError("rings must have same base ring")
if domain.ngens() != sum([R.ngens() for R, _ in intermediate_rings]):
raise ValueError("rings must have the same number of variables")
self._intermediate_rings = intermediate_rings
hom = Homset(domain, codomain, base=ring, check=False)
Morphism.__init__(self, hom)
self._repr_type_str = 'Unflattening'
def _call_(self, p):
"""
Evaluate an unflattening morphism.
TESTS::
sage: from sage.rings.polynomial.flatten import FlatteningMorphism
sage: for R in [ZZ['x']['y']['a,b,c'], GF(4)['x','y']['a','b'],
....: AA['x']['a','b']['y'], QQbar['a1','a2']['t']['X','Y']]:
....: f = FlatteningMorphism(R)
....: g = f.section()
....: for _ in range(10):
....: p = R.random_element()
....: assert p == g(f(p))
....: z = R.zero()
....: assert z == g(f(z))
"""
index = [0]
for R, _ in reversed(self._intermediate_rings):
index.append(index[-1] + len(R.gens()))
newpol = [{} for _ in self._intermediate_rings]
expo = sorted(p.exponents(), key=lambda e: tuple(reversed(e)))
for i in range(len(expo)):
cur_exp = expo[i]
for l in range(len(self._intermediate_rings)):
R, univariate = self._intermediate_rings[-1 - l]
idx = index[l + 1]
sub_exp = (cur_exp[index[l]] if univariate
else cur_exp[index[l]:idx])
if l == 0:
newpol[l][sub_exp] = p[cur_exp]
else:
newpol[l][sub_exp] = newpol[l - 1]
newpol[l - 1] = {}
if (i == len(expo) - 1 or expo[i + 1][idx:] != cur_exp[idx:]):
newpol[l] = R(newpol[l], check=False)
else:
break
return R(newpol[-1], check=False)
class SpecializationMorphism(Morphism):
r"""
Morphisms to specialize parameters in (stacked) polynomial rings
EXAMPLES::
sage: R.<c> = PolynomialRing(QQ)
sage: S.<x,y,z> = PolynomialRing(R)
sage: D = dict({c:1})
sage: from sage.rings.polynomial.flatten import SpecializationMorphism
sage: f = SpecializationMorphism(S, D)
sage: g = f(x^2 + c*y^2 - z^2); g
x^2 + y^2 - z^2
sage: g.parent()
Multivariate Polynomial Ring in x, y, z over Rational Field
::
sage: R.<c> = PolynomialRing(QQ)
sage: S.<z> = PolynomialRing(R)
sage: from sage.rings.polynomial.flatten import SpecializationMorphism
sage: xi = SpecializationMorphism(S, {c:0}); xi
Specialization morphism:
From: Univariate Polynomial Ring in z over Univariate Polynomial Ring in c over Rational Field
To: Univariate Polynomial Ring in z over Rational Field
sage: xi(z^2+c)
z^2
::
sage: R1.<u,v> = PolynomialRing(QQ)
sage: R2.<a,b,c> = PolynomialRing(R1)
sage: S.<x,y,z> = PolynomialRing(R2)
sage: D = dict({a:1, b:2, x:0, u:1})
sage: from sage.rings.polynomial.flatten import SpecializationMorphism
sage: xi = SpecializationMorphism(S, D); xi
Specialization morphism:
From: Multivariate Polynomial Ring in x, y, z over Multivariate Polynomial Ring in a, b, c over Multivariate Polynomial Ring in u, v over Rational Field
To: Multivariate Polynomial Ring in y, z over Univariate Polynomial Ring in c over Univariate Polynomial Ring in v over Rational Field
sage: xi(a*(x*z+y^2)*u+b*v*u*(x*z+y^2)*y^2*c+c*y^2*z^2)
2*v*c*y^4 + c*y^2*z^2 + y^2
"""
def __init__(self, domain, D):
"""
The Python constructor
EXAMPLES::
sage: S.<x,y> = PolynomialRing(QQ)
sage: D = dict({x:1})
sage: from sage.rings.polynomial.flatten import SpecializationMorphism
sage: phi = SpecializationMorphism(S, D); phi
Specialization morphism:
From: Multivariate Polynomial Ring in x, y over Rational Field
To: Univariate Polynomial Ring in y over Rational Field
sage: phi(x^2 + y^2)
y^2 + 1
::
sage: R.<a,b,c> = PolynomialRing(ZZ)
sage: S.<x,y,z> = PolynomialRing(R)
sage: from sage.rings.polynomial.flatten import SpecializationMorphism
sage: xi = SpecializationMorphism(S, {a:1/2})
Traceback (most recent call last):
...
TypeError: no conversion of this rational to integer
The following was fixed in :trac:`23811`::
sage: R.<c> = RR[]
sage: P.<z> = AffineSpace(R, 1)
sage: H = End(P)
sage: f = H([z^2 + c])
sage: f.specialization({c:1})
Scheme endomorphism of Affine Space of dimension 1 over Real Field with 53 bits of precision
Defn: Defined on coordinates by sending (z) to
(z^2 + 1.00000000000000)
"""
if not is_PolynomialRing(domain) and not is_MPolynomialRing(domain):
raise TypeError("domain should be a polynomial ring")
# use only the generators that are in the stack somewhere,
# and ignore the rest
all_gens = domain.gens_dict_recursive()
new_D = {}
for gen in D:
if str(gen) in all_gens:
new_D[gen] = D[gen]
D = new_D
# _sub_specialization is a specialization morphism (recursive)
# which is applied to the base Fraction field, or None if it's
# any other base ring
self._sub_specialization = None
# We use this composition where "flat" is a flattened
# polynomial ring.
#
# phi D psi
# domain → flat → flat → R
# │ │ │
# └─────────┴───────────────┘
# _flattening_morph _eval_morph
# = phi = psi ∘ D
phi = FlatteningMorphism(domain)
flat = phi.codomain()
base = flat.base_ring()
# Change domain of D to "flat" and ensure that the values lie
# in the base ring.
D = {phi(k): base(D[k]) for k in D}
# Construct unflattened codomain R
new_vars = []
R = domain
while is_PolynomialRing(R) or is_MPolynomialRing(R) or is_FractionField(R):
if is_FractionField(R):
# We've hit base_ring, so set _sub_specialization and exit the loop
field_over = R.base()
applicable_vars = {key: val for key, val in D.items()
if key not in flat.gens()}
# If there are any variables in D to set in _sub_specialization
if applicable_vars:
# Coerce the generators to be in the right ring
# This un-does changing the domain of D to be in the flat base ring
tmp = {}
for var, val in applicable_vars.items():
for gstr, gen in field_over.gens_dict_recursive().items():
if str(var) == gstr:
tmp[gen] = val
break
else:
# Should have been caught earlier
raise NameError("argument " + str(var) + " is not a generator anywhere in the polynomial tower")
applicable_vars = tmp
self._sub_specialization = FractionSpecializationMorphism(R, applicable_vars)
break
# We're still in the polynomials, so keep track of the tower
old = R.gens()
new = [t for t in old if t not in D]
force_multivariate = ((len(old) == 1) and is_MPolynomialRing(R))
new_vars.append((new, force_multivariate, old))
R = R.base_ring()
if self._sub_specialization:
# The sub_specialization range will be different
# if it applied some variables from D
R = self._sub_specialization.codomain().fraction_field()
# Construct unflattening map psi (only defined on the variables
# of "flat" which are not involved in D)
psi = dict()
# Reconstruct the proper domain of this morphism
# based on the sub_specialization domains
new_domain = R
for new, force_multivariate, old in reversed(new_vars):
if self._sub_specialization:
if force_multivariate:
new_domain = PolynomialRing(new_domain, old, len(old))
else:
new_domain = PolynomialRing(new_domain, old)
if not new:
continue
var_names = [str(var) for var in new]
if force_multivariate:
R = PolynomialRing(R, var_names, len(var_names))
else:
R = PolynomialRing(R, var_names)
# Map variables in "new" to R
psi.update(zip([phi(w) for w in new], R.gens()))
# Fix domain of eval_morph
# (note: phi's domain is correct)
if self._sub_specialization:
phi_prime = FlatteningMorphism(new_domain)
flat_old = flat
flat = phi_prime.codomain()
base_prime = flat.base_ring()
D = {phi(k): base_prime(D[k]) for k in D}
else:
# The bottom of our tower has not changed
def flat_old(x):
return x
# Compose D with psi
vals = []
for t in flat.gens():
if t in D:
vals.append(R.coerce(D[t]))
else:
# Make sure keys are in the old domain
# or else they won't match exactly
vals.append(psi[flat_old(t)])
self._flattening_morph = phi
self._eval_morph = flat.hom(vals, R)
self._repr_type_str = 'Specialization'
Morphism.__init__(self, domain, R)
def _call_(self, p):
"""
Evaluate a specialization morphism.
EXAMPLES::
sage: R.<a,b,c> = PolynomialRing(ZZ)
sage: S.<x,y,z> = PolynomialRing(R)
sage: D = dict({a:1, b:2, c:3})
sage: from sage.rings.polynomial.flatten import SpecializationMorphism
sage: xi = SpecializationMorphism(S, D)
sage: xi(a*x + b*y + c*z)
x + 2*y + 3*z
"""
flat = self._flattening_morph(p)
if self._sub_specialization is not None:
# The base_ring should be a fraction field, so
# apply _sub_specialization to each coefficient
# in the flattened polynomial
tmp = {}
for exponent, coefficient in flat.dict().items():
# Fix the type of exponent from (a,) to a
# (necessary for R(tmp) later)
if isinstance(exponent, ETuple) and len(exponent) == 1:
exponent = exponent[0]
# Coefficient should be a fraction
tmp[exponent] = self._sub_specialization._call_(coefficient)
# tmp's parent should be the same construction as flat
# but over _sub_specialization's codomain
ring_constructor = flat.parent().construction()[0]
fraction_type = self._sub_specialization.codomain()
R = ring_constructor(fraction_type)
flat = R(tmp)
return self._eval_morph(flat)
class FractionSpecializationMorphism(Morphism):
"""
A specialization morphism for fraction fields over (stacked) polynomial rings
"""
def __init__(self, domain, D):
"""
Initialize the morphism with a domain and dictionary of specializations
EXAMPLES::
sage: R.<a,c> = QQ[]
sage: S.<x,y> = R[]
sage: from sage.rings.polynomial.flatten import FractionSpecializationMorphism
sage: phi = FractionSpecializationMorphism(Frac(S), {c:3})
sage: phi
Fraction Specialization morphism:
From: Fraction Field of Multivariate Polynomial Ring in x, y over Multivariate Polynomial Ring in a, c over Rational Field
To: Fraction Field of Multivariate Polynomial Ring in x, y over Univariate Polynomial Ring in a over Rational Field
"""
if not is_FractionField(domain):
raise TypeError("domain must be a fraction field")
self._specialization = SpecializationMorphism(domain.base(), D)
self._repr_type_str = 'Fraction Specialization'
Morphism.__init__(self, domain, self._specialization.codomain().fraction_field())
def _call_(self, p):
"""
Evaluate a fraction specialization morphism
EXAMPLES::
sage: R.<a,b,c> = QQ[]
sage: S.<x,y,z> = R[]
sage: from sage.rings.polynomial.flatten import FractionSpecializationMorphism
sage: phi = FractionSpecializationMorphism(Frac(S), {a:3, b:2, c:-2})
sage: spec = phi((a*x + b*y) / (c*z))
sage: spec
(3*x + 2*y)/(-2*z)
sage: spec.parent()
Fraction Field of Multivariate Polynomial Ring in x, y, z over Rational Field
"""
if not isinstance(p, FractionFieldElement):
raise TypeError("p must be a fraction field element")
numerator = self._specialization._call_(p.numerator())
denominator = self._specialization._call_(p.denominator())
return numerator / denominator
| 39.918398 | 179 | 0.55551 |
from __future__ import absolute_import, print_function
import itertools
from sage.categories.homset import Homset
from sage.categories.morphism import Morphism
from sage.misc.cachefunc import cached_method
from .polynomial_ring_constructor import PolynomialRing
from .polynomial_ring import is_PolynomialRing
from .multi_polynomial_ring_base import is_MPolynomialRing
from sage.rings.fraction_field import is_FractionField
from sage.rings.fraction_field_element import FractionFieldElement
from sage.rings.polynomial.polydict import ETuple
class FlatteningMorphism(Morphism):
def __init__(self, domain):
if not is_PolynomialRing(domain) and not is_MPolynomialRing(domain):
raise ValueError("domain should be a polynomial ring")
ring = domain
variables = []
intermediate_rings = []
while is_PolynomialRing(ring) or is_MPolynomialRing(ring):
intermediate_rings.append(ring)
v = ring.variable_names()
variables.extend(reversed(v))
ring = ring.base_ring()
self._intermediate_rings = intermediate_rings
variables.reverse()
for i, a in enumerate(variables):
if a in variables[:i]:
for index in itertools.count():
b = a + str(index)
if b not in variables:
break
variables[i] = b
if is_MPolynomialRing(domain):
codomain = PolynomialRing(ring, variables, len(variables))
else:
codomain = PolynomialRing(ring, variables)
hom = Homset(domain, codomain, base=ring, check=False)
Morphism.__init__(self, hom)
self._repr_type_str = 'Flattening'
def _call_(self, p):
if self.codomain().ngens() == 1:
return p
p = {(): p}
for ring in self._intermediate_rings:
new_p = {}
if is_PolynomialRing(ring):
for mon, pp in p.items():
assert pp.parent() is ring
for i, j in pp.dict().items():
new_p[(i,)+(mon)] = j
elif is_MPolynomialRing(ring):
for mon, pp in p.items():
assert pp.parent() is ring
for mmon, q in pp.dict().items():
new_p[tuple(mmon)+mon] = q
else:
raise RuntimeError
p = new_p
return self.codomain()(p, check=False)
@cached_method
def section(self):
return UnflatteningMorphism(self.codomain(), self.domain())
class UnflatteningMorphism(Morphism):
def __init__(self, domain, codomain):
if not is_MPolynomialRing(domain):
raise ValueError("domain should be a multivariate polynomial ring")
if not is_PolynomialRing(codomain) and not is_MPolynomialRing(codomain):
raise ValueError("codomain should be a polynomial ring")
ring = codomain
intermediate_rings = []
while True:
is_polynomial_ring = is_PolynomialRing(ring)
if not (is_polynomial_ring or is_MPolynomialRing(ring)):
break
intermediate_rings.append((ring, is_polynomial_ring))
ring = ring.base_ring()
if domain.base_ring() != intermediate_rings[-1][0].base_ring():
raise ValueError("rings must have same base ring")
if domain.ngens() != sum([R.ngens() for R, _ in intermediate_rings]):
raise ValueError("rings must have the same number of variables")
self._intermediate_rings = intermediate_rings
hom = Homset(domain, codomain, base=ring, check=False)
Morphism.__init__(self, hom)
self._repr_type_str = 'Unflattening'
def _call_(self, p):
index = [0]
for R, _ in reversed(self._intermediate_rings):
index.append(index[-1] + len(R.gens()))
newpol = [{} for _ in self._intermediate_rings]
expo = sorted(p.exponents(), key=lambda e: tuple(reversed(e)))
for i in range(len(expo)):
cur_exp = expo[i]
for l in range(len(self._intermediate_rings)):
R, univariate = self._intermediate_rings[-1 - l]
idx = index[l + 1]
sub_exp = (cur_exp[index[l]] if univariate
else cur_exp[index[l]:idx])
if l == 0:
newpol[l][sub_exp] = p[cur_exp]
else:
newpol[l][sub_exp] = newpol[l - 1]
newpol[l - 1] = {}
if (i == len(expo) - 1 or expo[i + 1][idx:] != cur_exp[idx:]):
newpol[l] = R(newpol[l], check=False)
else:
break
return R(newpol[-1], check=False)
class SpecializationMorphism(Morphism):
def __init__(self, domain, D):
if not is_PolynomialRing(domain) and not is_MPolynomialRing(domain):
raise TypeError("domain should be a polynomial ring")
all_gens = domain.gens_dict_recursive()
new_D = {}
for gen in D:
if str(gen) in all_gens:
new_D[gen] = D[gen]
D = new_D
# any other base ring
self._sub_specialization = None
# We use this composition where "flat" is a flattened
# polynomial ring.
#
# phi D psi
# domain → flat → flat → R
# │ │ │
# └─────────┴───────────────┘
# _flattening_morph _eval_morph
# = phi = psi ∘ D
phi = FlatteningMorphism(domain)
flat = phi.codomain()
base = flat.base_ring()
# Change domain of D to "flat" and ensure that the values lie
# in the base ring.
D = {phi(k): base(D[k]) for k in D}
# Construct unflattened codomain R
new_vars = []
R = domain
while is_PolynomialRing(R) or is_MPolynomialRing(R) or is_FractionField(R):
if is_FractionField(R):
# We've hit base_ring, so set _sub_specialization and exit the loop
field_over = R.base()
applicable_vars = {key: val for key, val in D.items()
if key not in flat.gens()}
if applicable_vars:
tmp = {}
for var, val in applicable_vars.items():
for gstr, gen in field_over.gens_dict_recursive().items():
if str(var) == gstr:
tmp[gen] = val
break
else:
raise NameError("argument " + str(var) + " is not a generator anywhere in the polynomial tower")
applicable_vars = tmp
self._sub_specialization = FractionSpecializationMorphism(R, applicable_vars)
break
old = R.gens()
new = [t for t in old if t not in D]
force_multivariate = ((len(old) == 1) and is_MPolynomialRing(R))
new_vars.append((new, force_multivariate, old))
R = R.base_ring()
if self._sub_specialization:
# The sub_specialization range will be different
# if it applied some variables from D
R = self._sub_specialization.codomain().fraction_field()
# Construct unflattening map psi (only defined on the variables
# of "flat" which are not involved in D)
psi = dict()
# Reconstruct the proper domain of this morphism
# based on the sub_specialization domains
new_domain = R
for new, force_multivariate, old in reversed(new_vars):
if self._sub_specialization:
if force_multivariate:
new_domain = PolynomialRing(new_domain, old, len(old))
else:
new_domain = PolynomialRing(new_domain, old)
if not new:
continue
var_names = [str(var) for var in new]
if force_multivariate:
R = PolynomialRing(R, var_names, len(var_names))
else:
R = PolynomialRing(R, var_names)
# Map variables in "new" to R
psi.update(zip([phi(w) for w in new], R.gens()))
# Fix domain of eval_morph
# (note: phi's domain is correct)
if self._sub_specialization:
phi_prime = FlatteningMorphism(new_domain)
flat_old = flat
flat = phi_prime.codomain()
base_prime = flat.base_ring()
D = {phi(k): base_prime(D[k]) for k in D}
else:
def flat_old(x):
return x
vals = []
for t in flat.gens():
if t in D:
vals.append(R.coerce(D[t]))
else:
vals.append(psi[flat_old(t)])
self._flattening_morph = phi
self._eval_morph = flat.hom(vals, R)
self._repr_type_str = 'Specialization'
Morphism.__init__(self, domain, R)
def _call_(self, p):
flat = self._flattening_morph(p)
if self._sub_specialization is not None:
# The base_ring should be a fraction field, so
# apply _sub_specialization to each coefficient
# in the flattened polynomial
tmp = {}
for exponent, coefficient in flat.dict().items():
# Fix the type of exponent from (a,) to a
# (necessary for R(tmp) later)
if isinstance(exponent, ETuple) and len(exponent) == 1:
exponent = exponent[0]
# Coefficient should be a fraction
tmp[exponent] = self._sub_specialization._call_(coefficient)
# tmp's parent should be the same construction as flat
ring_constructor = flat.parent().construction()[0]
fraction_type = self._sub_specialization.codomain()
R = ring_constructor(fraction_type)
flat = R(tmp)
return self._eval_morph(flat)
class FractionSpecializationMorphism(Morphism):
def __init__(self, domain, D):
if not is_FractionField(domain):
raise TypeError("domain must be a fraction field")
self._specialization = SpecializationMorphism(domain.base(), D)
self._repr_type_str = 'Fraction Specialization'
Morphism.__init__(self, domain, self._specialization.codomain().fraction_field())
def _call_(self, p):
if not isinstance(p, FractionFieldElement):
raise TypeError("p must be a fraction field element")
numerator = self._specialization._call_(p.numerator())
denominator = self._specialization._call_(p.denominator())
return numerator / denominator
| true | true |
f7168ba8849334a57d1b394944e515d207126631 | 19,617 | py | Python | main.py | gmathez/Project_ADA_2018_Bruttin_Mathez_Petitpierre | e237300b3d9fb966b0eb747dd66816cc6cfc11b3 | [
"Apache-2.0"
] | 1 | 2018-12-01T12:17:58.000Z | 2018-12-01T12:17:58.000Z | main.py | gmathez/Project_ADA_2018_Bruttin_Mathez_Petitpierre | e237300b3d9fb966b0eb747dd66816cc6cfc11b3 | [
"Apache-2.0"
] | null | null | null | main.py | gmathez/Project_ADA_2018_Bruttin_Mathez_Petitpierre | e237300b3d9fb966b0eb747dd66816cc6cfc11b3 | [
"Apache-2.0"
] | null | null | null | # Import kivy tools
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.recycleboxlayout import RecycleBoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.checkbox import CheckBox
from kivy.uix.spinner import Spinner
from kivy.uix.recycleview import RecycleView
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.properties import BooleanProperty, ObjectProperty
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder
# Import the kv files
Builder.load_file('./src/rv.kv')
Builder.load_file('./src/screenhome.kv')
Builder.load_file('./src/screenprofile.kv')
Builder.load_file('./src/screensettings.kv')
Builder.load_file('./src/screenproduct.kv')
Builder.load_file('./src/screenquantities.kv')
Builder.load_file('./src/screenfinal.kv')
Builder.load_file('./src/manager.kv')
# Other imports
import pandas as pd
import re
from Algo_main import algo # Import the algorithm for NutriScore computation
class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior,
RecycleBoxLayout):
''' Add selection and focus behaviour to the view '''
pass
class SelectableGrid(RecycleDataViewBehavior, GridLayout):
''' Add selection support to the Label '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
self.ids['id_label1'].text = data['label1']['text']
self.ids['id_label2'].text = data['label2']['text']
self.ids['id_label3'].text = data['label3']['text']
return super(SelectableGrid, self).refresh_view_attrs(
rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableGrid, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
return self.parent.select_with_touch(self.index, touch)
def apply_selection(self, rv, index, is_selected):
''' Respond to the selection of items '''
self.selected = is_selected
class SelectableQuantity(RecycleDataViewBehavior, GridLayout):
''' Add selection support to the Label '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
self.ids['id_label1'].text = data['label1']['text']
self.ids['id_label2'].text = data['label2']['text']
self.ids['id_label3'].text = data['label3']['text']
return super(SelectableQuantity, self).refresh_view_attrs(
rv, index, data)
class RV(RecycleView):
''' Class for the RecycleView Controller '''
def __init__(self, **kwargs):
super(RV, self).__init__(**kwargs)
def upload(self, query, active):
''' Search data according to the user input '''
# Reset data
self.data = []
# Check if the Raw Food CheckBox is active or not
if active:
self.parent.parent.getSelection('API', query, True)
self.data = [{'label1': {'text': 'API'}, 'label2': {'text': query}, 'label3': {'text': 'Add/Remove'}}]
else:
isinside = allTrue
for item in query.split(): # Split the query in keywords
isinside = isinside & \
(DF['product_name'].str.contains(item, case=False) | \
DF['Brands'].str.contains(item, case=False))
if any(isinside):
selection = DF[isinside] # Select products to display
for row in selection.itertuples(): # Iterate through the columns of DF
d = {'label1': {'text': str(row[0])}, \
'label2': {'text': str(row[1])},
'label3': {'text': str(row[-1])}} # barcode, product_name, brand
self.data.append(d)
else:
isinside = DF.index.str.contains(query, case=False) # Search for Barcode
if any(isinside):
selection = DF[isinside]
for row in selection.itertuples():
d = {'label1': {'text': str(row[0])}, \
'label2': {'text': str(row[1])},
'label3': {'text': str(row[-1])}} # barcode, product_name, brand
self.data.append(d)
else:
# In case no product is found
self.data = [{'label1': {'text': ''}, \
'label2': {'text': 'No product found'}, 'label3': {'text': ''}}]
def getQuantities(self, dict):
''' Gather data for display on Quantities Screen '''
self.data = []
code = dict['code']
product_name = dict['product_name']
quantity = dict['quantity']
for index in range(len(code)):
d = {'label1': {'text': code[index]}, 'label2': {'text': product_name[index]}, \
'label3': {'text': quantity[index]}}
self.data.append(d)
class ScreenHome(Screen):
''' Class for the Home Screen. No variables or functions needed for this screen '''
pass
class ScreenProfile(Screen):
''' Class for the Profile Screen '''
def updateDF(self):
global DF
DF = pd.read_csv('https://drive.google.com/uc?export=download&id=1aLUh1UoQcS9lBa6oVRln-DuskxK5uK3y', \
index_col=[0], low_memory = False)
DF.to_csv('./data/OpenFoodFacts_final.csv.gz', compression='gzip')
self.ids['update'].text = 'Updated'
self.ids['update'].background_color = (0,1,0,1)
def update(self):
self.ids['update'].text = 'Updating'
self.ids['update'].background_color = (50/255,164/255,206/255,1)
class ScreenSettings(Screen):
''' Class for the Settings Screen '''
settings = {'rec': True,'name': '', 'surname': '', 'age': 0, 'sex': True, 'weight': 0, \
'email': '', 'activity': 0, 'days': 0}
id_profile = -999
def resetForm(self):
''' Reset the indicators of invalid input '''
self.ids.sex.color = (1,1,1,1)
self.ids.activity.color = (1,1,1,1)
self.ids.age.hint_text_color = (0.5, 0.5, 0.5, 1.0)
self.ids.weight.hint_text_color = (0.5, 0.5, 0.5, 1.0)
self.ids.days.hint_text_color = (0.5, 0.5, 0.5, 1.0)
self.ids.email.hint_text_color = (0.5, 0.5, 0.5, 1.0)
self.ids.name.hint_text_color = (0.5, 0.5, 0.5, 1.0)
self.ids.surname.hint_text_color = (0.5, 0.5, 0.5, 1.0)
def setForm(self, id_profile):
self.id_profile = id_profile
self.settings = {'rec': True,'name': '', 'surname': '', 'age': 0, 'sex': True, 'weight': 0, \
'email': '', 'activity': 0, 'days': 0}
if int(self.id_profile) >= 0:
self.ids.name.text = str(profile_list.iloc[self.id_profile]['name'])
self.ids.surname.text= str(profile_list.iloc[self.id_profile]['surname'])
self.ids.age.text = str(profile_list.iloc[self.id_profile]['age'])
if bool(profile_list.iloc[self.id_profile]['sex']):
self.ids.male.active = True
self.ids.female.active = False
else:
self.ids.male.active = False
self.ids.female.active = True
self.ids.weight.text = str(profile_list.iloc[self.id_profile]['weight'])
self.ids.email.text = str(profile_list.iloc[self.id_profile]['email'])
self.ids.days.text = str(profile_list.iloc[self.id_profile]['days'])
if int(profile_list.iloc[self.id_profile]['activity']) == 1.8:
self.ids.seated.active = False
self.ids.both.active = False
self.ids.standing.active = True
elif int(profile_list.iloc[self.id_profile]['activity']) == 1.6:
self.ids.seated.active = False
self.ids.both.active = True
self.ids.standing.active = False
else:
self.ids.seated.active = True
self.ids.both.active = False
self.ids.standing.active = False
elif int(self.id_profile) == -999:
self.ids.name.text = ''
self.ids.surname.text = ''
self.ids.age.text = ''
self.ids.male.active = False
self.ids.female.active = False
self.ids.email.text = ''
self.ids.weight.text = ''
self.ids.seated.active = False
self.ids.both.active = False
self.ids.standing.active = False
self.ids.days.text = ''
else:
self.changeScreen(False)
def changeScreen(self, valid):
''' Handle the validity of the inputs and the change of current screen '''
if valid:
self.resetForm()
# Check name validity
if self.ids.name.text.strip() == '':
self.ids.name.hint_text_color = (1,0,0,1)
return False
# Check surname validity
elif self.ids.surname.text.strip() == '':
self.ids.surname.hint_text_color = (1,0,0,1)
return False
# Check age validity
elif self.ids.age.text.strip() == '' or int(self.ids.age.text) <= 0 or \
int(self.ids.age.text) >= 120:
self.ids.age.text = ''
self.ids.age.hint_text_color = (1,0,0,1)
return False
# Check sex validity
elif not(self.ids.male.active or self.ids.female.active):
self.ids.sex.color = (1,0,0,1)
return False
# Check email validity
elif not re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", self.ids.email.text):
self.ids.email.text = ''
self.ids.email.hint_text_color = (1,0,0,1)
return False
# Check weight validity
elif self.ids.weight.text.strip() == '' or int(self.ids.weight.text) <= 0:
self.ids.weight.text = ''
self.ids.weight.hint_text_color = (1,0,0,1)
return False
# Check activity validity
elif not(self.ids.seated.active or self.ids.both.active or self.ids.standing.active):
self.ids.activity.color = (1,0,0,1)
return False
# Check days validity
elif self.ids.days.text.strip() == '' or int(self.ids.days.text) <= 0:
self.ids.days.text = ''
self.ids.days.hint_text_color = (1,0,0,1)
return False
else: # Validation of the form and reset
self.settings['rec'] = True
self.settings['name'] = self.ids.name.text
self.settings['surname'] = self.ids.surname.text
self.settings['age'] = int(self.ids.age.text)
self.settings['weight'] = int(self.ids.weight.text)
self.settings['email'] = self.ids.email.text
self.settings['days'] = int(self.ids.days.text)
self.settings['sex'] = self.ids.male.active
if self.ids.seated.active:
self.settings['activity'] = 1.4
if self.ids.both.active:
self.settings['activity'] = 1.6
if self.ids.standing.active:
self.settings['activity'] = 1.8
self.resetForm()
else: # If the user pass the settings screen
self.settings['rec'] = False
self.manager.setSettings(self.settings, self.id_profile)
# Change the current screen
self.manager.current = 'Product Screen'
class ScreenProduct(Screen):
''' Class for the Product Screen '''
temp_dict = {'code':'', 'product_name': ''}
def getSelection(self, text1, text2, state):
# Select or deselect temporarly a product
if state:
self.temp_dict['code'] = text1
self.temp_dict['product_name'] = text2
else:
self.temp_dict['code'] = ''
self.temp_dict['product_name'] = ''
class ScreenQuantities(Screen):
''' Class for the Quantities Screen '''
temp_dict = {'code': [], 'product_name': [], 'quantity': [], 'color': []}
def initQuantity(self, data):
''' Initialize the dictionary of the products '''
if self.temp_dict['quantity'] == []:
self.temp_dict = data
self.ids.rv.getQuantities(data)
def updateQuantity(self, index, text1, text2, text3):
''' Store the quantities input by the user '''
l = len(self.temp_dict['quantity'])
if text3 == '' or text3 == '-' or int(text3) < 0:
text3 = '0'
if index < l:
self.temp_dict['code'][index] = text1
self.temp_dict['product_name'][index] = text2
self.temp_dict['quantity'][index] = text3
# Append the list of quantities if needed
else:
temp = ['0' for i in range(index-l)]
self.temp_dict['code'] = self.temp_dict['code'] + temp + [text1]
self.temp_dict['product_name'] = self.temp_dict['product_name'] + temp + [text2]
self.temp_dict['quantity'] = self.temp_dict['quantity'] + temp + [text3]
# Update the data displayed
self.initQuantity(self.temp_dict)
class ScreenFinal(Screen):
''' Class for the Final Screen. No variables or functions needed for this screen '''
pass
class Manager(ScreenManager):
''' Class for the Manager Controller. Store main data '''
selected_products = {'code': [], 'product_name': [], 'quantity': []}
settings = {'Rec': True, 'Name': '', 'Surname': '', 'Email': '', 'Age': 0, 'Sex': True, 'Pal': 0, \
'Weight': 0, 'Day': 0}
def getProfiles(self):
self.ids.screen_profile.ids.profile_spinner.values = \
[str(index + 1) + ' : ' + str(profile_list['name'][index]) + ' ' + str(profile_list['surname'][index]) \
for index in profile_list.index]
def toSettings(self, text):
if text == 'new':
id_profile = -999
elif text == 'pass':
id_profile = -1000
else:
items = text.split()
id_profile = items[0].strip()
id_profile = int(id_profile) - 1
self.ids.screen_settings.setForm(id_profile)
if id_profile != -1000:
self.current = 'Settings Screen'
def addProduct(self):
''' Add product to main storage '''
item1 = self.ids.screen_product.temp_dict['code']
item2 = self.ids.screen_product.temp_dict['product_name']
if item1 != '' and item2 != '':
self.selected_products['code'].append(item1)
self.selected_products['product_name'].append(item2)
self.selected_products['quantity'].append('0')
def deleteProduct(self):
''' Remove product of main storage '''
item1 = self.ids.screen_product.temp_dict['code']
item2 = self.ids.screen_product.temp_dict['product_name']
if item1 in self.selected_products['code'] and item2 in self.selected_products['product_name']:
self.selected_products['code'].remove(item1)
self.selected_products['product_name'].remove(item2)
self.selected_products['quantity'].pop()
def getQuantities(self, data):
''' Add quantities to main storage '''
self.selected_products['quantity'] = data['quantity']
l = len(self.selected_products['quantity'])
for item in range(l):
if self.selected_products['quantity'][item] == '':
self.selected_products['quantity'][item] = '0'
self.current = 'Final Screen'
def setSettings(self, data, new):
''' Add settings to main storage '''
self.settings['Rec'] = data['rec']
self.settings['Name'] = data['name']
self.settings['Surname'] = data['surname']
self.settings['Email'] = data['email']
self.settings['Pal'] = data['activity']
self.settings['Weight'] = data['weight']
self.settings['Day'] = data['days']
self.settings['Sex'] = data['sex']
self.settings['Age'] = data['age']
update = True
if new == -999:
temp_df = pd.DataFrame.from_dict({'index': [len(profile_list)], \
'name': [data['name']], 'surname': [data['surname']], \
'age': [data['age']], 'sex': [data['sex']], 'email': [data['email']], \
'weight': [data['weight']], \
'activity': [data['activity']], 'days': [data['days']]}).set_index('index')
new_profile_list = pd.concat([profile_list, temp_df])
elif new == -1000:
update = False
else:
temp_df = pd.DataFrame.from_dict({'name': [data['name']], 'surname': [data['surname']], \
'age': [data['age']], 'sex': [data['sex']], 'email': [data['email']], 'weight': [data['weight']], \
'activity': [data['activity']], 'days': [data['days']]})
new_profile_list= profile_list
new_profile_list.iloc[new] = temp_df.iloc[0]
if update:
new_profile_list.to_csv('./data/profile.csv', sep=';')
def computation(self):
''' Call algo for computation of NutriScore and recommendation. Display results '''
dict_product = {'Product': [], 'API': []}
for index in range(len(self.selected_products['code'])):
# Separation of API and OpenFoodFacts data
if str(self.selected_products['code'][index]) == 'API':
dict_product['API'].append((str(self.selected_products[
'product_name'][index]), int(self.selected_products['quantity'][index])))
else:
dict_product['Product'].append((str(self.selected_products[
'code'][index]), int(self.selected_products['quantity'][index])))
# Run the algorithm to get the recommendation to print on-screen
text_app_beverages, text_app_nonbeverages = algo(dict_product, self.settings, DF)
self.ids.screen_final.ids.beverages.text = text_app_beverages
self.ids.screen_final.ids.non_beverages.text = text_app_nonbeverages
class NutriScoreApp(App):
''' Main class of the App '''
def build(self):
''' Import the database for the whole application '''
global DF, allTrue, profile_list
try:
DF = pd.read_csv('./data/OpenFoodFacts_final.csv.gz', low_memory=False, index_col = [0])
allTrue = DF['product_name'].str.contains('', case=False) # True Vector of length len(DF)
profile_list = pd.read_csv('./data/profile.csv', sep=';', index_col=[0])
except:
print('Fatal error: files missing')
return Manager()
if __name__ == '__main__':
NutriScoreApp().run()
| 39.470825 | 116 | 0.568181 |
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.recycleboxlayout import RecycleBoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.checkbox import CheckBox
from kivy.uix.spinner import Spinner
from kivy.uix.recycleview import RecycleView
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.properties import BooleanProperty, ObjectProperty
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder
Builder.load_file('./src/rv.kv')
Builder.load_file('./src/screenhome.kv')
Builder.load_file('./src/screenprofile.kv')
Builder.load_file('./src/screensettings.kv')
Builder.load_file('./src/screenproduct.kv')
Builder.load_file('./src/screenquantities.kv')
Builder.load_file('./src/screenfinal.kv')
Builder.load_file('./src/manager.kv')
import pandas as pd
import re
from Algo_main import algo
class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior,
RecycleBoxLayout):
pass
class SelectableGrid(RecycleDataViewBehavior, GridLayout):
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
self.index = index
self.ids['id_label1'].text = data['label1']['text']
self.ids['id_label2'].text = data['label2']['text']
self.ids['id_label3'].text = data['label3']['text']
return super(SelectableGrid, self).refresh_view_attrs(
rv, index, data)
def on_touch_down(self, touch):
if super(SelectableGrid, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
return self.parent.select_with_touch(self.index, touch)
def apply_selection(self, rv, index, is_selected):
self.selected = is_selected
class SelectableQuantity(RecycleDataViewBehavior, GridLayout):
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
self.index = index
self.ids['id_label1'].text = data['label1']['text']
self.ids['id_label2'].text = data['label2']['text']
self.ids['id_label3'].text = data['label3']['text']
return super(SelectableQuantity, self).refresh_view_attrs(
rv, index, data)
class RV(RecycleView):
def __init__(self, **kwargs):
super(RV, self).__init__(**kwargs)
def upload(self, query, active):
self.data = []
if active:
self.parent.parent.getSelection('API', query, True)
self.data = [{'label1': {'text': 'API'}, 'label2': {'text': query}, 'label3': {'text': 'Add/Remove'}}]
else:
isinside = allTrue
for item in query.split():
isinside = isinside & \
(DF['product_name'].str.contains(item, case=False) | \
DF['Brands'].str.contains(item, case=False))
if any(isinside):
selection = DF[isinside]
for row in selection.itertuples():
d = {'label1': {'text': str(row[0])}, \
'label2': {'text': str(row[1])},
'label3': {'text': str(row[-1])}}
self.data.append(d)
else:
isinside = DF.index.str.contains(query, case=False)
if any(isinside):
selection = DF[isinside]
for row in selection.itertuples():
d = {'label1': {'text': str(row[0])}, \
'label2': {'text': str(row[1])},
'label3': {'text': str(row[-1])}}
self.data.append(d)
else:
self.data = [{'label1': {'text': ''}, \
'label2': {'text': 'No product found'}, 'label3': {'text': ''}}]
def getQuantities(self, dict):
self.data = []
code = dict['code']
product_name = dict['product_name']
quantity = dict['quantity']
for index in range(len(code)):
d = {'label1': {'text': code[index]}, 'label2': {'text': product_name[index]}, \
'label3': {'text': quantity[index]}}
self.data.append(d)
class ScreenHome(Screen):
pass
class ScreenProfile(Screen):
def updateDF(self):
global DF
DF = pd.read_csv('https://drive.google.com/uc?export=download&id=1aLUh1UoQcS9lBa6oVRln-DuskxK5uK3y', \
index_col=[0], low_memory = False)
DF.to_csv('./data/OpenFoodFacts_final.csv.gz', compression='gzip')
self.ids['update'].text = 'Updated'
self.ids['update'].background_color = (0,1,0,1)
def update(self):
self.ids['update'].text = 'Updating'
self.ids['update'].background_color = (50/255,164/255,206/255,1)
class ScreenSettings(Screen):
settings = {'rec': True,'name': '', 'surname': '', 'age': 0, 'sex': True, 'weight': 0, \
'email': '', 'activity': 0, 'days': 0}
id_profile = -999
def resetForm(self):
self.ids.sex.color = (1,1,1,1)
self.ids.activity.color = (1,1,1,1)
self.ids.age.hint_text_color = (0.5, 0.5, 0.5, 1.0)
self.ids.weight.hint_text_color = (0.5, 0.5, 0.5, 1.0)
self.ids.days.hint_text_color = (0.5, 0.5, 0.5, 1.0)
self.ids.email.hint_text_color = (0.5, 0.5, 0.5, 1.0)
self.ids.name.hint_text_color = (0.5, 0.5, 0.5, 1.0)
self.ids.surname.hint_text_color = (0.5, 0.5, 0.5, 1.0)
def setForm(self, id_profile):
self.id_profile = id_profile
self.settings = {'rec': True,'name': '', 'surname': '', 'age': 0, 'sex': True, 'weight': 0, \
'email': '', 'activity': 0, 'days': 0}
if int(self.id_profile) >= 0:
self.ids.name.text = str(profile_list.iloc[self.id_profile]['name'])
self.ids.surname.text= str(profile_list.iloc[self.id_profile]['surname'])
self.ids.age.text = str(profile_list.iloc[self.id_profile]['age'])
if bool(profile_list.iloc[self.id_profile]['sex']):
self.ids.male.active = True
self.ids.female.active = False
else:
self.ids.male.active = False
self.ids.female.active = True
self.ids.weight.text = str(profile_list.iloc[self.id_profile]['weight'])
self.ids.email.text = str(profile_list.iloc[self.id_profile]['email'])
self.ids.days.text = str(profile_list.iloc[self.id_profile]['days'])
if int(profile_list.iloc[self.id_profile]['activity']) == 1.8:
self.ids.seated.active = False
self.ids.both.active = False
self.ids.standing.active = True
elif int(profile_list.iloc[self.id_profile]['activity']) == 1.6:
self.ids.seated.active = False
self.ids.both.active = True
self.ids.standing.active = False
else:
self.ids.seated.active = True
self.ids.both.active = False
self.ids.standing.active = False
elif int(self.id_profile) == -999:
self.ids.name.text = ''
self.ids.surname.text = ''
self.ids.age.text = ''
self.ids.male.active = False
self.ids.female.active = False
self.ids.email.text = ''
self.ids.weight.text = ''
self.ids.seated.active = False
self.ids.both.active = False
self.ids.standing.active = False
self.ids.days.text = ''
else:
self.changeScreen(False)
def changeScreen(self, valid):
if valid:
self.resetForm()
if self.ids.name.text.strip() == '':
self.ids.name.hint_text_color = (1,0,0,1)
return False
elif self.ids.surname.text.strip() == '':
self.ids.surname.hint_text_color = (1,0,0,1)
return False
elif self.ids.age.text.strip() == '' or int(self.ids.age.text) <= 0 or \
int(self.ids.age.text) >= 120:
self.ids.age.text = ''
self.ids.age.hint_text_color = (1,0,0,1)
return False
elif not(self.ids.male.active or self.ids.female.active):
self.ids.sex.color = (1,0,0,1)
return False
elif not re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", self.ids.email.text):
self.ids.email.text = ''
self.ids.email.hint_text_color = (1,0,0,1)
return False
elif self.ids.weight.text.strip() == '' or int(self.ids.weight.text) <= 0:
self.ids.weight.text = ''
self.ids.weight.hint_text_color = (1,0,0,1)
return False
elif not(self.ids.seated.active or self.ids.both.active or self.ids.standing.active):
self.ids.activity.color = (1,0,0,1)
return False
elif self.ids.days.text.strip() == '' or int(self.ids.days.text) <= 0:
self.ids.days.text = ''
self.ids.days.hint_text_color = (1,0,0,1)
return False
else:
self.settings['rec'] = True
self.settings['name'] = self.ids.name.text
self.settings['surname'] = self.ids.surname.text
self.settings['age'] = int(self.ids.age.text)
self.settings['weight'] = int(self.ids.weight.text)
self.settings['email'] = self.ids.email.text
self.settings['days'] = int(self.ids.days.text)
self.settings['sex'] = self.ids.male.active
if self.ids.seated.active:
self.settings['activity'] = 1.4
if self.ids.both.active:
self.settings['activity'] = 1.6
if self.ids.standing.active:
self.settings['activity'] = 1.8
self.resetForm()
else:
self.settings['rec'] = False
self.manager.setSettings(self.settings, self.id_profile)
self.manager.current = 'Product Screen'
class ScreenProduct(Screen):
temp_dict = {'code':'', 'product_name': ''}
def getSelection(self, text1, text2, state):
if state:
self.temp_dict['code'] = text1
self.temp_dict['product_name'] = text2
else:
self.temp_dict['code'] = ''
self.temp_dict['product_name'] = ''
class ScreenQuantities(Screen):
temp_dict = {'code': [], 'product_name': [], 'quantity': [], 'color': []}
def initQuantity(self, data):
if self.temp_dict['quantity'] == []:
self.temp_dict = data
self.ids.rv.getQuantities(data)
def updateQuantity(self, index, text1, text2, text3):
l = len(self.temp_dict['quantity'])
if text3 == '' or text3 == '-' or int(text3) < 0:
text3 = '0'
if index < l:
self.temp_dict['code'][index] = text1
self.temp_dict['product_name'][index] = text2
self.temp_dict['quantity'][index] = text3
else:
temp = ['0' for i in range(index-l)]
self.temp_dict['code'] = self.temp_dict['code'] + temp + [text1]
self.temp_dict['product_name'] = self.temp_dict['product_name'] + temp + [text2]
self.temp_dict['quantity'] = self.temp_dict['quantity'] + temp + [text3]
self.initQuantity(self.temp_dict)
class ScreenFinal(Screen):
pass
class Manager(ScreenManager):
selected_products = {'code': [], 'product_name': [], 'quantity': []}
settings = {'Rec': True, 'Name': '', 'Surname': '', 'Email': '', 'Age': 0, 'Sex': True, 'Pal': 0, \
'Weight': 0, 'Day': 0}
def getProfiles(self):
self.ids.screen_profile.ids.profile_spinner.values = \
[str(index + 1) + ' : ' + str(profile_list['name'][index]) + ' ' + str(profile_list['surname'][index]) \
for index in profile_list.index]
def toSettings(self, text):
if text == 'new':
id_profile = -999
elif text == 'pass':
id_profile = -1000
else:
items = text.split()
id_profile = items[0].strip()
id_profile = int(id_profile) - 1
self.ids.screen_settings.setForm(id_profile)
if id_profile != -1000:
self.current = 'Settings Screen'
def addProduct(self):
item1 = self.ids.screen_product.temp_dict['code']
item2 = self.ids.screen_product.temp_dict['product_name']
if item1 != '' and item2 != '':
self.selected_products['code'].append(item1)
self.selected_products['product_name'].append(item2)
self.selected_products['quantity'].append('0')
def deleteProduct(self):
item1 = self.ids.screen_product.temp_dict['code']
item2 = self.ids.screen_product.temp_dict['product_name']
if item1 in self.selected_products['code'] and item2 in self.selected_products['product_name']:
self.selected_products['code'].remove(item1)
self.selected_products['product_name'].remove(item2)
self.selected_products['quantity'].pop()
def getQuantities(self, data):
self.selected_products['quantity'] = data['quantity']
l = len(self.selected_products['quantity'])
for item in range(l):
if self.selected_products['quantity'][item] == '':
self.selected_products['quantity'][item] = '0'
self.current = 'Final Screen'
def setSettings(self, data, new):
self.settings['Rec'] = data['rec']
self.settings['Name'] = data['name']
self.settings['Surname'] = data['surname']
self.settings['Email'] = data['email']
self.settings['Pal'] = data['activity']
self.settings['Weight'] = data['weight']
self.settings['Day'] = data['days']
self.settings['Sex'] = data['sex']
self.settings['Age'] = data['age']
update = True
if new == -999:
temp_df = pd.DataFrame.from_dict({'index': [len(profile_list)], \
'name': [data['name']], 'surname': [data['surname']], \
'age': [data['age']], 'sex': [data['sex']], 'email': [data['email']], \
'weight': [data['weight']], \
'activity': [data['activity']], 'days': [data['days']]}).set_index('index')
new_profile_list = pd.concat([profile_list, temp_df])
elif new == -1000:
update = False
else:
temp_df = pd.DataFrame.from_dict({'name': [data['name']], 'surname': [data['surname']], \
'age': [data['age']], 'sex': [data['sex']], 'email': [data['email']], 'weight': [data['weight']], \
'activity': [data['activity']], 'days': [data['days']]})
new_profile_list= profile_list
new_profile_list.iloc[new] = temp_df.iloc[0]
if update:
new_profile_list.to_csv('./data/profile.csv', sep=';')
def computation(self):
dict_product = {'Product': [], 'API': []}
for index in range(len(self.selected_products['code'])):
if str(self.selected_products['code'][index]) == 'API':
dict_product['API'].append((str(self.selected_products[
'product_name'][index]), int(self.selected_products['quantity'][index])))
else:
dict_product['Product'].append((str(self.selected_products[
'code'][index]), int(self.selected_products['quantity'][index])))
text_app_beverages, text_app_nonbeverages = algo(dict_product, self.settings, DF)
self.ids.screen_final.ids.beverages.text = text_app_beverages
self.ids.screen_final.ids.non_beverages.text = text_app_nonbeverages
class NutriScoreApp(App):
def build(self):
global DF, allTrue, profile_list
try:
DF = pd.read_csv('./data/OpenFoodFacts_final.csv.gz', low_memory=False, index_col = [0])
allTrue = DF['product_name'].str.contains('', case=False)
profile_list = pd.read_csv('./data/profile.csv', sep=';', index_col=[0])
except:
print('Fatal error: files missing')
return Manager()
if __name__ == '__main__':
NutriScoreApp().run()
| true | true |
f7168bb426ad7afb8dbd70d8b80b3ec7a14dbc4b | 28,177 | py | Python | sppas/sppas/src/ui/phoenix/page_files/associate.py | mirfan899/MTTS | 3167b65f576abcc27a8767d24c274a04712bd948 | [
"MIT"
] | null | null | null | sppas/sppas/src/ui/phoenix/page_files/associate.py | mirfan899/MTTS | 3167b65f576abcc27a8767d24c274a04712bd948 | [
"MIT"
] | null | null | null | sppas/sppas/src/ui/phoenix/page_files/associate.py | mirfan899/MTTS | 3167b65f576abcc27a8767d24c274a04712bd948 | [
"MIT"
] | null | null | null | """
..
---------------------------------------------------------------------
___ __ __ __ ___
/ | \ | \ | \ / the automatic
\__ |__/ |__/ |___| \__ annotation and
\ | | | | \ analysis
___/ | | | | ___/ of speech
http://www.sppas.org/
Use of this software is governed by the GNU Public License, version 3.
SPPAS 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 3 of the License, or
(at your option) any later version.
SPPAS is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with SPPAS. If not, see <http://www.gnu.org/licenses/>.
This banner notice must not be removed.
---------------------------------------------------------------------
ui.phoenix.page_files.associate.py
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Actions to associate files and references of the catalogue.
"""
import wx
import logging
from sppas import sppasTypeError
from sppas import sg
from sppas.src.config import ui_translation
from sppas.src.files import FileData
from sppas.src.files import States
from sppas.src.files import sppasFileDataFilters
from ..dialogs import Information, Error
from ..windows import sppasStaticText, sppasTextCtrl
from ..windows import sppasPanel
from ..windows import sppasDialog
from ..windows import sppasToolbar
from ..windows import BitmapTextButton, CheckButton
from ..windows import sppasRadioBoxPanel
from ..main_events import DataChangedEvent
from .filesutils import IdentifierTextValidator
# ---------------------------------------------------------------------------
MSG_HEADER_FILTER = ui_translation.gettext("Checking files")
MSG_NB_CHECKED = "{:d} files were matching the given filters and were checked."
MSG_NO_CHECKED = "None of the files is matching the given filters."
ASS_ACT_CHECK_ERROR = "Files can't be filtered due to the following" \
" error:\n{!s:s}"
# ---------------------------------------------------------------------------
class AssociatePanel(sppasPanel):
"""Panel with tools to associate files and references of the catalogue.
:author: Brigitte Bigi
:organization: Laboratoire Parole et Langage, Aix-en-Provence, France
:contact: develop@sppas.org
:license: GPL, v3
:copyright: Copyright (C) 2011-2019 Brigitte Bigi
"""
def __init__(self, parent, name=wx.PanelNameStr):
super(AssociatePanel, self).__init__(
parent,
id=wx.ID_ANY,
pos=wx.DefaultPosition,
size=wx.DefaultSize,
style=wx.BORDER_NONE | wx.TAB_TRAVERSAL | wx.WANTS_CHARS | wx.NO_FULL_REPAINT_ON_RESIZE | wx.CLIP_CHILDREN,
name=name)
# The data this page is working on
self.__data = FileData()
# State of the button to check all or none of the filenames
self._checkall = False
# Construct the panel
self._create_content()
self._setup_events()
self.Layout()
# ------------------------------------------------------------------------
def set_data(self, data):
"""Assign new data to this panel.
:param data: (FileData)
"""
if isinstance(data, FileData) is False:
raise sppasTypeError("FileData", type(data))
logging.debug('New data to set in the associate panel. '
'Id={:s}'.format(data.id))
self.__data = data
# ------------------------------------------------------------------------
# Private methods to construct the panel.
# ------------------------------------------------------------------------
def _create_content(self):
"""Create the main content."""
filtr = self.__create_button("check_filter")
check = self.__create_button("checklist")
link = self.__create_button("link_add")
unlink = self.__create_button("link_del")
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.AddStretchSpacer(4)
sizer.Add(filtr, 1, wx.TOP | wx.ALIGN_CENTRE, 0)
sizer.Add(check, 1, wx.TOP | wx.ALIGN_CENTRE, 0)
sizer.AddStretchSpacer(2)
sizer.Add(link, 1, wx.BOTTOM | wx.ALIGN_CENTRE, 0)
sizer.Add(unlink, 1, wx.BOTTOM | wx.ALIGN_CENTRE, 0)
sizer.AddStretchSpacer(4)
self.SetMinSize(wx.Size(sppasPanel.fix_size(32), -1))
self.SetSizer(sizer)
# ------------------------------------------------------------------------
# ------------------------------------------------------------------------
def __create_button(self, icon, label=None):
btn = BitmapTextButton(self, name=icon, label=label)
btn.FocusStyle = wx.PENSTYLE_SOLID
btn.FocusWidth = 3
btn.FocusColour = wx.Colour(128, 128, 196, 128) # violet
btn.LabelPosition = wx.BOTTOM
btn.Spacing = 4
btn.BorderWidth = 0
btn.BitmapColour = self.GetForegroundColour()
btn.SetMinSize(wx.Size(sppasPanel.fix_size(24),
sppasPanel.fix_size(24)))
return btn
# -----------------------------------------------------------------------
# Events management
# -----------------------------------------------------------------------
def _setup_events(self):
"""Associate a handler function with the events.
It means that when an event occurs then the process handler function
will be called.
"""
# The user pressed a key of its keyboard
self.Bind(wx.EVT_KEY_DOWN, self._process_key_event)
# The user clicked (LeftDown - LeftUp) an action button
self.Bind(wx.EVT_BUTTON, self._process_action)
# ------------------------------------------------------------------------
def notify(self):
"""Send the EVT_DATA_CHANGED to the parent."""
if self.GetParent() is not None:
self.__data.set_state(States().CHECKED)
evt = DataChangedEvent(data=self.__data)
evt.SetEventObject(self)
wx.PostEvent(self.GetParent(), evt)
# ------------------------------------------------------------------------
# Callbacks to events
# ------------------------------------------------------------------------
def _process_key_event(self, event):
"""Respond to a keypress event."""
key_code = event.GetKeyCode()
logging.debug('Associate panel received a key event. key_code={:d}'.format(key_code))
logging.debug('Key event skipped by the associate panel.')
event.Skip()
# ------------------------------------------------------------------------
def _process_action(self, event):
"""Respond to an association event."""
name = event.GetButtonObj().GetName()
if name == "check_filter":
self.check_filter()
elif name == "checklist":
self.check_all()
elif name == "link_add":
self.add_links()
elif name == "link_del":
self.delete_links()
event.Skip()
# ------------------------------------------------------------------------
# GUI methods to perform actions on the data
# ------------------------------------------------------------------------
def check_filter(self):
"""Check filenames matching the user-defined filters."""
dlg = sppasFilesFilterDialog(self)
response = dlg.ShowModal()
if response != wx.ID_CANCEL:
data_filters = dlg.get_filters()
if len(data_filters) > 0:
wx.BeginBusyCursor()
try:
data_set = self.__process_filter(data_filters, dlg.match_all)
if len(data_set) == 0:
Information(MSG_NO_CHECKED)
else:
# Uncheck all files (except the locked ones!) and all references
self.__data.set_object_state(States().UNUSED)
roots = list()
# Check files of the filtered data_set
for fn in data_set:
self.__data.set_object_state(States().CHECKED, fn)
root = self.__data.get_parent(fn)
if root not in roots:
roots.append(root)
Information(MSG_NB_CHECKED.format(len(data_set)))
# Check references matching the checked files
for fr in roots:
for ref in fr.get_references():
ref.set_state(States().CHECKED)
self.notify()
wx.EndBusyCursor()
except Exception as e:
wx.EndBusyCursor()
Error(ASS_ACT_CHECK_ERROR.format(str(e)), "Check error")
dlg.Destroy()
# ------------------------------------------------------------------------
def __process_filter(self, data_filters, match_all=True):
"""Perform the filter process.
:param data_filters: list of tuples with (filter name, function name, values)
:param match_all: (bool)
"""
logging.info("Check files matching the following: ")
logging.info(" >>> filter = sppasFileDataFilters()")
f = sppasFileDataFilters(self.__data)
data_sets = list()
for d in data_filters:
if len(d) != 3:
logging.error("Bad data format: {:s}".format(str(d)))
continue
# the method to be uses by Compare
method = d[0]
# the function to be applied
fct = d[1]
if method == "att":
# identifier:value are separated by a ":" but a tuple is needed
values = tuple(d[2].split(":"))
logging.info(" >>> filter.{:s}({:s}={!s:s})".format(method, fct, str(values)))
data_set = getattr(f, method)(**{fct: values})
# a little bit of doc:
# - getattr() returns the value of the named attributed of object:
# it returns f.tag if called like getattr(f, "tag")
# - func(**{'x': '3'}) is equivalent to func(x='3')
else:
# all the possible values are separated by commas
values = d[2].split(",")
logging.info(" >>> filter.{:s}({:s}={!s:s})".format(method, fct, values[0]))
data_set = getattr(f, method)(**{fct: values[0]})
# Apply "or" between each data_set matching a value
for i in range(1, len(values)):
v = values[i].strip()
data_set = data_set | getattr(f, method)(**{fct: v})
logging.info(" >>> | filter.{:s}({:s}={!s:s})".format(method, fct, v))
data_sets.append(data_set)
# no filename is matching
if len(data_sets) == 0:
return list()
# Merge results (apply '&' or '|' on the resulting data sets)
data_set = data_sets[0]
if match_all is True:
for i in range(1, len(data_sets)):
data_set = data_set & data_sets[i]
if len(data_set) == 0:
# no need to go further...
return list()
else:
for i in range(1, len(data_sets)):
data_set = data_set | data_sets[i]
return data_set
# ------------------------------------------------------------------------
def check_all(self):
"""Check all or any of the filenames and references."""
# reverse the current state
self._checkall = not self._checkall
# ask the data to change their state
if self._checkall is True:
state = States().CHECKED
else:
state = States().UNUSED
self.__data.set_object_state(state)
# update the view of checked references & checked files
self.notify()
# ------------------------------------------------------------------------
def add_links(self):
"""Associate checked filenames with checked references."""
associed = self.__data.associate()
if associed > 0:
self.notify()
# ------------------------------------------------------------------------
def delete_links(self):
"""Dissociate checked filenames with checked references."""
dissocied = self.__data.dissociate()
if dissocied > 0:
self.notify()
# ---------------------------------------------------------------------------
class sppasFilesFilterDialog(sppasDialog):
"""Dialog to get filters to check files and references.
:author: Brigitte Bigi
:organization: Laboratoire Parole et Langage, Aix-en-Provence, France
:contact: develop@sppas.org
:license: GPL, v3
:copyright: Copyright (C) 2011-2019 Brigitte Bigi
"""
def __init__(self, parent):
"""Create a files filter dialog.
:param parent: (wx.Window)
"""
super(sppasFilesFilterDialog, self).__init__(
parent=parent,
title='{:s} Files selection'.format(sg.__name__),
style=wx.DEFAULT_FRAME_STYLE)
self.match_all = True
self.CreateHeader(title="Define filters to check files",
icon_name="check_filter")
self._create_content()
self._create_buttons()
self.Bind(wx.EVT_BUTTON, self._process_event)
self.SetSize(wx.Size(480, 320))
self.LayoutComponents()
self.CenterOnParent()
self.FadeIn(deltaN=-8)
# -----------------------------------------------------------------------
# Public methods
# -----------------------------------------------------------------------
def get_filters(self):
"""Return a list of (filter, function, values)."""
filters = list()
for i in range(self.listctrl.GetItemCount()):
filter_name = self.listctrl.GetValue(i, 0)
fct_name = self.listctrl.GetValue(i, 1)
values = self.listctrl.GetValue(i, 2)
filters.append((filter_name, fct_name, values))
return filters
# -----------------------------------------------------------------------
# Methods to construct the GUI
# -----------------------------------------------------------------------
def _create_content(self):
"""Create the content of the message dialog."""
panel = sppasPanel(self, name="content")
tb = self.__create_toolbar(panel)
self.listctrl = wx.dataview.DataViewListCtrl(panel, wx.ID_ANY)
self.listctrl.AppendTextColumn("filter", width=80)
self.listctrl.AppendTextColumn("function", width=90)
self.listctrl.AppendTextColumn("value", width=120)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(tb, proportion=0, flag=wx.EXPAND, border=0)
sizer.Add(self.listctrl, proportion=1, flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5)
panel.SetSizer(sizer)
self.SetMinSize(wx.Size(320, 200))
panel.SetAutoLayout(True)
self.SetContent(panel)
# -----------------------------------------------------------------------
def __create_toolbar(self, parent):
"""Create the toolbar."""
tb = sppasToolbar(parent)
tb.set_focus_color(wx.Colour(196, 196, 96, 128))
tb.AddTextButton("filter_path", "+ Path")
tb.AddTextButton("filter_name", "+ Name")
tb.AddTextButton("filter_ext", "+ Type")
tb.AddTextButton("filter_ref", "+ Ref.")
tb.AddTextButton("filter_att", "+ Value")
tb.AddSpacer()
#tb.AddTextButton(None, "- Remove")
return tb
# -----------------------------------------------------------------------
def _create_buttons(self):
"""Create the buttons and bind events."""
panel = sppasPanel(self, name="actions")
# panel.SetMinSize(wx.Size(-1, wx.GetApp().settings.action_height))
sizer = wx.BoxSizer(wx.HORIZONTAL)
# Create the buttons
cancel_btn = self.__create_action_button(panel, "Cancel", "cancel")
apply_or_btn = self.__create_action_button(panel, "Apply - OR", "apply")
apply_and_btn = self.__create_action_button(panel, "Apply - AND", "ok")
apply_and_btn.SetFocus()
sizer.Add(cancel_btn, 1, wx.ALL | wx.EXPAND, 0)
sizer.Add(self.VertLine(parent=panel), 0, wx.ALL | wx.EXPAND, 0)
sizer.Add(apply_or_btn, 1, wx.ALL | wx.EXPAND, 0)
sizer.Add(self.VertLine(parent=panel), 0, wx.ALL | wx.EXPAND, 0)
sizer.Add(apply_and_btn, 1, wx.ALL | wx.EXPAND, 0)
panel.SetSizer(sizer)
self.SetActions(panel)
# -----------------------------------------------------------------------
def __create_action_button(self, parent, text, icon):
btn = BitmapTextButton(parent, label=text, name=icon)
btn.LabelPosition = wx.RIGHT
btn.Spacing = sppasDialog.fix_size(12)
btn.BorderWidth = 0
btn.BitmapColour = self.GetForegroundColour()
btn.SetMinSize(wx.Size(sppasDialog.fix_size(32),
sppasDialog.fix_size(32)))
return btn
# ------------------------------------------------------------------------
# Callback to events
# ------------------------------------------------------------------------
def _process_event(self, event):
"""Process any kind of events.
:param event: (wx.Event)
"""
event_obj = event.GetEventObject()
event_name = event_obj.GetName()
if event_name == "filter_path":
self.__append_filter("path")
elif event_name == "filter_name":
self.__append_filter("name")
elif event_name == "filter_ext":
self.__append_filter("extension")
elif event_name == "filter_ref":
self.__append_filter("ref")
elif event_name == "filter_att":
dlg = sppasAttributeFilterDialog(self)
response = dlg.ShowModal()
if response == wx.ID_OK:
# Name of the method in sppasFileDataFilters,
# Name of the function and its value
f = dlg.get_data()
v = f[1].split(':')
if len(v[0].strip()) > 1 and len(v[1].strip()) > 0:
self.listctrl.AppendItem(["att", f[0], f[1].strip()])
else:
logging.error("Invalid input string for identifier or value.")
dlg.Destroy()
elif event_name == "cancel":
self.SetReturnCode(wx.ID_CANCEL)
self.Close()
elif event_name == "apply":
self.match_all = False
self.EndModal(wx.ID_APPLY)
elif event_name == "ok":
self.match_all = True
self.EndModal(wx.ID_OK)
else:
event.Skip()
# ------------------------------------------------------------------------
def __append_filter(self, fct):
dlg = sppasStringFilterDialog(self)
response = dlg.ShowModal()
if response == wx.ID_OK:
# Name of the method in sppasFileDataFilters,
# Name of the function and its value
f = dlg.get_data()
if len(f[1].strip()) > 0:
self.listctrl.AppendItem([fct, f[0], f[1].strip()])
else:
logging.error("Empty input pattern.")
dlg.Destroy()
# ---------------------------------------------------------------------------
class sppasStringFilterDialog(sppasDialog):
"""Dialog to get a filter on a string.
:author: Brigitte Bigi
:organization: Laboratoire Parole et Langage, Aix-en-Provence, France
:contact: develop@sppas.org
:license: GPL, v3
:copyright: Copyright (C) 2011-2019 Brigitte Bigi
"""
choices = (
("exact", "exact"),
("contains", "contains"),
("starts with", "startswith"),
("ends with", "endswith"),
("match (regexp)", "regexp"),
("not exact", "exact"),
("not contains", "contains"),
("not starts with", "startswith"),
("not ends with", "endswith"),
("not match", "regexp")
)
def __init__(self, parent):
"""Create a string filter dialog.
:param parent: (wx.Window)
"""
super(sppasStringFilterDialog, self).__init__(
parent=parent,
title='{:s} filter'.format(sg.__name__),
style=wx.DEFAULT_FRAME_STYLE)
self._create_content()
self.CreateActions([wx.ID_CANCEL, wx.ID_OK])
self.SetSize(wx.Size(380, 320))
self.LayoutComponents()
self.CenterOnParent()
# -----------------------------------------------------------------------
def get_data(self):
"""Return the data defined by the user.
Returns: (tuple) with:
- function (str): one of the methods in Compare
- values (list): patterns to find separated by commas
"""
idx = self.radiobox.GetSelection()
label = self.radiobox.GetStringSelection()
given_fct = self.choices[idx][1]
# Fill the resulting dict
prepend_fct = ""
if given_fct != "regexp":
# prepend "not_" if reverse
if "not" in label:
prepend_fct += "not_"
# prepend "i" if case-insensitive
if self.checkbox.GetValue() is False:
prepend_fct += "i"
return prepend_fct+given_fct, self.text.GetValue()
# -----------------------------------------------------------------------
# Methods to construct the GUI
# -----------------------------------------------------------------------
def _create_content(self):
"""Create the content of the message dialog."""
panel = sppasPanel(self, name="content")
label = sppasStaticText(panel, label="Search for pattern(s): ")
self.text = sppasTextCtrl(panel, value="")
choices = [row[0] for row in self.choices]
self.radiobox = sppasRadioBoxPanel(
panel,
choices=choices,
majorDimension=2,
style=wx.RA_SPECIFY_COLS)
self.radiobox.SetSelection(1)
self.checkbox = CheckButton(panel, label="Case sensitive")
self.checkbox.SetValue(False)
# Layout
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(label, 0, flag=wx.EXPAND | wx.ALL, border=4)
sizer.Add(self.text, 0, flag=wx.EXPAND | wx.ALL, border=4)
sizer.Add(self.radiobox, 1, flag=wx.EXPAND | wx.ALL, border=4)
sizer.Add(self.checkbox, 0, flag=wx.EXPAND | wx.ALL, border=4)
panel.SetSizer(sizer)
panel.SetMinSize((240, 160))
panel.SetAutoLayout(True)
self.SetContent(panel)
# ---------------------------------------------------------------------------
class sppasAttributeFilterDialog(sppasDialog):
"""Dialog to get a filter on an attribute.
:author: Brigitte Bigi
:organization: Laboratoire Parole et Langage, Aix-en-Provence, France
:contact: develop@sppas.org
:license: GPL, v3
:copyright: Copyright (C) 2011-2019 Brigitte Bigi
"""
choices = (
("exact", "exact"),
("contains", "contains"),
("starts with", "startswith"),
("ends with", "endswith"),
("match (regexp)", "regexp"),
("not exact", "exact"),
("not contains", "contains"),
("not starts with", "startswith"),
("not ends with", "endswith"),
("not match", "regexp"),
("equal", "equal"),
("greater than", "gt"),
("greater or equal", "ge"),
("lower than", "lt"),
("lower or equal", "le")
)
def __init__(self, parent):
"""Create an attribute filter dialog.
:param parent: (wx.Window)
"""
super(sppasAttributeFilterDialog, self).__init__(
parent=parent,
title='{:s} filter'.format(sg.__name__),
style=wx.DEFAULT_FRAME_STYLE)
self._create_content()
self.CreateActions([wx.ID_CANCEL, wx.ID_OK])
self.SetMinSize(wx.Size(sppasDialog.fix_size(420),
sppasDialog.fix_size(320)))
self.LayoutComponents()
self.CenterOnParent()
# ------------------------------------------------------------------------
def get_data(self):
"""Return the data defined by the user.
Returns: (tuple) with:
- function (str): one of the methods in Compare
- values (list): attribute to find as identifier, value
"""
idx = self.radiobox.GetSelection()
label = self.radiobox.GetStringSelection()
given_fct = self.choices[idx][1]
# Fill the resulting dict
prepend_fct = ""
if idx < 10 and given_fct != "regexp":
# prepend "not_" if reverse
if "not" in label:
prepend_fct += "not_"
# prepend "i" if case-insensitive
if self.checkbox.GetValue() is False:
prepend_fct += "i"
return prepend_fct + given_fct, \
self.text_ident.GetValue() + ":" + self.text_value.GetValue()
# -----------------------------------------------------------------------
# Methods to construct the GUI
# -----------------------------------------------------------------------
def _create_content(self):
"""Create the content of the message dialog."""
panel = sppasPanel(self, name="content")
label = sppasStaticText(panel, label="Identifier: ")
self.text_ident = sppasTextCtrl(
panel,
value="",
validator=IdentifierTextValidator())
choices = [row[0] for row in sppasAttributeFilterDialog.choices]
self.radiobox = sppasRadioBoxPanel(
panel,
choices=choices,
majorDimension=3,
style=wx.RA_SPECIFY_COLS)
self.radiobox.SetSelection(1)
self.radiobox.Bind(wx.EVT_RADIOBOX, self._on_radiobox_checked)
self.checkbox = CheckButton(panel, label="Case sensitive")
self.checkbox.SetValue(False)
self.text_value = sppasTextCtrl(panel, value="")
# Layout
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(label, 0, flag=wx.EXPAND | wx.ALL, border=4)
sizer.Add(self.text_ident, 0, flag=wx.EXPAND | wx.ALL, border=4)
sizer.Add(self.radiobox, 1, flag=wx.EXPAND | wx.ALL, border=4)
sizer.Add(self.text_value, 0, flag=wx.EXPAND | wx.ALL, border=4)
sizer.Add(self.checkbox, 0, flag=wx.EXPAND | wx.ALL, border=4)
panel.SetSizer(sizer)
panel.SetMinSize((240, 160))
panel.SetAutoLayout(True)
self.SetContent(panel)
def _on_radiobox_checked(self, event):
value = self.radiobox.GetStringSelection()
if value in sppasAttributeFilterDialog.choices[10:]:
self.checkbox.SetValue(False)
self.checkbox.Enable(False)
else:
self.checkbox.Enable(True)
| 35.894268 | 119 | 0.509245 |
import wx
import logging
from sppas import sppasTypeError
from sppas import sg
from sppas.src.config import ui_translation
from sppas.src.files import FileData
from sppas.src.files import States
from sppas.src.files import sppasFileDataFilters
from ..dialogs import Information, Error
from ..windows import sppasStaticText, sppasTextCtrl
from ..windows import sppasPanel
from ..windows import sppasDialog
from ..windows import sppasToolbar
from ..windows import BitmapTextButton, CheckButton
from ..windows import sppasRadioBoxPanel
from ..main_events import DataChangedEvent
from .filesutils import IdentifierTextValidator
MSG_HEADER_FILTER = ui_translation.gettext("Checking files")
MSG_NB_CHECKED = "{:d} files were matching the given filters and were checked."
MSG_NO_CHECKED = "None of the files is matching the given filters."
ASS_ACT_CHECK_ERROR = "Files can't be filtered due to the following" \
" error:\n{!s:s}"
# ---------------------------------------------------------------------------
class AssociatePanel(sppasPanel):
def __init__(self, parent, name=wx.PanelNameStr):
super(AssociatePanel, self).__init__(
parent,
id=wx.ID_ANY,
pos=wx.DefaultPosition,
size=wx.DefaultSize,
style=wx.BORDER_NONE | wx.TAB_TRAVERSAL | wx.WANTS_CHARS | wx.NO_FULL_REPAINT_ON_RESIZE | wx.CLIP_CHILDREN,
name=name)
# The data this page is working on
self.__data = FileData()
# State of the button to check all or none of the filenames
self._checkall = False
# Construct the panel
self._create_content()
self._setup_events()
self.Layout()
# ------------------------------------------------------------------------
def set_data(self, data):
if isinstance(data, FileData) is False:
raise sppasTypeError("FileData", type(data))
logging.debug('New data to set in the associate panel. '
'Id={:s}'.format(data.id))
self.__data = data
# ------------------------------------------------------------------------
# Private methods to construct the panel.
# ------------------------------------------------------------------------
def _create_content(self):
filtr = self.__create_button("check_filter")
check = self.__create_button("checklist")
link = self.__create_button("link_add")
unlink = self.__create_button("link_del")
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.AddStretchSpacer(4)
sizer.Add(filtr, 1, wx.TOP | wx.ALIGN_CENTRE, 0)
sizer.Add(check, 1, wx.TOP | wx.ALIGN_CENTRE, 0)
sizer.AddStretchSpacer(2)
sizer.Add(link, 1, wx.BOTTOM | wx.ALIGN_CENTRE, 0)
sizer.Add(unlink, 1, wx.BOTTOM | wx.ALIGN_CENTRE, 0)
sizer.AddStretchSpacer(4)
self.SetMinSize(wx.Size(sppasPanel.fix_size(32), -1))
self.SetSizer(sizer)
# ------------------------------------------------------------------------
# ------------------------------------------------------------------------
def __create_button(self, icon, label=None):
btn = BitmapTextButton(self, name=icon, label=label)
btn.FocusStyle = wx.PENSTYLE_SOLID
btn.FocusWidth = 3
btn.FocusColour = wx.Colour(128, 128, 196, 128) # violet
btn.LabelPosition = wx.BOTTOM
btn.Spacing = 4
btn.BorderWidth = 0
btn.BitmapColour = self.GetForegroundColour()
btn.SetMinSize(wx.Size(sppasPanel.fix_size(24),
sppasPanel.fix_size(24)))
return btn
# -----------------------------------------------------------------------
# Events management
# -----------------------------------------------------------------------
def _setup_events(self):
# The user pressed a key of its keyboard
self.Bind(wx.EVT_KEY_DOWN, self._process_key_event)
# The user clicked (LeftDown - LeftUp) an action button
self.Bind(wx.EVT_BUTTON, self._process_action)
# ------------------------------------------------------------------------
def notify(self):
if self.GetParent() is not None:
self.__data.set_state(States().CHECKED)
evt = DataChangedEvent(data=self.__data)
evt.SetEventObject(self)
wx.PostEvent(self.GetParent(), evt)
# ------------------------------------------------------------------------
# Callbacks to events
# ------------------------------------------------------------------------
def _process_key_event(self, event):
key_code = event.GetKeyCode()
logging.debug('Associate panel received a key event. key_code={:d}'.format(key_code))
logging.debug('Key event skipped by the associate panel.')
event.Skip()
# ------------------------------------------------------------------------
def _process_action(self, event):
name = event.GetButtonObj().GetName()
if name == "check_filter":
self.check_filter()
elif name == "checklist":
self.check_all()
elif name == "link_add":
self.add_links()
elif name == "link_del":
self.delete_links()
event.Skip()
# ------------------------------------------------------------------------
# GUI methods to perform actions on the data
# ------------------------------------------------------------------------
def check_filter(self):
dlg = sppasFilesFilterDialog(self)
response = dlg.ShowModal()
if response != wx.ID_CANCEL:
data_filters = dlg.get_filters()
if len(data_filters) > 0:
wx.BeginBusyCursor()
try:
data_set = self.__process_filter(data_filters, dlg.match_all)
if len(data_set) == 0:
Information(MSG_NO_CHECKED)
else:
# Uncheck all files (except the locked ones!) and all references
self.__data.set_object_state(States().UNUSED)
roots = list()
# Check files of the filtered data_set
for fn in data_set:
self.__data.set_object_state(States().CHECKED, fn)
root = self.__data.get_parent(fn)
if root not in roots:
roots.append(root)
Information(MSG_NB_CHECKED.format(len(data_set)))
# Check references matching the checked files
for fr in roots:
for ref in fr.get_references():
ref.set_state(States().CHECKED)
self.notify()
wx.EndBusyCursor()
except Exception as e:
wx.EndBusyCursor()
Error(ASS_ACT_CHECK_ERROR.format(str(e)), "Check error")
dlg.Destroy()
# ------------------------------------------------------------------------
def __process_filter(self, data_filters, match_all=True):
logging.info("Check files matching the following: ")
logging.info(" >>> filter = sppasFileDataFilters()")
f = sppasFileDataFilters(self.__data)
data_sets = list()
for d in data_filters:
if len(d) != 3:
logging.error("Bad data format: {:s}".format(str(d)))
continue
# the method to be uses by Compare
method = d[0]
# the function to be applied
fct = d[1]
if method == "att":
# identifier:value are separated by a ":" but a tuple is needed
values = tuple(d[2].split(":"))
logging.info(" >>> filter.{:s}({:s}={!s:s})".format(method, fct, str(values)))
data_set = getattr(f, method)(**{fct: values})
# a little bit of doc:
# - getattr() returns the value of the named attributed of object:
# it returns f.tag if called like getattr(f, "tag")
# - func(**{'x': '3'}) is equivalent to func(x='3')
else:
# all the possible values are separated by commas
values = d[2].split(",")
logging.info(" >>> filter.{:s}({:s}={!s:s})".format(method, fct, values[0]))
data_set = getattr(f, method)(**{fct: values[0]})
# Apply "or" between each data_set matching a value
for i in range(1, len(values)):
v = values[i].strip()
data_set = data_set | getattr(f, method)(**{fct: v})
logging.info(" >>> | filter.{:s}({:s}={!s:s})".format(method, fct, v))
data_sets.append(data_set)
# no filename is matching
if len(data_sets) == 0:
return list()
# Merge results (apply '&' or '|' on the resulting data sets)
data_set = data_sets[0]
if match_all is True:
for i in range(1, len(data_sets)):
data_set = data_set & data_sets[i]
if len(data_set) == 0:
# no need to go further...
return list()
else:
for i in range(1, len(data_sets)):
data_set = data_set | data_sets[i]
return data_set
# ------------------------------------------------------------------------
def check_all(self):
# reverse the current state
self._checkall = not self._checkall
# ask the data to change their state
if self._checkall is True:
state = States().CHECKED
else:
state = States().UNUSED
self.__data.set_object_state(state)
# update the view of checked references & checked files
self.notify()
# ------------------------------------------------------------------------
def add_links(self):
associed = self.__data.associate()
if associed > 0:
self.notify()
# ------------------------------------------------------------------------
def delete_links(self):
dissocied = self.__data.dissociate()
if dissocied > 0:
self.notify()
# ---------------------------------------------------------------------------
class sppasFilesFilterDialog(sppasDialog):
def __init__(self, parent):
super(sppasFilesFilterDialog, self).__init__(
parent=parent,
title='{:s} Files selection'.format(sg.__name__),
style=wx.DEFAULT_FRAME_STYLE)
self.match_all = True
self.CreateHeader(title="Define filters to check files",
icon_name="check_filter")
self._create_content()
self._create_buttons()
self.Bind(wx.EVT_BUTTON, self._process_event)
self.SetSize(wx.Size(480, 320))
self.LayoutComponents()
self.CenterOnParent()
self.FadeIn(deltaN=-8)
# -----------------------------------------------------------------------
# Public methods
# -----------------------------------------------------------------------
def get_filters(self):
filters = list()
for i in range(self.listctrl.GetItemCount()):
filter_name = self.listctrl.GetValue(i, 0)
fct_name = self.listctrl.GetValue(i, 1)
values = self.listctrl.GetValue(i, 2)
filters.append((filter_name, fct_name, values))
return filters
# -----------------------------------------------------------------------
# Methods to construct the GUI
# -----------------------------------------------------------------------
def _create_content(self):
panel = sppasPanel(self, name="content")
tb = self.__create_toolbar(panel)
self.listctrl = wx.dataview.DataViewListCtrl(panel, wx.ID_ANY)
self.listctrl.AppendTextColumn("filter", width=80)
self.listctrl.AppendTextColumn("function", width=90)
self.listctrl.AppendTextColumn("value", width=120)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(tb, proportion=0, flag=wx.EXPAND, border=0)
sizer.Add(self.listctrl, proportion=1, flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5)
panel.SetSizer(sizer)
self.SetMinSize(wx.Size(320, 200))
panel.SetAutoLayout(True)
self.SetContent(panel)
# -----------------------------------------------------------------------
def __create_toolbar(self, parent):
tb = sppasToolbar(parent)
tb.set_focus_color(wx.Colour(196, 196, 96, 128))
tb.AddTextButton("filter_path", "+ Path")
tb.AddTextButton("filter_name", "+ Name")
tb.AddTextButton("filter_ext", "+ Type")
tb.AddTextButton("filter_ref", "+ Ref.")
tb.AddTextButton("filter_att", "+ Value")
tb.AddSpacer()
#tb.AddTextButton(None, "- Remove")
return tb
# -----------------------------------------------------------------------
def _create_buttons(self):
panel = sppasPanel(self, name="actions")
# panel.SetMinSize(wx.Size(-1, wx.GetApp().settings.action_height))
sizer = wx.BoxSizer(wx.HORIZONTAL)
# Create the buttons
cancel_btn = self.__create_action_button(panel, "Cancel", "cancel")
apply_or_btn = self.__create_action_button(panel, "Apply - OR", "apply")
apply_and_btn = self.__create_action_button(panel, "Apply - AND", "ok")
apply_and_btn.SetFocus()
sizer.Add(cancel_btn, 1, wx.ALL | wx.EXPAND, 0)
sizer.Add(self.VertLine(parent=panel), 0, wx.ALL | wx.EXPAND, 0)
sizer.Add(apply_or_btn, 1, wx.ALL | wx.EXPAND, 0)
sizer.Add(self.VertLine(parent=panel), 0, wx.ALL | wx.EXPAND, 0)
sizer.Add(apply_and_btn, 1, wx.ALL | wx.EXPAND, 0)
panel.SetSizer(sizer)
self.SetActions(panel)
# -----------------------------------------------------------------------
def __create_action_button(self, parent, text, icon):
btn = BitmapTextButton(parent, label=text, name=icon)
btn.LabelPosition = wx.RIGHT
btn.Spacing = sppasDialog.fix_size(12)
btn.BorderWidth = 0
btn.BitmapColour = self.GetForegroundColour()
btn.SetMinSize(wx.Size(sppasDialog.fix_size(32),
sppasDialog.fix_size(32)))
return btn
# ------------------------------------------------------------------------
# Callback to events
# ------------------------------------------------------------------------
def _process_event(self, event):
event_obj = event.GetEventObject()
event_name = event_obj.GetName()
if event_name == "filter_path":
self.__append_filter("path")
elif event_name == "filter_name":
self.__append_filter("name")
elif event_name == "filter_ext":
self.__append_filter("extension")
elif event_name == "filter_ref":
self.__append_filter("ref")
elif event_name == "filter_att":
dlg = sppasAttributeFilterDialog(self)
response = dlg.ShowModal()
if response == wx.ID_OK:
# Name of the method in sppasFileDataFilters,
# Name of the function and its value
f = dlg.get_data()
v = f[1].split(':')
if len(v[0].strip()) > 1 and len(v[1].strip()) > 0:
self.listctrl.AppendItem(["att", f[0], f[1].strip()])
else:
logging.error("Invalid input string for identifier or value.")
dlg.Destroy()
elif event_name == "cancel":
self.SetReturnCode(wx.ID_CANCEL)
self.Close()
elif event_name == "apply":
self.match_all = False
self.EndModal(wx.ID_APPLY)
elif event_name == "ok":
self.match_all = True
self.EndModal(wx.ID_OK)
else:
event.Skip()
# ------------------------------------------------------------------------
def __append_filter(self, fct):
dlg = sppasStringFilterDialog(self)
response = dlg.ShowModal()
if response == wx.ID_OK:
# Name of the method in sppasFileDataFilters,
# Name of the function and its value
f = dlg.get_data()
if len(f[1].strip()) > 0:
self.listctrl.AppendItem([fct, f[0], f[1].strip()])
else:
logging.error("Empty input pattern.")
dlg.Destroy()
# ---------------------------------------------------------------------------
class sppasStringFilterDialog(sppasDialog):
choices = (
("exact", "exact"),
("contains", "contains"),
("starts with", "startswith"),
("ends with", "endswith"),
("match (regexp)", "regexp"),
("not exact", "exact"),
("not contains", "contains"),
("not starts with", "startswith"),
("not ends with", "endswith"),
("not match", "regexp")
)
def __init__(self, parent):
super(sppasStringFilterDialog, self).__init__(
parent=parent,
title='{:s} filter'.format(sg.__name__),
style=wx.DEFAULT_FRAME_STYLE)
self._create_content()
self.CreateActions([wx.ID_CANCEL, wx.ID_OK])
self.SetSize(wx.Size(380, 320))
self.LayoutComponents()
self.CenterOnParent()
# -----------------------------------------------------------------------
def get_data(self):
idx = self.radiobox.GetSelection()
label = self.radiobox.GetStringSelection()
given_fct = self.choices[idx][1]
# Fill the resulting dict
prepend_fct = ""
if given_fct != "regexp":
# prepend "not_" if reverse
if "not" in label:
prepend_fct += "not_"
# prepend "i" if case-insensitive
if self.checkbox.GetValue() is False:
prepend_fct += "i"
return prepend_fct+given_fct, self.text.GetValue()
# -----------------------------------------------------------------------
# Methods to construct the GUI
# -----------------------------------------------------------------------
def _create_content(self):
panel = sppasPanel(self, name="content")
label = sppasStaticText(panel, label="Search for pattern(s): ")
self.text = sppasTextCtrl(panel, value="")
choices = [row[0] for row in self.choices]
self.radiobox = sppasRadioBoxPanel(
panel,
choices=choices,
majorDimension=2,
style=wx.RA_SPECIFY_COLS)
self.radiobox.SetSelection(1)
self.checkbox = CheckButton(panel, label="Case sensitive")
self.checkbox.SetValue(False)
# Layout
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(label, 0, flag=wx.EXPAND | wx.ALL, border=4)
sizer.Add(self.text, 0, flag=wx.EXPAND | wx.ALL, border=4)
sizer.Add(self.radiobox, 1, flag=wx.EXPAND | wx.ALL, border=4)
sizer.Add(self.checkbox, 0, flag=wx.EXPAND | wx.ALL, border=4)
panel.SetSizer(sizer)
panel.SetMinSize((240, 160))
panel.SetAutoLayout(True)
self.SetContent(panel)
# ---------------------------------------------------------------------------
class sppasAttributeFilterDialog(sppasDialog):
choices = (
("exact", "exact"),
("contains", "contains"),
("starts with", "startswith"),
("ends with", "endswith"),
("match (regexp)", "regexp"),
("not exact", "exact"),
("not contains", "contains"),
("not starts with", "startswith"),
("not ends with", "endswith"),
("not match", "regexp"),
("equal", "equal"),
("greater than", "gt"),
("greater or equal", "ge"),
("lower than", "lt"),
("lower or equal", "le")
)
def __init__(self, parent):
super(sppasAttributeFilterDialog, self).__init__(
parent=parent,
title='{:s} filter'.format(sg.__name__),
style=wx.DEFAULT_FRAME_STYLE)
self._create_content()
self.CreateActions([wx.ID_CANCEL, wx.ID_OK])
self.SetMinSize(wx.Size(sppasDialog.fix_size(420),
sppasDialog.fix_size(320)))
self.LayoutComponents()
self.CenterOnParent()
# ------------------------------------------------------------------------
def get_data(self):
idx = self.radiobox.GetSelection()
label = self.radiobox.GetStringSelection()
given_fct = self.choices[idx][1]
# Fill the resulting dict
prepend_fct = ""
if idx < 10 and given_fct != "regexp":
# prepend "not_" if reverse
if "not" in label:
prepend_fct += "not_"
# prepend "i" if case-insensitive
if self.checkbox.GetValue() is False:
prepend_fct += "i"
return prepend_fct + given_fct, \
self.text_ident.GetValue() + ":" + self.text_value.GetValue()
# -----------------------------------------------------------------------
# Methods to construct the GUI
# -----------------------------------------------------------------------
def _create_content(self):
panel = sppasPanel(self, name="content")
label = sppasStaticText(panel, label="Identifier: ")
self.text_ident = sppasTextCtrl(
panel,
value="",
validator=IdentifierTextValidator())
choices = [row[0] for row in sppasAttributeFilterDialog.choices]
self.radiobox = sppasRadioBoxPanel(
panel,
choices=choices,
majorDimension=3,
style=wx.RA_SPECIFY_COLS)
self.radiobox.SetSelection(1)
self.radiobox.Bind(wx.EVT_RADIOBOX, self._on_radiobox_checked)
self.checkbox = CheckButton(panel, label="Case sensitive")
self.checkbox.SetValue(False)
self.text_value = sppasTextCtrl(panel, value="")
# Layout
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(label, 0, flag=wx.EXPAND | wx.ALL, border=4)
sizer.Add(self.text_ident, 0, flag=wx.EXPAND | wx.ALL, border=4)
sizer.Add(self.radiobox, 1, flag=wx.EXPAND | wx.ALL, border=4)
sizer.Add(self.text_value, 0, flag=wx.EXPAND | wx.ALL, border=4)
sizer.Add(self.checkbox, 0, flag=wx.EXPAND | wx.ALL, border=4)
panel.SetSizer(sizer)
panel.SetMinSize((240, 160))
panel.SetAutoLayout(True)
self.SetContent(panel)
def _on_radiobox_checked(self, event):
value = self.radiobox.GetStringSelection()
if value in sppasAttributeFilterDialog.choices[10:]:
self.checkbox.SetValue(False)
self.checkbox.Enable(False)
else:
self.checkbox.Enable(True)
| true | true |
f7168c18be9b4f3d5729f54a2173850564c1755b | 617 | py | Python | src/DoorControl_manual.py | oulkaid/MoSIG-SystemDesign-WCET | bbe640ebbad7a372e4bd826a3334a69f3aca28e7 | [
"MIT"
] | null | null | null | src/DoorControl_manual.py | oulkaid/MoSIG-SystemDesign-WCET | bbe640ebbad7a372e4bd826a3334a69f3aca28e7 | [
"MIT"
] | null | null | null | src/DoorControl_manual.py | oulkaid/MoSIG-SystemDesign-WCET | bbe640ebbad7a372e4bd826a3334a69f3aca28e7 | [
"MIT"
] | null | null | null |
start_addr = []
next_addr = []
start_addr.append(['8478'])
next_addr.append(['84a4','8498'])
start_addr.append(['8498'])
next_addr.append(['84b0','84a4'])
start_addr.append(['84a4'])
next_addr.append(['84b0'])
start_addr.append(['84b0'])
next_addr.append(['84e0','84d4'])
start_addr.append(['84d4'])
next_addr.append(['84ec','84e0'])
start_addr.append(['84e0'])
next_addr.append(['84ec'])
start_addr.append(['84ec'])
next_addr.append(['8514','84fc'])
for index in range(len(start_addr)):
print("BB " + str(index+1) + ": Start@ = " + str(start_addr[index]) + " , Next@ = " + str(next_addr[index]))
| 20.566667 | 117 | 0.648298 |
start_addr = []
next_addr = []
start_addr.append(['8478'])
next_addr.append(['84a4','8498'])
start_addr.append(['8498'])
next_addr.append(['84b0','84a4'])
start_addr.append(['84a4'])
next_addr.append(['84b0'])
start_addr.append(['84b0'])
next_addr.append(['84e0','84d4'])
start_addr.append(['84d4'])
next_addr.append(['84ec','84e0'])
start_addr.append(['84e0'])
next_addr.append(['84ec'])
start_addr.append(['84ec'])
next_addr.append(['8514','84fc'])
for index in range(len(start_addr)):
print("BB " + str(index+1) + ": Start@ = " + str(start_addr[index]) + " , Next@ = " + str(next_addr[index]))
| true | true |
f7168c43af7fe79343018a0288432cf66f89741a | 1,124 | py | Python | app/auth/views.py | 0xff-dev/SutAcmDRA | f3e744c19f66f930deb3f921b75d5f1189354b41 | [
"MIT"
] | 2 | 2018-07-16T16:14:32.000Z | 2018-07-23T06:48:29.000Z | app/auth/views.py | 0xff-dev/SutAcmDRA | f3e744c19f66f930deb3f921b75d5f1189354b41 | [
"MIT"
] | 3 | 2021-06-08T19:23:40.000Z | 2021-12-13T19:56:54.000Z | app/auth/views.py | stevenshuang/SutAcmDRA | f3e744c19f66f930deb3f921b75d5f1189354b41 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# coding=utf-8
from flask import render_template, request
from flask import redirect, url_for, flash
from flask_login import login_user
from flask_login import login_required
from flask_login import logout_user
from . import auth
from ..models import User
from .. import logger
@auth.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'GET':
return render_template('login.html')
else:
user_name = request.form.get('username')
passwd = request.form.get('password')
try:
user = User.query.filter_by(hdoj_username=user_name).first()
except Exception as e:
logger.info('用户不存在')
if user is not None and user.verify_password(passwd):
login_user(user)
return redirect(
request.args.get('next') or
url_for('main.index', )
)
flash('Invald Username Or Password')
@auth.route('/logout')
@login_required
def logout():
logout_user()
flash('You have been logged out')
return redirect(url_for('main.index'))
| 28.1 | 72 | 0.6379 |
from flask import render_template, request
from flask import redirect, url_for, flash
from flask_login import login_user
from flask_login import login_required
from flask_login import logout_user
from . import auth
from ..models import User
from .. import logger
@auth.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'GET':
return render_template('login.html')
else:
user_name = request.form.get('username')
passwd = request.form.get('password')
try:
user = User.query.filter_by(hdoj_username=user_name).first()
except Exception as e:
logger.info('用户不存在')
if user is not None and user.verify_password(passwd):
login_user(user)
return redirect(
request.args.get('next') or
url_for('main.index', )
)
flash('Invald Username Or Password')
@auth.route('/logout')
@login_required
def logout():
logout_user()
flash('You have been logged out')
return redirect(url_for('main.index'))
| true | true |
f7168e80f5e8ed5edf7f7288316f9a3d0d8192e3 | 5,675 | py | Python | nimiqclient/models/block.py | rraallvv/python-client | 65d0c3f835ed8ce3ba6bfa2565cac61f7da6b748 | [
"Apache-2.0"
] | 4 | 2020-11-03T21:13:13.000Z | 2022-01-18T08:40:27.000Z | nimiqclient/models/block.py | rraallvv/python-client | 65d0c3f835ed8ce3ba6bfa2565cac61f7da6b748 | [
"Apache-2.0"
] | 1 | 2020-08-09T21:36:02.000Z | 2020-08-09T21:36:02.000Z | nimiqclient/models/block.py | rraallvv/python-client | 65d0c3f835ed8ce3ba6bfa2565cac61f7da6b748 | [
"Apache-2.0"
] | 1 | 2020-08-03T01:05:44.000Z | 2020-08-03T01:05:44.000Z | __all__ = ["Block", "BlockTemplateHeader", "BlockTemplateBody", "BlockTemplate"]
from .transaction import Transaction
class Block:
"""
Block returned by the server.
:param number: Height of the block.
:type number: int
:param hash: Hex-encoded 32-byte hash of the block.
:type hash: str
:param pow: Hex-encoded 32-byte Proof-of-Work hash of the block.
:type pow: str
:param parentHash: Hex-encoded 32-byte hash of the predecessor block.
:type parentHash: str
:param nonce: The nonce of the block used to fulfill the Proof-of-Work.
:type nonce: int
:param bodyHash: Hex-encoded 32-byte hash of the block body Merkle root.
:type bodyHash: str
:param accountsHash: Hex-encoded 32-byte hash of the accounts tree root.
:type accountsHash: str
:param difficulty: Block difficulty, encoded as decimal number in string.
:type difficulty: str
:param timestamp: UNIX timestamp of the block.
:type timestamp: int
:param confirmations: Number of confirmations for this transaction (number of blocks on top of the block where this transaction was in).
:type confirmations: int
:param miner: Hex-encoded 20 byte address of the miner of the block.
:type miner: str
:param minerAddress: User friendly address (NQ-address) of the miner of the block.
:type minerAddress: str
:param extraData: Hex-encoded value of the extra data field, maximum of 255 bytes.
:type extraData: str
:param size: Block size in byte.
:type size: int
:param transactions: List of transactions. Either represented by the transaction hash or a Transaction object.
:type transactions: list of (Transaction or str)
"""
def __init__(
self,
number,
hash,
pow,
parentHash,
nonce,
bodyHash,
accountsHash,
difficulty,
timestamp,
confirmations,
miner,
minerAddress,
extraData,
size,
transactions,
):
self.number = number
self.hash = hash
self.pow = pow
self.parentHash = parentHash
self.nonce = nonce
self.bodyHash = bodyHash
self.accountsHash = accountsHash
self.difficulty = difficulty
self.timestamp = timestamp
self.confirmations = confirmations
self.miner = miner
self.minerAddress = minerAddress
self.extraData = extraData
self.size = size
for index, transaction in enumerate(transactions):
tt = type(transaction)
if tt is not str and tt is not Transaction:
if tt is dict:
transactions[index] = Transaction(**transaction)
else:
from ..nimiq_client import InternalErrorException
raise InternalErrorException(
"Couldn't parse Transaction {0}".format(transaction)
)
self.transactions = transactions
class BlockTemplateHeader:
"""
Block template header returned by the server.
:param version: Version in block header.
:type version: int
:param prevHash: 32-byte hex-encoded hash of the previous block.
:type prevHash: str
:param interlinkHash: 32-byte hex-encoded hash of the interlink.
:type interlinkHash: str
:param accountsHash: 32-byte hex-encoded hash of the accounts tree.
:type accountsHash: str
:param nBits: Compact form of the hash target for this block.
:type nBits: int
:param height: Height of the block in the block chain (also known as block number).
:type height: int
"""
def __init__(self, version, prevHash, interlinkHash, accountsHash, nBits, height):
self.version = version
self.prevHash = prevHash
self.interlinkHash = interlinkHash
self.accountsHash = accountsHash
self.nBits = nBits
self.height = height
class BlockTemplateBody:
"""
Block template body returned by the server.
:param hash: 32-byte hex-encoded hash of the block body.
:type hash: str
:param minerAddr: 20-byte hex-encoded miner address.
:type minerAddr: str
:param extraData: Hex-encoded value of the extra data field.
:type extraData: str
:param transactions: List of hex-encoded transactions for this block.
:type transactions: str
:param prunedAccounts: List of hex-encoded pruned accounts for this block.
:type prunedAccounts: str
:param merkleHashes: List of hex-encoded hashes that verify the path of the miner address in the merkle tree. This can be used to change the miner address easily.
:type merkleHashes: str
"""
def __init__(
self, hash, minerAddr, extraData, transactions, prunedAccounts, merkleHashes
):
self.hash = hash
self.minerAddr = minerAddr
self.extraData = extraData
self.transactions = transactions
self.prunedAccounts = prunedAccounts
self.merkleHashes = merkleHashes
class BlockTemplate:
"""
Block template returned by the server.
:param header: Block template header returned by the server.
:type header: BlockTemplateHeader
:param interlink: Hex-encoded interlink.
:type interlink: str
:param body: Block template body returned by the server.
:type body: BlockTemplateBody
:param target: Compact form of the hash target to submit a block to this client.
:type target: int
"""
def __init__(self, header, interlink, body, target):
self.header = header
self.interlink = interlink
self.body = body
self.target = target
| 34.815951 | 166 | 0.66185 | __all__ = ["Block", "BlockTemplateHeader", "BlockTemplateBody", "BlockTemplate"]
from .transaction import Transaction
class Block:
def __init__(
self,
number,
hash,
pow,
parentHash,
nonce,
bodyHash,
accountsHash,
difficulty,
timestamp,
confirmations,
miner,
minerAddress,
extraData,
size,
transactions,
):
self.number = number
self.hash = hash
self.pow = pow
self.parentHash = parentHash
self.nonce = nonce
self.bodyHash = bodyHash
self.accountsHash = accountsHash
self.difficulty = difficulty
self.timestamp = timestamp
self.confirmations = confirmations
self.miner = miner
self.minerAddress = minerAddress
self.extraData = extraData
self.size = size
for index, transaction in enumerate(transactions):
tt = type(transaction)
if tt is not str and tt is not Transaction:
if tt is dict:
transactions[index] = Transaction(**transaction)
else:
from ..nimiq_client import InternalErrorException
raise InternalErrorException(
"Couldn't parse Transaction {0}".format(transaction)
)
self.transactions = transactions
class BlockTemplateHeader:
def __init__(self, version, prevHash, interlinkHash, accountsHash, nBits, height):
self.version = version
self.prevHash = prevHash
self.interlinkHash = interlinkHash
self.accountsHash = accountsHash
self.nBits = nBits
self.height = height
class BlockTemplateBody:
def __init__(
self, hash, minerAddr, extraData, transactions, prunedAccounts, merkleHashes
):
self.hash = hash
self.minerAddr = minerAddr
self.extraData = extraData
self.transactions = transactions
self.prunedAccounts = prunedAccounts
self.merkleHashes = merkleHashes
class BlockTemplate:
def __init__(self, header, interlink, body, target):
self.header = header
self.interlink = interlink
self.body = body
self.target = target
| true | true |
f7168f6333b407972ae83a3eb73553f078b2cd44 | 7,304 | py | Python | src/sage/combinat/kazhdan_lusztig.py | saraedum/sage-renamed | d2da67b14da2ad766a5906425d60d43a3b3e1270 | [
"BSL-1.0"
] | null | null | null | src/sage/combinat/kazhdan_lusztig.py | saraedum/sage-renamed | d2da67b14da2ad766a5906425d60d43a3b3e1270 | [
"BSL-1.0"
] | null | null | null | src/sage/combinat/kazhdan_lusztig.py | saraedum/sage-renamed | d2da67b14da2ad766a5906425d60d43a3b3e1270 | [
"BSL-1.0"
] | null | null | null | r"""
Kazhdan-Lusztig Polynomials
AUTHORS:
- Daniel Bump (2008): initial version
- Alan J.X. Guo (2014-03-18): ``R_tilde()`` method.
"""
#*****************************************************************************
# Copyright (C) 2008 Daniel Bump <bump at match.stanford.edu>
#
# 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.
# http://www.gnu.org/licenses/
#*****************************************************************************
from __future__ import absolute_import, print_function, division
from sage.rings.polynomial.polynomial_element import is_Polynomial
from sage.misc.cachefunc import cached_method
from sage.rings.polynomial.laurent_polynomial import LaurentPolynomial
from sage.structure.sage_object import SageObject
from sage.structure.unique_representation import UniqueRepresentation
class KazhdanLusztigPolynomial(UniqueRepresentation, SageObject):
"""
A Kazhdan-Lusztig polynomial.
INPUT:
- ``W`` -- a Weyl Group
- ``q`` -- an indeterminate
OPTIONAL:
- ``trace`` -- if ``True``, then this displays the trace: the intermediate
results. This is instructive and fun.
The parent of ``q`` may be a :class:`PolynomialRing` or a
:class:`LaurentPolynomialRing`.
REFERENCES:
.. [KL79] \D. Kazhdan and G. Lusztig. *Representations of Coxeter
groups and Hecke algebras*. Invent. Math. **53** (1979).
no. 2, 165--184. :doi:`10.1007/BF01390031` :mathscinet:`MR0560412`
.. [Dy93] \M. J. Dyer. *Hecke algebras and shellings of Bruhat
intervals*. Compositio Mathematica, 1993, 89(1): 91-115.
.. [BB05] \A. Bjorner, F. Brenti. *Combinatorics of Coxeter
groups*. New York: Springer, 2005.
EXAMPLES::
sage: W = WeylGroup("B3",prefix="s")
sage: [s1,s2,s3] = W.simple_reflections()
sage: R.<q> = LaurentPolynomialRing(QQ)
sage: KL = KazhdanLusztigPolynomial(W,q)
sage: KL.P(s2,s3*s2*s3*s1*s2)
1 + q
A faster implementation (using the optional package Coxeter 3) is given by::
sage: W = CoxeterGroup(['B', 3], implementation='coxeter3') # optional - coxeter3
sage: W.kazhdan_lusztig_polynomial([2], [3,2,3,1,2]) # optional - coxeter3
q + 1
"""
def __init__(self, W, q, trace=False):
"""
Initialize ``self``.
EXAMPLES::
sage: W = WeylGroup("B3",prefix="s")
sage: R.<q> = LaurentPolynomialRing(QQ)
sage: KL = KazhdanLusztigPolynomial(W,q)
sage: TestSuite(KL).run()
"""
self._coxeter_group = W
self._q = q
self._trace = trace
self._one = W.one()
self._base_ring = q.parent()
if is_Polynomial(q):
self._base_ring_type = "polynomial"
elif isinstance(q, LaurentPolynomial):
self._base_ring_type = "laurent"
else:
self._base_ring_type = "unknown"
@cached_method
def R(self, x, y):
"""
Return the Kazhdan-Lusztig `R` polynomial.
INPUT:
- ``x``, ``y`` -- elements of the underlying Coxeter group
EXAMPLES::
sage: R.<q>=QQ[]
sage: W = WeylGroup("A2", prefix="s")
sage: [s1,s2]=W.simple_reflections()
sage: KL = KazhdanLusztigPolynomial(W, q)
sage: [KL.R(x,s2*s1) for x in [1,s1,s2,s1*s2]]
[q^2 - 2*q + 1, q - 1, q - 1, 0]
"""
if x == 1:
x = self._one
if y == 1:
y = self._one
if x == y:
return self._base_ring.one()
if not x.bruhat_le(y):
return self._base_ring.zero()
if y.length() == 0:
if x.length() == 0:
return self._base_ring.one()
else:
return self._base_ring.zero()
s = self._coxeter_group.simple_reflection(y.first_descent(side="left"))
if (s*x).length() < x.length():
ret = self.R(s*x,s*y)
if self._trace:
print(" R(%s,%s)=%s" % (x, y, ret))
return ret
else:
ret = (self._q-1)*self.R(s*x,y)+self._q*self.R(s*x,s*y)
if self._trace:
print(" R(%s,%s)=%s" % (x, y, ret))
return ret
@cached_method
def R_tilde(self, x, y):
r"""
Return the Kazhdan-Lusztig `\tilde{R}` polynomial.
Information about the `\tilde{R}` polynomials can be found in
[Dy93]_ and [BB05]_.
INPUT:
- ``x``, ``y`` -- elements of the underlying Coxeter group
EXAMPLES::
sage: R.<q> = QQ[]
sage: W = WeylGroup("A2", prefix="s")
sage: [s1,s2] = W.simple_reflections()
sage: KL = KazhdanLusztigPolynomial(W, q)
sage: [KL.R_tilde(x,s2*s1) for x in [1,s1,s2,s1*s2]]
[q^2, q, q, 0]
"""
if x == 1:
x = self._one
if y == 1:
y = self._one
if not x.bruhat_le(y):
return self._base_ring.zero()
if x == y:
return self._base_ring.one()
s = self._coxeter_group.simple_reflection(y.first_descent(side="right"))
if (x * s).length() < x.length():
ret = self.R_tilde(x * s, y * s)
if self._trace:
print(" R_tilde(%s,%s)=%s" % (x, y, ret))
return ret
else:
ret = self.R_tilde(x * s, y * s) + self._q * self.R_tilde(x, y * s)
if self._trace:
print(" R_tilde(%s,%s)=%s" % (x, y, ret))
return ret
@cached_method
def P(self, x, y):
"""
Return the Kazhdan-Lusztig `P` polynomial.
If the rank is large, this runs slowly at first but speeds up
as you do repeated calculations due to the caching.
INPUT:
- ``x``, ``y`` -- elements of the underlying Coxeter group
.. SEEALSO::
:mod:`~sage.libs.coxeter3.coxeter_group.CoxeterGroup.kazhdan_lusztig_polynomial`
for a faster implementation using Fokko Ducloux's Coxeter3 C++ library.
EXAMPLES::
sage: R.<q> = QQ[]
sage: W = WeylGroup("A3", prefix="s")
sage: [s1,s2,s3] = W.simple_reflections()
sage: KL = KazhdanLusztigPolynomial(W, q)
sage: KL.P(s2,s2*s1*s3*s2)
q + 1
"""
if x == 1:
x = self._one
if y == 1:
y = self._one
if x == y:
return self._base_ring.one()
if not x.bruhat_le(y):
return self._base_ring.zero()
if y.length() == 0:
if x.length() == 0:
return self._base_ring.one()
else:
return self._base_ring.zero()
p = sum(-self.R(x, t) * self.P(t, y)
for t in self._coxeter_group.bruhat_interval(x, y) if t != x)
tr = (y.length() - x.length() + 1) // 2
ret = p.truncate(tr)
if self._trace:
print(" P({},{})={}".format(x, y, ret))
return ret
| 32.035088 | 92 | 0.529299 |
from __future__ import absolute_import, print_function, division
from sage.rings.polynomial.polynomial_element import is_Polynomial
from sage.misc.cachefunc import cached_method
from sage.rings.polynomial.laurent_polynomial import LaurentPolynomial
from sage.structure.sage_object import SageObject
from sage.structure.unique_representation import UniqueRepresentation
class KazhdanLusztigPolynomial(UniqueRepresentation, SageObject):
def __init__(self, W, q, trace=False):
self._coxeter_group = W
self._q = q
self._trace = trace
self._one = W.one()
self._base_ring = q.parent()
if is_Polynomial(q):
self._base_ring_type = "polynomial"
elif isinstance(q, LaurentPolynomial):
self._base_ring_type = "laurent"
else:
self._base_ring_type = "unknown"
@cached_method
def R(self, x, y):
if x == 1:
x = self._one
if y == 1:
y = self._one
if x == y:
return self._base_ring.one()
if not x.bruhat_le(y):
return self._base_ring.zero()
if y.length() == 0:
if x.length() == 0:
return self._base_ring.one()
else:
return self._base_ring.zero()
s = self._coxeter_group.simple_reflection(y.first_descent(side="left"))
if (s*x).length() < x.length():
ret = self.R(s*x,s*y)
if self._trace:
print(" R(%s,%s)=%s" % (x, y, ret))
return ret
else:
ret = (self._q-1)*self.R(s*x,y)+self._q*self.R(s*x,s*y)
if self._trace:
print(" R(%s,%s)=%s" % (x, y, ret))
return ret
@cached_method
def R_tilde(self, x, y):
if x == 1:
x = self._one
if y == 1:
y = self._one
if not x.bruhat_le(y):
return self._base_ring.zero()
if x == y:
return self._base_ring.one()
s = self._coxeter_group.simple_reflection(y.first_descent(side="right"))
if (x * s).length() < x.length():
ret = self.R_tilde(x * s, y * s)
if self._trace:
print(" R_tilde(%s,%s)=%s" % (x, y, ret))
return ret
else:
ret = self.R_tilde(x * s, y * s) + self._q * self.R_tilde(x, y * s)
if self._trace:
print(" R_tilde(%s,%s)=%s" % (x, y, ret))
return ret
@cached_method
def P(self, x, y):
if x == 1:
x = self._one
if y == 1:
y = self._one
if x == y:
return self._base_ring.one()
if not x.bruhat_le(y):
return self._base_ring.zero()
if y.length() == 0:
if x.length() == 0:
return self._base_ring.one()
else:
return self._base_ring.zero()
p = sum(-self.R(x, t) * self.P(t, y)
for t in self._coxeter_group.bruhat_interval(x, y) if t != x)
tr = (y.length() - x.length() + 1) // 2
ret = p.truncate(tr)
if self._trace:
print(" P({},{})={}".format(x, y, ret))
return ret
| true | true |
f716900640c20a86067bea4f88ec8a40a962d91a | 1,771 | py | Python | server/apps/widgets/serializers/widget.py | Sergey-x/SibdevPractice | 12e3f7e704af93911a0c4a66aad60733d2121e15 | [
"MIT"
] | null | null | null | server/apps/widgets/serializers/widget.py | Sergey-x/SibdevPractice | 12e3f7e704af93911a0c4a66aad60733d2121e15 | [
"MIT"
] | null | null | null | server/apps/widgets/serializers/widget.py | Sergey-x/SibdevPractice | 12e3f7e704af93911a0c4a66aad60733d2121e15 | [
"MIT"
] | null | null | null | from datetime import timedelta
from rest_framework import serializers
from ..models.widget import Widget
class BaseWidgetSerializer(serializers.ModelSerializer):
"""
This is the base serializer class for Widget model.
Other widget serializers must be inherited from it.
"""
class Meta:
model = Widget
fields = (
'id',
'category',
'limit',
'duration',
'criteria',
'color',
'creation_date',
)
class CreateWidgetSerializer(BaseWidgetSerializer):
color = serializers.CharField(max_length=10)
def validate_duration(self, value: timedelta):
"""
Check that duration is acceptable quantity of days.
"""
if value.days not in Widget.VALID_DURATION:
raise serializers.ValidationError(
f"You can chose only this day-periods {Widget.VALID_DURATION}."
)
return timedelta(days=value.days)
def validate_color(self, value):
"""
Check that color specified in hex correctly.
"""
if value.startswith('0x'):
return value[2:]
return value
def create(self, validated_data):
validated_data['owner'] = self.context['request'].user
return Widget.objects.create(**validated_data)
class DestroyWidgetSerializer(BaseWidgetSerializer):
pass
class ListWidgetSerializer(BaseWidgetSerializer):
class Meta(BaseWidgetSerializer.Meta):
fields = (
'id',
'category',
'limit',
'duration',
'criteria',
'color',
'creation_date',
'ending_date',
'sum',
'owner',
)
| 24.943662 | 79 | 0.579898 | from datetime import timedelta
from rest_framework import serializers
from ..models.widget import Widget
class BaseWidgetSerializer(serializers.ModelSerializer):
class Meta:
model = Widget
fields = (
'id',
'category',
'limit',
'duration',
'criteria',
'color',
'creation_date',
)
class CreateWidgetSerializer(BaseWidgetSerializer):
color = serializers.CharField(max_length=10)
def validate_duration(self, value: timedelta):
if value.days not in Widget.VALID_DURATION:
raise serializers.ValidationError(
f"You can chose only this day-periods {Widget.VALID_DURATION}."
)
return timedelta(days=value.days)
def validate_color(self, value):
if value.startswith('0x'):
return value[2:]
return value
def create(self, validated_data):
validated_data['owner'] = self.context['request'].user
return Widget.objects.create(**validated_data)
class DestroyWidgetSerializer(BaseWidgetSerializer):
pass
class ListWidgetSerializer(BaseWidgetSerializer):
class Meta(BaseWidgetSerializer.Meta):
fields = (
'id',
'category',
'limit',
'duration',
'criteria',
'color',
'creation_date',
'ending_date',
'sum',
'owner',
)
| true | true |
f716900a4d34d8a8bb3af91bb18c52ab94dfe78e | 2,563 | py | Python | src/server.py | alamminsalo/lua-webshop | 2f0f1123a9d693103c4dbaef02836777e779844c | [
"MIT"
] | 1 | 2016-09-12T16:16:33.000Z | 2016-09-12T16:16:33.000Z | src/server.py | alamminsalo/py-webshop | 2f0f1123a9d693103c4dbaef02836777e779844c | [
"MIT"
] | null | null | null | src/server.py | alamminsalo/py-webshop | 2f0f1123a9d693103c4dbaef02836777e779844c | [
"MIT"
] | null | null | null |
# Restfull api using falcon framework
from wsgiref import simple_server
import falcon
import json
#Resource endpoints import
from cartsResource import *
from productsResource import *
# Check that client has application/json in Accept header
# and Content-Type, if request has body
class RequireJSON(object):
def process_request(self, req, resp):
if not req.client_accepts_json:
raise falcon.HTTPNotAcceptable(
'This API only supports responses encoded as JSON.',
href='http://docs.examples.com/api/json')
if req.method in ('POST', 'PUT'):
if 'application/json' not in req.content_type:
raise falcon.HTTPUnsupportedMediaType(
'This API only supports requests encoded as JSON.',
href='http://docs.examples.com/api/json')
#JSON builder func for both incoming and outgoing messages
class JSONBuilder(object):
def process_request(self, req, resp):
if req.content_length in (None, 0):
# Nothing to do
return
body = req.stream.read()
if not body:
raise falcon.HTTPBadRequest('Empty request body',
'A valid JSON document is required.')
try:
req.context['doc'] = json.loads(body.decode('utf-8'))
except (ValueError, UnicodeDecodeError):
raise falcon.HTTPError(falcon.HTTP_753,
'Malformed JSON',
'Could not decode the request body. The '
'JSON was incorrect or not encoded as '
'UTF-8.')
def process_response(self, req, resp, resource):
if 'result' not in req.context:
return
resp.body = json.dumps(req.context['result'])
api = falcon.API(middleware=[
RequireJSON(),
JSONBuilder()
])
#Add api endpoints
products = ProductsResource()
api.add_route('/api/products', products)
product = ProductResource()
api.add_route('/api/products/{productId}', product)
shopcart = ShopCartResource()
api.add_route('/api/shopcarts/{userId}', shopcart)
shopcartProducts = ShopCartProductsResource()
api.add_route('/api/shopcarts/{userId}/products', shopcartProducts)
#Start the server
if __name__ == '__main__':
print("Staring server in 127.0.0.1:8000")
httpd = simple_server.make_server('127.0.0.1', 8000, api)
httpd.serve_forever()
| 29.802326 | 81 | 0.60359 |
from wsgiref import simple_server
import falcon
import json
from cartsResource import *
from productsResource import *
class RequireJSON(object):
def process_request(self, req, resp):
if not req.client_accepts_json:
raise falcon.HTTPNotAcceptable(
'This API only supports responses encoded as JSON.',
href='http://docs.examples.com/api/json')
if req.method in ('POST', 'PUT'):
if 'application/json' not in req.content_type:
raise falcon.HTTPUnsupportedMediaType(
'This API only supports requests encoded as JSON.',
href='http://docs.examples.com/api/json')
class JSONBuilder(object):
def process_request(self, req, resp):
if req.content_length in (None, 0):
return
body = req.stream.read()
if not body:
raise falcon.HTTPBadRequest('Empty request body',
'A valid JSON document is required.')
try:
req.context['doc'] = json.loads(body.decode('utf-8'))
except (ValueError, UnicodeDecodeError):
raise falcon.HTTPError(falcon.HTTP_753,
'Malformed JSON',
'Could not decode the request body. The '
'JSON was incorrect or not encoded as '
'UTF-8.')
def process_response(self, req, resp, resource):
if 'result' not in req.context:
return
resp.body = json.dumps(req.context['result'])
api = falcon.API(middleware=[
RequireJSON(),
JSONBuilder()
])
products = ProductsResource()
api.add_route('/api/products', products)
product = ProductResource()
api.add_route('/api/products/{productId}', product)
shopcart = ShopCartResource()
api.add_route('/api/shopcarts/{userId}', shopcart)
shopcartProducts = ShopCartProductsResource()
api.add_route('/api/shopcarts/{userId}/products', shopcartProducts)
if __name__ == '__main__':
print("Staring server in 127.0.0.1:8000")
httpd = simple_server.make_server('127.0.0.1', 8000, api)
httpd.serve_forever()
| true | true |
f7169146ec3baeb91915b19f26b91545909663f8 | 149 | py | Python | foundation/migrate.py | shreyashah115/foundation | 42f19d23cfda77bae533f4884aecc15b3cd07f14 | [
"MIT"
] | null | null | null | foundation/migrate.py | shreyashah115/foundation | 42f19d23cfda77bae533f4884aecc15b3cd07f14 | [
"MIT"
] | null | null | null | foundation/migrate.py | shreyashah115/foundation | 42f19d23cfda77bae533f4884aecc15b3cd07f14 | [
"MIT"
] | null | null | null | import frappe
from frappe.database import Database
from markdown2 import markdown
from frappe.utils import validate_email_add
def migrate():
pass
| 16.555556 | 43 | 0.832215 | import frappe
from frappe.database import Database
from markdown2 import markdown
from frappe.utils import validate_email_add
def migrate():
pass
| true | true |
f716914b86089ef9a2f697d9a1dfeb32bd90f95f | 599 | py | Python | HelloWorld/Models/admin.py | xautshuanglong/PythonWebApp | 68ae417121740e4115f0e56c12a2a4831df30fc1 | [
"MIT"
] | null | null | null | HelloWorld/Models/admin.py | xautshuanglong/PythonWebApp | 68ae417121740e4115f0e56c12a2a4831df30fc1 | [
"MIT"
] | null | null | null | HelloWorld/Models/admin.py | xautshuanglong/PythonWebApp | 68ae417121740e4115f0e56c12a2a4831df30fc1 | [
"MIT"
] | null | null | null | from django.contrib import admin
from Models.models import UserInfo, Question, Choice
admin.site.register(UserInfo)
# admin.site.register(Question)
# admin.site.register(Choice)
class ChoiceInline(admin.StackedInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date'], 'classes':['collapse']}),
]
inlines = [ChoiceInline]
list_display = ('question_text', 'pub_date')
admin.site.register(Question, QuestionAdmin)
| 23.038462 | 80 | 0.661102 | from django.contrib import admin
from Models.models import UserInfo, Question, Choice
admin.site.register(UserInfo)
class ChoiceInline(admin.StackedInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date'], 'classes':['collapse']}),
]
inlines = [ChoiceInline]
list_display = ('question_text', 'pub_date')
admin.site.register(Question, QuestionAdmin)
| true | true |
f71693818cb726573e4d1f282b8d61fe8a87df6b | 678 | py | Python | resource-timing/resources/fake_responses.py | shs96c/web-platform-tests | 61acad6dd9bb99d32340eb41f5146de64f542359 | [
"BSD-3-Clause"
] | 1 | 2022-03-19T09:43:35.000Z | 2022-03-19T09:43:35.000Z | resource-timing/resources/fake_responses.py | shs96c/web-platform-tests | 61acad6dd9bb99d32340eb41f5146de64f542359 | [
"BSD-3-Clause"
] | 1 | 2021-12-13T19:49:45.000Z | 2021-12-13T19:49:45.000Z | resource-timing/resources/fake_responses.py | shs96c/web-platform-tests | 61acad6dd9bb99d32340eb41f5146de64f542359 | [
"BSD-3-Clause"
] | 1 | 2021-04-06T20:06:58.000Z | 2021-04-06T20:06:58.000Z | # /xhr/resources/conditional.py -- to fake a 304 response
def main(request, response):
tag = request.GET.first("tag", None)
match = request.headers.get("If-None-Match", None)
date = request.GET.first("date", "")
modified = request.headers.get("If-Modified-Since", None)
if tag:
response.headers.set("ETag", '"%s"' % tag)
elif date:
response.headers.set("Last-Modified", date)
if ((match is not None and match == tag) or
(modified is not None and modified == date)):
response.status = (304, "SUPERCOOL")
return ""
else:
response.headers.set("Content-Type", "text/plain")
return "MAYBE NOT" | 35.684211 | 61 | 0.613569 |
def main(request, response):
tag = request.GET.first("tag", None)
match = request.headers.get("If-None-Match", None)
date = request.GET.first("date", "")
modified = request.headers.get("If-Modified-Since", None)
if tag:
response.headers.set("ETag", '"%s"' % tag)
elif date:
response.headers.set("Last-Modified", date)
if ((match is not None and match == tag) or
(modified is not None and modified == date)):
response.status = (304, "SUPERCOOL")
return ""
else:
response.headers.set("Content-Type", "text/plain")
return "MAYBE NOT" | true | true |
f71695c7f499b72a9e1e239c8622fe0294a9c60f | 3,752 | py | Python | personal/Ervin/run_knn_collaborative_item.py | edervishaj/spotify-recsys-challenge | 4077201ac7e4ed9da433bd10a92c183614182437 | [
"Apache-2.0"
] | 3 | 2018-10-12T20:19:57.000Z | 2019-12-11T01:11:38.000Z | personal/Ervin/run_knn_collaborative_item.py | kiminh/spotify-recsys-challenge | 5e7844a77ce3c26658400f161d2d74d682f30e69 | [
"Apache-2.0"
] | null | null | null | personal/Ervin/run_knn_collaborative_item.py | kiminh/spotify-recsys-challenge | 5e7844a77ce3c26658400f161d2d74d682f30e69 | [
"Apache-2.0"
] | 4 | 2018-10-27T20:30:18.000Z | 2020-10-14T07:43:27.000Z | from utils.datareader import Datareader
from utils.evaluator import Evaluator
from utils.submitter import Submitter
from utils.post_processing import eurm_to_recommendation_list_submission
from utils.post_processing import eurm_to_recommendation_list
from utils.pre_processing import norm_l1_row, norm_max_row, norm_max_col
from recommenders.knn_collaborative_item import Knn_collaborative_item
import recommenders.similarity.similarity as sm
import scipy.sparse as sps
import sys
import numpy as np
from personal.Ervin.other_similarity import position_similarity
'''
This file contains just an example on how to run the algorithm.
The parameter used are just the result of a first research of the optimum value.
To run this file just set the parameter at the start of the main function or set from console as argv parameter.
As argv you can even set mode of execution (online, offline) and the name of the result file
'''
if __name__ == '__main__':
### Select execution mode: 'offline', 'online' ###
mode = "offline"
name = "CFitem"
knn = 200
topk = 750
if len(sys.argv) > 1:
mode = sys.argv[1]
name = sys.argv[2]
knn = int(sys.argv[3])
topk = int(sys.argv[4])
complete_name = mode+"_"+name+"_knn="+str(knn)+"_topk="+str(topk)
if mode == "offline":
"""Test Set"""
#Data initialization
dr = Datareader(verbose=True, mode=mode, only_load=True)
#Evaluetor initialization
ev = Evaluator(dr)
#Recommender algorithm initialization
rec = Knn_collaborative_item()
#Getting for the recommender algorithm
urm = dr.get_urm()
urm.data = np.ones(len(urm.data))
position_urm = dr.get_position_matrix(position_type='last')
pos_urm = position_urm.T.tocoo().tocsr()
pid = dr.get_test_pids()
#Fitting data
rec.fit(urm, pid)
#Computing similarity/model
rec.compute_model(top_k= knn, sm_type=sm.TVERSKY, shrink=200, alpha=0.1, beta=1, binary=True, verbose=True)
rec.model = rec.model.tocsr()
rec.model.eliminate_zeros()
# rec.model = norm_max_row(rec.model)
print('Initial model has {:2} data'.format(len(rec.model.data)))
print('[ Updating the model ]')
rec.model = position_similarity(rec.model, pos_urm, knn=knn, verbose=True)
rec.model.eliminate_zeros()
print('New model has {:2} data'.format(len(rec.model.data)))
#Computing ratings
rec.compute_rating(top_k=topk,verbose=True, small=True, remove_seed=False)
#evaluation and saving
sps.save_npz(complete_name+".npz", rec.eurm)
ev.evaluate(recommendation_list=eurm_to_recommendation_list(rec.eurm, datareader=dr, remove_seed=True),
name=name, old_mode=False)
if mode == "online":
"""Submission"""
#Data initialization
dr = Datareader(verbose=True, mode=mode, only_load=False)
#Recommender algorithm initialization
rec = Knn_collaborative_item()
#Submitter initialization
sb = Submitter(dr)
#Getting for the recommender algorithm
urm = dr.get_urm()
pid = dr.get_test_pids()
#Fitting data
rec.fit(urm, pid)
#Computing similarity/model
rec.compute_model(top_k=knn, sm_type=sm.TVERSKY,shrink=200, alpha=0.1, beta=1, binary=True, verbose=True)
#Computing ratings
rec.compute_rating(top_k=topk, verbose=True, small=True)
#submission
sps.save_npz(complete_name+".npz", rec.eurm)
sb.submit(recommendation_list=eurm_to_recommendation_list_submission(rec.eurm), name=name, track="main", verify=True, gzipped=False)
| 32.912281 | 140 | 0.676972 | from utils.datareader import Datareader
from utils.evaluator import Evaluator
from utils.submitter import Submitter
from utils.post_processing import eurm_to_recommendation_list_submission
from utils.post_processing import eurm_to_recommendation_list
from utils.pre_processing import norm_l1_row, norm_max_row, norm_max_col
from recommenders.knn_collaborative_item import Knn_collaborative_item
import recommenders.similarity.similarity as sm
import scipy.sparse as sps
import sys
import numpy as np
from personal.Ervin.other_similarity import position_similarity
if __name__ == '__main__':
mode = sys.argv[1]
name = sys.argv[2]
knn = int(sys.argv[3])
topk = int(sys.argv[4])
complete_name = mode+"_"+name+"_knn="+str(knn)+"_topk="+str(topk)
if mode == "offline":
dr = Datareader(verbose=True, mode=mode, only_load=True)
ev = Evaluator(dr)
rec = Knn_collaborative_item()
urm = dr.get_urm()
urm.data = np.ones(len(urm.data))
position_urm = dr.get_position_matrix(position_type='last')
pos_urm = position_urm.T.tocoo().tocsr()
pid = dr.get_test_pids()
rec.fit(urm, pid)
rec.compute_model(top_k= knn, sm_type=sm.TVERSKY, shrink=200, alpha=0.1, beta=1, binary=True, verbose=True)
rec.model = rec.model.tocsr()
rec.model.eliminate_zeros()
print('Initial model has {:2} data'.format(len(rec.model.data)))
print('[ Updating the model ]')
rec.model = position_similarity(rec.model, pos_urm, knn=knn, verbose=True)
rec.model.eliminate_zeros()
print('New model has {:2} data'.format(len(rec.model.data)))
rec.compute_rating(top_k=topk,verbose=True, small=True, remove_seed=False)
sps.save_npz(complete_name+".npz", rec.eurm)
ev.evaluate(recommendation_list=eurm_to_recommendation_list(rec.eurm, datareader=dr, remove_seed=True),
name=name, old_mode=False)
if mode == "online":
dr = Datareader(verbose=True, mode=mode, only_load=False)
rec = Knn_collaborative_item()
sb = Submitter(dr)
urm = dr.get_urm()
pid = dr.get_test_pids()
rec.fit(urm, pid)
rec.compute_model(top_k=knn, sm_type=sm.TVERSKY,shrink=200, alpha=0.1, beta=1, binary=True, verbose=True)
rec.compute_rating(top_k=topk, verbose=True, small=True)
sps.save_npz(complete_name+".npz", rec.eurm)
sb.submit(recommendation_list=eurm_to_recommendation_list_submission(rec.eurm), name=name, track="main", verify=True, gzipped=False)
| true | true |
f71695f6ec0e1e0a59e525bb30d5fb132322b04b | 564 | py | Python | wagtail/core/migrations/0036_populate_page_last_published_at.py | brownaa/wagtail | c97bc56c6822eb1b6589d5c33e07f71acfc48845 | [
"BSD-3-Clause"
] | 8,851 | 2016-12-09T19:01:45.000Z | 2022-03-31T04:45:06.000Z | wagtail/core/migrations/0036_populate_page_last_published_at.py | brownaa/wagtail | c97bc56c6822eb1b6589d5c33e07f71acfc48845 | [
"BSD-3-Clause"
] | 5,197 | 2016-12-09T19:24:37.000Z | 2022-03-31T22:17:55.000Z | wagtail/core/migrations/0036_populate_page_last_published_at.py | brownaa/wagtail | c97bc56c6822eb1b6589d5c33e07f71acfc48845 | [
"BSD-3-Clause"
] | 2,548 | 2016-12-09T18:16:55.000Z | 2022-03-31T21:34:38.000Z | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-01 11:03
from django.db import migrations
from django.db.models import F
def forwards_func(apps, schema_editor):
Page = apps.get_model("wagtailcore", "Page")
Page.objects.filter(has_unpublished_changes=False).update(last_published_at=F('latest_revision_created_at'))
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0035_page_last_published_at'),
]
operations = [
migrations.RunPython(forwards_func, migrations.RunPython.noop),
]
| 26.857143 | 112 | 0.719858 |
from django.db import migrations
from django.db.models import F
def forwards_func(apps, schema_editor):
Page = apps.get_model("wagtailcore", "Page")
Page.objects.filter(has_unpublished_changes=False).update(last_published_at=F('latest_revision_created_at'))
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0035_page_last_published_at'),
]
operations = [
migrations.RunPython(forwards_func, migrations.RunPython.noop),
]
| true | true |
f71696347edb214d95d4dd5dbb9b50d0df5285c4 | 5,287 | py | Python | integration-testing/test/test_multiple_deploys.py | ArturGajowy/rchain | 7785a9195a4863a89f8aa22743e245c3e5f7940c | [
"Apache-2.0"
] | null | null | null | integration-testing/test/test_multiple_deploys.py | ArturGajowy/rchain | 7785a9195a4863a89f8aa22743e245c3e5f7940c | [
"Apache-2.0"
] | null | null | null | integration-testing/test/test_multiple_deploys.py | ArturGajowy/rchain | 7785a9195a4863a89f8aa22743e245c3e5f7940c | [
"Apache-2.0"
] | 1 | 2018-09-12T10:26:23.000Z | 2018-09-12T10:26:23.000Z | import logging
import contextlib
import threading
from typing import (
TYPE_CHECKING,
Generator,
)
import pytest
import conftest
from rnode_testing.common import TestingContext
from rnode_testing.rnode import (
docker_network_with_started_bootstrap,
started_peer,
)
from rnode_testing.wait import (
wait_for_blocks_count_at_least,
wait_for_approved_block_received_handler_state,
)
if TYPE_CHECKING:
from _pytest.fixtures import SubRequest
from docker.client import DockerClient
from rnode_testing.rnode import Node
class DeployThread(threading.Thread):
def __init__(self, name, node, contract, count):
threading.Thread.__init__(self)
self.name = name
self.node = node
self.contract = contract
self.count = count
logging.info(f"Setup thread - {self.contract} to node {self.name}, amount {count}.")
def run(self):
for i in range(self.count):
logging.info(f"[{self.name}]-[{i}] Will deploy {self.contract}.")
d = self.node.deploy(self.contract)
logging.info(f"[{self.name}]-[{i}] Deploy {self.contract}: {d}")
p = self.node.propose()
logging.info(f"[{self.name}]-[{i}] Proposed {self.contract}: {p}")
s = self.node.show_blocks_with_depth(1)
logging.info(f"[{self.name}]-[{i}] Show blocks: {s}")
BOOTSTRAP_NODE_KEYS = conftest.KeyPair(private_key='80366db5fbb8dad7946f27037422715e4176dda41d582224db87b6c3b783d709', public_key='1cd8bf79a2c1bd0afa160f6cdfeb8597257e48135c9bf5e4823f2875a1492c97')
BONDED_VALIDATOR_KEY_1 = conftest.KeyPair(private_key='120d42175739387af0264921bb117e4c4c05fbe2ce5410031e8b158c6e414bb5', public_key='02ab69930f74b931209df3ce54e3993674ab3e7c98f715608a5e74048b332821')
BONDED_VALIDATOR_KEY_2 = conftest.KeyPair(private_key='120d42175739387af0264921bb117e4c4c05fbe2ce5410031e8b158c6e414bb5', public_key='02ab69930f74b931209df3ce54e3993674ab3e7c98f715608a5e74048b332821')
BONDED_VALIDATOR_KEY_3 = conftest.KeyPair(private_key='120d42175739387af0264921bb117e4c4c05fbe2ce5410031e8b158c6e414bb5', public_key='02ab69930f74b931209df3ce54e3993674ab3e7c98f715608a5e74048b332821')
@contextlib.contextmanager
def started_bonded_validator(context: TestingContext, bootstrap_node: "Node", no, key_pair) -> Generator["Node", None, None]:
with started_peer(
context=context,
network=bootstrap_node.network,
name='bonded-validator-' + str(no),
bootstrap=bootstrap_node,
key_pair=key_pair,
) as bonded_validator:
wait_for_approved_block_received_handler_state(bonded_validator, context.node_startup_timeout)
yield bonded_validator
@pytest.mark.xfail
def test_multiple_deploys_at_once(command_line_options_fixture, docker_client_fixture) -> None:
contract_path = '/opt/docker/examples/hello_world_again.rho'
peers_keypairs = [BONDED_VALIDATOR_KEY_1, BONDED_VALIDATOR_KEY_2, BONDED_VALIDATOR_KEY_3]
with conftest.testing_context(command_line_options_fixture, docker_client_fixture, bootstrap_keypair=BOOTSTRAP_NODE_KEYS, peers_keypairs=peers_keypairs) as context:
with docker_network_with_started_bootstrap(context=context) as bootstrap_node:
with started_bonded_validator(context, bootstrap_node, 1, BONDED_VALIDATOR_KEY_1) as no1:
with started_bonded_validator(context, bootstrap_node, 2, BONDED_VALIDATOR_KEY_2) as no2:
with started_bonded_validator(context, bootstrap_node, 3, BONDED_VALIDATOR_KEY_3) as no3:
deploy1 = DeployThread("node1", no1, contract_path, 1)
deploy1.start()
expected_blocks_count = 1
max_retrieved_blocks = 1
wait_for_blocks_count_at_least(
no1,
expected_blocks_count,
max_retrieved_blocks,
expected_blocks_count * 10,
)
deploy2 = DeployThread("node2", no2, contract_path, 3)
deploy2.start()
deploy3 = DeployThread("node3", no3, contract_path, 3)
deploy3.start()
expected_blocks_count = 7
max_retrieved_blocks = 7
wait_for_blocks_count_at_least(
no1,
expected_blocks_count,
max_retrieved_blocks,
480
)
wait_for_blocks_count_at_least(
no2,
expected_blocks_count,
max_retrieved_blocks,
expected_blocks_count * 10,
)
wait_for_blocks_count_at_least(
no3,
expected_blocks_count,
max_retrieved_blocks,
expected_blocks_count * 10,
)
deploy1.join()
deploy2.join()
deploy3.join()
| 44.058333 | 200 | 0.635521 | import logging
import contextlib
import threading
from typing import (
TYPE_CHECKING,
Generator,
)
import pytest
import conftest
from rnode_testing.common import TestingContext
from rnode_testing.rnode import (
docker_network_with_started_bootstrap,
started_peer,
)
from rnode_testing.wait import (
wait_for_blocks_count_at_least,
wait_for_approved_block_received_handler_state,
)
if TYPE_CHECKING:
from _pytest.fixtures import SubRequest
from docker.client import DockerClient
from rnode_testing.rnode import Node
class DeployThread(threading.Thread):
def __init__(self, name, node, contract, count):
threading.Thread.__init__(self)
self.name = name
self.node = node
self.contract = contract
self.count = count
logging.info(f"Setup thread - {self.contract} to node {self.name}, amount {count}.")
def run(self):
for i in range(self.count):
logging.info(f"[{self.name}]-[{i}] Will deploy {self.contract}.")
d = self.node.deploy(self.contract)
logging.info(f"[{self.name}]-[{i}] Deploy {self.contract}: {d}")
p = self.node.propose()
logging.info(f"[{self.name}]-[{i}] Proposed {self.contract}: {p}")
s = self.node.show_blocks_with_depth(1)
logging.info(f"[{self.name}]-[{i}] Show blocks: {s}")
BOOTSTRAP_NODE_KEYS = conftest.KeyPair(private_key='80366db5fbb8dad7946f27037422715e4176dda41d582224db87b6c3b783d709', public_key='1cd8bf79a2c1bd0afa160f6cdfeb8597257e48135c9bf5e4823f2875a1492c97')
BONDED_VALIDATOR_KEY_1 = conftest.KeyPair(private_key='120d42175739387af0264921bb117e4c4c05fbe2ce5410031e8b158c6e414bb5', public_key='02ab69930f74b931209df3ce54e3993674ab3e7c98f715608a5e74048b332821')
BONDED_VALIDATOR_KEY_2 = conftest.KeyPair(private_key='120d42175739387af0264921bb117e4c4c05fbe2ce5410031e8b158c6e414bb5', public_key='02ab69930f74b931209df3ce54e3993674ab3e7c98f715608a5e74048b332821')
BONDED_VALIDATOR_KEY_3 = conftest.KeyPair(private_key='120d42175739387af0264921bb117e4c4c05fbe2ce5410031e8b158c6e414bb5', public_key='02ab69930f74b931209df3ce54e3993674ab3e7c98f715608a5e74048b332821')
@contextlib.contextmanager
def started_bonded_validator(context: TestingContext, bootstrap_node: "Node", no, key_pair) -> Generator["Node", None, None]:
with started_peer(
context=context,
network=bootstrap_node.network,
name='bonded-validator-' + str(no),
bootstrap=bootstrap_node,
key_pair=key_pair,
) as bonded_validator:
wait_for_approved_block_received_handler_state(bonded_validator, context.node_startup_timeout)
yield bonded_validator
@pytest.mark.xfail
def test_multiple_deploys_at_once(command_line_options_fixture, docker_client_fixture) -> None:
contract_path = '/opt/docker/examples/hello_world_again.rho'
peers_keypairs = [BONDED_VALIDATOR_KEY_1, BONDED_VALIDATOR_KEY_2, BONDED_VALIDATOR_KEY_3]
with conftest.testing_context(command_line_options_fixture, docker_client_fixture, bootstrap_keypair=BOOTSTRAP_NODE_KEYS, peers_keypairs=peers_keypairs) as context:
with docker_network_with_started_bootstrap(context=context) as bootstrap_node:
with started_bonded_validator(context, bootstrap_node, 1, BONDED_VALIDATOR_KEY_1) as no1:
with started_bonded_validator(context, bootstrap_node, 2, BONDED_VALIDATOR_KEY_2) as no2:
with started_bonded_validator(context, bootstrap_node, 3, BONDED_VALIDATOR_KEY_3) as no3:
deploy1 = DeployThread("node1", no1, contract_path, 1)
deploy1.start()
expected_blocks_count = 1
max_retrieved_blocks = 1
wait_for_blocks_count_at_least(
no1,
expected_blocks_count,
max_retrieved_blocks,
expected_blocks_count * 10,
)
deploy2 = DeployThread("node2", no2, contract_path, 3)
deploy2.start()
deploy3 = DeployThread("node3", no3, contract_path, 3)
deploy3.start()
expected_blocks_count = 7
max_retrieved_blocks = 7
wait_for_blocks_count_at_least(
no1,
expected_blocks_count,
max_retrieved_blocks,
480
)
wait_for_blocks_count_at_least(
no2,
expected_blocks_count,
max_retrieved_blocks,
expected_blocks_count * 10,
)
wait_for_blocks_count_at_least(
no3,
expected_blocks_count,
max_retrieved_blocks,
expected_blocks_count * 10,
)
deploy1.join()
deploy2.join()
deploy3.join()
| true | true |
f716972ac65d7ac3dcdcd16d28ba7fac85854f2f | 4,791 | py | Python | estonian_learner/verb.py | natter1/estonian_learner | da7837f0d64f4c1f6a212a9c473252c4b834699a | [
"MIT"
] | null | null | null | estonian_learner/verb.py | natter1/estonian_learner | da7837f0d64f4c1f6a212a9c473252c4b834699a | [
"MIT"
] | null | null | null | estonian_learner/verb.py | natter1/estonian_learner | da7837f0d64f4c1f6a212a9c473252c4b834699a | [
"MIT"
] | null | null | null | """
@author: Nathanael Jöhrmann
"""
import json
import textwrap
class Conjugations:
def __init__(self):
self.person = {}
self.negative = ["", ""]
self.passive = ["", ""]
self.passive_negative = ["", ""]
@property
def summary(self) -> str:
result = ""
sep = " "
for i in range(1, 7):
try:
result += sep.join([f"{i}P", self.person[str(i)][0], self.person[i][1]]) + "\n"
except KeyError: # needed, if data where put to json and back (int becomes str)
result += sep.join([f"{i}P", self.person[str(i)][0], self.person[str(i)][1]]) + "\n"
result += sep.join(["negative", self.negative[0], self.negative[1]]) + "\n"
result += sep.join(["passive", self.passive[0], self.passive[1]]) + "\n"
result += sep.join(["passive negative", self.passive_negative[0], self.passive_negative[1]]) + "\n"
return result
# def add_person(self, original, translation, index):
# self.person[index] = original
# self.person_translation[index] = translation
def to_json(self) -> dict:
"""
Returns a jsonified dict containing the data of self.
:return: dict
"""
my_dict = {"person": self.person,
"negative": self.negative,
"passive": self.passive,
"passive_negative": self.passive_negative
}
result = json.loads(json.dumps(my_dict, indent=2, ensure_ascii=False))
# print((my_dict))
# print(result)
# return my_dict # todo: test if this works with SQLAlchemy
return result
def from_json(self, _json: dict) -> None:
self.person = _json["person"]
self.negative = _json["negative"]
self.passive = _json["passive"]
self.passive_negative = _json["passive_negative"]
class Verb:
def __init__(self):
self.infinitive_ma = ("", "")
self.infinitive_da = ("", "")
self.past_active_participle = ("", "")
self.past_passive_participle = ("", "")
self.present = Conjugations()
self.conditional_mood = Conjugations()
self.imperative_mood = Conjugations()
self.imperative_negative_mood = Conjugations()
self.perfect = Conjugations()
self.past = Conjugations()
self.plusperfect = Conjugations()
self.conditional_perfect_mood = Conjugations()
self.quotative = Conjugations()
self.quotative_perfect = Conjugations()
self.jussive = Conjugations()
self.jussive_perfect = Conjugations()
self.other = {}
self.usage_info = ""
self.audio = None
@property
def summary(self) -> str:
result = textwrap.dedent(f"""\
---------------------------------------------------------
Usage info:
{self.usage_info}\n
Infinitive (-ma -da translation):
{self.infinitive_ma[0]} {self.infinitive_da[0]} {self.infinitive_ma[1]}\n
Past active participle:
{self.past_active_participle[0]} {self.past_active_participle[1]}\n
Past passive participle:
{self.past_passive_participle[0]} {self.past_passive_participle[1]}
""")
result += "\nPast passive participle\n"
result += self.past_passive_participle[0] + " " + self.past_passive_participle[1] + "\n"
result += "\nPresent tense\n"
result += self.present.summary
result += "\nConditional mood\n"
result += self.conditional_mood.summary
result += "\nImperative mood\n"
result += self.imperative_mood.summary
result += "\nImperative negative mood\n"
result += self.imperative_negative_mood.summary
result += "\nPerfect tense\n"
result += self.perfect.summary
result += "\nPast tense\n"
result += self.past.summary
result += "\nPlusperfect tense\n"
result += self.plusperfect.summary
result += "\nConditional perfect mood\n"
result += self.conditional_perfect_mood.summary
result += "\nQuotative tense\n"
result += self.quotative.summary
result += "\nQuotative perfect tense\n"
result += self.quotative_perfect.summary
result += "\nJussive tense\n"
result += self.jussive.summary
result += "\nJussive perfect tense\n"
result += self.jussive_perfect.summary
result += "\nOther\n"
for key in self.other:
result += key + " " + self.other[key][0] + " " + self.other[key][1] + "\n"
result += "---------------------------------------------------------\n"
return result
| 33.041379 | 107 | 0.557921 |
import json
import textwrap
class Conjugations:
def __init__(self):
self.person = {}
self.negative = ["", ""]
self.passive = ["", ""]
self.passive_negative = ["", ""]
@property
def summary(self) -> str:
result = ""
sep = " "
for i in range(1, 7):
try:
result += sep.join([f"{i}P", self.person[str(i)][0], self.person[i][1]]) + "\n"
except KeyError:
result += sep.join([f"{i}P", self.person[str(i)][0], self.person[str(i)][1]]) + "\n"
result += sep.join(["negative", self.negative[0], self.negative[1]]) + "\n"
result += sep.join(["passive", self.passive[0], self.passive[1]]) + "\n"
result += sep.join(["passive negative", self.passive_negative[0], self.passive_negative[1]]) + "\n"
return result
def to_json(self) -> dict:
my_dict = {"person": self.person,
"negative": self.negative,
"passive": self.passive,
"passive_negative": self.passive_negative
}
result = json.loads(json.dumps(my_dict, indent=2, ensure_ascii=False))
self, _json: dict) -> None:
self.person = _json["person"]
self.negative = _json["negative"]
self.passive = _json["passive"]
self.passive_negative = _json["passive_negative"]
class Verb:
def __init__(self):
self.infinitive_ma = ("", "")
self.infinitive_da = ("", "")
self.past_active_participle = ("", "")
self.past_passive_participle = ("", "")
self.present = Conjugations()
self.conditional_mood = Conjugations()
self.imperative_mood = Conjugations()
self.imperative_negative_mood = Conjugations()
self.perfect = Conjugations()
self.past = Conjugations()
self.plusperfect = Conjugations()
self.conditional_perfect_mood = Conjugations()
self.quotative = Conjugations()
self.quotative_perfect = Conjugations()
self.jussive = Conjugations()
self.jussive_perfect = Conjugations()
self.other = {}
self.usage_info = ""
self.audio = None
@property
def summary(self) -> str:
result = textwrap.dedent(f"""\
---------------------------------------------------------
Usage info:
{self.usage_info}\n
Infinitive (-ma -da translation):
{self.infinitive_ma[0]} {self.infinitive_da[0]} {self.infinitive_ma[1]}\n
Past active participle:
{self.past_active_participle[0]} {self.past_active_participle[1]}\n
Past passive participle:
{self.past_passive_participle[0]} {self.past_passive_participle[1]}
""")
result += "\nPast passive participle\n"
result += self.past_passive_participle[0] + " " + self.past_passive_participle[1] + "\n"
result += "\nPresent tense\n"
result += self.present.summary
result += "\nConditional mood\n"
result += self.conditional_mood.summary
result += "\nImperative mood\n"
result += self.imperative_mood.summary
result += "\nImperative negative mood\n"
result += self.imperative_negative_mood.summary
result += "\nPerfect tense\n"
result += self.perfect.summary
result += "\nPast tense\n"
result += self.past.summary
result += "\nPlusperfect tense\n"
result += self.plusperfect.summary
result += "\nConditional perfect mood\n"
result += self.conditional_perfect_mood.summary
result += "\nQuotative tense\n"
result += self.quotative.summary
result += "\nQuotative perfect tense\n"
result += self.quotative_perfect.summary
result += "\nJussive tense\n"
result += self.jussive.summary
result += "\nJussive perfect tense\n"
result += self.jussive_perfect.summary
result += "\nOther\n"
for key in self.other:
result += key + " " + self.other[key][0] + " " + self.other[key][1] + "\n"
result += "---------------------------------------------------------\n"
return result
| true | true |
f71697bced2a9b09c787e7d1ea296be902ceb742 | 2,498 | py | Python | src/cobald/daemon/runners/asyncio_runner.py | thoto/cobald | 27f7a0b5208383e8a7a386f358009a433084908e | [
"MIT"
] | 7 | 2019-06-11T12:57:10.000Z | 2019-10-07T17:46:41.000Z | src/cobald/daemon/runners/asyncio_runner.py | thoto/cobald | 27f7a0b5208383e8a7a386f358009a433084908e | [
"MIT"
] | 76 | 2019-03-01T08:24:08.000Z | 2022-03-24T20:37:23.000Z | src/cobald/daemon/runners/asyncio_runner.py | thoto/cobald | 27f7a0b5208383e8a7a386f358009a433084908e | [
"MIT"
] | 8 | 2019-06-27T13:06:12.000Z | 2022-02-15T15:27:58.000Z | import asyncio
from functools import partial
from .base_runner import BaseRunner
from .async_tools import raise_return, AsyncExecution
class AsyncioRunner(BaseRunner):
"""Runner for coroutines with :py:mod:`asyncio`"""
flavour = asyncio
def __init__(self):
super().__init__()
self.event_loop = asyncio.new_event_loop()
self._tasks = set()
def register_payload(self, payload):
super().register_payload(partial(raise_return, payload))
def run_payload(self, payload):
execution = AsyncExecution(payload)
super().register_payload(execution.coroutine)
return execution.wait()
def _run(self):
asyncio.set_event_loop(self.event_loop)
self.event_loop.run_until_complete(self._run_payloads())
async def _run_payloads(self):
"""Async component of _run"""
delay = 0.0
try:
while self.running.is_set():
await self._start_payloads()
await self._reap_payloads()
await asyncio.sleep(delay)
delay = min(delay + 0.1, 1.0)
except Exception:
await self._cancel_payloads()
raise
async def _start_payloads(self):
"""Start all queued payloads"""
with self._lock:
for coroutine in self._payloads:
task = self.event_loop.create_task(coroutine())
self._tasks.add(task)
self._payloads.clear()
await asyncio.sleep(0)
async def _reap_payloads(self):
"""Clean up all finished payloads"""
for task in self._tasks.copy():
if task.done():
self._tasks.remove(task)
if task.exception() is not None:
raise task.exception()
await asyncio.sleep(0)
async def _cancel_payloads(self):
"""Cancel all remaining payloads"""
for task in self._tasks:
task.cancel()
await asyncio.sleep(0)
for task in self._tasks:
while not task.done():
await asyncio.sleep(0.1)
task.cancel()
def stop(self):
if not self.running.wait(0.2):
return
self._logger.debug("runner disabled: %s", self)
with self._lock:
self.running.clear()
for task in self._tasks:
task.cancel()
self._stopped.wait()
self.event_loop.stop()
self.event_loop.close()
| 30.463415 | 64 | 0.583667 | import asyncio
from functools import partial
from .base_runner import BaseRunner
from .async_tools import raise_return, AsyncExecution
class AsyncioRunner(BaseRunner):
flavour = asyncio
def __init__(self):
super().__init__()
self.event_loop = asyncio.new_event_loop()
self._tasks = set()
def register_payload(self, payload):
super().register_payload(partial(raise_return, payload))
def run_payload(self, payload):
execution = AsyncExecution(payload)
super().register_payload(execution.coroutine)
return execution.wait()
def _run(self):
asyncio.set_event_loop(self.event_loop)
self.event_loop.run_until_complete(self._run_payloads())
async def _run_payloads(self):
delay = 0.0
try:
while self.running.is_set():
await self._start_payloads()
await self._reap_payloads()
await asyncio.sleep(delay)
delay = min(delay + 0.1, 1.0)
except Exception:
await self._cancel_payloads()
raise
async def _start_payloads(self):
with self._lock:
for coroutine in self._payloads:
task = self.event_loop.create_task(coroutine())
self._tasks.add(task)
self._payloads.clear()
await asyncio.sleep(0)
async def _reap_payloads(self):
for task in self._tasks.copy():
if task.done():
self._tasks.remove(task)
if task.exception() is not None:
raise task.exception()
await asyncio.sleep(0)
async def _cancel_payloads(self):
for task in self._tasks:
task.cancel()
await asyncio.sleep(0)
for task in self._tasks:
while not task.done():
await asyncio.sleep(0.1)
task.cancel()
def stop(self):
if not self.running.wait(0.2):
return
self._logger.debug("runner disabled: %s", self)
with self._lock:
self.running.clear()
for task in self._tasks:
task.cancel()
self._stopped.wait()
self.event_loop.stop()
self.event_loop.close()
| true | true |
f71697bcf73bda98b7059ee2d3fd8ac5e69857ec | 2,881 | py | Python | tests/test_fuzzy_completion.py | vijayraavi/mssql-cli | bc16073e371314b970479c2830266ff24d63bd16 | [
"BSD-3-Clause"
] | null | null | null | tests/test_fuzzy_completion.py | vijayraavi/mssql-cli | bc16073e371314b970479c2830266ff24d63bd16 | [
"BSD-3-Clause"
] | null | null | null | tests/test_fuzzy_completion.py | vijayraavi/mssql-cli | bc16073e371314b970479c2830266ff24d63bd16 | [
"BSD-3-Clause"
] | null | null | null | from __future__ import unicode_literals
import pytest
@pytest.fixture
def completer():
import mssqlcli.mssqlcompleter as mssqlcompleter
return mssqlcompleter.MssqlCompleter()
def test_ranking_ignores_identifier_quotes(completer):
"""When calculating result rank, identifier quotes should be ignored.
The result ranking algorithm ignores identifier quotes. Without this
correction, the match "user", which Postgres requires to be quoted
since it is also a reserved word, would incorrectly fall below the
match user_action because the literal quotation marks in "user"
alter the position of the match.
This test checks that the fuzzy ranking algorithm correctly ignores
quotation marks when computing match ranks.
"""
text = 'user'
collection = ['user_action', '"user"']
matches = completer.find_matches(text, collection)
assert len(matches) == 2
def test_ranking_based_on_shortest_match(completer):
"""Fuzzy result rank should be based on shortest match.
Result ranking in fuzzy searching is partially based on the length
of matches: shorter matches are considered more relevant than
longer ones. When searching for the text 'user', the length
component of the match 'user_group' could be either 4 ('user') or
7 ('user_gr').
This test checks that the fuzzy ranking algorithm uses the shorter
match when calculating result rank.
"""
text = 'user'
collection = ['api_user', 'user_group']
matches = completer.find_matches(text, collection)
assert matches[1].priority > matches[0].priority
@pytest.mark.parametrize('collection', [
['user_action', 'user'],
['user_group', 'user'],
['user_group', 'user_action'],
])
def test_should_break_ties_using_lexical_order(completer, collection):
"""Fuzzy result rank should use lexical order to break ties.
When fuzzy matching, if multiple matches have the same match length and
start position, present them in lexical (rather than arbitrary) order. For
example, if we have tables 'user', 'user_action', and 'user_group', a
search for the text 'user' should present these tables in this order.
The input collections to this test are out of order; each run checks that
the search text 'user' results in the input tables being reordered
lexically.
"""
text = 'user'
matches = completer.find_matches(text, collection)
assert matches[1].priority > matches[0].priority
def test_matching_should_be_case_insensitive(completer):
"""Fuzzy matching should keep matches even if letter casing doesn't match.
This test checks that variations of the text which have different casing
are still matched.
"""
text = 'foo'
collection = ['Foo', 'FOO', 'fOO']
matches = completer.find_matches(text, collection)
assert len(matches) == 3
| 32.370787 | 78 | 0.72579 | from __future__ import unicode_literals
import pytest
@pytest.fixture
def completer():
import mssqlcli.mssqlcompleter as mssqlcompleter
return mssqlcompleter.MssqlCompleter()
def test_ranking_ignores_identifier_quotes(completer):
text = 'user'
collection = ['user_action', '"user"']
matches = completer.find_matches(text, collection)
assert len(matches) == 2
def test_ranking_based_on_shortest_match(completer):
text = 'user'
collection = ['api_user', 'user_group']
matches = completer.find_matches(text, collection)
assert matches[1].priority > matches[0].priority
@pytest.mark.parametrize('collection', [
['user_action', 'user'],
['user_group', 'user'],
['user_group', 'user_action'],
])
def test_should_break_ties_using_lexical_order(completer, collection):
text = 'user'
matches = completer.find_matches(text, collection)
assert matches[1].priority > matches[0].priority
def test_matching_should_be_case_insensitive(completer):
text = 'foo'
collection = ['Foo', 'FOO', 'fOO']
matches = completer.find_matches(text, collection)
assert len(matches) == 3
| true | true |
f71697d88f48702950eaef9afcbbc278acd2b761 | 606 | py | Python | codewars/7 kyu/string-ends-with.py | sirken/coding-practice | 9c5e23b2c24f525a89a5e1d15ce3aec3ad1a01ab | [
"MIT"
] | null | null | null | codewars/7 kyu/string-ends-with.py | sirken/coding-practice | 9c5e23b2c24f525a89a5e1d15ce3aec3ad1a01ab | [
"MIT"
] | null | null | null | codewars/7 kyu/string-ends-with.py | sirken/coding-practice | 9c5e23b2c24f525a89a5e1d15ce3aec3ad1a01ab | [
"MIT"
] | null | null | null | from Test import Test, Test as test
'''
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
'''
def solution(string, ending):
return True if string[-len(ending):] == ending or len(ending) == 0 else False
# Top solution
def solution(string, ending):
return string.endswith(ending)
test.assert_equals(solution('abcde', 'cde'), True)
test.assert_equals(solution('abcde', 'abc'), False)
test.assert_equals(solution('abcde', ''), True) | 28.857143 | 129 | 0.714521 | from Test import Test, Test as test
def solution(string, ending):
return True if string[-len(ending):] == ending or len(ending) == 0 else False
def solution(string, ending):
return string.endswith(ending)
test.assert_equals(solution('abcde', 'cde'), True)
test.assert_equals(solution('abcde', 'abc'), False)
test.assert_equals(solution('abcde', ''), True) | true | true |
f7169805436b5cf887fbf1c99fd59f5c2e43d93c | 7,209 | py | Python | ros/src/styx/bridge.py | Valentinkvn/Udacity-Full-Autonomous-Vehicle-Project | b1313345a09f84c122a91c1145230fe69da0d20f | [
"MIT"
] | null | null | null | ros/src/styx/bridge.py | Valentinkvn/Udacity-Full-Autonomous-Vehicle-Project | b1313345a09f84c122a91c1145230fe69da0d20f | [
"MIT"
] | 6 | 2021-02-22T08:44:36.000Z | 2022-03-12T00:13:46.000Z | ros/src/styx/bridge.py | Valentinkvn/Udacity-Full-Autonomous-Vehicle-Project | b1313345a09f84c122a91c1145230fe69da0d20f | [
"MIT"
] | null | null | null |
import rospy
import tf
from geometry_msgs.msg import PoseStamped, Quaternion, TwistStamped
from dbw_mkz_msgs.msg import SteeringReport, ThrottleCmd, BrakeCmd, SteeringCmd
from std_msgs.msg import Float32 as Float
from std_msgs.msg import Bool
from sensor_msgs.msg import PointCloud2
from sensor_msgs.msg import Image
import sensor_msgs.point_cloud2 as pcl2
from std_msgs.msg import Header
from cv_bridge import CvBridge, CvBridgeError
from styx_msgs.msg import TrafficLight, TrafficLightArray, Lane
import numpy as np
from PIL import Image as PIL_Image
from io import BytesIO
import base64
import math
TYPE = {
'bool': Bool,
'float': Float,
'pose': PoseStamped,
'pcl': PointCloud2,
'twist': TwistStamped,
'steer': SteeringReport,
'trafficlights': TrafficLightArray,
'steer_cmd': SteeringCmd,
'brake_cmd': BrakeCmd,
'throttle_cmd': ThrottleCmd,
'path_draw': Lane,
'image':Image
}
NUM_IMAGES_TO_SKIP = 2
class Bridge(object):
def __init__(self, conf, server):
rospy.init_node('styx_server')
self.server = server
self.vel = 0.
self.yaw = None
self.angular_vel = 0.
self.bridge = CvBridge()
self.img_count = 0
self.callbacks = {
'/vehicle/steering_cmd': self.callback_steering,
'/vehicle/throttle_cmd': self.callback_throttle,
'/vehicle/brake_cmd': self.callback_brake,
'/final_waypoints': self.callback_path
}
self.subscribers = [rospy.Subscriber(e.topic, TYPE[e.type], self.callbacks[e.topic])
for e in conf.subscribers]
self.publishers = {e.name: rospy.Publisher(e.topic, TYPE[e.type], queue_size=1)
for e in conf.publishers}
def create_light(self, x, y, z, yaw, state):
light = TrafficLight()
light.header = Header()
light.header.stamp = rospy.Time.now()
light.header.frame_id = '/world'
light.pose = self.create_pose(x, y, z, yaw)
light.state = state
return light
def create_pose(self, x, y, z, yaw=0.):
pose = PoseStamped()
pose.header = Header()
pose.header.stamp = rospy.Time.now()
pose.header.frame_id = '/world'
pose.pose.position.x = x
pose.pose.position.y = y
pose.pose.position.z = z
q = tf.transformations.quaternion_from_euler(0., 0., math.pi * yaw/180.)
pose.pose.orientation = Quaternion(*q)
return pose
def create_float(self, val):
fl = Float()
fl.data = val
return fl
def create_twist(self, velocity, angular):
tw = TwistStamped()
tw.twist.linear.x = velocity
tw.twist.angular.z = angular
return tw
def create_steer(self, val):
st = SteeringReport()
st.steering_wheel_angle_cmd = val * math.pi/180.
st.enabled = True
st.speed = self.vel
return st
def calc_angular(self, yaw):
angular_vel = 0.
if self.yaw is not None:
angular_vel = (yaw - self.yaw)/(rospy.get_time() - self.prev_time)
self.yaw = yaw
self.prev_time = rospy.get_time()
return angular_vel
def create_point_cloud_message(self, pts):
header = Header()
header.stamp = rospy.Time.now()
header.frame_id = '/world'
cloud_message = pcl2.create_cloud_xyz32(header, pts)
return cloud_message
def broadcast_transform(self, name, position, orientation):
br = tf.TransformBroadcaster()
br.sendTransform(position,
orientation,
rospy.Time.now(),
name,
"world")
def publish_odometry(self, data):
pose = self.create_pose(data['x'], data['y'], data['z'], data['yaw'])
position = (data['x'], data['y'], data['z'])
orientation = tf.transformations.quaternion_from_euler(0, 0, math.pi * data['yaw']/180.)
self.broadcast_transform("base_link", position, orientation)
self.publishers['current_pose'].publish(pose)
self.vel = data['velocity']* 0.44704
self.angular = self.calc_angular(data['yaw'] * math.pi/180.)
self.publishers['current_velocity'].publish(self.create_twist(self.vel, self.angular))
def publish_controls(self, data):
steering, throttle, brake = data['steering_angle'], data['throttle'], data['brake']
self.publishers['steering_report'].publish(self.create_steer(steering))
self.publishers['throttle_report'].publish(self.create_float(throttle))
self.publishers['brake_report'].publish(self.create_float(brake))
def publish_obstacles(self, data):
for obs in data['obstacles']:
pose = self.create_pose(obs[0], obs[1], obs[2])
self.publishers['obstacle'].publish(pose)
header = Header()
header.stamp = rospy.Time.now()
header.frame_id = '/world'
cloud = pcl2.create_cloud_xyz32(header, data['obstacles'])
self.publishers['obstacle_points'].publish(cloud)
def publish_lidar(self, data):
self.publishers['lidar'].publish(self.create_point_cloud_message(zip(data['lidar_x'], data['lidar_y'], data['lidar_z'])))
def publish_traffic(self, data):
x, y, z = data['light_pos_x'], data['light_pos_y'], data['light_pos_z'],
yaw = [math.atan2(dy, dx) for dx, dy in zip(data['light_pos_dx'], data['light_pos_dy'])]
status = data['light_state']
lights = TrafficLightArray()
header = Header()
header.stamp = rospy.Time.now()
header.frame_id = '/world'
lights.lights = [self.create_light(*e) for e in zip(x, y, z, yaw, status)]
self.publishers['trafficlights'].publish(lights)
def publish_dbw_status(self, data):
self.publishers['dbw_status'].publish(Bool(data))
def publish_camera(self, data):
self.img_count += 1
if self.img_count >= NUM_IMAGES_TO_SKIP:
# rospy.logwarn("Publish camera data")
imgString = data["image"]
image = PIL_Image.open(BytesIO(base64.b64decode(imgString)))
image_array = np.asarray(image)
image_message = self.bridge.cv2_to_imgmsg(image_array, encoding="rgb8")
self.publishers['image'].publish(image_message)
self.img_count = 0
def callback_steering(self, data):
self.server('steer', data={'steering_angle': str(data.steering_wheel_angle_cmd)})
def callback_throttle(self, data):
self.server('throttle', data={'throttle': str(data.pedal_cmd)})
def callback_brake(self, data):
self.server('brake', data={'brake': str(data.pedal_cmd)})
def callback_path(self, data):
x_values = []
y_values = []
z_values = []
for waypoint in data.waypoints:
x = waypoint.pose.pose.position.x
y = waypoint.pose.pose.position.y
z = waypoint.pose.pose.position.z+0.5
x_values.append(x)
y_values.append(y)
z_values.append(z)
self.server('drawline', data={'next_x': x_values, 'next_y': y_values, 'next_z': z_values})
| 34.004717 | 129 | 0.627688 |
import rospy
import tf
from geometry_msgs.msg import PoseStamped, Quaternion, TwistStamped
from dbw_mkz_msgs.msg import SteeringReport, ThrottleCmd, BrakeCmd, SteeringCmd
from std_msgs.msg import Float32 as Float
from std_msgs.msg import Bool
from sensor_msgs.msg import PointCloud2
from sensor_msgs.msg import Image
import sensor_msgs.point_cloud2 as pcl2
from std_msgs.msg import Header
from cv_bridge import CvBridge, CvBridgeError
from styx_msgs.msg import TrafficLight, TrafficLightArray, Lane
import numpy as np
from PIL import Image as PIL_Image
from io import BytesIO
import base64
import math
TYPE = {
'bool': Bool,
'float': Float,
'pose': PoseStamped,
'pcl': PointCloud2,
'twist': TwistStamped,
'steer': SteeringReport,
'trafficlights': TrafficLightArray,
'steer_cmd': SteeringCmd,
'brake_cmd': BrakeCmd,
'throttle_cmd': ThrottleCmd,
'path_draw': Lane,
'image':Image
}
NUM_IMAGES_TO_SKIP = 2
class Bridge(object):
def __init__(self, conf, server):
rospy.init_node('styx_server')
self.server = server
self.vel = 0.
self.yaw = None
self.angular_vel = 0.
self.bridge = CvBridge()
self.img_count = 0
self.callbacks = {
'/vehicle/steering_cmd': self.callback_steering,
'/vehicle/throttle_cmd': self.callback_throttle,
'/vehicle/brake_cmd': self.callback_brake,
'/final_waypoints': self.callback_path
}
self.subscribers = [rospy.Subscriber(e.topic, TYPE[e.type], self.callbacks[e.topic])
for e in conf.subscribers]
self.publishers = {e.name: rospy.Publisher(e.topic, TYPE[e.type], queue_size=1)
for e in conf.publishers}
def create_light(self, x, y, z, yaw, state):
light = TrafficLight()
light.header = Header()
light.header.stamp = rospy.Time.now()
light.header.frame_id = '/world'
light.pose = self.create_pose(x, y, z, yaw)
light.state = state
return light
def create_pose(self, x, y, z, yaw=0.):
pose = PoseStamped()
pose.header = Header()
pose.header.stamp = rospy.Time.now()
pose.header.frame_id = '/world'
pose.pose.position.x = x
pose.pose.position.y = y
pose.pose.position.z = z
q = tf.transformations.quaternion_from_euler(0., 0., math.pi * yaw/180.)
pose.pose.orientation = Quaternion(*q)
return pose
def create_float(self, val):
fl = Float()
fl.data = val
return fl
def create_twist(self, velocity, angular):
tw = TwistStamped()
tw.twist.linear.x = velocity
tw.twist.angular.z = angular
return tw
def create_steer(self, val):
st = SteeringReport()
st.steering_wheel_angle_cmd = val * math.pi/180.
st.enabled = True
st.speed = self.vel
return st
def calc_angular(self, yaw):
angular_vel = 0.
if self.yaw is not None:
angular_vel = (yaw - self.yaw)/(rospy.get_time() - self.prev_time)
self.yaw = yaw
self.prev_time = rospy.get_time()
return angular_vel
def create_point_cloud_message(self, pts):
header = Header()
header.stamp = rospy.Time.now()
header.frame_id = '/world'
cloud_message = pcl2.create_cloud_xyz32(header, pts)
return cloud_message
def broadcast_transform(self, name, position, orientation):
br = tf.TransformBroadcaster()
br.sendTransform(position,
orientation,
rospy.Time.now(),
name,
"world")
def publish_odometry(self, data):
pose = self.create_pose(data['x'], data['y'], data['z'], data['yaw'])
position = (data['x'], data['y'], data['z'])
orientation = tf.transformations.quaternion_from_euler(0, 0, math.pi * data['yaw']/180.)
self.broadcast_transform("base_link", position, orientation)
self.publishers['current_pose'].publish(pose)
self.vel = data['velocity']* 0.44704
self.angular = self.calc_angular(data['yaw'] * math.pi/180.)
self.publishers['current_velocity'].publish(self.create_twist(self.vel, self.angular))
def publish_controls(self, data):
steering, throttle, brake = data['steering_angle'], data['throttle'], data['brake']
self.publishers['steering_report'].publish(self.create_steer(steering))
self.publishers['throttle_report'].publish(self.create_float(throttle))
self.publishers['brake_report'].publish(self.create_float(brake))
def publish_obstacles(self, data):
for obs in data['obstacles']:
pose = self.create_pose(obs[0], obs[1], obs[2])
self.publishers['obstacle'].publish(pose)
header = Header()
header.stamp = rospy.Time.now()
header.frame_id = '/world'
cloud = pcl2.create_cloud_xyz32(header, data['obstacles'])
self.publishers['obstacle_points'].publish(cloud)
def publish_lidar(self, data):
self.publishers['lidar'].publish(self.create_point_cloud_message(zip(data['lidar_x'], data['lidar_y'], data['lidar_z'])))
def publish_traffic(self, data):
x, y, z = data['light_pos_x'], data['light_pos_y'], data['light_pos_z'],
yaw = [math.atan2(dy, dx) for dx, dy in zip(data['light_pos_dx'], data['light_pos_dy'])]
status = data['light_state']
lights = TrafficLightArray()
header = Header()
header.stamp = rospy.Time.now()
header.frame_id = '/world'
lights.lights = [self.create_light(*e) for e in zip(x, y, z, yaw, status)]
self.publishers['trafficlights'].publish(lights)
def publish_dbw_status(self, data):
self.publishers['dbw_status'].publish(Bool(data))
def publish_camera(self, data):
self.img_count += 1
if self.img_count >= NUM_IMAGES_TO_SKIP:
imgString = data["image"]
image = PIL_Image.open(BytesIO(base64.b64decode(imgString)))
image_array = np.asarray(image)
image_message = self.bridge.cv2_to_imgmsg(image_array, encoding="rgb8")
self.publishers['image'].publish(image_message)
self.img_count = 0
def callback_steering(self, data):
self.server('steer', data={'steering_angle': str(data.steering_wheel_angle_cmd)})
def callback_throttle(self, data):
self.server('throttle', data={'throttle': str(data.pedal_cmd)})
def callback_brake(self, data):
self.server('brake', data={'brake': str(data.pedal_cmd)})
def callback_path(self, data):
x_values = []
y_values = []
z_values = []
for waypoint in data.waypoints:
x = waypoint.pose.pose.position.x
y = waypoint.pose.pose.position.y
z = waypoint.pose.pose.position.z+0.5
x_values.append(x)
y_values.append(y)
z_values.append(z)
self.server('drawline', data={'next_x': x_values, 'next_y': y_values, 'next_z': z_values})
| true | true |
f716984bca20b513662e2e393027677207b388b1 | 1,954 | py | Python | mfr2.py | HeegyuKim/face_recognition | d96d2c94225e49d3dd8f2cae4444d35d5c88d13b | [
"MIT"
] | null | null | null | mfr2.py | HeegyuKim/face_recognition | d96d2c94225e49d3dd8f2cae4444d35d5c88d13b | [
"MIT"
] | null | null | null | mfr2.py | HeegyuKim/face_recognition | d96d2c94225e49d3dd8f2cae4444d35d5c88d13b | [
"MIT"
] | null | null | null | import os
import shutil
import os
from glob import glob
import pandas as pd
import random
from collections import defaultdict
from PIL import Image
from torch.utils.data import Dataset, DataLoader
def get_all_images(dir):
types = ["jpeg", "jpg", "png"]
files = []
for t in types:
path = os.path.join(dir, "**", "*." + t)
files.extend(glob(path))
return files
def casia(dir):
files = get_all_images(dir)
users = defaultdict(set)
rows = []
for file in files:
user = file.split("/")[-2]
users[user].add(file)
rows.append({
"image": file,
"id": user
})
df = pd.DataFrame(rows)
positives = []
negatives = []
for user, files in users.items():
if len(files) <= 1:
continue
samples = random.sample(files, 2)
positives.append({
"image1": samples[0],
"image2": samples[1],
"id1": user,
"id2": user,
"label": 1
})
user_ids = list(users.keys())
for i in range(0, len(user_ids), 2):
if i == len(user_ids) - 1:
continue
id1, id2 = user_ids[i], user_ids[i + 1]
files1, files2 = users[id1], users[id2]
if len(files1) < 2 or len(files2) < 2:
break
samples1, samples2 = random.sample(files1, 2), random.sample(files2, 2)
for j in range(2):
negatives.append({
"image1": samples1[j],
"image2": samples2[j],
"id1": id1,
"id2": id2,
"label": -1
})
test_set = pd.DataFrame(positives + negatives)
return df, test_set
# trainset, testset = casia("train/")
# trainset.to_csv("train.csv", index=False)
# testset.to_csv("train_eval.csv", index=False)
for file in glob("dataset/validation/**/*.png", recursive=True):
tokens = file.split("/")
filename = tokens[-1]
id = tokens[-3]
dst = f"mfeval/{id}/{filename}"
os.makedirs(os.path.abspath(os.path.dirname(dst)), exist_ok=True)
shutil.copyfile(file, dst) | 22.45977 | 75 | 0.592119 | import os
import shutil
import os
from glob import glob
import pandas as pd
import random
from collections import defaultdict
from PIL import Image
from torch.utils.data import Dataset, DataLoader
def get_all_images(dir):
types = ["jpeg", "jpg", "png"]
files = []
for t in types:
path = os.path.join(dir, "**", "*." + t)
files.extend(glob(path))
return files
def casia(dir):
files = get_all_images(dir)
users = defaultdict(set)
rows = []
for file in files:
user = file.split("/")[-2]
users[user].add(file)
rows.append({
"image": file,
"id": user
})
df = pd.DataFrame(rows)
positives = []
negatives = []
for user, files in users.items():
if len(files) <= 1:
continue
samples = random.sample(files, 2)
positives.append({
"image1": samples[0],
"image2": samples[1],
"id1": user,
"id2": user,
"label": 1
})
user_ids = list(users.keys())
for i in range(0, len(user_ids), 2):
if i == len(user_ids) - 1:
continue
id1, id2 = user_ids[i], user_ids[i + 1]
files1, files2 = users[id1], users[id2]
if len(files1) < 2 or len(files2) < 2:
break
samples1, samples2 = random.sample(files1, 2), random.sample(files2, 2)
for j in range(2):
negatives.append({
"image1": samples1[j],
"image2": samples2[j],
"id1": id1,
"id2": id2,
"label": -1
})
test_set = pd.DataFrame(positives + negatives)
return df, test_set
for file in glob("dataset/validation/**/*.png", recursive=True):
tokens = file.split("/")
filename = tokens[-1]
id = tokens[-3]
dst = f"mfeval/{id}/{filename}"
os.makedirs(os.path.abspath(os.path.dirname(dst)), exist_ok=True)
shutil.copyfile(file, dst) | true | true |
f716985e68c4ca47db77d1c2d95da2329e93bfc9 | 1,483 | py | Python | official/nlp/modeling/networks/__init__.py | akineeic/models | 2912042352009c9993dc05403624100bfe42d9c1 | [
"Apache-2.0"
] | 15 | 2018-08-15T19:29:39.000Z | 2021-11-05T02:14:59.000Z | official/nlp/modeling/networks/__init__.py | yangxl-2014-fe/models | 11ea5237818e791a5717716d5413977f4c4db1e3 | [
"Apache-2.0"
] | 5 | 2020-10-01T09:02:34.000Z | 2021-02-21T12:50:11.000Z | official/nlp/modeling/networks/__init__.py | yangxl-2014-fe/models | 11ea5237818e791a5717716d5413977f4c4db1e3 | [
"Apache-2.0"
] | 8 | 2019-06-06T20:37:15.000Z | 2022-03-04T13:54:38.000Z | # Copyright 2019 The TensorFlow 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.
# ==============================================================================
"""Networks package definition."""
from official.nlp.modeling.networks.albert_encoder import AlbertEncoder
from official.nlp.modeling.networks.bert_encoder import BertEncoder
from official.nlp.modeling.networks.classification import Classification
from official.nlp.modeling.networks.encoder_scaffold import EncoderScaffold
from official.nlp.modeling.networks.mobile_bert_encoder import MobileBERTEncoder
from official.nlp.modeling.networks.packed_sequence_embedding import PackedSequenceEmbedding
from official.nlp.modeling.networks.span_labeling import SpanLabeling
from official.nlp.modeling.networks.span_labeling import XLNetSpanLabeling
from official.nlp.modeling.networks.xlnet_base import XLNetBase
# Backward compatibility. The modules are deprecated.
TransformerEncoder = BertEncoder
| 54.925926 | 92 | 0.784895 |
from official.nlp.modeling.networks.albert_encoder import AlbertEncoder
from official.nlp.modeling.networks.bert_encoder import BertEncoder
from official.nlp.modeling.networks.classification import Classification
from official.nlp.modeling.networks.encoder_scaffold import EncoderScaffold
from official.nlp.modeling.networks.mobile_bert_encoder import MobileBERTEncoder
from official.nlp.modeling.networks.packed_sequence_embedding import PackedSequenceEmbedding
from official.nlp.modeling.networks.span_labeling import SpanLabeling
from official.nlp.modeling.networks.span_labeling import XLNetSpanLabeling
from official.nlp.modeling.networks.xlnet_base import XLNetBase
TransformerEncoder = BertEncoder
| true | true |
f71698db8367f39cb85d20a59c8f5d11cc1b4ccc | 4,301 | py | Python | coding_problems/move_zeros.py | NescobarAlopLop/miscellaneous | 8e33cb34ddc54dad233d2418d4a90a96ce3c393e | [
"MIT"
] | null | null | null | coding_problems/move_zeros.py | NescobarAlopLop/miscellaneous | 8e33cb34ddc54dad233d2418d4a90a96ce3c393e | [
"MIT"
] | null | null | null | coding_problems/move_zeros.py | NescobarAlopLop/miscellaneous | 8e33cb34ddc54dad233d2418d4a90a96ce3c393e | [
"MIT"
] | null | null | null | """
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the
non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
"""
from unittest import TestCase
class Solution:
@staticmethod
def get_next(nums, start, zero=True):
for idx in range(start, len(nums)):
if zero and nums[idx] == 0:
return idx
if not zero and nums[idx] != zero:
return idx
return len(nums)
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
z = self.get_next(nums, 0, zero=True)
n = self.get_next(nums, 0, zero=False)
while n < len(nums):
if n > z and nums[n] != 0:
nums[z], nums[n] = nums[n], nums[z]
z = self.get_next(nums, z, zero=True)
n = self.get_next(nums, n, zero=False)
continue
else:
n += 1
class TestSolution(TestCase):
sol = Solution()
def test_0(self):
nums = [0, 1, 2, 3, 4]
self.sol.moveZeroes(nums)
print("result: {}".format(nums))
self.assertEqual([1, 2, 3, 4, 0], nums)
def test_1(self):
nums = [0, 1, 0, 2, 0, 3, 0, 1]
self.sol.moveZeroes(nums)
print("result: {}".format(nums))
self.assertEqual([1, 2, 3, 1, 0, 0, 0, 0], nums)
def test_3(self):
nums = [0,1,0,3,12]
self.sol.moveZeroes(nums)
print("result: {}".format(nums))
self.assertEqual([1, 3, 12, 0, 0], nums)
def test_4(self):
nums = [1]
self.sol.moveZeroes(nums)
print("result: {}".format(nums))
self.assertEqual([1], nums)
def test_5(self):
nums = [1, -2, 0, 0, 3, 0, 4, 0]
self.sol.moveZeroes(nums)
print("result: {}".format(nums))
self.assertEqual([1, -2, 3, 4, 0, 0, 0, 0], nums)
def test_6(self):
nums = [-959151711,623836953,209446690,-1950418142,1339915067,-733626417,481171539,-2125997010,-1225423476,1462109565,147434687,-1800073781,-1431212205,-450443973,50097298,753533734,-747189404,-2070885638,0,-1484353894,-340296594,-2133744570,619639811,-1626162038,669689561,0,112220218,502447212,-787793179,0,-726846372,-1611013491,204107194,1605165582,-566891128,2082852116,0,532995238,-1502590712,0,2136989777,-2031153343,371398938,-1907397429,342796391,609166045,-2007448660,-1096076344,-323570318,0,-2082980371,2129956379,-243553361,-1549960929,1502383415,0,-1394618779,694799815,78595689,-1439173023,-1416578800,685225786,-333502212,-1181308536,-380569313,772035354,0,-915266376,663709718,1443496021,-777017729,-883300731,-387828385,1907473488,-725483724,-972961871,-1255712537,383120918,1383877998,1722751914,0,-1156050682,1952527902,-560244497,1304305692,1173974542,-1313227247,-201476579,-298899493,-1828496581,-1724396350,1933643204,1531804925,1728655262,-955565449,0,-69843702,-461760848,268336768,1446130876]
self.sol.moveZeroes(nums)
print("result: {}".format(nums))
self.assertEqual([-959151711,623836953,209446690,-1950418142,1339915067,-733626417,481171539,-2125997010,-1225423476,1462109565,147434687,-1800073781,-1431212205,-450443973,50097298,753533734,-747189404,-2070885638,-1484353894,-340296594,-2133744570,619639811,-1626162038,669689561,112220218,502447212,-787793179,-726846372,-1611013491,204107194,1605165582,-566891128,2082852116,532995238,-1502590712,2136989777,-2031153343,371398938,-1907397429,342796391,609166045,-2007448660,-1096076344,-323570318,-2082980371,2129956379,-243553361,-1549960929,1502383415,-1394618779,694799815,78595689,-1439173023,-1416578800,685225786,-333502212,-1181308536,-380569313,772035354,-915266376,663709718,1443496021,-777017729,-883300731,-387828385,1907473488,-725483724,-972961871,-1255712537,383120918,1383877998,1722751914,-1156050682,1952527902,-560244497,1304305692,1173974542,-1313227247,-201476579,-298899493,-1828496581,-1724396350,1933643204,1531804925,1728655262,-955565449,-69843702,-461760848,268336768,1446130876,0,0,0,0,0,0,0,0,0,0], nums)
| 52.45122 | 1,044 | 0.681702 | from unittest import TestCase
class Solution:
@staticmethod
def get_next(nums, start, zero=True):
for idx in range(start, len(nums)):
if zero and nums[idx] == 0:
return idx
if not zero and nums[idx] != zero:
return idx
return len(nums)
def moveZeroes(self, nums):
z = self.get_next(nums, 0, zero=True)
n = self.get_next(nums, 0, zero=False)
while n < len(nums):
if n > z and nums[n] != 0:
nums[z], nums[n] = nums[n], nums[z]
z = self.get_next(nums, z, zero=True)
n = self.get_next(nums, n, zero=False)
continue
else:
n += 1
class TestSolution(TestCase):
sol = Solution()
def test_0(self):
nums = [0, 1, 2, 3, 4]
self.sol.moveZeroes(nums)
print("result: {}".format(nums))
self.assertEqual([1, 2, 3, 4, 0], nums)
def test_1(self):
nums = [0, 1, 0, 2, 0, 3, 0, 1]
self.sol.moveZeroes(nums)
print("result: {}".format(nums))
self.assertEqual([1, 2, 3, 1, 0, 0, 0, 0], nums)
def test_3(self):
nums = [0,1,0,3,12]
self.sol.moveZeroes(nums)
print("result: {}".format(nums))
self.assertEqual([1, 3, 12, 0, 0], nums)
def test_4(self):
nums = [1]
self.sol.moveZeroes(nums)
print("result: {}".format(nums))
self.assertEqual([1], nums)
def test_5(self):
nums = [1, -2, 0, 0, 3, 0, 4, 0]
self.sol.moveZeroes(nums)
print("result: {}".format(nums))
self.assertEqual([1, -2, 3, 4, 0, 0, 0, 0], nums)
def test_6(self):
nums = [-959151711,623836953,209446690,-1950418142,1339915067,-733626417,481171539,-2125997010,-1225423476,1462109565,147434687,-1800073781,-1431212205,-450443973,50097298,753533734,-747189404,-2070885638,0,-1484353894,-340296594,-2133744570,619639811,-1626162038,669689561,0,112220218,502447212,-787793179,0,-726846372,-1611013491,204107194,1605165582,-566891128,2082852116,0,532995238,-1502590712,0,2136989777,-2031153343,371398938,-1907397429,342796391,609166045,-2007448660,-1096076344,-323570318,0,-2082980371,2129956379,-243553361,-1549960929,1502383415,0,-1394618779,694799815,78595689,-1439173023,-1416578800,685225786,-333502212,-1181308536,-380569313,772035354,0,-915266376,663709718,1443496021,-777017729,-883300731,-387828385,1907473488,-725483724,-972961871,-1255712537,383120918,1383877998,1722751914,0,-1156050682,1952527902,-560244497,1304305692,1173974542,-1313227247,-201476579,-298899493,-1828496581,-1724396350,1933643204,1531804925,1728655262,-955565449,0,-69843702,-461760848,268336768,1446130876]
self.sol.moveZeroes(nums)
print("result: {}".format(nums))
self.assertEqual([-959151711,623836953,209446690,-1950418142,1339915067,-733626417,481171539,-2125997010,-1225423476,1462109565,147434687,-1800073781,-1431212205,-450443973,50097298,753533734,-747189404,-2070885638,-1484353894,-340296594,-2133744570,619639811,-1626162038,669689561,112220218,502447212,-787793179,-726846372,-1611013491,204107194,1605165582,-566891128,2082852116,532995238,-1502590712,2136989777,-2031153343,371398938,-1907397429,342796391,609166045,-2007448660,-1096076344,-323570318,-2082980371,2129956379,-243553361,-1549960929,1502383415,-1394618779,694799815,78595689,-1439173023,-1416578800,685225786,-333502212,-1181308536,-380569313,772035354,-915266376,663709718,1443496021,-777017729,-883300731,-387828385,1907473488,-725483724,-972961871,-1255712537,383120918,1383877998,1722751914,-1156050682,1952527902,-560244497,1304305692,1173974542,-1313227247,-201476579,-298899493,-1828496581,-1724396350,1933643204,1531804925,1728655262,-955565449,-69843702,-461760848,268336768,1446130876,0,0,0,0,0,0,0,0,0,0], nums)
| true | true |
f71699ccf4bde15c74f7288f21e09a3602fee877 | 4,755 | py | Python | events/yukicon2015/management/commands/setup_yukicon2015.py | jlaunonen/turska | fc6ec4e0ae50a823e931152ce8835098b96f5966 | [
"CC-BY-3.0"
] | null | null | null | events/yukicon2015/management/commands/setup_yukicon2015.py | jlaunonen/turska | fc6ec4e0ae50a823e931152ce8835098b96f5966 | [
"CC-BY-3.0"
] | null | null | null | events/yukicon2015/management/commands/setup_yukicon2015.py | jlaunonen/turska | fc6ec4e0ae50a823e931152ce8835098b96f5966 | [
"CC-BY-3.0"
] | null | null | null | # encoding: utf-8
from datetime import datetime, timedelta
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils.timezone import now
from dateutil.tz import tzlocal
from core.utils import slugify
class Setup(object):
def setup(self, test=False):
self.test = test
self.tz = tzlocal()
self.setup_core()
self.setup_tickets()
def setup_core(self):
from core.models import Venue, Event
self.venue, unused = Venue.objects.get_or_create(name='Espoon kulttuurikeskus', defaults=dict(
name_inessive='Espoon kulttuurikeskuksessa',
))
self.event, unused = Event.objects.get_or_create(slug='yukicon2015', defaults=dict(
name='Yukicon 2.0',
name_genitive='Yukicon 2.0 -tapahtuman',
name_illative='Yukicon 2.0 -tapahtumaan',
name_inessive='Yukicon 2.0 -tapahtumassa',
homepage_url='http://www.yukicon.fi',
organization_name='Yukitea ry',
organization_url='http://www.yukicon.fi',
start_time=datetime(2015, 1, 10, 10, 0, tzinfo=self.tz),
end_time=datetime(2015, 1, 11, 18, 0, tzinfo=self.tz),
venue=self.venue,
))
def setup_tickets(self):
from tickets.models import TicketsEventMeta, LimitGroup, Product
tickets_admin_group, = TicketsEventMeta.get_or_create_groups(self.event, ['admins'])
defaults = dict(
admin_group=tickets_admin_group,
due_days=14,
shipping_and_handling_cents=0,
reference_number_template="2015{:05d}",
contact_email='Yukicon <yukicon@yukicon.fi>',
plain_contact_email='yukicon@yukicon.fi',
ticket_free_text=u"Tämä on sähköinen lippusi Yukicon 2.0 -tapahtumaan. Sähköinen lippu vaihdetaan rannekkeeseen\n"
u"lipunvaihtopisteessä saapuessasi tapahtumaan. Voit tulostaa tämän lipun tai näyttää sen\n"
u"älypuhelimen tai tablettitietokoneen näytöltä. Mikäli kumpikaan näistä ei ole mahdollista, ota ylös\n"
u"kunkin viivakoodin alla oleva neljästä tai viidestä sanasta koostuva sanakoodi ja ilmoita se\n"
u"lipunvaihtopisteessä.\n\n"
u"Tervetuloa Yukiconiin!",
front_page_text=u"<h2>Tervetuloa ostamaan pääsylippuja Yukicon 2.0 -tapahtumaan!</h2>"
u"<p>Liput maksetaan suomalaisilla verkkopankkitunnuksilla heti tilauksen yhteydessä.</p>"
u"<p>Lue lisää tapahtumasta <a href='http://www.yukicon.fi'>Yukiconin kotisivuilta</a>.</p>",
)
if self.test:
t = now()
defaults.update(
ticket_sales_starts=t - timedelta(days=60),
ticket_sales_ends=t + timedelta(days=60),
)
else:
defaults.update(
ticket_sales_starts=datetime(2014, 11, 20, 18, 0, tzinfo=self.tz),
ticket_sales_ends=datetime(2015, 1, 11, 18, 0, tzinfo=self.tz),
)
meta, unused = TicketsEventMeta.objects.get_or_create(event=self.event, defaults=defaults)
def limit_group(description, limit):
limit_group, unused = LimitGroup.objects.get_or_create(
event=self.event,
description=description,
defaults=dict(limit=limit),
)
return limit_group
def ordering():
ordering.counter += 10
return ordering.counter
ordering.counter = 0
for product_info in [
dict(
name=u'Yukicon 2015 -pääsylippu',
description=u'Lippu kattaa koko viikonlopun. Maksettuasi sinulle lähetetään PDF-lippu antamaasi sähköpostiin, jota vastaan saat rannekkeen tapahtuman ovelta.',
limit_groups=[
limit_group('Pääsyliput', 1450),
],
price_cents=1700,
requires_shipping=False,
electronic_ticket=True,
available=True,
ordering=ordering(),
),
]:
name = product_info.pop('name')
limit_groups = product_info.pop('limit_groups')
product, unused = Product.objects.get_or_create(
event=self.event,
name=name,
defaults=product_info
)
if not product.limit_groups.exists():
product.limit_groups = limit_groups
product.save()
class Command(BaseCommand):
args = ''
help = 'Setup yukicon2015 specific stuff'
def handle(self, *args, **opts):
Setup().setup(test=settings.DEBUG)
| 38.04 | 175 | 0.606519 |
from datetime import datetime, timedelta
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils.timezone import now
from dateutil.tz import tzlocal
from core.utils import slugify
class Setup(object):
def setup(self, test=False):
self.test = test
self.tz = tzlocal()
self.setup_core()
self.setup_tickets()
def setup_core(self):
from core.models import Venue, Event
self.venue, unused = Venue.objects.get_or_create(name='Espoon kulttuurikeskus', defaults=dict(
name_inessive='Espoon kulttuurikeskuksessa',
))
self.event, unused = Event.objects.get_or_create(slug='yukicon2015', defaults=dict(
name='Yukicon 2.0',
name_genitive='Yukicon 2.0 -tapahtuman',
name_illative='Yukicon 2.0 -tapahtumaan',
name_inessive='Yukicon 2.0 -tapahtumassa',
homepage_url='http://www.yukicon.fi',
organization_name='Yukitea ry',
organization_url='http://www.yukicon.fi',
start_time=datetime(2015, 1, 10, 10, 0, tzinfo=self.tz),
end_time=datetime(2015, 1, 11, 18, 0, tzinfo=self.tz),
venue=self.venue,
))
def setup_tickets(self):
from tickets.models import TicketsEventMeta, LimitGroup, Product
tickets_admin_group, = TicketsEventMeta.get_or_create_groups(self.event, ['admins'])
defaults = dict(
admin_group=tickets_admin_group,
due_days=14,
shipping_and_handling_cents=0,
reference_number_template="2015{:05d}",
contact_email='Yukicon <yukicon@yukicon.fi>',
plain_contact_email='yukicon@yukicon.fi',
ticket_free_text=u"Tämä on sähköinen lippusi Yukicon 2.0 -tapahtumaan. Sähköinen lippu vaihdetaan rannekkeeseen\n"
u"lipunvaihtopisteessä saapuessasi tapahtumaan. Voit tulostaa tämän lipun tai näyttää sen\n"
u"älypuhelimen tai tablettitietokoneen näytöltä. Mikäli kumpikaan näistä ei ole mahdollista, ota ylös\n"
u"kunkin viivakoodin alla oleva neljästä tai viidestä sanasta koostuva sanakoodi ja ilmoita se\n"
u"lipunvaihtopisteessä.\n\n"
u"Tervetuloa Yukiconiin!",
front_page_text=u"<h2>Tervetuloa ostamaan pääsylippuja Yukicon 2.0 -tapahtumaan!</h2>"
u"<p>Liput maksetaan suomalaisilla verkkopankkitunnuksilla heti tilauksen yhteydessä.</p>"
u"<p>Lue lisää tapahtumasta <a href='http://www.yukicon.fi'>Yukiconin kotisivuilta</a>.</p>",
)
if self.test:
t = now()
defaults.update(
ticket_sales_starts=t - timedelta(days=60),
ticket_sales_ends=t + timedelta(days=60),
)
else:
defaults.update(
ticket_sales_starts=datetime(2014, 11, 20, 18, 0, tzinfo=self.tz),
ticket_sales_ends=datetime(2015, 1, 11, 18, 0, tzinfo=self.tz),
)
meta, unused = TicketsEventMeta.objects.get_or_create(event=self.event, defaults=defaults)
def limit_group(description, limit):
limit_group, unused = LimitGroup.objects.get_or_create(
event=self.event,
description=description,
defaults=dict(limit=limit),
)
return limit_group
def ordering():
ordering.counter += 10
return ordering.counter
ordering.counter = 0
for product_info in [
dict(
name=u'Yukicon 2015 -pääsylippu',
description=u'Lippu kattaa koko viikonlopun. Maksettuasi sinulle lähetetään PDF-lippu antamaasi sähköpostiin, jota vastaan saat rannekkeen tapahtuman ovelta.',
limit_groups=[
limit_group('Pääsyliput', 1450),
],
price_cents=1700,
requires_shipping=False,
electronic_ticket=True,
available=True,
ordering=ordering(),
),
]:
name = product_info.pop('name')
limit_groups = product_info.pop('limit_groups')
product, unused = Product.objects.get_or_create(
event=self.event,
name=name,
defaults=product_info
)
if not product.limit_groups.exists():
product.limit_groups = limit_groups
product.save()
class Command(BaseCommand):
args = ''
help = 'Setup yukicon2015 specific stuff'
def handle(self, *args, **opts):
Setup().setup(test=settings.DEBUG)
| true | true |
f7169a3697dd8cdb379fbd71762594e9c77e9d4a | 5,784 | py | Python | emerge.py | puiterwijk/dnf-plugins-emerge | fc5640a374fb9fbc5eb6c749e1f6f32617dd9532 | [
"MIT"
] | 2 | 2018-02-27T23:25:36.000Z | 2018-03-01T09:18:47.000Z | emerge.py | puiterwijk/dnf-plugins-emerge | fc5640a374fb9fbc5eb6c749e1f6f32617dd9532 | [
"MIT"
] | null | null | null | emerge.py | puiterwijk/dnf-plugins-emerge | fc5640a374fb9fbc5eb6c749e1f6f32617dd9532 | [
"MIT"
] | null | null | null | import dnf
import dnf.cli
from glob import glob
import logging
import threading
import tempfile
import subprocess
import shutil
import os
logger = logging.getLogger('dnf')
class ErrorThread(threading.Thread):
_my_exception = None
def run(self, *args):
try:
self._run(*self._args)
except Exception as ex:
self._my_exception = ex
class BuildThread(ErrorThread):
@property
def branch(self):
return 'master'
@property
def template_mock_config(self):
return '/etc/mock/fedora-rawhide-x86_64.cfg'
def _run(self, workdir, pkg):
pkgdir = os.path.join(workdir, pkg)
# Grab sources
logger.info('Grabbing sources')
subprocess.run(['fedpkg', 'clone', '--anonymous', '--branch', self.branch, 'rpms/%s' % pkg, pkgdir],
check=True)
# Generate mockconfig
logger.info('Generating mock config')
mock_config = os.path.join(workdir, '_mockconfig', 'emerge-%s.cfg' % pkg)
with open(self.template_mock_config, 'r') as template:
with open(mock_config, 'w') as out:
out.write("config_opts['basedir'] = '%s'\n" % (os.path.join(workdir, '_mockroots')))
for line in template.readlines():
if "config_opts['root']" in line:
out.write("config_opts['root'] = 'emerge-%s'\n" % pkg)
else:
out.write(line)
# Run mockbuild
logger.info('Building')
subprocess.run(['fedpkg', 'mockbuild', '--root', mock_config, '--no-clean-all'], check=True, cwd=pkgdir)
@dnf.plugin.register_command
class EmergeCommand(dnf.cli.Command):
aliases = ['emerge']
workdir = None
def configure(self):
self.cli.demands.available_repos = True
self.cli.demands.sack_activation = True
self.cli.demands.root_user = True
self.cli.demands.resolving = True
@staticmethod
def set_argparser(parser):
parser.add_argument('package', nargs='+', metavar='package',
help='Package to emerge')
parser.add_argument('--workdir')
parser.add_argument('--skip-build', action='store_true')
parser.add_argument('--skip-clean', action='store_true')
def run_transaction(self):
self._rmworkdir()
def _rmworkdir(self):
if self.workdir and not self.opts.workdir and not self.opts.skip_clean:
shutil.rmtree(self.workdir)
def run(self):
try:
self._run()
except:
self._rmworkdir()
raise
def _run(self):
q = self.base.sack.query()
pkgs = self.base.sack.query().available().filter(name=self.opts.package).latest().run()
if not pkgs:
raise dnf.exceptions.Error('no package matched')
to_build_install = {}
for pkg in pkgs:
if pkg.source_name in to_build_install:
to_build_install[pkg.source_name].add(pkg.name)
else:
to_build_install[pkg.source_name] = set([pkg.name])
logger.info('Building/installing: %s' % to_build_install)
if self.opts.workdir:
self.workdir = self.opts.workdir
else:
self.workdir = tempfile.TemporaryDirectory(prefix='dnf-emerge-').name
logger.debug('Workdir: %s', self.workdir)
self._build(self.workdir, to_build_install)
pkgs = self._find_packages(self.workdir, to_build_install)
err_pkgs = []
for pkg in self.base.add_remote_rpms(pkgs):
try:
self.base.package_install(pkg)
except dnf.exceptions.MarkingError:
logger.info('Unable to install %s' % self.base.output.term.bold(pkg.location))
err_pkgs.append(pkg)
if len(err_pkgs) != 0 and strict:
raise dnf.exceptions.PackagesNotAvailableError(
'Unable to find a match', packages=err_pkgs)
@staticmethod
def _is_wanted_file(fname, haystack):
for needle in haystack:
if fname.endswith('.src.rpm'):
continue
if not fname.startswith(needle + '-'):
continue
rest = fname[len(needle)+1:].split('-')
if len(rest) > 2:
continue
if not rest[0][0].isdigit():
continue
return True
return False
def _find_packages(self, workdir, to_build_install):
to_install = []
for source, binaries in to_build_install.items():
sourcedir = os.path.join(workdir, source, 'results_%s' % source, '*', '*', '*.rpm')
for fpath in glob(sourcedir):
fname = os.path.basename(fpath)
if self._is_wanted_file(fname, binaries):
to_install.append(fpath)
logger.info('Marking for installation: %s', to_install)
return to_install
def _build(self, workdir, to_build_install):
if self.opts.skip_build:
logger.error('Skipping build per request')
return
os.makedirs(os.path.join(workdir, '_mockconfig'))
os.makedirs(os.path.join(workdir, '_mockroots'))
buildthreads = []
for pkg in to_build_install.keys():
bthread = BuildThread(name='emerge-build-%s' % pkg, args=(workdir, pkg))
buildthreads.append(bthread)
bthread.start()
logger.info('All builds started, waiting for them to finish...')
for bthread in buildthreads:
bthread.join()
if bthread._my_exception:
raise bthread._my_exception
logger.info('All builds finished') | 32.494382 | 112 | 0.584198 | import dnf
import dnf.cli
from glob import glob
import logging
import threading
import tempfile
import subprocess
import shutil
import os
logger = logging.getLogger('dnf')
class ErrorThread(threading.Thread):
_my_exception = None
def run(self, *args):
try:
self._run(*self._args)
except Exception as ex:
self._my_exception = ex
class BuildThread(ErrorThread):
@property
def branch(self):
return 'master'
@property
def template_mock_config(self):
return '/etc/mock/fedora-rawhide-x86_64.cfg'
def _run(self, workdir, pkg):
pkgdir = os.path.join(workdir, pkg)
logger.info('Grabbing sources')
subprocess.run(['fedpkg', 'clone', '--anonymous', '--branch', self.branch, 'rpms/%s' % pkg, pkgdir],
check=True)
logger.info('Generating mock config')
mock_config = os.path.join(workdir, '_mockconfig', 'emerge-%s.cfg' % pkg)
with open(self.template_mock_config, 'r') as template:
with open(mock_config, 'w') as out:
out.write("config_opts['basedir'] = '%s'\n" % (os.path.join(workdir, '_mockroots')))
for line in template.readlines():
if "config_opts['root']" in line:
out.write("config_opts['root'] = 'emerge-%s'\n" % pkg)
else:
out.write(line)
logger.info('Building')
subprocess.run(['fedpkg', 'mockbuild', '--root', mock_config, '--no-clean-all'], check=True, cwd=pkgdir)
@dnf.plugin.register_command
class EmergeCommand(dnf.cli.Command):
aliases = ['emerge']
workdir = None
def configure(self):
self.cli.demands.available_repos = True
self.cli.demands.sack_activation = True
self.cli.demands.root_user = True
self.cli.demands.resolving = True
@staticmethod
def set_argparser(parser):
parser.add_argument('package', nargs='+', metavar='package',
help='Package to emerge')
parser.add_argument('--workdir')
parser.add_argument('--skip-build', action='store_true')
parser.add_argument('--skip-clean', action='store_true')
def run_transaction(self):
self._rmworkdir()
def _rmworkdir(self):
if self.workdir and not self.opts.workdir and not self.opts.skip_clean:
shutil.rmtree(self.workdir)
def run(self):
try:
self._run()
except:
self._rmworkdir()
raise
def _run(self):
q = self.base.sack.query()
pkgs = self.base.sack.query().available().filter(name=self.opts.package).latest().run()
if not pkgs:
raise dnf.exceptions.Error('no package matched')
to_build_install = {}
for pkg in pkgs:
if pkg.source_name in to_build_install:
to_build_install[pkg.source_name].add(pkg.name)
else:
to_build_install[pkg.source_name] = set([pkg.name])
logger.info('Building/installing: %s' % to_build_install)
if self.opts.workdir:
self.workdir = self.opts.workdir
else:
self.workdir = tempfile.TemporaryDirectory(prefix='dnf-emerge-').name
logger.debug('Workdir: %s', self.workdir)
self._build(self.workdir, to_build_install)
pkgs = self._find_packages(self.workdir, to_build_install)
err_pkgs = []
for pkg in self.base.add_remote_rpms(pkgs):
try:
self.base.package_install(pkg)
except dnf.exceptions.MarkingError:
logger.info('Unable to install %s' % self.base.output.term.bold(pkg.location))
err_pkgs.append(pkg)
if len(err_pkgs) != 0 and strict:
raise dnf.exceptions.PackagesNotAvailableError(
'Unable to find a match', packages=err_pkgs)
@staticmethod
def _is_wanted_file(fname, haystack):
for needle in haystack:
if fname.endswith('.src.rpm'):
continue
if not fname.startswith(needle + '-'):
continue
rest = fname[len(needle)+1:].split('-')
if len(rest) > 2:
continue
if not rest[0][0].isdigit():
continue
return True
return False
def _find_packages(self, workdir, to_build_install):
to_install = []
for source, binaries in to_build_install.items():
sourcedir = os.path.join(workdir, source, 'results_%s' % source, '*', '*', '*.rpm')
for fpath in glob(sourcedir):
fname = os.path.basename(fpath)
if self._is_wanted_file(fname, binaries):
to_install.append(fpath)
logger.info('Marking for installation: %s', to_install)
return to_install
def _build(self, workdir, to_build_install):
if self.opts.skip_build:
logger.error('Skipping build per request')
return
os.makedirs(os.path.join(workdir, '_mockconfig'))
os.makedirs(os.path.join(workdir, '_mockroots'))
buildthreads = []
for pkg in to_build_install.keys():
bthread = BuildThread(name='emerge-build-%s' % pkg, args=(workdir, pkg))
buildthreads.append(bthread)
bthread.start()
logger.info('All builds started, waiting for them to finish...')
for bthread in buildthreads:
bthread.join()
if bthread._my_exception:
raise bthread._my_exception
logger.info('All builds finished') | true | true |
f7169acccf677a901455907c655d4e12841b5f55 | 11,443 | py | Python | tf_agents/experimental/examples/sac/haarnoja18/sac_train_eval.py | cmarlin/agents | 1729e06f42237b34dab8bd9d8c01980c2d2b391c | [
"Apache-2.0"
] | 1 | 2021-04-19T02:28:24.000Z | 2021-04-19T02:28:24.000Z | tf_agents/experimental/examples/sac/haarnoja18/sac_train_eval.py | cmarlin/agents | 1729e06f42237b34dab8bd9d8c01980c2d2b391c | [
"Apache-2.0"
] | null | null | null | tf_agents/experimental/examples/sac/haarnoja18/sac_train_eval.py | cmarlin/agents | 1729e06f42237b34dab8bd9d8c01980c2d2b391c | [
"Apache-2.0"
] | null | null | null | # coding=utf-8
# Copyright 2020 The TF-Agents 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
#
# https://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.
# Lint as: python3
r"""Train and Eval SAC.
All hyperparameters come from the SAC paper
https://arxiv.org/pdf/1812.05905.pdf
"""
import functools
import os
from absl import app
from absl import flags
from absl import logging
import gin
import reverb
import tensorflow as tf
from tf_agents.agents.sac import sac_agent
from tf_agents.agents.sac import tanh_normal_projection_network
from tf_agents.environments import suite_mujoco
from tf_agents.keras_layers import inner_reshape
from tf_agents.metrics import py_metrics
from tf_agents.networks import nest_map
from tf_agents.networks import sequential
from tf_agents.policies import greedy_policy
from tf_agents.policies import py_tf_eager_policy
from tf_agents.policies import random_py_policy
from tf_agents.replay_buffers import reverb_replay_buffer
from tf_agents.replay_buffers import reverb_utils
from tf_agents.train import actor
from tf_agents.train import learner
from tf_agents.train import triggers
from tf_agents.train.utils import spec_utils
from tf_agents.train.utils import train_utils
FLAGS = flags.FLAGS
flags.DEFINE_string('root_dir', os.getenv('TEST_UNDECLARED_OUTPUTS_DIR'),
'Root directory for writing logs/summaries/checkpoints.')
flags.DEFINE_integer(
'reverb_port', None,
'Port for reverb server, if None, use a randomly chosen unused port.')
flags.DEFINE_integer('num_iterations', 3000000,
'Total number train/eval iterations to perform.')
flags.DEFINE_integer(
'eval_interval', 10000,
'Number of train steps between evaluations. Set to 0 to skip.')
flags.DEFINE_multi_string('gin_file', None, 'Paths to the gin-config files.')
flags.DEFINE_multi_string('gin_bindings', None, 'Gin binding parameters.')
dense = functools.partial(
tf.keras.layers.Dense,
activation=tf.keras.activations.relu,
kernel_initializer='glorot_uniform')
def create_fc_network(layer_units):
return sequential.Sequential([dense(num_units) for num_units in layer_units])
def create_identity_layer():
return tf.keras.layers.Lambda(lambda x: x)
def create_sequential_critic_network(obs_fc_layer_units,
action_fc_layer_units,
joint_fc_layer_units):
"""Create a sequential critic network."""
# Split the inputs into observations and actions.
def split_inputs(inputs):
return {'observation': inputs[0], 'action': inputs[1]}
# Create an observation network.
obs_network = (create_fc_network(obs_fc_layer_units) if obs_fc_layer_units
else create_identity_layer())
# Create an action network.
action_network = (create_fc_network(action_fc_layer_units)
if action_fc_layer_units else create_identity_layer())
# Create a joint network.
joint_network = (create_fc_network(joint_fc_layer_units)
if joint_fc_layer_units else create_identity_layer())
# Final layer.
value_layer = tf.keras.layers.Dense(1, kernel_initializer='glorot_uniform')
return sequential.Sequential([
tf.keras.layers.Lambda(split_inputs),
nest_map.NestMap({
'observation': obs_network,
'action': action_network
}),
nest_map.NestFlatten(),
tf.keras.layers.Concatenate(),
joint_network,
value_layer,
inner_reshape.InnerReshape(current_shape=[1], new_shape=[])
], name='sequential_critic')
class _TanhNormalProjectionNetworkWrapper(
tanh_normal_projection_network.TanhNormalProjectionNetwork):
"""Wrapper to pass predefined `outer_rank` to underlying projection net."""
def __init__(self, sample_spec, predefined_outer_rank=1):
super(_TanhNormalProjectionNetworkWrapper, self).__init__(sample_spec)
self.predefined_outer_rank = predefined_outer_rank
def call(self, inputs, network_state=(), **kwargs):
kwargs['outer_rank'] = self.predefined_outer_rank
if 'step_type' in kwargs:
del kwargs['step_type']
return super(_TanhNormalProjectionNetworkWrapper,
self).call(inputs, **kwargs)
def create_sequential_actor_network(actor_fc_layers, action_tensor_spec):
"""Create a sequential actor network."""
def tile_as_nest(non_nested_output):
return tf.nest.map_structure(lambda _: non_nested_output,
action_tensor_spec)
return sequential.Sequential(
[dense(num_units) for num_units in actor_fc_layers] +
[tf.keras.layers.Lambda(tile_as_nest)] + [
nest_map.NestMap(
tf.nest.map_structure(_TanhNormalProjectionNetworkWrapper,
action_tensor_spec))
])
@gin.configurable
def train_eval(
root_dir,
env_name='HalfCheetah-v2',
# Training params
initial_collect_steps=10000,
num_iterations=3200000,
actor_fc_layers=(256, 256),
critic_obs_fc_layers=None,
critic_action_fc_layers=None,
critic_joint_fc_layers=(256, 256),
# Agent params
batch_size=256,
actor_learning_rate=3e-4,
critic_learning_rate=3e-4,
alpha_learning_rate=3e-4,
gamma=0.99,
target_update_tau=0.005,
target_update_period=1,
reward_scale_factor=0.1,
# Replay params
reverb_port=None,
replay_capacity=1000000,
# Others
policy_save_interval=10000,
replay_buffer_save_interval=100000,
eval_interval=10000,
eval_episodes=30,
debug_summaries=False,
summarize_grads_and_vars=False):
"""Trains and evaluates SAC."""
logging.info('Training SAC on: %s', env_name)
collect_env = suite_mujoco.load(env_name)
eval_env = suite_mujoco.load(env_name)
_, action_tensor_spec, time_step_tensor_spec = (
spec_utils.get_tensor_specs(collect_env))
train_step = train_utils.create_train_step()
actor_net = create_sequential_actor_network(
actor_fc_layers=actor_fc_layers, action_tensor_spec=action_tensor_spec)
critic_net = create_sequential_critic_network(
obs_fc_layer_units=critic_obs_fc_layers,
action_fc_layer_units=critic_action_fc_layers,
joint_fc_layer_units=critic_joint_fc_layers)
agent = sac_agent.SacAgent(
time_step_tensor_spec,
action_tensor_spec,
actor_network=actor_net,
critic_network=critic_net,
actor_optimizer=tf.keras.optimizers.Adam(
learning_rate=actor_learning_rate),
critic_optimizer=tf.keras.optimizers.Adam(
learning_rate=critic_learning_rate),
alpha_optimizer=tf.keras.optimizers.Adam(
learning_rate=alpha_learning_rate),
target_update_tau=target_update_tau,
target_update_period=target_update_period,
td_errors_loss_fn=tf.math.squared_difference,
gamma=gamma,
reward_scale_factor=reward_scale_factor,
gradient_clipping=None,
debug_summaries=debug_summaries,
summarize_grads_and_vars=summarize_grads_and_vars,
train_step_counter=train_step)
agent.initialize()
table_name = 'uniform_table'
table = reverb.Table(
table_name,
max_size=replay_capacity,
sampler=reverb.selectors.Uniform(),
remover=reverb.selectors.Fifo(),
rate_limiter=reverb.rate_limiters.MinSize(1))
reverb_checkpoint_dir = os.path.join(root_dir, learner.TRAIN_DIR,
learner.REPLAY_BUFFER_CHECKPOINT_DIR)
reverb_checkpointer = reverb.platform.checkpointers_lib.DefaultCheckpointer(
path=reverb_checkpoint_dir)
reverb_server = reverb.Server([table],
port=reverb_port,
checkpointer=reverb_checkpointer)
reverb_replay = reverb_replay_buffer.ReverbReplayBuffer(
agent.collect_data_spec,
sequence_length=2,
table_name=table_name,
local_server=reverb_server)
rb_observer = reverb_utils.ReverbAddTrajectoryObserver(
reverb_replay.py_client,
table_name,
sequence_length=2,
stride_length=1)
dataset = reverb_replay.as_dataset(
sample_batch_size=batch_size, num_steps=2).prefetch(50)
experience_dataset_fn = lambda: dataset
saved_model_dir = os.path.join(root_dir, learner.POLICY_SAVED_MODEL_DIR)
env_step_metric = py_metrics.EnvironmentSteps()
learning_triggers = [
triggers.PolicySavedModelTrigger(
saved_model_dir,
agent,
train_step,
interval=policy_save_interval,
metadata_metrics={triggers.ENV_STEP_METADATA_KEY: env_step_metric}),
triggers.ReverbCheckpointTrigger(
train_step,
interval=replay_buffer_save_interval,
reverb_client=reverb_replay.py_client),
# TODO(b/165023684): Add SIGTERM handler to checkpoint before preemption.
triggers.StepPerSecondLogTrigger(train_step, interval=1000),
]
agent_learner = learner.Learner(
root_dir,
train_step,
agent,
experience_dataset_fn,
triggers=learning_triggers)
random_policy = random_py_policy.RandomPyPolicy(
collect_env.time_step_spec(), collect_env.action_spec())
initial_collect_actor = actor.Actor(
collect_env,
random_policy,
train_step,
steps_per_run=initial_collect_steps,
observers=[rb_observer])
logging.info('Doing initial collect.')
initial_collect_actor.run()
tf_collect_policy = agent.collect_policy
collect_policy = py_tf_eager_policy.PyTFEagerPolicy(
tf_collect_policy, use_tf_function=True)
collect_actor = actor.Actor(
collect_env,
collect_policy,
train_step,
steps_per_run=1,
metrics=actor.collect_metrics(10),
summary_dir=os.path.join(root_dir, learner.TRAIN_DIR),
observers=[rb_observer, env_step_metric])
tf_greedy_policy = greedy_policy.GreedyPolicy(agent.policy)
eval_greedy_policy = py_tf_eager_policy.PyTFEagerPolicy(
tf_greedy_policy, use_tf_function=True)
eval_actor = actor.Actor(
eval_env,
eval_greedy_policy,
train_step,
episodes_per_run=eval_episodes,
metrics=actor.eval_metrics(eval_episodes),
summary_dir=os.path.join(root_dir, 'eval'),
)
if eval_interval:
logging.info('Evaluating.')
eval_actor.run_and_log()
logging.info('Training.')
for _ in range(num_iterations):
collect_actor.run()
agent_learner.run(iterations=1)
if eval_interval and agent_learner.train_step_numpy % eval_interval == 0:
logging.info('Evaluating.')
eval_actor.run_and_log()
rb_observer.close()
reverb_server.stop()
def main(_):
logging.set_verbosity(logging.INFO)
tf.compat.v1.enable_v2_behavior()
gin.parse_config_files_and_bindings(FLAGS.gin_file, FLAGS.gin_bindings)
train_eval(
FLAGS.root_dir,
num_iterations=FLAGS.num_iterations,
reverb_port=FLAGS.reverb_port,
eval_interval=FLAGS.eval_interval)
if __name__ == '__main__':
flags.mark_flag_as_required('root_dir')
app.run(main)
| 33.361516 | 79 | 0.733811 |
import functools
import os
from absl import app
from absl import flags
from absl import logging
import gin
import reverb
import tensorflow as tf
from tf_agents.agents.sac import sac_agent
from tf_agents.agents.sac import tanh_normal_projection_network
from tf_agents.environments import suite_mujoco
from tf_agents.keras_layers import inner_reshape
from tf_agents.metrics import py_metrics
from tf_agents.networks import nest_map
from tf_agents.networks import sequential
from tf_agents.policies import greedy_policy
from tf_agents.policies import py_tf_eager_policy
from tf_agents.policies import random_py_policy
from tf_agents.replay_buffers import reverb_replay_buffer
from tf_agents.replay_buffers import reverb_utils
from tf_agents.train import actor
from tf_agents.train import learner
from tf_agents.train import triggers
from tf_agents.train.utils import spec_utils
from tf_agents.train.utils import train_utils
FLAGS = flags.FLAGS
flags.DEFINE_string('root_dir', os.getenv('TEST_UNDECLARED_OUTPUTS_DIR'),
'Root directory for writing logs/summaries/checkpoints.')
flags.DEFINE_integer(
'reverb_port', None,
'Port for reverb server, if None, use a randomly chosen unused port.')
flags.DEFINE_integer('num_iterations', 3000000,
'Total number train/eval iterations to perform.')
flags.DEFINE_integer(
'eval_interval', 10000,
'Number of train steps between evaluations. Set to 0 to skip.')
flags.DEFINE_multi_string('gin_file', None, 'Paths to the gin-config files.')
flags.DEFINE_multi_string('gin_bindings', None, 'Gin binding parameters.')
dense = functools.partial(
tf.keras.layers.Dense,
activation=tf.keras.activations.relu,
kernel_initializer='glorot_uniform')
def create_fc_network(layer_units):
return sequential.Sequential([dense(num_units) for num_units in layer_units])
def create_identity_layer():
return tf.keras.layers.Lambda(lambda x: x)
def create_sequential_critic_network(obs_fc_layer_units,
action_fc_layer_units,
joint_fc_layer_units):
def split_inputs(inputs):
return {'observation': inputs[0], 'action': inputs[1]}
obs_network = (create_fc_network(obs_fc_layer_units) if obs_fc_layer_units
else create_identity_layer())
action_network = (create_fc_network(action_fc_layer_units)
if action_fc_layer_units else create_identity_layer())
joint_network = (create_fc_network(joint_fc_layer_units)
if joint_fc_layer_units else create_identity_layer())
value_layer = tf.keras.layers.Dense(1, kernel_initializer='glorot_uniform')
return sequential.Sequential([
tf.keras.layers.Lambda(split_inputs),
nest_map.NestMap({
'observation': obs_network,
'action': action_network
}),
nest_map.NestFlatten(),
tf.keras.layers.Concatenate(),
joint_network,
value_layer,
inner_reshape.InnerReshape(current_shape=[1], new_shape=[])
], name='sequential_critic')
class _TanhNormalProjectionNetworkWrapper(
tanh_normal_projection_network.TanhNormalProjectionNetwork):
def __init__(self, sample_spec, predefined_outer_rank=1):
super(_TanhNormalProjectionNetworkWrapper, self).__init__(sample_spec)
self.predefined_outer_rank = predefined_outer_rank
def call(self, inputs, network_state=(), **kwargs):
kwargs['outer_rank'] = self.predefined_outer_rank
if 'step_type' in kwargs:
del kwargs['step_type']
return super(_TanhNormalProjectionNetworkWrapper,
self).call(inputs, **kwargs)
def create_sequential_actor_network(actor_fc_layers, action_tensor_spec):
def tile_as_nest(non_nested_output):
return tf.nest.map_structure(lambda _: non_nested_output,
action_tensor_spec)
return sequential.Sequential(
[dense(num_units) for num_units in actor_fc_layers] +
[tf.keras.layers.Lambda(tile_as_nest)] + [
nest_map.NestMap(
tf.nest.map_structure(_TanhNormalProjectionNetworkWrapper,
action_tensor_spec))
])
@gin.configurable
def train_eval(
root_dir,
env_name='HalfCheetah-v2',
initial_collect_steps=10000,
num_iterations=3200000,
actor_fc_layers=(256, 256),
critic_obs_fc_layers=None,
critic_action_fc_layers=None,
critic_joint_fc_layers=(256, 256),
batch_size=256,
actor_learning_rate=3e-4,
critic_learning_rate=3e-4,
alpha_learning_rate=3e-4,
gamma=0.99,
target_update_tau=0.005,
target_update_period=1,
reward_scale_factor=0.1,
reverb_port=None,
replay_capacity=1000000,
policy_save_interval=10000,
replay_buffer_save_interval=100000,
eval_interval=10000,
eval_episodes=30,
debug_summaries=False,
summarize_grads_and_vars=False):
logging.info('Training SAC on: %s', env_name)
collect_env = suite_mujoco.load(env_name)
eval_env = suite_mujoco.load(env_name)
_, action_tensor_spec, time_step_tensor_spec = (
spec_utils.get_tensor_specs(collect_env))
train_step = train_utils.create_train_step()
actor_net = create_sequential_actor_network(
actor_fc_layers=actor_fc_layers, action_tensor_spec=action_tensor_spec)
critic_net = create_sequential_critic_network(
obs_fc_layer_units=critic_obs_fc_layers,
action_fc_layer_units=critic_action_fc_layers,
joint_fc_layer_units=critic_joint_fc_layers)
agent = sac_agent.SacAgent(
time_step_tensor_spec,
action_tensor_spec,
actor_network=actor_net,
critic_network=critic_net,
actor_optimizer=tf.keras.optimizers.Adam(
learning_rate=actor_learning_rate),
critic_optimizer=tf.keras.optimizers.Adam(
learning_rate=critic_learning_rate),
alpha_optimizer=tf.keras.optimizers.Adam(
learning_rate=alpha_learning_rate),
target_update_tau=target_update_tau,
target_update_period=target_update_period,
td_errors_loss_fn=tf.math.squared_difference,
gamma=gamma,
reward_scale_factor=reward_scale_factor,
gradient_clipping=None,
debug_summaries=debug_summaries,
summarize_grads_and_vars=summarize_grads_and_vars,
train_step_counter=train_step)
agent.initialize()
table_name = 'uniform_table'
table = reverb.Table(
table_name,
max_size=replay_capacity,
sampler=reverb.selectors.Uniform(),
remover=reverb.selectors.Fifo(),
rate_limiter=reverb.rate_limiters.MinSize(1))
reverb_checkpoint_dir = os.path.join(root_dir, learner.TRAIN_DIR,
learner.REPLAY_BUFFER_CHECKPOINT_DIR)
reverb_checkpointer = reverb.platform.checkpointers_lib.DefaultCheckpointer(
path=reverb_checkpoint_dir)
reverb_server = reverb.Server([table],
port=reverb_port,
checkpointer=reverb_checkpointer)
reverb_replay = reverb_replay_buffer.ReverbReplayBuffer(
agent.collect_data_spec,
sequence_length=2,
table_name=table_name,
local_server=reverb_server)
rb_observer = reverb_utils.ReverbAddTrajectoryObserver(
reverb_replay.py_client,
table_name,
sequence_length=2,
stride_length=1)
dataset = reverb_replay.as_dataset(
sample_batch_size=batch_size, num_steps=2).prefetch(50)
experience_dataset_fn = lambda: dataset
saved_model_dir = os.path.join(root_dir, learner.POLICY_SAVED_MODEL_DIR)
env_step_metric = py_metrics.EnvironmentSteps()
learning_triggers = [
triggers.PolicySavedModelTrigger(
saved_model_dir,
agent,
train_step,
interval=policy_save_interval,
metadata_metrics={triggers.ENV_STEP_METADATA_KEY: env_step_metric}),
triggers.ReverbCheckpointTrigger(
train_step,
interval=replay_buffer_save_interval,
reverb_client=reverb_replay.py_client),
triggers.StepPerSecondLogTrigger(train_step, interval=1000),
]
agent_learner = learner.Learner(
root_dir,
train_step,
agent,
experience_dataset_fn,
triggers=learning_triggers)
random_policy = random_py_policy.RandomPyPolicy(
collect_env.time_step_spec(), collect_env.action_spec())
initial_collect_actor = actor.Actor(
collect_env,
random_policy,
train_step,
steps_per_run=initial_collect_steps,
observers=[rb_observer])
logging.info('Doing initial collect.')
initial_collect_actor.run()
tf_collect_policy = agent.collect_policy
collect_policy = py_tf_eager_policy.PyTFEagerPolicy(
tf_collect_policy, use_tf_function=True)
collect_actor = actor.Actor(
collect_env,
collect_policy,
train_step,
steps_per_run=1,
metrics=actor.collect_metrics(10),
summary_dir=os.path.join(root_dir, learner.TRAIN_DIR),
observers=[rb_observer, env_step_metric])
tf_greedy_policy = greedy_policy.GreedyPolicy(agent.policy)
eval_greedy_policy = py_tf_eager_policy.PyTFEagerPolicy(
tf_greedy_policy, use_tf_function=True)
eval_actor = actor.Actor(
eval_env,
eval_greedy_policy,
train_step,
episodes_per_run=eval_episodes,
metrics=actor.eval_metrics(eval_episodes),
summary_dir=os.path.join(root_dir, 'eval'),
)
if eval_interval:
logging.info('Evaluating.')
eval_actor.run_and_log()
logging.info('Training.')
for _ in range(num_iterations):
collect_actor.run()
agent_learner.run(iterations=1)
if eval_interval and agent_learner.train_step_numpy % eval_interval == 0:
logging.info('Evaluating.')
eval_actor.run_and_log()
rb_observer.close()
reverb_server.stop()
def main(_):
logging.set_verbosity(logging.INFO)
tf.compat.v1.enable_v2_behavior()
gin.parse_config_files_and_bindings(FLAGS.gin_file, FLAGS.gin_bindings)
train_eval(
FLAGS.root_dir,
num_iterations=FLAGS.num_iterations,
reverb_port=FLAGS.reverb_port,
eval_interval=FLAGS.eval_interval)
if __name__ == '__main__':
flags.mark_flag_as_required('root_dir')
app.run(main)
| true | true |
f7169b0b69005cd6f9c943ebfaa084ff31332512 | 1,045 | py | Python | parameter_tutorial_py/setup.py | JaehyunShim/ros2_tutorial_py | ed94477341ae6053dbd126fe5092b5cbf44ffa89 | [
"Apache-2.0"
] | null | null | null | parameter_tutorial_py/setup.py | JaehyunShim/ros2_tutorial_py | ed94477341ae6053dbd126fe5092b5cbf44ffa89 | [
"Apache-2.0"
] | null | null | null | parameter_tutorial_py/setup.py | JaehyunShim/ros2_tutorial_py | ed94477341ae6053dbd126fe5092b5cbf44ffa89 | [
"Apache-2.0"
] | null | null | null | from glob import glob
import os
from setuptools import setup
package_name = 'parameter_tutorial_py'
setup(
name=package_name,
version='0.0.0',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
(os.path.join('share', package_name), glob('launch/*.launch.py')),
# (os.path.join('share', package_name), glob('param/*')),
('share/' + package_name, ['param/param.yaml']),
# ('share/' + package_name, ['param']),
],
install_requires=['setuptools'],
zip_safe=True,
maintainer='Jaehyun Shim',
maintainer_email='jhshim@robotis.com',
description='ROS 2 packages for parameter_tutorial_py',
license='Apache 2.0',
author='Jaehyun Shim',
author_email='jhshim@robotis.com',
tests_require=['pytest'],
entry_points={
'console_scripts': [
'parameter = parameter_tutorial_py.parameter:main'
],
},
)
| 29.027778 | 74 | 0.622967 | from glob import glob
import os
from setuptools import setup
package_name = 'parameter_tutorial_py'
setup(
name=package_name,
version='0.0.0',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
(os.path.join('share', package_name), glob('launch/*.launch.py')),
('share/' + package_name, ['param/param.yaml']),
],
install_requires=['setuptools'],
zip_safe=True,
maintainer='Jaehyun Shim',
maintainer_email='jhshim@robotis.com',
description='ROS 2 packages for parameter_tutorial_py',
license='Apache 2.0',
author='Jaehyun Shim',
author_email='jhshim@robotis.com',
tests_require=['pytest'],
entry_points={
'console_scripts': [
'parameter = parameter_tutorial_py.parameter:main'
],
},
)
| true | true |
f7169bb6a32f8e404c1c0086cbe414701694aecd | 2,198 | py | Python | ros/src/twist_controller/twist_controller.py | ysavchenko/carnd-capstone | 682eb7ed52153c667f63e7c7eb46f13584469888 | [
"MIT"
] | null | null | null | ros/src/twist_controller/twist_controller.py | ysavchenko/carnd-capstone | 682eb7ed52153c667f63e7c7eb46f13584469888 | [
"MIT"
] | null | null | null | ros/src/twist_controller/twist_controller.py | ysavchenko/carnd-capstone | 682eb7ed52153c667f63e7c7eb46f13584469888 | [
"MIT"
] | null | null | null | from yaw_controller import YawController
from pid import PID
from lowpass import LowPassFilter
import rospy
GAS_DENSITY = 2.858
ONE_MPH = 0.44704
class Controller(object):
def __init__(self, vehicle_mass, wheel_radius, decel_limit):
self.yaw_controller = None
self.throttle_controller = None
self.velocity_filter = LowPassFilter(.5, .02)
self.vehicle_mass = vehicle_mass
self.wheel_radius = wheel_radius
self.decel_limit = decel_limit
self.last_time = rospy.get_time()
def init_yaw(self, wheel_base, steer_ratio, min_speed, max_lat_accel, max_steer_angle):
self.yaw_controller = YawController(
wheel_base,
steer_ratio,
min_speed,
max_lat_accel,
max_steer_angle
)
def init_throttle(self, kp, ki, kd, min_throttle, max_throttle):
self.throttle_controller = PID(kp, ki, kd, min_throttle, max_throttle)
def control(self, target_linear_velocity, target_angular_velocity, current_linear_velocity):
if self.yaw_controller is None or self.throttle_controller is None:
return 0., 0., 0.
current_linear_velocity = self.velocity_filter.filt(current_linear_velocity)
steering = self.yaw_controller.get_steering(target_linear_velocity, target_angular_velocity, current_linear_velocity)
delta_velocity = target_linear_velocity - current_linear_velocity
current_time = rospy.get_time()
delta_time = current_time - self.last_time
self.last_time = current_time
throttle = self.throttle_controller.step(delta_velocity, delta_time)
brake = 0.
if target_linear_velocity == 0. and current_linear_velocity < 0.1:
# Full stop
throttle = 0.
brake = 400
elif throttle < .1 and delta_velocity < 0:
# Slow deceleration
throttle = 0.
deceleration = max(delta_velocity, self.decel_limit)
brake = abs(deceleration) * self.vehicle_mass * self.wheel_radius
return throttle, brake, steering
def reset(self):
self.throttle_controller.reset() | 33.815385 | 125 | 0.674249 | from yaw_controller import YawController
from pid import PID
from lowpass import LowPassFilter
import rospy
GAS_DENSITY = 2.858
ONE_MPH = 0.44704
class Controller(object):
def __init__(self, vehicle_mass, wheel_radius, decel_limit):
self.yaw_controller = None
self.throttle_controller = None
self.velocity_filter = LowPassFilter(.5, .02)
self.vehicle_mass = vehicle_mass
self.wheel_radius = wheel_radius
self.decel_limit = decel_limit
self.last_time = rospy.get_time()
def init_yaw(self, wheel_base, steer_ratio, min_speed, max_lat_accel, max_steer_angle):
self.yaw_controller = YawController(
wheel_base,
steer_ratio,
min_speed,
max_lat_accel,
max_steer_angle
)
def init_throttle(self, kp, ki, kd, min_throttle, max_throttle):
self.throttle_controller = PID(kp, ki, kd, min_throttle, max_throttle)
def control(self, target_linear_velocity, target_angular_velocity, current_linear_velocity):
if self.yaw_controller is None or self.throttle_controller is None:
return 0., 0., 0.
current_linear_velocity = self.velocity_filter.filt(current_linear_velocity)
steering = self.yaw_controller.get_steering(target_linear_velocity, target_angular_velocity, current_linear_velocity)
delta_velocity = target_linear_velocity - current_linear_velocity
current_time = rospy.get_time()
delta_time = current_time - self.last_time
self.last_time = current_time
throttle = self.throttle_controller.step(delta_velocity, delta_time)
brake = 0.
if target_linear_velocity == 0. and current_linear_velocity < 0.1:
throttle = 0.
brake = 400
elif throttle < .1 and delta_velocity < 0:
throttle = 0.
deceleration = max(delta_velocity, self.decel_limit)
brake = abs(deceleration) * self.vehicle_mass * self.wheel_radius
return throttle, brake, steering
def reset(self):
self.throttle_controller.reset() | true | true |
f7169e22e550d5a34ea898f7d6792737a32dc834 | 2,050 | py | Python | pyJCal.py | Geeknux/jalali-calendar-widget | 034d6895cead2059825a931294ef9ffce7436caa | [
"MIT"
] | 1 | 2015-09-01T03:57:05.000Z | 2015-09-01T03:57:05.000Z | pyJCal.py | Geeknux/jalali-calendar-widget | 034d6895cead2059825a931294ef9ffce7436caa | [
"MIT"
] | 1 | 2015-09-01T03:56:35.000Z | 2015-09-01T03:56:35.000Z | pyJCal.py | Geeknux/jalali-calendar-widget | 034d6895cead2059825a931294ef9ffce7436caa | [
"MIT"
] | null | null | null | #! /usr/bin/python2
# coding=utf-8
class pyJCal:
def __init__(self):
pass
def div(self, a, b):
return a / b
def gregorian_to_jalali(self, g_y, g_m, g_d):
"""
this function returns result of converting ye gregorian date to jalali
"""
g_days_in_month = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
j_days_in_month = (31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29)
gy = g_y - 1600
gm = g_m - 1
gd = g_d - 1
g_day_no = 365 * gy + self.div(gy+3, 4) - self.div(gy+99, 100) + self.div(gy+399, 400)
i = 0
while i < gm:
g_day_no += g_days_in_month[i]
i += 1
if(gm > 1 and ((gy % 4 == 0 and gy % 100 != 0) or (gy % 400 == 0))):
g_day_no += 1
g_day_no += gd
j_day_no = g_day_no - 79
j_np = self.div(j_day_no, 12053)
j_day_no = j_day_no % 12053
jy = 979 + 33 * j_np + 4 * self.div(j_day_no, 1461)
j_day_no %= 1461
if j_day_no >= 365:
jy += self.div(j_day_no - 1, 365)
j_day_no = (j_day_no - 1) % 365
i = 0
while (i < 11 and j_day_no >= j_days_in_month[i]):
j_day_no -= j_days_in_month[i]
i += 1
jm = i + 1
jd = j_day_no + 1
return (jy, jm, jd)
def MonthName(self, _m_num):
_m_num = int(_m_num)
if _m_num == 1:
return 'فروردین'
elif _m_num == 2:
return 'اردیبهشت'
elif _m_num == 3:
return 'خرداد'
elif _m_num == 4:
return 'تیر'
elif _m_num == 5:
return 'مرداد'
elif _m_num == 6:
return 'شهریور'
elif _m_num == 7:
return 'مهر'
elif _m_num == 8:
return 'آبان'
elif _m_num == 9:
return 'آذر'
elif _m_num == 10:
return 'دی'
elif _m_num == 11:
return 'بهمن'
elif _m_num == 12:
return 'اسفند'
else:
return False
def WeekDayName(self, _d):
if _d == 'Saturday':
return 'شنبه'
elif _d == 'Sunday':
return 'یکشنبه'
elif _d == 'Monday':
return 'دوشنبه'
elif _d == 'Tuesday':
return 'سه شنبه'
elif _d == 'Wednesday':
return 'چهارشنبه'
elif _d == 'Thursday':
return 'پنجشنبه'
elif _d == 'Friday':
return 'جمعه'
else:
return _d
| 19.711538 | 88 | 0.57122 |
class pyJCal:
def __init__(self):
pass
def div(self, a, b):
return a / b
def gregorian_to_jalali(self, g_y, g_m, g_d):
g_days_in_month = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
j_days_in_month = (31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29)
gy = g_y - 1600
gm = g_m - 1
gd = g_d - 1
g_day_no = 365 * gy + self.div(gy+3, 4) - self.div(gy+99, 100) + self.div(gy+399, 400)
i = 0
while i < gm:
g_day_no += g_days_in_month[i]
i += 1
if(gm > 1 and ((gy % 4 == 0 and gy % 100 != 0) or (gy % 400 == 0))):
g_day_no += 1
g_day_no += gd
j_day_no = g_day_no - 79
j_np = self.div(j_day_no, 12053)
j_day_no = j_day_no % 12053
jy = 979 + 33 * j_np + 4 * self.div(j_day_no, 1461)
j_day_no %= 1461
if j_day_no >= 365:
jy += self.div(j_day_no - 1, 365)
j_day_no = (j_day_no - 1) % 365
i = 0
while (i < 11 and j_day_no >= j_days_in_month[i]):
j_day_no -= j_days_in_month[i]
i += 1
jm = i + 1
jd = j_day_no + 1
return (jy, jm, jd)
def MonthName(self, _m_num):
_m_num = int(_m_num)
if _m_num == 1:
return 'فروردین'
elif _m_num == 2:
return 'اردیبهشت'
elif _m_num == 3:
return 'خرداد'
elif _m_num == 4:
return 'تیر'
elif _m_num == 5:
return 'مرداد'
elif _m_num == 6:
return 'شهریور'
elif _m_num == 7:
return 'مهر'
elif _m_num == 8:
return 'آبان'
elif _m_num == 9:
return 'آذر'
elif _m_num == 10:
return 'دی'
elif _m_num == 11:
return 'بهمن'
elif _m_num == 12:
return 'اسفند'
else:
return False
def WeekDayName(self, _d):
if _d == 'Saturday':
return 'شنبه'
elif _d == 'Sunday':
return 'یکشنبه'
elif _d == 'Monday':
return 'دوشنبه'
elif _d == 'Tuesday':
return 'سه شنبه'
elif _d == 'Wednesday':
return 'چهارشنبه'
elif _d == 'Thursday':
return 'پنجشنبه'
elif _d == 'Friday':
return 'جمعه'
else:
return _d
| true | true |
f7169ea9d45728fbd3a7a434bf6954f50de55d91 | 8,833 | py | Python | source/conf.py | abhivishal/website | 5debb3bc7da05a018996a7fbf7d140ad8b91a66e | [
"Apache-2.0"
] | 40 | 2015-07-24T14:11:25.000Z | 2021-08-02T14:25:09.000Z | source/conf.py | abhivishal/website | 5debb3bc7da05a018996a7fbf7d140ad8b91a66e | [
"Apache-2.0"
] | 79 | 2015-01-07T20:46:42.000Z | 2021-06-08T19:02:48.000Z | source/conf.py | abhivishal/website | 5debb3bc7da05a018996a7fbf7d140ad8b91a66e | [
"Apache-2.0"
] | 41 | 2015-01-29T00:10:00.000Z | 2022-03-20T02:55:45.000Z | # -*- coding: utf-8 -*-
#
# OSU DevOps BootCamp documentation build configuration file, created by
# sphinx-quickstart on Tue Oct 15 12:20:17 2013.
#
# 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.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# 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.todo',]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'OSU DevOps BootCamp'
copyright = u'2013-2017, Oregon State Unviersity'
# The version info for the project 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 = '0.0.1'
# The full version, including alpha/beta/rc tags.
release = '0.0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Hieroglyph Congfig -------------------------------------------------------
# When autoslides is True, Hieroglyph will generate slides from the document
# sections. If autoslides is set to False, only generate slides from the slide
# directive.
# This can be overridden on a per-document basis using the slideconf directive.
if not os.environ.get('READTHEDOCS', None):
extensions += ['hieroglyph',]
autoslides = True
slide_theme = 'single-level'
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
html_context = {
'display_github': True,
'github_user': 'devopsbootcamp',
'github_repo': 'website',
'github_version': 'master',
'conf_py_path': '/source/',
'source_suffix': '.rst'
}
# 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 = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# 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']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
html_style = 'styles.css'
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'OSUDevOpsBootCampdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'OSUDevOpsBootCamp.tex', u'OSU DevOps BootCamp Documentation',
u'OSU OSL & OSU LUG', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'osudevopsbootcamp', u'OSU DevOps BootCamp Documentation',
[u'OSU OSL & OSU LUG'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'OSUDevOpsBootCamp', u'OSU DevOps BootCamp Documentation',
u'OSU OSL & OSU LUG', 'OSUDevOpsBootCamp', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
slide_theme_options = {
'custom_css': 'custom.css',
'custom_js': 'ga.js',
}
if not os.environ.get('READTHEDOCS', None):
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
| 32.355311 | 81 | 0.709498 |
import sys, os
extensions = ['sphinx.ext.todo',]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'OSU DevOps BootCamp'
copyright = u'2013-2017, Oregon State Unviersity'
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.0.1'
# The full version, including alpha/beta/rc tags.
release = '0.0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Hieroglyph Congfig -------------------------------------------------------
# When autoslides is True, Hieroglyph will generate slides from the document
# sections. If autoslides is set to False, only generate slides from the slide
# directive.
# This can be overridden on a per-document basis using the slideconf directive.
if not os.environ.get('READTHEDOCS', None):
extensions += ['hieroglyph',]
autoslides = True
slide_theme = 'single-level'
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
html_context = {
'display_github': True,
'github_user': 'devopsbootcamp',
'github_repo': 'website',
'github_version': 'master',
'conf_py_path': '/source/',
'source_suffix': '.rst'
}
# 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 = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# 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']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
html_style = 'styles.css'
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'OSUDevOpsBootCampdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'OSUDevOpsBootCamp.tex', u'OSU DevOps BootCamp Documentation',
u'OSU OSL & OSU LUG', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'osudevopsbootcamp', u'OSU DevOps BootCamp Documentation',
[u'OSU OSL & OSU LUG'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'OSUDevOpsBootCamp', u'OSU DevOps BootCamp Documentation',
u'OSU OSL & OSU LUG', 'OSUDevOpsBootCamp', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
slide_theme_options = {
'custom_css': 'custom.css',
'custom_js': 'ga.js',
}
if not os.environ.get('READTHEDOCS', None):
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
| true | true |
f7169eeeb7b39a8b509cb6a7cc0f4ab643571126 | 331 | py | Python | api/app/api/endpoints/bets.py | franloza/apiestas | 46978f58858b1d3822b2f80eb8948009944aa005 | [
"MIT"
] | 53 | 2019-11-19T03:02:06.000Z | 2022-01-13T15:29:38.000Z | api/app/api/endpoints/bets.py | franloza/apiestas | 46978f58858b1d3822b2f80eb8948009944aa005 | [
"MIT"
] | 3 | 2019-12-27T22:49:11.000Z | 2021-03-31T18:59:36.000Z | api/app/api/endpoints/bets.py | franloza/apiestas | 46978f58858b1d3822b2f80eb8948009944aa005 | [
"MIT"
] | 5 | 2021-04-25T13:02:48.000Z | 2022-02-16T13:57:21.000Z | from fastapi import APIRouter, Depends
from ...api.dependencies.bets import get_bet_by_slug_from_path
from ...models.bets import Bet
router = APIRouter()
@router.get(
'/{slug}',
response_model=Bet,
name="bets:get-bet"
)
async def get_bet(bet=Depends(get_bet_by_slug_from_path)) -> Bet:
return Bet(**bet.dict())
| 20.6875 | 65 | 0.719033 | from fastapi import APIRouter, Depends
from ...api.dependencies.bets import get_bet_by_slug_from_path
from ...models.bets import Bet
router = APIRouter()
@router.get(
'/{slug}',
response_model=Bet,
name="bets:get-bet"
)
async def get_bet(bet=Depends(get_bet_by_slug_from_path)) -> Bet:
return Bet(**bet.dict())
| true | true |
f7169fa15e8d91d107ba43a0da61b69e67f59f1d | 34,678 | py | Python | networking_sfc/tests/unit/extensions/test_flowclassifier.py | huiweics/networking-sfc | e7675aa1a31769d55740c025a39644cc6e1ca8dd | [
"Apache-2.0"
] | null | null | null | networking_sfc/tests/unit/extensions/test_flowclassifier.py | huiweics/networking-sfc | e7675aa1a31769d55740c025a39644cc6e1ca8dd | [
"Apache-2.0"
] | null | null | null | networking_sfc/tests/unit/extensions/test_flowclassifier.py | huiweics/networking-sfc | e7675aa1a31769d55740c025a39644cc6e1ca8dd | [
"Apache-2.0"
] | null | null | null | # Copyright 2015 Futurewei. 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 copy
import mock
from neutron.api.v2 import resource as api_res_log
from neutron import manager
from neutron.notifiers import nova as nova_log
from neutron.tests.unit.api.v2 import test_base as test_api_v2
from neutron.tests.unit.extensions import base as test_api_v2_extension
from neutron_lib import constants as const
from oslo_config import cfg
from oslo_utils import uuidutils
from webob import exc
import webtest
from networking_sfc.extensions import flowclassifier as fc_ext
_uuid = uuidutils.generate_uuid
_get_path = test_api_v2._get_path
FLOW_CLASSIFIER_PATH = (fc_ext.FLOW_CLASSIFIER_PREFIX[1:] + '/' +
fc_ext.FLOW_CLASSIFIER_EXT + 's')
class FlowClassifierExtensionTestCase(
test_api_v2_extension.ExtensionTestCase
):
fmt = 'json'
def setUp(self):
self._mock_unnecessary_logging()
super(FlowClassifierExtensionTestCase, self).setUp()
self.setup_extension(
'networking_sfc.extensions.flowclassifier.'
'FlowClassifierPluginBase',
fc_ext.FLOW_CLASSIFIER_EXT,
fc_ext.Flowclassifier,
fc_ext.FLOW_CLASSIFIER_PREFIX[1:],
plural_mappings={}
)
def _mock_unnecessary_logging(self):
mock_log_cfg_p = mock.patch.object(cfg, 'LOG')
self.mock_log_cfg = mock_log_cfg_p.start()
mock_log_manager_p = mock.patch.object(manager, 'LOG')
self.mock_log_manager = mock_log_manager_p.start()
mock_log_nova_p = mock.patch.object(nova_log, 'LOG')
self.mock_log_nova = mock_log_nova_p.start()
mock_log_api_res_log_p = mock.patch.object(api_res_log, 'LOG')
self.mock_log_api_res_log = mock_log_api_res_log_p.start()
def _get_expected_flow_classifier(self, data):
source_port_range_min = data['flow_classifier'].get(
'source_port_range_min')
if source_port_range_min is not None:
source_port_range_min = int(source_port_range_min)
source_port_range_max = data['flow_classifier'].get(
'source_port_range_max')
if source_port_range_max is not None:
source_port_range_max = int(source_port_range_max)
destination_port_range_min = data['flow_classifier'].get(
'destination_port_range_min')
if destination_port_range_min is not None:
destination_port_range_min = int(destination_port_range_min)
destination_port_range_max = data['flow_classifier'].get(
'destination_port_range_max')
if destination_port_range_max is not None:
destination_port_range_max = int(destination_port_range_max)
return {'flow_classifier': {
'name': data['flow_classifier'].get('name') or '',
'description': data['flow_classifier'].get('description') or '',
'tenant_id': data['flow_classifier']['tenant_id'],
'project_id': data['flow_classifier']['project_id'],
'source_port_range_min': source_port_range_min,
'source_port_range_max': source_port_range_max,
'destination_port_range_min': destination_port_range_min,
'destination_port_range_max': destination_port_range_max,
'l7_parameters': data['flow_classifier'].get(
'l7_parameters') or {},
'destination_ip_prefix': data['flow_classifier'].get(
'destination_ip_prefix'),
'source_ip_prefix': data['flow_classifier'].get(
'source_ip_prefix'),
'logical_source_port': data['flow_classifier'].get(
'logical_source_port'),
'logical_destination_port': data['flow_classifier'].get(
'logical_destination_port'),
'ethertype': data['flow_classifier'].get(
'ethertype') or 'IPv4',
'protocol': data['flow_classifier'].get(
'protocol')
}}
def test_create_flow_classifier(self):
flowclassifier_id = _uuid()
tenant_id = _uuid()
data = {'flow_classifier': {
'logical_source_port': _uuid(),
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
expected_data = self._get_expected_flow_classifier(data)
return_value = copy.copy(expected_data['flow_classifier'])
return_value.update({'id': flowclassifier_id})
instance = self.plugin.return_value
instance.create_flow_classifier.return_value = return_value
res = self.api.post(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
instance.create_flow_classifier.assert_called_with(
mock.ANY,
flow_classifier=expected_data)
self.assertEqual(exc.HTTPCreated.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifier', res)
self.assertEqual(return_value, res['flow_classifier'])
def test_create_flow_classifier_source_port_range(self):
for source_port_range_min in [None, 100, '100']:
for source_port_range_max in [None, 200, '200']:
flowclassifier_id = _uuid()
tenant_id = _uuid()
data = {'flow_classifier': {
'source_port_range_min': source_port_range_min,
'source_port_range_max': source_port_range_max,
'logical_source_port': _uuid(),
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
expected_data = self._get_expected_flow_classifier(data)
return_value = copy.copy(expected_data['flow_classifier'])
return_value.update({'id': flowclassifier_id})
instance = self.plugin.return_value
instance.create_flow_classifier.return_value = return_value
res = self.api.post(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
instance.create_flow_classifier.assert_called_with(
mock.ANY,
flow_classifier=expected_data)
self.assertEqual(exc.HTTPCreated.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifier', res)
self.assertEqual(return_value, res['flow_classifier'])
def test_create_flow_classifier_destination_port_range(self):
for destination_port_range_min in [None, 100, '100']:
for destination_port_range_max in [None, 200, '200']:
flowclassifier_id = _uuid()
tenant_id = _uuid()
data = {'flow_classifier': {
'destination_port_range_min': destination_port_range_min,
'destination_port_range_max': destination_port_range_max,
'logical_source_port': _uuid(),
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
expected_data = self._get_expected_flow_classifier(data)
return_value = copy.copy(expected_data['flow_classifier'])
return_value.update({'id': flowclassifier_id})
instance = self.plugin.return_value
instance.create_flow_classifier.return_value = return_value
res = self.api.post(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
instance.create_flow_classifier.assert_called_with(
mock.ANY,
flow_classifier=expected_data)
self.assertEqual(exc.HTTPCreated.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifier', res)
self.assertEqual(return_value, res['flow_classifier'])
def test_create_flow_classifier_source_ip_prefix(self):
for logical_source_ip_prefix in [
None, '10.0.0.0/8'
]:
flowclassifier_id = _uuid()
tenant_id = _uuid()
data = {'flow_classifier': {
'source_ip_prefix': logical_source_ip_prefix,
'logical_source_port': _uuid(),
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
expected_data = self._get_expected_flow_classifier(data)
return_value = copy.copy(expected_data['flow_classifier'])
return_value.update({'id': flowclassifier_id})
instance = self.plugin.return_value
instance.create_flow_classifier.return_value = return_value
res = self.api.post(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
instance.create_flow_classifier.assert_called_with(
mock.ANY,
flow_classifier=expected_data)
self.assertEqual(exc.HTTPCreated.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifier', res)
self.assertEqual(return_value, res['flow_classifier'])
def test_create_flow_classifier_destination_ip_prefix(self):
for logical_destination_ip_prefix in [
None, '10.0.0.0/8'
]:
flowclassifier_id = _uuid()
tenant_id = _uuid()
data = {'flow_classifier': {
'destination_ip_prefix': logical_destination_ip_prefix,
'logical_source_port': _uuid(),
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
expected_data = self._get_expected_flow_classifier(data)
return_value = copy.copy(expected_data['flow_classifier'])
return_value.update({'id': flowclassifier_id})
instance = self.plugin.return_value
instance.create_flow_classifier.return_value = return_value
res = self.api.post(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
instance.create_flow_classifier.assert_called_with(
mock.ANY,
flow_classifier=expected_data)
self.assertEqual(res.status_int, exc.HTTPCreated.code)
res = self.deserialize(res)
self.assertIn('flow_classifier', res)
self.assertEqual(return_value, res['flow_classifier'])
def test_create_flow_classifier_logical_source_port(self):
for logical_source_port in [
None, _uuid()
]:
flowclassifier_id = _uuid()
tenant_id = _uuid()
data = {'flow_classifier': {
'logical_source_port': logical_source_port,
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
expected_data = self._get_expected_flow_classifier(data)
return_value = copy.copy(expected_data['flow_classifier'])
return_value.update({'id': flowclassifier_id})
instance = self.plugin.return_value
instance.create_flow_classifier.return_value = return_value
res = self.api.post(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
instance.create_flow_classifier.assert_called_with(
mock.ANY,
flow_classifier=expected_data)
self.assertEqual(exc.HTTPCreated.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifier', res)
self.assertEqual(return_value, res['flow_classifier'])
def test_create_flow_classifier_logical_destination_port(self):
for logical_destination_port in [
None, _uuid()
]:
flowclassifier_id = _uuid()
tenant_id = _uuid()
data = {'flow_classifier': {
'logical_destination_port': logical_destination_port,
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
expected_data = self._get_expected_flow_classifier(data)
return_value = copy.copy(expected_data['flow_classifier'])
return_value.update({'id': flowclassifier_id})
instance = self.plugin.return_value
instance.create_flow_classifier.return_value = return_value
res = self.api.post(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
instance.create_flow_classifier.assert_called_with(
mock.ANY,
flow_classifier=expected_data)
self.assertEqual(exc.HTTPCreated.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifier', res)
self.assertEqual(return_value, res['flow_classifier'])
def test_create_flow_classifier_l7_parameters(self):
for l7_parameters in [None, {}]:
flowclassifier_id = _uuid()
tenant_id = _uuid()
data = {'flow_classifier': {
'logical_source_port': _uuid(),
'tenant_id': tenant_id, 'project_id': tenant_id,
'l7_parameters': l7_parameters
}}
expected_data = self._get_expected_flow_classifier(data)
return_value = copy.copy(expected_data['flow_classifier'])
return_value.update({'id': flowclassifier_id})
instance = self.plugin.return_value
instance.create_flow_classifier.return_value = return_value
res = self.api.post(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
instance.create_flow_classifier.assert_called_with(
mock.ANY,
flow_classifier=expected_data)
self.assertEqual(exc.HTTPCreated.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifier', res)
self.assertEqual(return_value, res['flow_classifier'])
def test_create_flow_classifier_ethertype(self):
for ethertype in [None, 'IPv4', 'IPv6']:
flowclassifier_id = _uuid()
tenant_id = _uuid()
data = {'flow_classifier': {
'logical_source_port': _uuid(),
'tenant_id': tenant_id, 'project_id': tenant_id,
'ethertype': ethertype
}}
expected_data = self._get_expected_flow_classifier(data)
return_value = copy.copy(expected_data['flow_classifier'])
return_value.update({'id': flowclassifier_id})
instance = self.plugin.return_value
instance.create_flow_classifier.return_value = return_value
res = self.api.post(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
instance.create_flow_classifier.assert_called_with(
mock.ANY,
flow_classifier=expected_data)
self.assertEqual(exc.HTTPCreated.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifier', res)
self.assertEqual(return_value, res['flow_classifier'])
def test_create_flow_classifier_protocol(self):
for protocol in [
None, const.PROTO_NAME_TCP, const.PROTO_NAME_UDP,
const.PROTO_NAME_ICMP
]:
flowclassifier_id = _uuid()
tenant_id = _uuid()
data = {'flow_classifier': {
'logical_source_port': _uuid(),
'tenant_id': tenant_id, 'project_id': tenant_id,
'protocol': protocol
}}
expected_data = self._get_expected_flow_classifier(data)
return_value = copy.copy(expected_data['flow_classifier'])
return_value.update({'id': flowclassifier_id})
instance = self.plugin.return_value
instance.create_flow_classifier.return_value = return_value
res = self.api.post(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
instance.create_flow_classifier.assert_called_with(
mock.ANY,
flow_classifier=expected_data)
self.assertEqual(exc.HTTPCreated.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifier', res)
self.assertEqual(return_value, res['flow_classifier'])
def test_create_flow_classifier_all_fields(self):
flowclassifier_id = _uuid()
tenant_id = _uuid()
data = {'flow_classifier': {
'name': 'test1',
'description': 'desc',
'tenant_id': tenant_id, 'project_id': tenant_id,
'source_port_range_min': 100,
'source_port_range_max': 200,
'destination_port_range_min': 100,
'destination_port_range_max': 200,
'l7_parameters': {},
'destination_ip_prefix': '10.0.0.0/8',
'source_ip_prefix': '10.0.0.0/8',
'logical_source_port': _uuid(),
'logical_destination_port': _uuid(),
'ethertype': None,
'protocol': None
}}
expected_data = self._get_expected_flow_classifier(data)
return_value = copy.copy(expected_data['flow_classifier'])
return_value.update({'id': flowclassifier_id})
instance = self.plugin.return_value
instance.create_flow_classifier.return_value = return_value
res = self.api.post(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
instance.create_flow_classifier.assert_called_with(
mock.ANY,
flow_classifier=expected_data)
self.assertEqual(exc.HTTPCreated.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifier', res)
self.assertEqual(return_value, res['flow_classifier'])
def test_create_flow_classifier_invalid_l7_parameters(self):
tenant_id = _uuid()
data = {'flow_classifier': {
'logical_source_port': _uuid(),
'l7_parameters': {'abc': 'def'},
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.post,
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_create_flow_classifier_invalid_protocol(self):
tenant_id = _uuid()
data = {'flow_classifier': {
'logical_source_port': _uuid(),
'protocol': 'unknown',
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.post,
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_create_flow_classifier_invalid_ethertype(self):
tenant_id = _uuid()
data = {'flow_classifier': {
'logical_source_port': _uuid(),
'ethertype': 'unknown',
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.post,
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_create_flow_classifier_port_small(self):
tenant_id = _uuid()
data = {'flow_classifier': {
'logical_source_port': _uuid(),
'source_port_range_min': -1,
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.post,
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_create_flow_classifier_port_large(self):
tenant_id = _uuid()
data = {'flow_classifier': {
'logical_source_port': _uuid(),
'source_port_range_min': 65536,
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.post,
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_create_flow_classifier_ip_prefix_no_cidr(self):
tenant_id = _uuid()
data = {'flow_classifier': {
'source_ip_prefix': '10.0.0.0',
'logical_source_port': _uuid(),
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.post,
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_create_flow_classifier_ip_prefix_invalid_cidr(self):
tenant_id = _uuid()
data = {'flow_classifier': {
'source_ip_prefix': '10.0.0.0/33',
'logical_source_port': _uuid(),
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.post,
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_create_flow_classifier_port_id_nouuid(self):
tenant_id = _uuid()
data = {'flow_classifier': {
'logical_source_port': 'unknown',
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.post,
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_flow_classifier_list(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
return_value = [{
'tenant_id': tenant_id, 'project_id': tenant_id,
'id': flowclassifier_id
}]
instance = self.plugin.return_value
instance.get_flow_classifiers.return_value = return_value
res = self.api.get(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt))
instance.get_flow_classifiers.assert_called_with(
mock.ANY,
fields=mock.ANY,
filters=mock.ANY
)
self.assertEqual(exc.HTTPOk.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifiers', res)
self.assertEqual(return_value, res['flow_classifiers'])
def test_flow_classifier_list_all_fields(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
return_value = [{
'name': 'abc',
'description': 'abc',
'ethertype': 'IPv4',
'protocol': const.PROTO_NAME_TCP,
'source_ip_prefix': '10.0.0.0/8',
'destination_ip_prefix': '10.0.0.0/8',
'source_port_range_min': 100,
'source_port_range_max': 200,
'destination_port_range_min': 100,
'destination_port_range_max': 200,
'logical_source_port': _uuid(),
'logical_destination_port': _uuid(),
'l7_parameters': {},
'tenant_id': tenant_id, 'project_id': tenant_id,
'id': flowclassifier_id
}]
instance = self.plugin.return_value
instance.get_flow_classifiers.return_value = return_value
res = self.api.get(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt))
instance.get_flow_classifiers.assert_called_with(
mock.ANY,
fields=mock.ANY,
filters=mock.ANY
)
self.assertEqual(exc.HTTPOk.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifiers', res)
self.assertEqual(return_value, res['flow_classifiers'])
def test_flow_classifier_list_unknown_fields(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
return_value = [{
'logical_source_port': _uuid(),
'new_key': 'value',
'tenant_id': tenant_id, 'project_id': tenant_id,
'id': flowclassifier_id
}]
expected_return = copy.copy(return_value)
for item in expected_return:
del item['new_key']
instance = self.plugin.return_value
instance.get_flow_classifiers.return_value = return_value
res = self.api.get(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt))
instance.get_flow_classifiers.assert_called_with(
mock.ANY,
fields=mock.ANY,
filters=mock.ANY
)
self.assertEqual(exc.HTTPOk.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifiers', res)
self.assertEqual(expected_return, res['flow_classifiers'])
def test_flow_classifier_get(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
return_value = {
'logical_source_port': _uuid(),
'tenant_id': tenant_id, 'project_id': tenant_id,
'id': flowclassifier_id
}
instance = self.plugin.return_value
instance.get_flow_classifier.return_value = return_value
res = self.api.get(
_get_path(
FLOW_CLASSIFIER_PATH,
id=flowclassifier_id, fmt=self.fmt
)
)
instance.get_flow_classifier.assert_called_with(
mock.ANY,
flowclassifier_id,
fields=mock.ANY
)
self.assertEqual(exc.HTTPOk.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifier', res)
self.assertEqual(return_value, res['flow_classifier'])
def test_flow_classifier_update(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
update_data = {'flow_classifier': {
'name': 'new_name',
'description': 'new_desc',
}}
return_value = {
'tenant_id': tenant_id, 'project_id': tenant_id,
'id': flowclassifier_id
}
instance = self.plugin.return_value
instance.update_flow_classifier.return_value = return_value
res = self.api.put(
_get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id,
fmt=self.fmt),
self.serialize(update_data))
instance.update_flow_classifier.assert_called_with(
mock.ANY, flowclassifier_id,
flow_classifier=update_data)
self.assertEqual(exc.HTTPOk.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifier', res)
self.assertEqual(return_value, res['flow_classifier'])
def test_flow_classifier_update_source_port_range_min(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
data = {'flow_classifier': {
'source_port_range_min': 100,
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.put,
_get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id,
fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_flow_classifier_update_source_port_range_max(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
data = {'flow_classifier': {
'source_port_range_max': 100,
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.put,
_get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id,
fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_flow_classifier_update_destination_port_range_min(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
data = {'flow_classifier': {
'destination_port_range_min': 100,
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.put,
_get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id,
fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_flow_classifier_update_destination_port_range_max(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
data = {'flow_classifier': {
'destination_port_range_max': 100,
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.put,
_get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id,
fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_flow_classifier_update_source_ip_prefix(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
data = {'flow_classifier': {
'source_ip_prefix': '10.0.0.0/8',
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.put,
_get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id,
fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_flow_classifier_update_destination_ip_prefix(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
data = {'flow_classifier': {
'destination_ip_prefix': '10.0.0.0/8',
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.put,
_get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id,
fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_flow_classifier_update_logical_source_port(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
data = {'flow_classifier': {
'logical_source_port': _uuid(),
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.put,
_get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id,
fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_flow_classifier_update_logical_destination_port(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
data = {'flow_classifier': {
'logical_destination_port': _uuid(),
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.put,
_get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id,
fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_flow_classifier_update_ethertype(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
data = {'flow_classifier': {
'ethertype': None,
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.put,
_get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id,
fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_flow_classifier_update_protocol(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
data = {'flow_classifier': {
'protococol': None,
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.put,
_get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id,
fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_flow_classifier_update_l7_parameters(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
data = {'flow_classifier': {
'l7_parameters': {},
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.put,
_get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id,
fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_flow_classifier_delete(self):
self._test_entity_delete('flow_classifier')
| 41.630252 | 78 | 0.603639 |
import copy
import mock
from neutron.api.v2 import resource as api_res_log
from neutron import manager
from neutron.notifiers import nova as nova_log
from neutron.tests.unit.api.v2 import test_base as test_api_v2
from neutron.tests.unit.extensions import base as test_api_v2_extension
from neutron_lib import constants as const
from oslo_config import cfg
from oslo_utils import uuidutils
from webob import exc
import webtest
from networking_sfc.extensions import flowclassifier as fc_ext
_uuid = uuidutils.generate_uuid
_get_path = test_api_v2._get_path
FLOW_CLASSIFIER_PATH = (fc_ext.FLOW_CLASSIFIER_PREFIX[1:] + '/' +
fc_ext.FLOW_CLASSIFIER_EXT + 's')
class FlowClassifierExtensionTestCase(
test_api_v2_extension.ExtensionTestCase
):
fmt = 'json'
def setUp(self):
self._mock_unnecessary_logging()
super(FlowClassifierExtensionTestCase, self).setUp()
self.setup_extension(
'networking_sfc.extensions.flowclassifier.'
'FlowClassifierPluginBase',
fc_ext.FLOW_CLASSIFIER_EXT,
fc_ext.Flowclassifier,
fc_ext.FLOW_CLASSIFIER_PREFIX[1:],
plural_mappings={}
)
def _mock_unnecessary_logging(self):
mock_log_cfg_p = mock.patch.object(cfg, 'LOG')
self.mock_log_cfg = mock_log_cfg_p.start()
mock_log_manager_p = mock.patch.object(manager, 'LOG')
self.mock_log_manager = mock_log_manager_p.start()
mock_log_nova_p = mock.patch.object(nova_log, 'LOG')
self.mock_log_nova = mock_log_nova_p.start()
mock_log_api_res_log_p = mock.patch.object(api_res_log, 'LOG')
self.mock_log_api_res_log = mock_log_api_res_log_p.start()
def _get_expected_flow_classifier(self, data):
source_port_range_min = data['flow_classifier'].get(
'source_port_range_min')
if source_port_range_min is not None:
source_port_range_min = int(source_port_range_min)
source_port_range_max = data['flow_classifier'].get(
'source_port_range_max')
if source_port_range_max is not None:
source_port_range_max = int(source_port_range_max)
destination_port_range_min = data['flow_classifier'].get(
'destination_port_range_min')
if destination_port_range_min is not None:
destination_port_range_min = int(destination_port_range_min)
destination_port_range_max = data['flow_classifier'].get(
'destination_port_range_max')
if destination_port_range_max is not None:
destination_port_range_max = int(destination_port_range_max)
return {'flow_classifier': {
'name': data['flow_classifier'].get('name') or '',
'description': data['flow_classifier'].get('description') or '',
'tenant_id': data['flow_classifier']['tenant_id'],
'project_id': data['flow_classifier']['project_id'],
'source_port_range_min': source_port_range_min,
'source_port_range_max': source_port_range_max,
'destination_port_range_min': destination_port_range_min,
'destination_port_range_max': destination_port_range_max,
'l7_parameters': data['flow_classifier'].get(
'l7_parameters') or {},
'destination_ip_prefix': data['flow_classifier'].get(
'destination_ip_prefix'),
'source_ip_prefix': data['flow_classifier'].get(
'source_ip_prefix'),
'logical_source_port': data['flow_classifier'].get(
'logical_source_port'),
'logical_destination_port': data['flow_classifier'].get(
'logical_destination_port'),
'ethertype': data['flow_classifier'].get(
'ethertype') or 'IPv4',
'protocol': data['flow_classifier'].get(
'protocol')
}}
def test_create_flow_classifier(self):
flowclassifier_id = _uuid()
tenant_id = _uuid()
data = {'flow_classifier': {
'logical_source_port': _uuid(),
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
expected_data = self._get_expected_flow_classifier(data)
return_value = copy.copy(expected_data['flow_classifier'])
return_value.update({'id': flowclassifier_id})
instance = self.plugin.return_value
instance.create_flow_classifier.return_value = return_value
res = self.api.post(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
instance.create_flow_classifier.assert_called_with(
mock.ANY,
flow_classifier=expected_data)
self.assertEqual(exc.HTTPCreated.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifier', res)
self.assertEqual(return_value, res['flow_classifier'])
def test_create_flow_classifier_source_port_range(self):
for source_port_range_min in [None, 100, '100']:
for source_port_range_max in [None, 200, '200']:
flowclassifier_id = _uuid()
tenant_id = _uuid()
data = {'flow_classifier': {
'source_port_range_min': source_port_range_min,
'source_port_range_max': source_port_range_max,
'logical_source_port': _uuid(),
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
expected_data = self._get_expected_flow_classifier(data)
return_value = copy.copy(expected_data['flow_classifier'])
return_value.update({'id': flowclassifier_id})
instance = self.plugin.return_value
instance.create_flow_classifier.return_value = return_value
res = self.api.post(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
instance.create_flow_classifier.assert_called_with(
mock.ANY,
flow_classifier=expected_data)
self.assertEqual(exc.HTTPCreated.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifier', res)
self.assertEqual(return_value, res['flow_classifier'])
def test_create_flow_classifier_destination_port_range(self):
for destination_port_range_min in [None, 100, '100']:
for destination_port_range_max in [None, 200, '200']:
flowclassifier_id = _uuid()
tenant_id = _uuid()
data = {'flow_classifier': {
'destination_port_range_min': destination_port_range_min,
'destination_port_range_max': destination_port_range_max,
'logical_source_port': _uuid(),
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
expected_data = self._get_expected_flow_classifier(data)
return_value = copy.copy(expected_data['flow_classifier'])
return_value.update({'id': flowclassifier_id})
instance = self.plugin.return_value
instance.create_flow_classifier.return_value = return_value
res = self.api.post(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
instance.create_flow_classifier.assert_called_with(
mock.ANY,
flow_classifier=expected_data)
self.assertEqual(exc.HTTPCreated.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifier', res)
self.assertEqual(return_value, res['flow_classifier'])
def test_create_flow_classifier_source_ip_prefix(self):
for logical_source_ip_prefix in [
None, '10.0.0.0/8'
]:
flowclassifier_id = _uuid()
tenant_id = _uuid()
data = {'flow_classifier': {
'source_ip_prefix': logical_source_ip_prefix,
'logical_source_port': _uuid(),
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
expected_data = self._get_expected_flow_classifier(data)
return_value = copy.copy(expected_data['flow_classifier'])
return_value.update({'id': flowclassifier_id})
instance = self.plugin.return_value
instance.create_flow_classifier.return_value = return_value
res = self.api.post(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
instance.create_flow_classifier.assert_called_with(
mock.ANY,
flow_classifier=expected_data)
self.assertEqual(exc.HTTPCreated.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifier', res)
self.assertEqual(return_value, res['flow_classifier'])
def test_create_flow_classifier_destination_ip_prefix(self):
for logical_destination_ip_prefix in [
None, '10.0.0.0/8'
]:
flowclassifier_id = _uuid()
tenant_id = _uuid()
data = {'flow_classifier': {
'destination_ip_prefix': logical_destination_ip_prefix,
'logical_source_port': _uuid(),
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
expected_data = self._get_expected_flow_classifier(data)
return_value = copy.copy(expected_data['flow_classifier'])
return_value.update({'id': flowclassifier_id})
instance = self.plugin.return_value
instance.create_flow_classifier.return_value = return_value
res = self.api.post(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
instance.create_flow_classifier.assert_called_with(
mock.ANY,
flow_classifier=expected_data)
self.assertEqual(res.status_int, exc.HTTPCreated.code)
res = self.deserialize(res)
self.assertIn('flow_classifier', res)
self.assertEqual(return_value, res['flow_classifier'])
def test_create_flow_classifier_logical_source_port(self):
for logical_source_port in [
None, _uuid()
]:
flowclassifier_id = _uuid()
tenant_id = _uuid()
data = {'flow_classifier': {
'logical_source_port': logical_source_port,
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
expected_data = self._get_expected_flow_classifier(data)
return_value = copy.copy(expected_data['flow_classifier'])
return_value.update({'id': flowclassifier_id})
instance = self.plugin.return_value
instance.create_flow_classifier.return_value = return_value
res = self.api.post(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
instance.create_flow_classifier.assert_called_with(
mock.ANY,
flow_classifier=expected_data)
self.assertEqual(exc.HTTPCreated.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifier', res)
self.assertEqual(return_value, res['flow_classifier'])
def test_create_flow_classifier_logical_destination_port(self):
for logical_destination_port in [
None, _uuid()
]:
flowclassifier_id = _uuid()
tenant_id = _uuid()
data = {'flow_classifier': {
'logical_destination_port': logical_destination_port,
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
expected_data = self._get_expected_flow_classifier(data)
return_value = copy.copy(expected_data['flow_classifier'])
return_value.update({'id': flowclassifier_id})
instance = self.plugin.return_value
instance.create_flow_classifier.return_value = return_value
res = self.api.post(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
instance.create_flow_classifier.assert_called_with(
mock.ANY,
flow_classifier=expected_data)
self.assertEqual(exc.HTTPCreated.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifier', res)
self.assertEqual(return_value, res['flow_classifier'])
def test_create_flow_classifier_l7_parameters(self):
for l7_parameters in [None, {}]:
flowclassifier_id = _uuid()
tenant_id = _uuid()
data = {'flow_classifier': {
'logical_source_port': _uuid(),
'tenant_id': tenant_id, 'project_id': tenant_id,
'l7_parameters': l7_parameters
}}
expected_data = self._get_expected_flow_classifier(data)
return_value = copy.copy(expected_data['flow_classifier'])
return_value.update({'id': flowclassifier_id})
instance = self.plugin.return_value
instance.create_flow_classifier.return_value = return_value
res = self.api.post(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
instance.create_flow_classifier.assert_called_with(
mock.ANY,
flow_classifier=expected_data)
self.assertEqual(exc.HTTPCreated.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifier', res)
self.assertEqual(return_value, res['flow_classifier'])
def test_create_flow_classifier_ethertype(self):
for ethertype in [None, 'IPv4', 'IPv6']:
flowclassifier_id = _uuid()
tenant_id = _uuid()
data = {'flow_classifier': {
'logical_source_port': _uuid(),
'tenant_id': tenant_id, 'project_id': tenant_id,
'ethertype': ethertype
}}
expected_data = self._get_expected_flow_classifier(data)
return_value = copy.copy(expected_data['flow_classifier'])
return_value.update({'id': flowclassifier_id})
instance = self.plugin.return_value
instance.create_flow_classifier.return_value = return_value
res = self.api.post(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
instance.create_flow_classifier.assert_called_with(
mock.ANY,
flow_classifier=expected_data)
self.assertEqual(exc.HTTPCreated.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifier', res)
self.assertEqual(return_value, res['flow_classifier'])
def test_create_flow_classifier_protocol(self):
for protocol in [
None, const.PROTO_NAME_TCP, const.PROTO_NAME_UDP,
const.PROTO_NAME_ICMP
]:
flowclassifier_id = _uuid()
tenant_id = _uuid()
data = {'flow_classifier': {
'logical_source_port': _uuid(),
'tenant_id': tenant_id, 'project_id': tenant_id,
'protocol': protocol
}}
expected_data = self._get_expected_flow_classifier(data)
return_value = copy.copy(expected_data['flow_classifier'])
return_value.update({'id': flowclassifier_id})
instance = self.plugin.return_value
instance.create_flow_classifier.return_value = return_value
res = self.api.post(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
instance.create_flow_classifier.assert_called_with(
mock.ANY,
flow_classifier=expected_data)
self.assertEqual(exc.HTTPCreated.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifier', res)
self.assertEqual(return_value, res['flow_classifier'])
def test_create_flow_classifier_all_fields(self):
flowclassifier_id = _uuid()
tenant_id = _uuid()
data = {'flow_classifier': {
'name': 'test1',
'description': 'desc',
'tenant_id': tenant_id, 'project_id': tenant_id,
'source_port_range_min': 100,
'source_port_range_max': 200,
'destination_port_range_min': 100,
'destination_port_range_max': 200,
'l7_parameters': {},
'destination_ip_prefix': '10.0.0.0/8',
'source_ip_prefix': '10.0.0.0/8',
'logical_source_port': _uuid(),
'logical_destination_port': _uuid(),
'ethertype': None,
'protocol': None
}}
expected_data = self._get_expected_flow_classifier(data)
return_value = copy.copy(expected_data['flow_classifier'])
return_value.update({'id': flowclassifier_id})
instance = self.plugin.return_value
instance.create_flow_classifier.return_value = return_value
res = self.api.post(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
instance.create_flow_classifier.assert_called_with(
mock.ANY,
flow_classifier=expected_data)
self.assertEqual(exc.HTTPCreated.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifier', res)
self.assertEqual(return_value, res['flow_classifier'])
def test_create_flow_classifier_invalid_l7_parameters(self):
tenant_id = _uuid()
data = {'flow_classifier': {
'logical_source_port': _uuid(),
'l7_parameters': {'abc': 'def'},
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.post,
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_create_flow_classifier_invalid_protocol(self):
tenant_id = _uuid()
data = {'flow_classifier': {
'logical_source_port': _uuid(),
'protocol': 'unknown',
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.post,
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_create_flow_classifier_invalid_ethertype(self):
tenant_id = _uuid()
data = {'flow_classifier': {
'logical_source_port': _uuid(),
'ethertype': 'unknown',
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.post,
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_create_flow_classifier_port_small(self):
tenant_id = _uuid()
data = {'flow_classifier': {
'logical_source_port': _uuid(),
'source_port_range_min': -1,
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.post,
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_create_flow_classifier_port_large(self):
tenant_id = _uuid()
data = {'flow_classifier': {
'logical_source_port': _uuid(),
'source_port_range_min': 65536,
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.post,
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_create_flow_classifier_ip_prefix_no_cidr(self):
tenant_id = _uuid()
data = {'flow_classifier': {
'source_ip_prefix': '10.0.0.0',
'logical_source_port': _uuid(),
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.post,
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_create_flow_classifier_ip_prefix_invalid_cidr(self):
tenant_id = _uuid()
data = {'flow_classifier': {
'source_ip_prefix': '10.0.0.0/33',
'logical_source_port': _uuid(),
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.post,
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_create_flow_classifier_port_id_nouuid(self):
tenant_id = _uuid()
data = {'flow_classifier': {
'logical_source_port': 'unknown',
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.post,
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_flow_classifier_list(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
return_value = [{
'tenant_id': tenant_id, 'project_id': tenant_id,
'id': flowclassifier_id
}]
instance = self.plugin.return_value
instance.get_flow_classifiers.return_value = return_value
res = self.api.get(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt))
instance.get_flow_classifiers.assert_called_with(
mock.ANY,
fields=mock.ANY,
filters=mock.ANY
)
self.assertEqual(exc.HTTPOk.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifiers', res)
self.assertEqual(return_value, res['flow_classifiers'])
def test_flow_classifier_list_all_fields(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
return_value = [{
'name': 'abc',
'description': 'abc',
'ethertype': 'IPv4',
'protocol': const.PROTO_NAME_TCP,
'source_ip_prefix': '10.0.0.0/8',
'destination_ip_prefix': '10.0.0.0/8',
'source_port_range_min': 100,
'source_port_range_max': 200,
'destination_port_range_min': 100,
'destination_port_range_max': 200,
'logical_source_port': _uuid(),
'logical_destination_port': _uuid(),
'l7_parameters': {},
'tenant_id': tenant_id, 'project_id': tenant_id,
'id': flowclassifier_id
}]
instance = self.plugin.return_value
instance.get_flow_classifiers.return_value = return_value
res = self.api.get(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt))
instance.get_flow_classifiers.assert_called_with(
mock.ANY,
fields=mock.ANY,
filters=mock.ANY
)
self.assertEqual(exc.HTTPOk.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifiers', res)
self.assertEqual(return_value, res['flow_classifiers'])
def test_flow_classifier_list_unknown_fields(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
return_value = [{
'logical_source_port': _uuid(),
'new_key': 'value',
'tenant_id': tenant_id, 'project_id': tenant_id,
'id': flowclassifier_id
}]
expected_return = copy.copy(return_value)
for item in expected_return:
del item['new_key']
instance = self.plugin.return_value
instance.get_flow_classifiers.return_value = return_value
res = self.api.get(
_get_path(FLOW_CLASSIFIER_PATH, fmt=self.fmt))
instance.get_flow_classifiers.assert_called_with(
mock.ANY,
fields=mock.ANY,
filters=mock.ANY
)
self.assertEqual(exc.HTTPOk.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifiers', res)
self.assertEqual(expected_return, res['flow_classifiers'])
def test_flow_classifier_get(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
return_value = {
'logical_source_port': _uuid(),
'tenant_id': tenant_id, 'project_id': tenant_id,
'id': flowclassifier_id
}
instance = self.plugin.return_value
instance.get_flow_classifier.return_value = return_value
res = self.api.get(
_get_path(
FLOW_CLASSIFIER_PATH,
id=flowclassifier_id, fmt=self.fmt
)
)
instance.get_flow_classifier.assert_called_with(
mock.ANY,
flowclassifier_id,
fields=mock.ANY
)
self.assertEqual(exc.HTTPOk.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifier', res)
self.assertEqual(return_value, res['flow_classifier'])
def test_flow_classifier_update(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
update_data = {'flow_classifier': {
'name': 'new_name',
'description': 'new_desc',
}}
return_value = {
'tenant_id': tenant_id, 'project_id': tenant_id,
'id': flowclassifier_id
}
instance = self.plugin.return_value
instance.update_flow_classifier.return_value = return_value
res = self.api.put(
_get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id,
fmt=self.fmt),
self.serialize(update_data))
instance.update_flow_classifier.assert_called_with(
mock.ANY, flowclassifier_id,
flow_classifier=update_data)
self.assertEqual(exc.HTTPOk.code, res.status_int)
res = self.deserialize(res)
self.assertIn('flow_classifier', res)
self.assertEqual(return_value, res['flow_classifier'])
def test_flow_classifier_update_source_port_range_min(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
data = {'flow_classifier': {
'source_port_range_min': 100,
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.put,
_get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id,
fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_flow_classifier_update_source_port_range_max(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
data = {'flow_classifier': {
'source_port_range_max': 100,
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.put,
_get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id,
fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_flow_classifier_update_destination_port_range_min(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
data = {'flow_classifier': {
'destination_port_range_min': 100,
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.put,
_get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id,
fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_flow_classifier_update_destination_port_range_max(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
data = {'flow_classifier': {
'destination_port_range_max': 100,
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.put,
_get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id,
fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_flow_classifier_update_source_ip_prefix(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
data = {'flow_classifier': {
'source_ip_prefix': '10.0.0.0/8',
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.put,
_get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id,
fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_flow_classifier_update_destination_ip_prefix(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
data = {'flow_classifier': {
'destination_ip_prefix': '10.0.0.0/8',
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.put,
_get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id,
fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_flow_classifier_update_logical_source_port(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
data = {'flow_classifier': {
'logical_source_port': _uuid(),
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.put,
_get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id,
fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_flow_classifier_update_logical_destination_port(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
data = {'flow_classifier': {
'logical_destination_port': _uuid(),
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.put,
_get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id,
fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_flow_classifier_update_ethertype(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
data = {'flow_classifier': {
'ethertype': None,
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.put,
_get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id,
fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_flow_classifier_update_protocol(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
data = {'flow_classifier': {
'protococol': None,
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.put,
_get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id,
fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_flow_classifier_update_l7_parameters(self):
tenant_id = _uuid()
flowclassifier_id = _uuid()
data = {'flow_classifier': {
'l7_parameters': {},
'tenant_id': tenant_id, 'project_id': tenant_id,
}}
self.assertRaises(
webtest.app.AppError,
self.api.put,
_get_path(FLOW_CLASSIFIER_PATH, id=flowclassifier_id,
fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
def test_flow_classifier_delete(self):
self._test_entity_delete('flow_classifier')
| true | true |
f716a0394e3827031c5c048b941822b24f227531 | 7,848 | py | Python | research/compression/entropy_coder/core/entropy_coder_train.py | jdavidagudelo/tensorflow-models | 6f019beec73b01861363bf717706e27f4210b979 | [
"Apache-2.0"
] | 1 | 2021-05-17T01:42:29.000Z | 2021-05-17T01:42:29.000Z | research/compression/entropy_coder/core/entropy_coder_train.py | jdavidagudelo/tensorflow-models | 6f019beec73b01861363bf717706e27f4210b979 | [
"Apache-2.0"
] | null | null | null | research/compression/entropy_coder/core/entropy_coder_train.py | jdavidagudelo/tensorflow-models | 6f019beec73b01861363bf717706e27f4210b979 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 The TensorFlow 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.
# ==============================================================================
"""Train an entropy coder model."""
import time
import tensorflow as tf
from research.compression.entropy_coder.core import code_loader
from research.compression.entropy_coder.core import config_helper
# pylint: enable=unused-import
from research.compression.entropy_coder.model import model_factory
FLAGS = tf.app.flags.FLAGS
# Hardware resources configuration.
tf.app.flags.DEFINE_string('master', '',
"""Name of the TensorFlow master to use.""")
tf.app.flags.DEFINE_string('train_dir', None,
"""Directory where to write event logs.""")
tf.app.flags.DEFINE_integer('task', None,
"""Task id of the replica running the training.""")
tf.app.flags.DEFINE_integer('ps_tasks', 0, """Number of tasks in the ps job.
If 0 no ps job is used.""")
# Model selection and configuration.
tf.app.flags.DEFINE_string('model', None, """Underlying encoder model.""")
tf.app.flags.DEFINE_string('model_config', None,
"""Model config protobuf given as text file.""")
# Training data and parameters configuration.
tf.app.flags.DEFINE_string('input_config', None,
"""Path to the training input config file.""")
tf.app.flags.DEFINE_string('train_config', None,
"""Path to the training experiment config file.""")
def train():
if FLAGS.train_dir is None:
raise ValueError('Parameter train_dir must be provided')
if FLAGS.task is None:
raise ValueError('Parameter task must be provided')
if FLAGS.model is None:
raise ValueError('Parameter model must be provided')
input_config_string = config_helper.GetConfigString(FLAGS.input_config)
input_config = config_helper.InputConfig(input_config_string)
# Training parameters.
train_config_string = config_helper.GetConfigString(FLAGS.train_config)
train_config = config_helper.TrainConfig(train_config_string)
batch_size = train_config.batch_size
initial_learning_rate = train_config.learning_rate
decay_rate = train_config.decay_rate
samples_per_decay = train_config.samples_per_decay
# Parameters for learning-rate decay.
# The formula is decay_rate ** floor(steps / decay_steps).
decay_steps = samples_per_decay / batch_size
decay_steps = max(decay_steps, 1)
first_code = code_loader.ReadFirstCode(input_config.data)
first_code_height = (
first_code.features.feature['code_shape'].int64_list.value[0])
first_code_width = (
first_code.features.feature['code_shape'].int64_list.value[1])
max_bit_depth = (
first_code.features.feature['code_shape'].int64_list.value[2])
print('Maximum code depth: {}'.format(max_bit_depth))
with tf.Graph().as_default():
ps_ops = ["Variable", "VariableV2", "AutoReloadVariable", "VarHandleOp"]
with tf.device(tf.train.replica_device_setter(FLAGS.ps_tasks,
ps_ops=ps_ops)):
codes = code_loader.LoadBinaryCode(
input_config=input_config,
batch_size=batch_size)
if input_config.unique_code_size:
print('Input code size: {} x {}'.format(first_code_height,
first_code_width))
codes.set_shape(
[batch_size, first_code_height, first_code_width, max_bit_depth])
else:
codes.set_shape([batch_size, None, None, max_bit_depth])
codes_effective_shape = tf.shape(codes)
global_step = tf.contrib.framework.create_global_step()
# Apply learning-rate decay.
learning_rate = tf.train.exponential_decay(
learning_rate=initial_learning_rate,
global_step=global_step,
decay_steps=decay_steps,
decay_rate=decay_rate,
staircase=True)
tf.summary.scalar('Learning Rate', learning_rate)
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate,
epsilon=1.0)
# Create the entropy coder model.
model = model_factory.GetModelRegistry().CreateModel(FLAGS.model)
model_config_string = config_helper.GetConfigString(FLAGS.model_config)
model.Initialize(global_step, optimizer, model_config_string)
model.BuildGraph(codes)
summary_op = tf.summary.merge_all()
# Verify that the model can actually be trained.
if model.train_op is None:
raise ValueError('Input model {} is not trainable'.format(FLAGS.model))
# We disable the summary thread run by Supervisor class by passing
# summary_op=None. We still pass save_summaries_secs because it is used by
# the global step counter thread.
is_chief = (FLAGS.task == 0)
sv = tf.train.Supervisor(logdir=FLAGS.train_dir,
is_chief=is_chief,
global_step=global_step,
# saver=model.saver,
summary_op=None,
save_summaries_secs=120,
save_model_secs=600,
recovery_wait_secs=30)
sess = sv.PrepareSession(FLAGS.master)
sv.StartQueueRunners(sess)
step = sess.run(global_step)
print('Trainer initial step: {}.'.format(step))
# Once everything has been setup properly, save the configs.
if is_chief:
config_helper.SaveConfig(FLAGS.train_dir, 'input_config.json',
input_config_string)
config_helper.SaveConfig(FLAGS.train_dir, 'model_config.json',
model_config_string)
config_helper.SaveConfig(FLAGS.train_dir, 'train_config.json',
train_config_string)
# Train the model.
next_summary_time = time.time()
while not sv.ShouldStop():
feed_dict = None
# Once in a while, update the summaries on the chief worker.
if is_chief and next_summary_time < time.time():
summary_str = sess.run(summary_op, feed_dict=feed_dict)
sv.SummaryComputed(sess, summary_str)
next_summary_time = time.time() + sv.save_summaries_secs
else:
tf_tensors = {
'train': model.train_op,
'code_length': model.average_code_length
}
np_tensors = sess.run(tf_tensors, feed_dict=feed_dict)
print(np_tensors['code_length'])
sv.Stop()
def main(argv=None): # pylint: disable=unused-argument
train()
if __name__ == '__main__':
tf.app.run()
| 43.120879 | 87 | 0.605377 |
import time
import tensorflow as tf
from research.compression.entropy_coder.core import code_loader
from research.compression.entropy_coder.core import config_helper
from research.compression.entropy_coder.model import model_factory
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('master', '',
"""Name of the TensorFlow master to use.""")
tf.app.flags.DEFINE_string('train_dir', None,
"""Directory where to write event logs.""")
tf.app.flags.DEFINE_integer('task', None,
"""Task id of the replica running the training.""")
tf.app.flags.DEFINE_integer('ps_tasks', 0, """Number of tasks in the ps job.
If 0 no ps job is used.""")
tf.app.flags.DEFINE_string('model', None, """Underlying encoder model.""")
tf.app.flags.DEFINE_string('model_config', None,
"""Model config protobuf given as text file.""")
tf.app.flags.DEFINE_string('input_config', None,
"""Path to the training input config file.""")
tf.app.flags.DEFINE_string('train_config', None,
"""Path to the training experiment config file.""")
def train():
if FLAGS.train_dir is None:
raise ValueError('Parameter train_dir must be provided')
if FLAGS.task is None:
raise ValueError('Parameter task must be provided')
if FLAGS.model is None:
raise ValueError('Parameter model must be provided')
input_config_string = config_helper.GetConfigString(FLAGS.input_config)
input_config = config_helper.InputConfig(input_config_string)
train_config_string = config_helper.GetConfigString(FLAGS.train_config)
train_config = config_helper.TrainConfig(train_config_string)
batch_size = train_config.batch_size
initial_learning_rate = train_config.learning_rate
decay_rate = train_config.decay_rate
samples_per_decay = train_config.samples_per_decay
decay_steps = samples_per_decay / batch_size
decay_steps = max(decay_steps, 1)
first_code = code_loader.ReadFirstCode(input_config.data)
first_code_height = (
first_code.features.feature['code_shape'].int64_list.value[0])
first_code_width = (
first_code.features.feature['code_shape'].int64_list.value[1])
max_bit_depth = (
first_code.features.feature['code_shape'].int64_list.value[2])
print('Maximum code depth: {}'.format(max_bit_depth))
with tf.Graph().as_default():
ps_ops = ["Variable", "VariableV2", "AutoReloadVariable", "VarHandleOp"]
with tf.device(tf.train.replica_device_setter(FLAGS.ps_tasks,
ps_ops=ps_ops)):
codes = code_loader.LoadBinaryCode(
input_config=input_config,
batch_size=batch_size)
if input_config.unique_code_size:
print('Input code size: {} x {}'.format(first_code_height,
first_code_width))
codes.set_shape(
[batch_size, first_code_height, first_code_width, max_bit_depth])
else:
codes.set_shape([batch_size, None, None, max_bit_depth])
codes_effective_shape = tf.shape(codes)
global_step = tf.contrib.framework.create_global_step()
learning_rate = tf.train.exponential_decay(
learning_rate=initial_learning_rate,
global_step=global_step,
decay_steps=decay_steps,
decay_rate=decay_rate,
staircase=True)
tf.summary.scalar('Learning Rate', learning_rate)
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate,
epsilon=1.0)
model = model_factory.GetModelRegistry().CreateModel(FLAGS.model)
model_config_string = config_helper.GetConfigString(FLAGS.model_config)
model.Initialize(global_step, optimizer, model_config_string)
model.BuildGraph(codes)
summary_op = tf.summary.merge_all()
if model.train_op is None:
raise ValueError('Input model {} is not trainable'.format(FLAGS.model))
is_chief = (FLAGS.task == 0)
sv = tf.train.Supervisor(logdir=FLAGS.train_dir,
is_chief=is_chief,
global_step=global_step,
summary_op=None,
save_summaries_secs=120,
save_model_secs=600,
recovery_wait_secs=30)
sess = sv.PrepareSession(FLAGS.master)
sv.StartQueueRunners(sess)
step = sess.run(global_step)
print('Trainer initial step: {}.'.format(step))
if is_chief:
config_helper.SaveConfig(FLAGS.train_dir, 'input_config.json',
input_config_string)
config_helper.SaveConfig(FLAGS.train_dir, 'model_config.json',
model_config_string)
config_helper.SaveConfig(FLAGS.train_dir, 'train_config.json',
train_config_string)
next_summary_time = time.time()
while not sv.ShouldStop():
feed_dict = None
if is_chief and next_summary_time < time.time():
summary_str = sess.run(summary_op, feed_dict=feed_dict)
sv.SummaryComputed(sess, summary_str)
next_summary_time = time.time() + sv.save_summaries_secs
else:
tf_tensors = {
'train': model.train_op,
'code_length': model.average_code_length
}
np_tensors = sess.run(tf_tensors, feed_dict=feed_dict)
print(np_tensors['code_length'])
sv.Stop()
def main(argv=None):
train()
if __name__ == '__main__':
tf.app.run()
| true | true |
f716a0a3d08f1b810ae639fdca8086b153407a06 | 260,784 | py | Python | instances/passenger_demand/pas-20210422-1717-int14000000000000001e/48.py | LHcau/scheduling-shared-passenger-and-freight-transport-on-a-fixed-infrastructure | bba1e6af5bc8d9deaa2dc3b83f6fe9ddf15d2a11 | [
"BSD-3-Clause"
] | null | null | null | instances/passenger_demand/pas-20210422-1717-int14000000000000001e/48.py | LHcau/scheduling-shared-passenger-and-freight-transport-on-a-fixed-infrastructure | bba1e6af5bc8d9deaa2dc3b83f6fe9ddf15d2a11 | [
"BSD-3-Clause"
] | null | null | null | instances/passenger_demand/pas-20210422-1717-int14000000000000001e/48.py | LHcau/scheduling-shared-passenger-and-freight-transport-on-a-fixed-infrastructure | bba1e6af5bc8d9deaa2dc3b83f6fe9ddf15d2a11 | [
"BSD-3-Clause"
] | null | null | null |
"""
PASSENGERS
"""
numPassengers = 26645
passenger_arriving = (
(9, 10, 5, 5, 3, 2, 2, 3, 3, 1, 1, 0, 0, 6, 9, 0, 8, 12, 3, 4, 1, 0, 2, 2, 2, 0), # 0
(5, 10, 9, 11, 6, 2, 0, 5, 1, 1, 1, 0, 0, 11, 5, 5, 6, 6, 1, 2, 2, 1, 4, 0, 0, 0), # 1
(7, 9, 3, 3, 3, 3, 3, 5, 4, 4, 2, 0, 0, 9, 6, 5, 7, 9, 1, 5, 4, 2, 2, 2, 2, 0), # 2
(5, 10, 11, 9, 12, 3, 6, 6, 4, 1, 0, 0, 0, 6, 10, 2, 8, 8, 8, 2, 2, 3, 2, 2, 0, 0), # 3
(11, 9, 6, 8, 7, 3, 4, 5, 4, 1, 0, 0, 0, 8, 12, 3, 5, 10, 3, 0, 4, 1, 1, 0, 3, 0), # 4
(11, 9, 9, 13, 3, 3, 7, 7, 4, 2, 0, 2, 0, 7, 13, 7, 8, 9, 5, 5, 1, 2, 5, 1, 1, 0), # 5
(12, 13, 8, 8, 8, 4, 1, 4, 3, 4, 3, 2, 0, 9, 8, 7, 9, 6, 2, 7, 3, 6, 3, 0, 1, 0), # 6
(12, 8, 8, 11, 13, 3, 3, 1, 4, 1, 1, 0, 0, 12, 7, 11, 4, 9, 4, 3, 2, 3, 2, 1, 1, 0), # 7
(14, 11, 17, 10, 8, 3, 3, 2, 3, 1, 3, 0, 0, 11, 7, 9, 6, 11, 2, 7, 4, 1, 3, 1, 0, 0), # 8
(11, 10, 7, 9, 8, 8, 7, 5, 5, 0, 3, 3, 0, 17, 12, 9, 6, 10, 9, 4, 2, 3, 2, 4, 1, 0), # 9
(10, 12, 11, 10, 7, 3, 6, 3, 7, 3, 2, 2, 0, 18, 13, 12, 9, 12, 6, 2, 3, 6, 2, 3, 2, 0), # 10
(15, 11, 10, 11, 12, 7, 4, 3, 3, 1, 3, 2, 0, 10, 5, 13, 8, 12, 6, 6, 3, 1, 1, 4, 1, 0), # 11
(11, 16, 10, 11, 9, 2, 7, 4, 3, 3, 1, 2, 0, 17, 8, 9, 5, 8, 5, 5, 0, 6, 4, 1, 1, 0), # 12
(11, 17, 10, 10, 6, 7, 4, 2, 6, 1, 3, 1, 0, 14, 12, 4, 3, 5, 6, 4, 5, 3, 7, 3, 1, 0), # 13
(12, 21, 12, 12, 11, 7, 4, 4, 4, 3, 5, 0, 0, 10, 12, 6, 7, 12, 6, 7, 1, 4, 4, 0, 0, 0), # 14
(6, 12, 9, 21, 12, 3, 3, 4, 6, 2, 1, 2, 0, 9, 19, 8, 3, 6, 7, 7, 6, 8, 0, 0, 2, 0), # 15
(7, 12, 10, 13, 12, 7, 5, 4, 4, 3, 2, 3, 0, 12, 8, 4, 6, 14, 10, 4, 2, 4, 4, 1, 1, 0), # 16
(15, 15, 18, 15, 7, 9, 4, 3, 5, 6, 3, 1, 0, 12, 10, 7, 11, 10, 6, 2, 5, 7, 3, 1, 0, 0), # 17
(14, 14, 16, 17, 15, 4, 6, 4, 4, 1, 2, 1, 0, 16, 17, 7, 4, 7, 7, 9, 5, 6, 4, 2, 2, 0), # 18
(23, 16, 12, 13, 6, 6, 6, 3, 7, 0, 1, 1, 0, 17, 18, 11, 11, 15, 13, 6, 3, 5, 6, 4, 2, 0), # 19
(12, 12, 13, 13, 10, 7, 6, 4, 6, 2, 2, 1, 0, 10, 17, 13, 7, 11, 7, 5, 5, 6, 5, 4, 1, 0), # 20
(16, 18, 12, 13, 8, 6, 2, 6, 11, 2, 1, 1, 0, 7, 12, 10, 10, 16, 4, 4, 7, 4, 3, 1, 2, 0), # 21
(14, 13, 8, 11, 7, 7, 2, 3, 9, 4, 2, 0, 0, 18, 9, 6, 12, 12, 7, 3, 3, 3, 8, 0, 3, 0), # 22
(16, 9, 10, 8, 14, 9, 6, 2, 9, 3, 2, 1, 0, 16, 21, 9, 4, 5, 7, 6, 6, 1, 4, 1, 1, 0), # 23
(11, 13, 11, 10, 6, 4, 10, 6, 6, 1, 5, 1, 0, 18, 17, 16, 3, 12, 13, 8, 2, 4, 1, 4, 1, 0), # 24
(11, 16, 17, 7, 12, 5, 8, 5, 6, 2, 0, 2, 0, 10, 14, 10, 7, 20, 5, 12, 4, 3, 3, 3, 2, 0), # 25
(18, 15, 18, 8, 12, 4, 14, 2, 7, 1, 1, 1, 0, 9, 10, 10, 9, 16, 3, 4, 2, 4, 4, 1, 1, 0), # 26
(9, 9, 8, 9, 5, 7, 11, 5, 8, 2, 3, 1, 0, 10, 13, 9, 8, 12, 13, 3, 1, 3, 4, 1, 1, 0), # 27
(18, 14, 17, 16, 17, 2, 7, 7, 7, 7, 2, 2, 0, 20, 13, 12, 8, 7, 1, 4, 2, 6, 1, 2, 2, 0), # 28
(16, 16, 9, 15, 6, 4, 4, 7, 5, 3, 8, 1, 0, 12, 14, 11, 9, 11, 7, 2, 7, 2, 7, 6, 0, 0), # 29
(13, 12, 17, 14, 12, 7, 9, 4, 2, 1, 3, 0, 0, 22, 14, 9, 9, 20, 6, 9, 3, 11, 3, 0, 2, 0), # 30
(17, 9, 10, 22, 14, 6, 4, 2, 3, 5, 3, 0, 0, 19, 13, 9, 7, 15, 3, 2, 3, 5, 2, 1, 1, 0), # 31
(12, 14, 16, 12, 11, 11, 5, 5, 6, 1, 2, 1, 0, 15, 12, 13, 7, 8, 13, 4, 5, 4, 7, 1, 2, 0), # 32
(11, 16, 15, 17, 3, 7, 1, 6, 6, 1, 4, 1, 0, 18, 10, 9, 8, 14, 2, 3, 3, 5, 8, 1, 1, 0), # 33
(8, 11, 12, 15, 18, 9, 4, 6, 5, 2, 4, 0, 0, 13, 13, 5, 4, 11, 7, 6, 5, 2, 2, 1, 0, 0), # 34
(23, 16, 11, 5, 13, 3, 4, 4, 4, 3, 3, 1, 0, 13, 12, 8, 6, 9, 7, 4, 5, 6, 6, 6, 1, 0), # 35
(13, 12, 17, 16, 14, 3, 4, 4, 5, 3, 1, 0, 0, 11, 5, 6, 11, 6, 9, 6, 3, 6, 5, 1, 1, 0), # 36
(15, 9, 13, 12, 8, 5, 9, 8, 8, 1, 1, 1, 0, 22, 18, 11, 7, 14, 11, 8, 2, 5, 7, 3, 0, 0), # 37
(15, 14, 16, 13, 8, 4, 4, 4, 4, 6, 1, 1, 0, 13, 8, 16, 3, 4, 7, 7, 3, 7, 6, 2, 1, 0), # 38
(16, 17, 8, 14, 9, 4, 4, 3, 6, 0, 4, 0, 0, 17, 15, 11, 7, 13, 6, 4, 3, 5, 6, 0, 0, 0), # 39
(11, 13, 11, 7, 9, 3, 1, 6, 8, 3, 3, 0, 0, 15, 7, 6, 12, 11, 6, 5, 7, 5, 6, 3, 1, 0), # 40
(15, 11, 11, 7, 10, 5, 6, 3, 8, 5, 1, 1, 0, 9, 9, 13, 7, 9, 12, 6, 3, 3, 3, 3, 1, 0), # 41
(21, 12, 14, 12, 7, 0, 4, 5, 4, 0, 0, 2, 0, 22, 14, 7, 4, 14, 13, 6, 5, 7, 6, 1, 0, 0), # 42
(17, 16, 8, 12, 13, 1, 7, 4, 6, 1, 2, 0, 0, 15, 5, 9, 8, 13, 4, 9, 4, 1, 3, 2, 1, 0), # 43
(11, 17, 16, 10, 7, 5, 7, 4, 4, 3, 1, 4, 0, 18, 14, 8, 8, 15, 7, 5, 7, 4, 4, 0, 3, 0), # 44
(12, 14, 12, 14, 10, 4, 4, 4, 3, 2, 1, 2, 0, 13, 13, 13, 8, 6, 5, 5, 2, 4, 2, 4, 1, 0), # 45
(18, 21, 10, 16, 12, 4, 4, 6, 6, 3, 1, 0, 0, 8, 5, 7, 7, 13, 8, 5, 4, 10, 2, 0, 3, 0), # 46
(7, 10, 11, 16, 9, 8, 5, 3, 8, 0, 3, 1, 0, 20, 17, 8, 3, 7, 12, 6, 4, 7, 4, 2, 3, 0), # 47
(19, 12, 8, 5, 7, 4, 3, 3, 5, 3, 1, 1, 0, 9, 7, 12, 11, 19, 9, 8, 4, 8, 2, 3, 1, 0), # 48
(9, 7, 14, 20, 17, 2, 7, 3, 4, 3, 4, 3, 0, 13, 11, 10, 9, 13, 7, 4, 3, 3, 6, 1, 1, 0), # 49
(15, 21, 13, 12, 7, 6, 7, 4, 4, 1, 1, 2, 0, 18, 12, 11, 8, 13, 10, 7, 2, 4, 6, 3, 2, 0), # 50
(11, 9, 13, 15, 9, 2, 6, 2, 4, 7, 1, 2, 0, 21, 18, 9, 9, 14, 5, 5, 1, 5, 3, 3, 3, 0), # 51
(15, 15, 11, 10, 8, 4, 3, 5, 6, 1, 1, 1, 0, 7, 7, 12, 11, 14, 5, 5, 2, 4, 0, 1, 3, 0), # 52
(11, 11, 8, 13, 9, 4, 5, 5, 2, 3, 3, 1, 0, 13, 15, 8, 4, 16, 5, 6, 6, 5, 3, 2, 1, 0), # 53
(17, 18, 6, 15, 9, 4, 5, 6, 10, 4, 2, 2, 0, 21, 17, 14, 8, 16, 6, 4, 6, 6, 3, 1, 1, 0), # 54
(10, 12, 18, 10, 11, 7, 1, 7, 7, 3, 1, 0, 0, 14, 7, 15, 7, 7, 7, 5, 3, 1, 10, 0, 0, 0), # 55
(6, 12, 13, 14, 15, 2, 4, 4, 4, 1, 3, 1, 0, 21, 16, 11, 6, 15, 4, 7, 7, 5, 4, 4, 1, 0), # 56
(6, 16, 19, 17, 4, 4, 7, 6, 8, 2, 0, 0, 0, 19, 14, 6, 2, 13, 10, 6, 4, 4, 0, 2, 1, 0), # 57
(15, 13, 15, 19, 8, 3, 6, 6, 5, 0, 2, 2, 0, 14, 9, 8, 6, 14, 3, 9, 6, 7, 4, 4, 1, 0), # 58
(13, 4, 10, 14, 7, 4, 7, 3, 7, 6, 0, 2, 0, 10, 12, 9, 10, 11, 6, 3, 5, 7, 4, 2, 0, 0), # 59
(14, 24, 6, 17, 14, 6, 4, 1, 1, 2, 1, 3, 0, 14, 10, 12, 12, 19, 5, 9, 1, 6, 6, 1, 0, 0), # 60
(13, 20, 9, 10, 11, 7, 5, 9, 9, 1, 1, 2, 0, 16, 12, 11, 7, 16, 13, 3, 6, 6, 4, 0, 1, 0), # 61
(17, 7, 12, 12, 8, 5, 5, 4, 6, 3, 1, 0, 0, 13, 8, 10, 10, 11, 4, 4, 5, 3, 6, 4, 3, 0), # 62
(8, 14, 19, 12, 9, 5, 5, 5, 2, 0, 7, 0, 0, 12, 13, 3, 7, 10, 5, 1, 4, 3, 1, 1, 0, 0), # 63
(16, 10, 11, 8, 12, 2, 7, 8, 5, 1, 4, 0, 0, 14, 16, 8, 11, 14, 7, 5, 4, 8, 4, 1, 1, 0), # 64
(7, 13, 15, 14, 9, 2, 4, 4, 3, 1, 2, 0, 0, 16, 12, 19, 4, 13, 6, 5, 1, 11, 4, 1, 1, 0), # 65
(18, 14, 11, 11, 11, 2, 0, 5, 6, 6, 1, 1, 0, 15, 10, 7, 8, 14, 10, 2, 2, 5, 4, 0, 1, 0), # 66
(15, 17, 9, 12, 15, 4, 7, 7, 8, 0, 2, 3, 0, 17, 10, 6, 11, 9, 4, 12, 2, 1, 8, 3, 0, 0), # 67
(10, 11, 6, 11, 12, 4, 7, 4, 8, 2, 2, 1, 0, 10, 8, 9, 7, 11, 3, 8, 3, 4, 4, 5, 0, 0), # 68
(14, 10, 9, 16, 6, 4, 8, 7, 3, 1, 0, 4, 0, 12, 10, 9, 5, 12, 7, 9, 3, 4, 4, 2, 0, 0), # 69
(19, 11, 8, 18, 13, 6, 7, 4, 4, 0, 5, 1, 0, 16, 8, 10, 6, 11, 6, 6, 2, 6, 4, 1, 2, 0), # 70
(17, 6, 13, 11, 15, 9, 2, 1, 9, 4, 2, 0, 0, 11, 10, 8, 4, 7, 5, 9, 4, 6, 5, 0, 0, 0), # 71
(15, 9, 19, 17, 10, 5, 9, 6, 7, 3, 1, 0, 0, 16, 11, 12, 17, 9, 2, 8, 7, 7, 4, 2, 3, 0), # 72
(17, 11, 11, 15, 9, 6, 3, 7, 9, 2, 2, 0, 0, 16, 9, 5, 5, 16, 6, 7, 5, 2, 1, 2, 0, 0), # 73
(9, 8, 8, 14, 12, 11, 3, 2, 3, 3, 0, 0, 0, 18, 17, 13, 4, 13, 5, 5, 1, 5, 4, 4, 0, 0), # 74
(11, 13, 14, 11, 13, 7, 6, 3, 7, 3, 2, 1, 0, 14, 14, 9, 9, 7, 5, 6, 1, 8, 4, 3, 1, 0), # 75
(19, 12, 16, 10, 11, 5, 8, 3, 3, 6, 1, 0, 0, 7, 12, 10, 8, 19, 9, 7, 2, 5, 6, 4, 0, 0), # 76
(10, 8, 14, 12, 13, 5, 9, 5, 5, 1, 3, 0, 0, 18, 21, 9, 11, 6, 2, 2, 4, 8, 2, 3, 1, 0), # 77
(12, 14, 6, 17, 15, 6, 4, 4, 6, 2, 2, 0, 0, 11, 12, 9, 5, 11, 6, 4, 2, 5, 7, 0, 0, 0), # 78
(12, 8, 10, 13, 10, 6, 4, 6, 6, 3, 2, 0, 0, 16, 7, 7, 8, 5, 4, 5, 6, 9, 2, 1, 0, 0), # 79
(17, 17, 12, 9, 15, 8, 2, 3, 5, 1, 1, 1, 0, 10, 15, 13, 5, 13, 4, 6, 4, 7, 3, 1, 0, 0), # 80
(13, 11, 12, 8, 12, 6, 8, 6, 8, 2, 3, 0, 0, 19, 9, 12, 10, 12, 4, 5, 2, 5, 1, 1, 1, 0), # 81
(13, 13, 7, 15, 11, 7, 6, 6, 5, 2, 0, 7, 0, 18, 14, 7, 12, 7, 3, 3, 8, 3, 6, 3, 2, 0), # 82
(12, 6, 13, 6, 6, 5, 8, 3, 6, 4, 2, 0, 0, 17, 9, 8, 8, 12, 7, 5, 3, 7, 4, 2, 0, 0), # 83
(11, 13, 14, 16, 11, 7, 8, 7, 6, 2, 1, 1, 0, 7, 16, 8, 5, 5, 3, 6, 4, 5, 3, 2, 0, 0), # 84
(12, 14, 21, 14, 14, 7, 6, 3, 8, 4, 1, 1, 0, 9, 15, 10, 2, 13, 3, 6, 4, 6, 3, 3, 0, 0), # 85
(16, 11, 11, 11, 15, 4, 4, 4, 6, 1, 2, 1, 0, 11, 7, 8, 11, 10, 8, 3, 3, 5, 8, 2, 0, 0), # 86
(17, 7, 11, 12, 6, 3, 4, 2, 5, 2, 1, 0, 0, 11, 16, 8, 10, 7, 8, 5, 6, 7, 9, 1, 0, 0), # 87
(11, 17, 10, 9, 10, 6, 6, 2, 3, 4, 5, 0, 0, 21, 12, 9, 10, 13, 1, 2, 5, 6, 5, 2, 1, 0), # 88
(15, 9, 14, 15, 7, 4, 4, 5, 4, 1, 3, 1, 0, 18, 14, 9, 4, 9, 6, 9, 4, 5, 4, 2, 0, 0), # 89
(13, 8, 9, 11, 11, 9, 7, 2, 3, 2, 0, 0, 0, 13, 13, 7, 3, 6, 9, 4, 4, 6, 1, 3, 1, 0), # 90
(18, 13, 7, 14, 9, 4, 4, 0, 8, 2, 2, 0, 0, 14, 10, 11, 5, 7, 4, 10, 3, 2, 2, 5, 2, 0), # 91
(12, 12, 7, 13, 13, 7, 1, 8, 5, 4, 5, 1, 0, 14, 17, 8, 8, 11, 4, 5, 3, 5, 5, 2, 1, 0), # 92
(11, 5, 12, 12, 4, 4, 3, 4, 10, 3, 1, 0, 0, 13, 10, 10, 6, 21, 6, 4, 3, 2, 3, 2, 1, 0), # 93
(14, 13, 12, 13, 13, 2, 4, 7, 3, 2, 2, 1, 0, 12, 13, 4, 7, 15, 6, 5, 1, 6, 5, 0, 0, 0), # 94
(9, 19, 11, 11, 7, 5, 2, 4, 3, 4, 0, 3, 0, 12, 17, 7, 11, 11, 6, 5, 2, 3, 3, 0, 2, 0), # 95
(9, 8, 14, 10, 7, 6, 8, 7, 9, 3, 1, 2, 0, 10, 10, 9, 8, 7, 6, 3, 9, 9, 5, 5, 0, 0), # 96
(13, 10, 8, 14, 10, 4, 2, 10, 5, 2, 2, 3, 0, 11, 3, 8, 8, 12, 7, 5, 1, 8, 1, 2, 1, 0), # 97
(17, 8, 12, 12, 12, 7, 4, 2, 4, 4, 0, 2, 0, 8, 9, 5, 6, 10, 5, 3, 1, 7, 4, 4, 2, 0), # 98
(14, 10, 11, 15, 12, 4, 5, 3, 4, 1, 0, 2, 0, 14, 13, 13, 7, 9, 4, 4, 0, 2, 6, 4, 2, 0), # 99
(9, 9, 11, 10, 11, 5, 2, 5, 8, 1, 0, 5, 0, 12, 8, 12, 8, 12, 2, 7, 3, 10, 4, 4, 1, 0), # 100
(16, 11, 10, 7, 12, 3, 2, 3, 6, 1, 1, 1, 0, 13, 12, 4, 5, 10, 9, 6, 3, 6, 4, 2, 0, 0), # 101
(17, 12, 8, 14, 5, 6, 5, 5, 4, 2, 1, 0, 0, 15, 7, 5, 12, 9, 6, 2, 5, 3, 7, 3, 3, 0), # 102
(14, 12, 8, 12, 8, 5, 4, 5, 7, 2, 1, 0, 0, 20, 14, 10, 8, 6, 4, 4, 2, 8, 3, 0, 1, 0), # 103
(14, 6, 11, 14, 11, 4, 4, 5, 5, 3, 1, 1, 0, 10, 6, 14, 6, 8, 9, 4, 5, 2, 3, 1, 0, 0), # 104
(16, 11, 9, 13, 12, 5, 8, 5, 8, 2, 2, 0, 0, 17, 10, 15, 8, 10, 3, 6, 1, 6, 4, 3, 0, 0), # 105
(8, 12, 13, 10, 6, 5, 5, 2, 8, 2, 1, 1, 0, 19, 14, 7, 4, 12, 4, 3, 4, 5, 3, 1, 1, 0), # 106
(11, 12, 16, 5, 3, 9, 3, 2, 7, 2, 0, 2, 0, 15, 13, 3, 3, 8, 5, 7, 4, 6, 4, 3, 1, 0), # 107
(12, 9, 7, 9, 7, 5, 4, 3, 2, 1, 2, 3, 0, 24, 10, 11, 9, 9, 5, 6, 2, 6, 4, 1, 4, 0), # 108
(10, 15, 14, 10, 7, 7, 9, 5, 8, 2, 1, 2, 0, 17, 9, 6, 5, 9, 9, 3, 5, 9, 1, 3, 0, 0), # 109
(15, 7, 10, 8, 8, 4, 4, 4, 5, 0, 0, 0, 0, 13, 9, 13, 9, 9, 6, 5, 5, 5, 4, 0, 2, 0), # 110
(19, 13, 9, 13, 16, 2, 2, 2, 9, 4, 1, 0, 0, 8, 8, 11, 4, 10, 1, 5, 2, 6, 2, 3, 0, 0), # 111
(15, 18, 10, 14, 4, 2, 3, 2, 9, 0, 1, 0, 0, 12, 10, 6, 11, 7, 2, 2, 3, 10, 3, 2, 0, 0), # 112
(9, 7, 13, 17, 5, 2, 0, 1, 8, 1, 3, 1, 0, 18, 9, 11, 6, 9, 11, 2, 2, 5, 5, 4, 1, 0), # 113
(14, 4, 12, 10, 8, 7, 2, 2, 6, 2, 2, 0, 0, 13, 11, 9, 6, 10, 1, 6, 3, 4, 3, 2, 1, 0), # 114
(15, 7, 9, 13, 10, 3, 7, 1, 4, 0, 2, 2, 0, 11, 11, 15, 4, 12, 4, 3, 3, 4, 5, 4, 3, 0), # 115
(4, 14, 12, 13, 12, 6, 1, 6, 4, 0, 0, 1, 0, 11, 9, 9, 4, 7, 11, 3, 2, 4, 5, 1, 1, 0), # 116
(15, 9, 13, 10, 9, 6, 4, 3, 9, 5, 1, 2, 0, 10, 10, 9, 9, 12, 1, 3, 4, 5, 2, 1, 0, 0), # 117
(10, 10, 13, 17, 10, 6, 3, 3, 4, 1, 2, 2, 0, 12, 15, 10, 9, 5, 4, 3, 3, 6, 4, 0, 1, 0), # 118
(5, 8, 8, 7, 11, 3, 3, 5, 5, 2, 4, 1, 0, 10, 9, 11, 3, 11, 7, 3, 3, 3, 2, 4, 3, 0), # 119
(9, 9, 9, 9, 11, 4, 4, 2, 5, 3, 1, 0, 0, 11, 12, 7, 8, 8, 8, 3, 3, 8, 2, 4, 2, 0), # 120
(10, 15, 17, 15, 15, 5, 4, 4, 10, 3, 3, 0, 0, 17, 9, 6, 7, 4, 4, 2, 3, 4, 5, 4, 0, 0), # 121
(23, 10, 9, 8, 11, 4, 2, 3, 9, 1, 2, 0, 0, 17, 12, 6, 7, 8, 5, 2, 3, 8, 3, 3, 0, 0), # 122
(16, 5, 5, 14, 10, 3, 4, 1, 4, 3, 2, 1, 0, 17, 11, 11, 4, 9, 3, 5, 5, 3, 2, 4, 1, 0), # 123
(10, 19, 10, 15, 5, 6, 5, 2, 5, 2, 0, 0, 0, 7, 11, 6, 6, 10, 6, 2, 4, 7, 3, 0, 1, 0), # 124
(7, 8, 9, 6, 11, 4, 5, 2, 4, 3, 1, 0, 0, 13, 11, 11, 10, 11, 6, 7, 4, 5, 2, 4, 0, 0), # 125
(15, 13, 6, 12, 4, 5, 6, 2, 0, 3, 1, 1, 0, 19, 6, 6, 6, 8, 4, 4, 3, 4, 3, 1, 1, 0), # 126
(7, 8, 9, 11, 12, 4, 4, 2, 6, 2, 0, 0, 0, 8, 7, 4, 3, 9, 5, 2, 2, 6, 1, 5, 1, 0), # 127
(15, 12, 9, 9, 4, 7, 4, 2, 8, 5, 1, 2, 0, 11, 5, 9, 5, 11, 3, 4, 3, 3, 3, 4, 1, 0), # 128
(13, 9, 14, 9, 10, 5, 4, 1, 6, 1, 1, 1, 0, 14, 10, 6, 5, 10, 9, 5, 2, 1, 8, 0, 0, 0), # 129
(8, 12, 10, 11, 11, 5, 2, 6, 5, 1, 2, 1, 0, 8, 5, 5, 6, 9, 3, 7, 1, 2, 2, 3, 0, 0), # 130
(5, 6, 19, 7, 5, 2, 1, 4, 6, 1, 0, 0, 0, 9, 10, 9, 5, 8, 7, 3, 4, 3, 1, 2, 0, 0), # 131
(12, 10, 10, 5, 10, 6, 4, 7, 2, 1, 1, 0, 0, 17, 9, 5, 10, 13, 3, 2, 3, 1, 4, 7, 1, 0), # 132
(6, 10, 12, 11, 5, 4, 4, 4, 3, 1, 2, 3, 0, 9, 11, 6, 4, 14, 4, 6, 4, 10, 5, 3, 1, 0), # 133
(15, 8, 11, 16, 9, 5, 2, 3, 7, 2, 1, 1, 0, 11, 5, 12, 5, 12, 1, 5, 5, 5, 4, 2, 0, 0), # 134
(12, 11, 13, 13, 13, 2, 0, 2, 4, 2, 3, 0, 0, 10, 11, 7, 5, 15, 7, 6, 2, 3, 3, 1, 3, 0), # 135
(17, 7, 13, 15, 7, 6, 5, 2, 5, 1, 0, 1, 0, 10, 7, 8, 4, 14, 4, 4, 4, 5, 1, 2, 0, 0), # 136
(10, 11, 12, 12, 12, 5, 2, 3, 2, 2, 2, 0, 0, 18, 11, 8, 6, 12, 4, 7, 2, 6, 3, 3, 1, 0), # 137
(17, 4, 5, 12, 11, 3, 7, 2, 6, 6, 0, 1, 0, 11, 11, 6, 5, 8, 2, 3, 3, 7, 6, 3, 1, 0), # 138
(16, 12, 12, 8, 8, 6, 6, 3, 4, 1, 3, 1, 0, 13, 8, 8, 7, 9, 8, 2, 4, 4, 4, 5, 1, 0), # 139
(13, 9, 5, 14, 8, 5, 3, 5, 6, 2, 3, 1, 0, 6, 9, 7, 3, 11, 6, 5, 7, 5, 6, 3, 1, 0), # 140
(16, 6, 11, 8, 7, 6, 6, 2, 6, 0, 1, 1, 0, 14, 13, 8, 7, 10, 2, 4, 1, 5, 2, 1, 0, 0), # 141
(7, 5, 9, 11, 8, 5, 2, 6, 5, 2, 0, 2, 0, 12, 5, 4, 2, 10, 6, 5, 3, 3, 4, 0, 3, 0), # 142
(17, 14, 13, 10, 15, 4, 5, 5, 7, 0, 3, 4, 0, 13, 10, 6, 6, 15, 5, 6, 3, 2, 5, 1, 1, 0), # 143
(11, 11, 15, 13, 5, 4, 6, 6, 1, 4, 5, 0, 0, 11, 11, 7, 4, 11, 4, 4, 8, 7, 3, 1, 0, 0), # 144
(6, 13, 11, 4, 7, 6, 2, 7, 7, 1, 1, 1, 0, 9, 7, 13, 5, 8, 11, 6, 8, 5, 5, 2, 3, 0), # 145
(15, 12, 8, 10, 9, 5, 4, 5, 4, 0, 1, 1, 0, 11, 9, 13, 5, 11, 4, 5, 2, 3, 3, 1, 0, 0), # 146
(12, 12, 9, 8, 7, 4, 2, 5, 2, 1, 2, 1, 0, 16, 12, 6, 5, 9, 4, 3, 3, 4, 3, 2, 2, 0), # 147
(10, 9, 15, 12, 8, 7, 6, 6, 4, 2, 1, 2, 0, 14, 8, 9, 6, 8, 4, 4, 3, 2, 4, 2, 0, 0), # 148
(18, 13, 6, 15, 12, 4, 6, 2, 5, 4, 2, 0, 0, 10, 7, 8, 5, 8, 2, 3, 4, 7, 2, 3, 2, 0), # 149
(18, 3, 10, 10, 4, 5, 2, 3, 2, 1, 2, 0, 0, 9, 11, 4, 5, 18, 3, 7, 4, 6, 3, 2, 2, 0), # 150
(9, 5, 4, 3, 7, 5, 3, 3, 5, 0, 3, 0, 0, 10, 12, 8, 6, 10, 5, 1, 1, 1, 3, 1, 1, 0), # 151
(9, 3, 9, 12, 8, 3, 1, 1, 4, 3, 1, 0, 0, 14, 6, 3, 4, 9, 4, 3, 7, 3, 5, 0, 0, 0), # 152
(7, 5, 7, 12, 5, 6, 3, 3, 4, 3, 2, 0, 0, 10, 11, 5, 8, 9, 5, 2, 4, 7, 3, 2, 1, 0), # 153
(7, 10, 8, 8, 8, 3, 3, 0, 2, 2, 1, 1, 0, 9, 11, 10, 7, 14, 4, 4, 2, 3, 2, 1, 2, 0), # 154
(17, 6, 10, 13, 6, 1, 5, 2, 1, 0, 1, 0, 0, 14, 3, 5, 3, 7, 3, 2, 4, 5, 4, 1, 0, 0), # 155
(4, 5, 4, 8, 4, 6, 3, 4, 3, 0, 1, 1, 0, 10, 9, 5, 4, 7, 10, 3, 7, 4, 5, 1, 0, 0), # 156
(3, 7, 6, 5, 14, 6, 3, 1, 2, 2, 1, 2, 0, 13, 8, 6, 5, 11, 2, 4, 3, 3, 5, 4, 0, 0), # 157
(9, 5, 16, 8, 8, 4, 6, 4, 7, 3, 2, 0, 0, 5, 9, 1, 8, 12, 5, 4, 2, 3, 1, 4, 0, 0), # 158
(7, 6, 10, 5, 8, 5, 4, 5, 6, 1, 1, 0, 0, 6, 13, 7, 6, 7, 6, 3, 4, 4, 1, 1, 0, 0), # 159
(13, 5, 12, 5, 6, 4, 1, 5, 2, 2, 2, 0, 0, 11, 7, 6, 5, 7, 4, 1, 5, 5, 1, 1, 0, 0), # 160
(11, 6, 9, 7, 4, 2, 1, 6, 7, 2, 0, 0, 0, 6, 11, 7, 3, 6, 7, 7, 3, 6, 3, 2, 1, 0), # 161
(12, 10, 5, 6, 9, 6, 2, 5, 7, 1, 1, 0, 0, 10, 5, 10, 4, 13, 3, 1, 1, 7, 2, 3, 0, 0), # 162
(9, 6, 12, 8, 4, 3, 2, 3, 7, 2, 3, 0, 0, 12, 6, 7, 1, 5, 2, 3, 6, 3, 4, 2, 0, 0), # 163
(9, 5, 7, 9, 8, 3, 2, 3, 6, 1, 0, 0, 0, 9, 5, 4, 2, 8, 3, 3, 4, 5, 3, 1, 1, 0), # 164
(11, 8, 12, 7, 5, 4, 6, 1, 6, 3, 1, 1, 0, 6, 9, 3, 1, 4, 5, 2, 3, 2, 4, 0, 0, 0), # 165
(5, 3, 13, 9, 4, 2, 1, 4, 5, 1, 1, 0, 0, 12, 5, 5, 5, 9, 6, 2, 1, 2, 4, 1, 0, 0), # 166
(6, 7, 8, 8, 4, 3, 6, 5, 6, 1, 3, 0, 0, 13, 6, 10, 5, 5, 4, 1, 3, 5, 1, 0, 1, 0), # 167
(9, 5, 11, 11, 5, 3, 3, 3, 2, 2, 1, 2, 0, 8, 8, 6, 3, 8, 3, 3, 1, 1, 2, 1, 0, 0), # 168
(5, 5, 8, 10, 3, 2, 5, 3, 4, 0, 2, 0, 0, 13, 6, 4, 2, 6, 2, 2, 3, 0, 2, 3, 0, 0), # 169
(11, 5, 5, 6, 5, 2, 3, 3, 3, 0, 2, 1, 0, 9, 6, 9, 6, 7, 3, 3, 4, 6, 1, 2, 2, 0), # 170
(10, 4, 5, 4, 11, 4, 1, 4, 2, 1, 1, 1, 0, 7, 6, 11, 4, 13, 7, 0, 0, 2, 4, 0, 0, 0), # 171
(9, 2, 4, 6, 3, 5, 1, 1, 2, 3, 2, 0, 0, 4, 5, 4, 3, 8, 2, 2, 3, 1, 1, 3, 0, 0), # 172
(8, 6, 2, 4, 6, 3, 2, 0, 2, 1, 0, 0, 0, 8, 7, 9, 5, 4, 1, 3, 2, 3, 6, 0, 1, 0), # 173
(6, 5, 6, 6, 7, 3, 2, 0, 2, 2, 0, 0, 0, 8, 6, 3, 2, 6, 4, 0, 2, 4, 2, 0, 0, 0), # 174
(8, 3, 5, 7, 5, 1, 2, 0, 2, 2, 3, 1, 0, 6, 3, 1, 5, 5, 1, 0, 3, 2, 2, 2, 2, 0), # 175
(5, 5, 4, 7, 8, 4, 2, 1, 2, 1, 1, 2, 0, 5, 0, 2, 2, 5, 3, 1, 1, 2, 3, 0, 0, 0), # 176
(11, 4, 9, 6, 5, 3, 3, 2, 1, 2, 0, 1, 0, 8, 1, 4, 3, 5, 1, 3, 0, 3, 1, 0, 0, 0), # 177
(5, 4, 4, 3, 6, 2, 1, 3, 5, 1, 0, 2, 0, 9, 1, 1, 2, 4, 0, 2, 0, 5, 2, 2, 1, 0), # 178
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # 179
)
station_arriving_intensity = (
(7.029211809720476, 7.735403983570434, 7.29579652145751, 8.700534883408807, 7.776559850653457, 4.394116904852274, 5.804449861523481, 6.514446642171193, 8.52613868703521, 5.541221021731318, 5.887371229439844, 6.857081109628643, 7.117432297609708), # 0
(7.496058012827964, 8.246084971802663, 7.777485227862214, 9.275201954587263, 8.291486472463932, 4.684377017659578, 6.187256517769172, 6.943319212067992, 9.089143456866074, 5.90657296918801, 6.2763345903385845, 7.309703325140097, 7.587708306415797), # 1
(7.9614122125716245, 8.754739239247371, 8.257259199766379, 9.847582786530712, 8.804548163249642, 4.9734791603174235, 6.568545911144986, 7.370475347066188, 9.64990152962857, 6.270479285028765, 6.663752408286839, 7.760525712874277, 8.056110759493567), # 2
(8.423460910405188, 9.259348702711026, 8.733215217047796, 10.415406970544904, 9.313726346402664, 5.260276871619158, 6.946805098307138, 7.79422162049231, 10.206189225289531, 6.631495777796654, 7.0480877765583365, 8.207759958902646, 8.520781928755916), # 3
(8.880390607782374, 9.757895279000085, 9.203450059584252, 10.976404097935598, 9.81700244531509, 5.543623690358135, 7.320521135911843, 8.212864605672882, 10.75578286381579, 6.988178256034751, 7.4278037884268056, 8.64961774929667, 8.979864086115745), # 4
(9.330387806156915, 10.248360884921025, 9.666060507253526, 11.528303760008551, 10.312357883378994, 5.822373155327701, 7.688181080615314, 8.62471087593443, 11.296458765174183, 7.339082528286129, 7.801363537165986, 9.084310770127807, 9.43149950348596), # 5
(9.771639006982534, 10.728727437280302, 10.119143339933412, 12.068835548069513, 10.79777408398646, 6.09537880532121, 8.048271989073768, 9.028067004603484, 11.825993249331543, 7.682764403093862, 8.167230116049597, 9.510050707467531, 9.87383045277945), # 6
(10.202330711712957, 11.196976852884385, 10.56079533750169, 12.595729053424249, 11.271232470529577, 6.36149417913201, 8.39928091794342, 9.421239565006573, 12.342162636254702, 8.017779689001022, 8.523866618351377, 9.925049247387301, 10.304999205909127), # 7
(10.62064942180191, 11.651091048539739, 10.989113279836156, 13.1067138673785, 11.730714466400421, 6.619572815553446, 8.739694923880478, 9.802535130470215, 12.842743245910489, 8.342684194550685, 8.86973613734505, 10.327518075958585, 10.723148034787885), # 8
(11.02478163870312, 12.089051941052832, 11.402193946814586, 13.599519581238038, 12.174201494991074, 6.868468253378878, 9.068001063541168, 10.170260274320949, 13.325511398265744, 8.65603372828592, 9.20330176630435, 10.71566887925284, 11.126419211328628), # 9
(11.412913863870306, 12.508841447230123, 11.798134118314776, 14.071875786308604, 12.599674979693622, 7.107034031401651, 9.382686393581697, 10.522721569885295, 13.7882434132873, 8.956384098749801, 9.523026598503003, 11.087713343341534, 11.512955007444255), # 10
(11.783232598757209, 12.90844148387809, 12.175030574214501, 14.521512073895957, 13.005116343900148, 7.334123688415116, 9.682237970658283, 10.85822559048978, 14.228715610941991, 9.242291114485408, 9.82737372721475, 11.441863154296136, 11.880897695047656), # 11
(12.133924344817538, 13.285833967803178, 12.530980094391557, 14.946158035305858, 13.38850701100273, 7.5485907632126175, 9.965142851427137, 11.17507890946093, 14.644704311196652, 9.512310584035802, 10.114806245713309, 11.776329998188096, 12.22838954605175), # 12
(12.463175603505027, 13.639000815811869, 12.864079458723728, 15.343543261844063, 13.747828404393443, 7.749288794587514, 10.22988809254448, 11.471588100125276, 15.033985834018106, 9.764998315944066, 10.383787247272418, 12.08932556108889, 12.55357283236943), # 13
(12.769172876273403, 13.965923944710624, 13.172425447088806, 15.71139734481631, 14.081061947464386, 7.935071321333148, 10.474960750666526, 11.746059735809345, 15.39433649937319, 9.998910118753269, 10.6327798251658, 12.379061529069986, 12.85458982591359), # 14
(13.050102664576398, 14.264585271305906, 13.45411483936456, 16.047449875528383, 14.386189063607633, 8.104791882242878, 10.698847882449478, 11.99680038983966, 15.723532627228748, 10.212601801006487, 10.860247072667189, 12.64374958820284, 13.129582798597134), # 15
(13.30415146986772, 14.532966712404187, 13.707244415428796, 16.349430445286004, 14.661191176215267, 8.257304016110044, 10.900036544549568, 12.222116635542745, 16.019350537551603, 10.404629171246796, 11.06465208305032, 12.881601424558916, 13.376694022332964), # 16
(13.529505793601107, 14.769050184811926, 13.929910955159293, 16.61506864539496, 14.904049708679375, 8.391461261728, 11.077013793622996, 12.420315046245145, 16.27956655030858, 10.573548038017254, 11.24445794958892, 13.090828724209679, 13.594065769033982), # 17
(13.724352137230287, 14.970817605335585, 14.120211238433834, 16.842094067160993, 15.112746084392025, 8.506117157890104, 11.228266686325993, 12.589702195273366, 16.501956985466535, 10.717914209860952, 11.398127765556712, 13.269643173226603, 13.779840310613086), # 18
(13.88687700220898, 15.136250890781643, 14.27624204513021, 17.02823630188984, 15.285261726745313, 8.600125243389693, 11.352282279314753, 12.728584655953943, 16.68429816299229, 10.83628349532096, 11.52412462422743, 13.416256457681136, 13.932159918983176), # 19
(14.015266889990915, 15.263331957956549, 14.396100155126206, 17.171224940887296, 15.419578059131322, 8.672339057020126, 11.44754762924551, 12.835269001613405, 16.82436640285268, 10.927211702940342, 11.62091161887481, 13.528880263644748, 14.049166866057154), # 20
(14.107708302029813, 15.350042723666784, 14.477882348299607, 17.26878957545908, 15.513676504942126, 8.72161213757475, 11.512549792774463, 12.908061805578273, 16.91993802501453, 10.989254641262178, 11.686951842772585, 13.60572627718891, 14.12900342374791), # 21
(14.162387739779412, 15.394365104718803, 14.5196854045282, 17.31865979691097, 15.565538487569807, 8.746798023846914, 11.54577582655784, 12.945269641175082, 16.968789349444684, 11.02096811882954, 11.720708389194478, 13.645006184385087, 14.16981186396836), # 22
(14.182550708679697, 15.39961303155007, 14.524892455418383, 17.324903137860087, 15.578824878445637, 8.75, 11.549725603163076, 12.949291358024693, 16.974896728395063, 11.024709181527207, 11.724941252026436, 13.649856607224509, 14.175), # 23
(14.197417378247815, 15.396551851851854, 14.524040740740743, 17.324134722222226, 15.586350659060795, 8.75, 11.547555337690634, 12.943700000000002, 16.974078333333335, 11.02241086419753, 11.724474410774413, 13.648720987654322, 14.175), # 24
(14.211970122296213, 15.390517832647463, 14.522359396433473, 17.322614454732513, 15.593710923832306, 8.75, 11.543278463648836, 12.932716049382718, 16.97246141975309, 11.01788637402835, 11.723548759196907, 13.646479195244629, 14.175), # 25
(14.226207826667249, 15.381603155006863, 14.519871467764064, 17.320359619341563, 15.600905415789548, 8.75, 11.53696140563221, 12.916546913580248, 16.97006672839506, 11.011210992226795, 11.722172677391198, 13.643161957018751, 14.175), # 26
(14.240129377203292, 15.3699, 14.5166, 17.3173875, 15.607933877961901, 8.75, 11.528670588235297, 12.895400000000002, 16.966915, 11.00246, 11.720354545454546, 13.638800000000003, 14.175), # 27
(14.253733659746702, 15.355500548696845, 14.51256803840878, 17.313715380658437, 15.614796053378763, 8.75, 11.518472436052612, 12.869482716049385, 16.963026975308644, 10.9917086785551, 11.718102743484225, 13.633424051211708, 14.175), # 28
(14.26701956013985, 15.338496982167355, 14.50779862825789, 17.30936054526749, 15.62149168506951, 8.75, 11.506433373678693, 12.839002469135803, 16.95842339506173, 10.979032309099225, 11.715425651577503, 13.627064837677183, 14.175), # 29
(14.279985964225098, 15.318981481481483, 14.502314814814815, 17.30434027777778, 15.628020516063533, 8.75, 11.492619825708061, 12.804166666666665, 16.953125, 10.964506172839508, 11.71233164983165, 13.619753086419752, 14.175), # 30
(14.292631757844802, 15.297046227709194, 14.496139643347053, 17.29867186213992, 15.634382289390214, 8.75, 11.477098216735257, 12.765182716049384, 16.947152530864198, 10.948205550983083, 11.708829118343933, 13.611519524462738, 14.175), # 31
(14.304955826841338, 15.27278340192044, 14.489296159122084, 17.29237258230453, 15.640576748078935, 8.75, 11.4599349713548, 12.72225802469136, 16.940526728395064, 10.930205724737084, 11.704926437211622, 13.602394878829449, 14.175), # 32
(14.316957057057056, 15.246285185185185, 14.481807407407409, 17.28545972222222, 15.646603635159089, 8.75, 11.441196514161222, 12.675600000000001, 16.933268333333334, 10.910581975308643, 11.700631986531986, 13.59240987654321, 14.175), # 33
(14.328634334334335, 15.217643758573388, 14.473696433470508, 17.27795056584362, 15.652462693660054, 8.75, 11.420949269749054, 12.625416049382716, 16.925398086419758, 10.889409583904893, 11.695954146402293, 13.581595244627344, 14.175), # 34
(14.339986544515531, 15.186951303155007, 14.464986282578877, 17.26986239711934, 15.65815366661122, 8.75, 11.399259662712824, 12.571913580246914, 16.916936728395065, 10.866763831732968, 11.690901296919815, 13.569981710105168, 14.175), # 35
(14.35101257344301, 15.1543, 14.455700000000002, 17.2612125, 15.663676297041972, 8.75, 11.37619411764706, 12.515300000000002, 16.907905, 10.84272, 11.685481818181819, 13.557600000000003, 14.175), # 36
(14.361711306959135, 15.119782030178326, 14.445860631001374, 17.252018158436215, 15.669030327981691, 8.75, 11.351819059146292, 12.455782716049384, 16.89832364197531, 10.817353369913125, 11.679704090285574, 13.544480841335163, 14.175), # 37
(14.372081630906267, 15.083489574759948, 14.43549122085048, 17.242296656378603, 15.674215502459768, 8.75, 11.326200911805053, 12.393569135802473, 16.88821339506173, 10.790739222679472, 11.673576493328346, 13.530654961133976, 14.175), # 38
(14.382122431126781, 15.045514814814815, 14.424614814814818, 17.232065277777778, 15.679231563505585, 8.75, 11.299406100217867, 12.328866666666666, 16.877595000000003, 10.762952839506175, 11.667107407407409, 13.516153086419752, 14.175), # 39
(14.39183259346303, 15.005949931412895, 14.413254458161866, 17.221341306584364, 15.684078254148528, 8.75, 11.271501048979264, 12.261882716049385, 16.866489197530868, 10.734069501600368, 11.660305212620028, 13.501005944215823, 14.175), # 40
(14.40121100375738, 14.964887105624143, 14.401433196159124, 17.210142026748972, 15.688755317417984, 8.75, 11.242552182683774, 12.192824691358027, 16.85491672839506, 10.704164490169182, 11.653178289063476, 13.485244261545498, 14.175), # 41
(14.410256547852201, 14.922418518518521, 14.389174074074077, 17.198484722222226, 15.693262496343333, 8.75, 11.212625925925927, 12.121900000000002, 16.842898333333338, 10.673313086419753, 11.645735016835017, 13.4688987654321, 14.175), # 42
(14.418968111589852, 14.878636351165984, 14.376500137174213, 17.186386676954736, 15.697599533953966, 8.75, 11.181788703300251, 12.049316049382718, 16.83045475308642, 10.641590571559215, 11.637983776031925, 13.452000182898951, 14.175), # 43
(14.427344580812699, 14.83363278463649, 14.363434430727025, 17.173865174897124, 15.701766173279264, 8.75, 11.150106939401276, 11.975280246913583, 16.817606728395063, 10.609072226794698, 11.629932946751465, 13.434579240969367, 14.175), # 44
(14.435384841363105, 14.787500000000001, 14.350000000000001, 17.160937500000003, 15.705762157348616, 8.75, 11.11764705882353, 11.9, 16.804375, 10.575833333333335, 11.62159090909091, 13.416666666666666, 14.175), # 45
(14.443087779083434, 14.740330178326476, 14.336219890260631, 17.147620936213993, 15.709587229191404, 8.75, 11.084475486161544, 11.823682716049385, 16.790780308641974, 10.541949172382258, 11.612966043147525, 13.398293187014175, 14.175), # 46
(14.45045227981605, 14.692215500685872, 14.322117146776408, 17.133932767489714, 15.713241131837016, 8.75, 11.050658646009847, 11.746535802469136, 16.776843395061732, 10.507495025148607, 11.604066729018582, 13.37948952903521, 14.175), # 47
(14.457477229403315, 14.64324814814815, 14.307714814814817, 17.11989027777778, 15.716723608314837, 8.75, 11.016262962962964, 11.668766666666668, 16.762585, 10.472546172839506, 11.594901346801347, 13.360286419753088, 14.175), # 48
(14.464161513687602, 14.593520301783265, 14.29303593964335, 17.10551075102881, 15.720034401654251, 8.75, 10.981354861615428, 11.590582716049383, 16.748025864197533, 10.437177896662096, 11.585478276593093, 13.340714586191131, 14.175), # 49
(14.470504018511264, 14.543124142661183, 14.278103566529495, 17.090811471193415, 15.723173254884642, 8.75, 10.94600076656177, 11.512191358024692, 16.73318672839506, 10.401465477823503, 11.575805898491085, 13.32080475537266, 14.175), # 50
(14.476503629716676, 14.492151851851853, 14.262940740740742, 17.075809722222225, 15.726139911035398, 8.75, 10.910267102396515, 11.433800000000002, 16.718088333333338, 10.365484197530865, 11.565892592592595, 13.30058765432099, 14.175), # 51
(14.482159233146191, 14.440695610425243, 14.247570507544584, 17.060522788065846, 15.728934113135901, 8.75, 10.874220293714194, 11.355616049382716, 16.70275141975309, 10.329309336991313, 11.555746738994888, 13.280094010059445, 14.175), # 52
(14.487469714642183, 14.388847599451307, 14.232015912208508, 17.0449679526749, 15.731555604215542, 8.75, 10.837926765109337, 11.277846913580248, 16.687196728395065, 10.293016177411982, 11.545376717795238, 13.259354549611341, 14.175), # 53
(14.492433960047004, 14.336700000000002, 14.2163, 17.0291625, 15.734004127303704, 8.75, 10.801452941176471, 11.2007, 16.671445000000002, 10.256680000000001, 11.534790909090908, 13.2384, 14.175), # 54
(14.497050855203032, 14.284344993141291, 14.200445816186559, 17.01312371399177, 15.736279425429768, 8.75, 10.764865246510128, 11.124382716049384, 16.655516975308643, 10.220376085962506, 11.523997692979176, 13.217261088248744, 14.175), # 55
(14.501319285952622, 14.231874759945132, 14.184476406035667, 16.996868878600825, 15.738381241623124, 8.75, 10.728230105704835, 11.049102469135804, 16.63943339506173, 10.184179716506632, 11.513005449557303, 13.195968541380887, 14.175), # 56
(14.505238138138138, 14.179381481481483, 14.168414814814819, 16.98041527777778, 15.740309318913155, 8.75, 10.69161394335512, 10.975066666666669, 16.623215000000002, 10.148166172839508, 11.50182255892256, 13.174553086419753, 14.175), # 57
(14.508806297601952, 14.126957338820304, 14.152284087791497, 16.96378019547325, 15.742063400329245, 8.75, 10.655083184055517, 10.902482716049382, 16.606882530864198, 10.112410736168268, 11.490457401172218, 13.153045450388662, 14.175), # 58
(14.51202265018642, 14.07469451303155, 14.136107270233198, 16.946980915637862, 15.743643228900785, 8.75, 10.61870425240055, 10.83155802469136, 16.590456728395065, 10.076988687700048, 11.478918356403542, 13.131476360310929, 14.175), # 59
(14.51488608173391, 14.022685185185187, 14.119907407407407, 16.930034722222224, 15.745048547657152, 8.75, 10.582543572984749, 10.762500000000001, 16.573958333333337, 10.041975308641977, 11.467213804713806, 13.109876543209879, 14.175), # 60
(14.517395478086781, 13.971021536351168, 14.10370754458162, 16.912958899176957, 15.746279099627737, 8.75, 10.546667570402647, 10.695516049382718, 16.557408086419755, 10.00744588020119, 11.455352126200275, 13.088276726108827, 14.175), # 61
(14.519549725087407, 13.919795747599453, 14.087530727023323, 16.89577073045268, 15.74733462784193, 8.75, 10.51114266924877, 10.630813580246915, 16.540826728395064, 9.973475683584821, 11.44334170096022, 13.066707636031095, 14.175), # 62
(14.521347708578144, 13.869100000000001, 14.071400000000002, 16.878487500000002, 15.7482148753291, 8.75, 10.476035294117647, 10.568600000000002, 16.524235, 9.94014, 11.43119090909091, 13.045200000000001, 14.175), # 63
(14.522788314401359, 13.819026474622772, 14.05533840877915, 16.86112649176955, 15.74891958511865, 8.75, 10.44141186960381, 10.509082716049384, 16.50765364197531, 9.907514110653864, 11.41890813068961, 13.023784545038868, 14.175), # 64
(14.523870428399414, 13.769667352537724, 14.03936899862826, 16.843704989711934, 15.749448500239955, 8.75, 10.407338820301785, 10.45246913580247, 16.49110339506173, 9.875673296753543, 11.4065017458536, 13.00249199817101, 14.175), # 65
(14.524592936414676, 13.721114814814818, 14.023514814814817, 16.826240277777778, 15.749801363722403, 8.75, 10.373882570806101, 10.398966666666668, 16.474605000000004, 9.844692839506173, 11.393980134680135, 12.981353086419755, 14.175), # 66
(14.524954724289511, 13.673461042524005, 14.00779890260631, 16.808749639917696, 15.749977918595382, 8.75, 10.341109545711289, 10.348782716049385, 16.458179197530864, 9.814648020118886, 11.381351677266494, 12.960398536808412, 14.175), # 67
(14.524708260273156, 13.626548095048452, 13.99216832990398, 16.7910984366613, 15.749829137416285, 8.74983761621704, 10.308921272761506, 10.301681390032009, 16.44172298811157, 9.785468618306034, 11.368400383956526, 12.939542030659641, 14.174825210048013), # 68
(14.522398389694043, 13.578943727598569, 13.976183796296295, 16.772396920289854, 15.748474945533768, 8.748553909465022, 10.27637545388526, 10.25513827160494, 16.424516975308645, 9.756328946986201, 11.35380797448166, 12.918106562703056, 14.17344039351852), # 69
(14.517840102582454, 13.5304294437807, 13.95977580589849, 16.752521973966722, 15.74579903978052, 8.746025758268557, 10.243324188385918, 10.208733424782809, 16.40646404892547, 9.727087334247829, 11.337408441136512, 12.895991865809934, 14.170705268347055), # 70
(14.511097524900102, 13.481034236028144, 13.942950120027435, 16.731502905260335, 15.74183531025579, 8.742294131992075, 10.209782323354585, 10.162482213077277, 16.387591095107457, 9.697744503079695, 11.319262319097408, 12.873214112097802, 14.166655842764062), # 71
(14.502234782608697, 13.430787096774193, 13.9257125, 16.709369021739132, 15.736617647058825, 8.737400000000001, 10.175764705882354, 10.1164, 16.367925000000003, 9.668301176470589, 11.299430143540672, 12.849789473684211, 14.161328125), # 72
(14.491316001669949, 13.379717018452144, 13.90806870713306, 16.686149630971553, 15.730179940288872, 8.73138433165676, 10.141286183060329, 10.070502149062644, 16.347492649748517, 9.63875807740929, 11.277972449642624, 12.825734122686688, 14.154758123285324), # 73
(14.478405308045566, 13.32785299349529, 13.890024502743485, 16.661874040526033, 15.722556080045187, 8.72428809632678, 10.106361601979613, 10.024804023776863, 16.3263209304984, 9.609115928884586, 11.254949772579598, 12.801064231222776, 14.146981845850483), # 74
(14.463566827697262, 13.275224014336917, 13.871585648148148, 16.636571557971017, 15.713779956427018, 8.716152263374488, 10.0710058097313, 9.979320987654322, 16.30443672839506, 9.579375453885259, 11.23042264752791, 12.775795971410007, 14.138035300925928), # 75
(14.44686468658675, 13.22185907341033, 13.852757904663925, 16.610271490874936, 15.703885459533609, 8.707017802164305, 10.035233653406493, 9.934068404206677, 16.281866929583906, 9.549537375400092, 11.20445160966389, 12.749945515365916, 14.127954496742113), # 76
(14.428363010675731, 13.167787163148816, 13.833547033607681, 16.583003146806227, 15.692906479464213, 8.696925682060662, 9.999059980096293, 9.88906163694559, 16.258638420210335, 9.519602416417872, 11.177097194163862, 12.723529035208049, 14.116775441529496), # 77
(14.408125925925928, 13.113037275985667, 13.813958796296298, 16.554795833333333, 15.680876906318085, 8.685916872427983, 9.962499636891796, 9.844316049382718, 16.23477808641975, 9.489571299927379, 11.148419936204148, 12.696562703053933, 14.10453414351852), # 78
(14.386217558299041, 13.057638404354178, 13.793998954046641, 16.525678858024694, 15.667830630194468, 8.674032342630696, 9.925567470884102, 9.799847005029722, 16.210312814357568, 9.4594447489174, 11.118480370961072, 12.669062691021107, 14.091266610939643), # 79
(14.362702033756786, 13.001619540687642, 13.773673268175584, 16.495681528448742, 15.653801541192612, 8.661313062033226, 9.888278329164315, 9.755669867398264, 16.185269490169183, 9.429223486376719, 11.087339033610965, 12.64104517122711, 14.07700885202332), # 80
(14.337643478260873, 12.945009677419357, 13.752987500000001, 16.464833152173917, 15.638823529411765, 8.6478, 9.85064705882353, 9.711800000000002, 16.159675, 9.398908235294119, 11.055056459330146, 12.612526315789475, 14.061796875), # 81
(14.311106017773009, 12.887837806982612, 13.731947410836765, 16.433163036768654, 15.622930484951183, 8.633534125895444, 9.812688506952853, 9.668252766346594, 16.133556229995428, 9.368499718658382, 11.02169318329494, 12.583522296825743, 14.045666688100141), # 82
(14.283153778254908, 12.8301329218107, 13.710558762002744, 16.400700489801395, 15.606156297910111, 8.618556409083983, 9.774417520643375, 9.625043529949703, 16.10694006630087, 9.337998659458297, 10.987309740681672, 12.554049286453447, 14.028654299554185), # 83
(14.253850885668278, 12.77192401433692, 13.688827314814816, 16.36747481884058, 15.588534858387801, 8.602907818930042, 9.735848946986202, 9.582187654320988, 16.07985339506173, 9.307405780682645, 10.951966666666667, 12.524123456790125, 14.010795717592593), # 84
(14.223261465974833, 12.713240076994557, 13.666758830589849, 16.333515331454645, 15.5701000564835, 8.58662932479805, 9.696997633072435, 9.53970050297211, 16.05232310242341, 9.276721805320209, 10.915724496426252, 12.493760979953313, 13.992126950445819), # 85
(14.191449645136279, 12.654110102216913, 13.644359070644722, 16.298851335212028, 15.550885782296458, 8.569761896052432, 9.65787842599317, 9.497597439414724, 16.024376074531325, 9.245947456359774, 10.878643765136749, 12.462978028060553, 13.97268400634431), # 86
(14.15847954911433, 12.594563082437277, 13.621633796296296, 16.26351213768116, 15.53092592592593, 8.552346502057613, 9.618506172839506, 9.455893827160494, 15.996039197530868, 9.215083456790124, 10.840785007974482, 12.43179077322937, 13.95250289351852), # 87
(14.124415303870702, 12.534628010088941, 13.598588768861456, 16.22752704643049, 15.510254377471155, 8.534424112178023, 9.578895720702548, 9.414605029721079, 15.967339357567447, 9.184130529600042, 10.802208760115779, 12.400215387577312, 13.931619620198905), # 88
(14.089321035367092, 12.474333877605204, 13.575229749657066, 16.19092536902845, 15.488905027031391, 8.516035695778085, 9.539061916673392, 9.37374641060814, 15.938303440786468, 9.153089397778317, 10.762975556736963, 12.36826804322191, 13.910070194615912), # 89
(14.053260869565218, 12.413709677419357, 13.551562500000001, 16.153736413043482, 15.466911764705886, 8.497222222222224, 9.499019607843138, 9.333333333333334, 15.908958333333336, 9.121960784313726, 10.723145933014354, 12.335964912280703, 13.887890625), # 90
(14.016298932426789, 12.352784401964689, 13.527592781207133, 16.11598948604402, 15.444308480593882, 8.478024660874867, 9.458783641302887, 9.293381161408323, 15.879330921353455, 9.090745412195057, 10.682780424124285, 12.303322166871226, 13.865116919581618), # 91
(13.978499349913523, 12.2915870436745, 13.503326354595337, 16.0777138955985, 15.421129064794641, 8.458483981100443, 9.418368864143739, 9.253905258344766, 15.84944809099223, 9.059444004411093, 10.641939565243074, 12.270355979111017, 13.841785086591221), # 92
(13.939926247987117, 12.230146594982081, 13.478768981481483, 16.038938949275366, 15.397407407407409, 8.438641152263374, 9.37779012345679, 9.214920987654322, 15.819336728395063, 9.028057283950616, 10.600683891547051, 12.23708252111761, 13.81793113425926), # 93
(13.900643752609293, 12.168492048320722, 13.453926423182445, 15.999693954643051, 15.37317739853143, 8.418537143728091, 9.337062266333147, 9.176443712848654, 15.789023719707364, 8.996585973802416, 10.559073938212535, 12.203517965008546, 13.793591070816188), # 94
(13.860715989741754, 12.106652396123724, 13.42880444101509, 15.960008219269996, 15.34847292826596, 8.398212924859017, 9.296200139863902, 9.138488797439416, 15.758535951074533, 8.96503079695527, 10.517170240415854, 12.169678482901354, 13.768800904492457), # 95
(13.820207085346219, 12.044656630824377, 13.403408796296299, 15.91991105072464, 15.32332788671024, 8.377709465020576, 9.25521859114016, 9.101071604938273, 15.727900308641976, 8.933392476397968, 10.475033333333334, 12.135580246913582, 13.74359664351852), # 96
(13.779181165384388, 11.98253374485597, 13.377745250342937, 15.879431756575416, 15.297776163963531, 8.357067733577198, 9.21413246725302, 9.064207498856883, 15.6971436785551, 8.901671735119288, 10.432723752141296, 12.101239429162758, 13.718014296124831), # 97
(13.737702355817978, 11.9203127306518, 13.35181956447188, 15.83859964439077, 15.271851650125074, 8.336328699893311, 9.17295661529358, 9.027911842706905, 15.666292946959304, 8.86986929610802, 10.390302032016068, 12.066672201766417, 13.69208987054184), # 98
(13.695834782608697, 11.858022580645162, 13.325637500000003, 15.797444021739132, 15.24558823529412, 8.315533333333335, 9.131705882352943, 8.9922, 15.635375000000002, 8.83798588235294, 10.347828708133973, 12.031894736842107, 13.665859375000002), # 99
(13.653642571718258, 11.795692287269347, 13.29920481824417, 15.755994196188944, 15.21901980956992, 8.294722603261699, 9.090395115522204, 8.957087334247829, 15.60441672382259, 8.806022216842843, 10.305364315671335, 11.996923206507354, 13.639358817729768), # 100
(13.611189849108369, 11.733350842957654, 13.272527280521263, 15.714279475308645, 15.192180263051725, 8.273937479042829, 9.049039161892468, 8.922589208962048, 15.573445004572475, 8.773979022566504, 10.262969389804478, 11.961773782879694, 13.612624206961591), # 101
(13.568540740740744, 11.67102724014337, 13.245610648148148, 15.67232916666667, 15.165103485838781, 8.253218930041154, 9.00765286855483, 8.888720987654322, 15.542486728395062, 8.741857022512711, 10.22070446570973, 11.926462638076675, 13.585691550925928), # 102
(13.525759372577088, 11.60875047125979, 13.218460682441702, 15.630172577831457, 15.137823368030341, 8.232607925621096, 8.966251082600394, 8.855498033836307, 15.511568781435757, 8.709656939670245, 10.178630078563414, 11.891005944215824, 13.558596857853223), # 103
(13.482909870579116, 11.546549528740211, 13.191083144718794, 15.587839016371445, 15.110373799725652, 8.212145435147082, 8.924848651120257, 8.822935711019662, 15.480718049839965, 8.677379497027893, 10.13680676354185, 11.855419873414677, 13.53137613597394), # 104
(13.440056360708535, 11.484453405017922, 13.163483796296298, 15.545357789855073, 15.082788671023966, 8.19187242798354, 8.883460421205521, 8.79104938271605, 15.449961419753087, 8.64502541757444, 10.095295055821373, 11.819720597790775, 13.50406539351852), # 105
(13.39726296892706, 11.42249109252622, 13.135668398491084, 15.50275820585078, 15.055101872024531, 8.171829873494895, 8.842101239947283, 8.759854412437129, 15.41932577732053, 8.612595424298663, 10.054155490578298, 11.783924289461654, 13.476700638717421), # 106
(13.3545938211964, 11.360691583698395, 13.10764271262003, 15.460069571927, 15.027347292826596, 8.152058741045574, 8.800785954436646, 8.72936616369456, 15.388838008687703, 8.580090240189355, 10.013448602988953, 11.748047120544847, 13.449317879801098), # 107
(13.312113043478263, 11.299083870967744, 13.079412500000002, 15.417321195652177, 14.999558823529412, 8.132600000000002, 8.759529411764706, 8.699600000000002, 15.358525000000002, 8.547510588235296, 9.973234928229665, 11.712105263157897, 13.421953125000002), # 108
(13.26988476173436, 11.237696946767558, 13.050983521947876, 15.374542384594738, 14.97177035423223, 8.113494619722603, 8.718346459022568, 8.670571284865114, 15.328413637402836, 8.514857191425268, 9.933575001476758, 11.676114889418335, 13.394642382544584), # 109
(13.227973101926404, 11.176559803531132, 13.022361539780524, 15.331762446323136, 14.944015775034297, 8.094783569577809, 8.677251943301325, 8.642295381801555, 15.29853080704161, 8.482130772748057, 9.894529357906551, 11.640092171443701, 13.367421660665297), # 110
(13.186442190016104, 11.11570143369176, 12.993552314814819, 15.2890106884058, 14.91632897603486, 8.076507818930043, 8.636260711692085, 8.614787654320988, 15.26890339506173, 8.449332055192448, 9.856158532695375, 11.60405328135153, 13.340326967592594), # 111
(13.14535615196517, 11.055150829682729, 12.96456160836763, 15.246316418411165, 14.888743847333174, 8.05870833714373, 8.595387611285942, 8.588063465935072, 15.239558287608595, 8.416461761747223, 9.818523061019553, 11.568014391259355, 13.313394311556928), # 112
(13.104705913184263, 10.995038066300333, 12.935464959552897, 15.203767435488858, 14.861245952243188, 8.04141767690032, 8.554736349119478, 8.562193596292849, 15.21059793576207, 8.383626631257822, 9.781693468614014, 11.5320701111062, 13.286621461180511), # 113
(13.064073257060091, 10.935956056935751, 12.906663945030267, 15.161705189788272, 14.833550696392859, 8.024596451941862, 8.514825491774811, 8.537495763307168, 15.182466649998286, 8.351441235077896, 9.745742071958476, 11.496677040958165, 13.25978557982405), # 114
(13.023338864205595, 10.877926078156266, 12.878175705790246, 15.120118307254492, 14.805570749044042, 8.008200917498272, 8.475683510268187, 8.513963715990194, 15.155174970136306, 8.319955459183308, 9.710616315997932, 11.461852615582393, 13.232809284324528), # 115
(12.982451822532688, 10.820863593808383, 12.849945065977423, 15.078932610372966, 14.777263936937292, 7.992192428201937, 8.43724674453905, 8.491532438058591, 15.128653874918964, 8.289110701829367, 9.676248303780074, 11.427532476482286, 13.205650163658248), # 116
(12.941361219953283, 10.76468406773861, 12.82191684973638, 15.038073921629142, 14.748588086813156, 7.976532338685248, 8.399451534526854, 8.47013691322902, 15.102834343089086, 8.258848361271381, 9.642570138352598, 11.39365226516125, 13.178265806801516), # 117
(12.900016144379297, 10.709302963793455, 12.794035881211714, 14.997468063508467, 14.71950102541218, 7.9611820035805945, 8.362234220171041, 8.449712125218136, 15.07764735338951, 8.229109835764664, 9.609513922763194, 11.36014762312269, 13.150613802730636), # 118
(12.858365683722639, 10.654635745819421, 12.766246984548014, 14.95704085849639, 14.689960579474912, 7.946102777520366, 8.325531141411059, 8.430193057742605, 15.053023884563062, 8.199836523564521, 9.577011760059559, 11.326954191870009, 13.122651740421906), # 119
(12.816358925895228, 10.600597877663022, 12.738494983889867, 14.916718129078353, 14.659924575741897, 7.931256015136952, 8.289278638186355, 8.41151469451908, 15.028894915352582, 8.170969822926269, 9.544995753289383, 11.294007612906617, 13.094337208851638), # 120
(12.773944958808976, 10.547104823170763, 12.710724703381864, 14.876425697739808, 14.629350840953688, 7.9166030710627435, 8.253413050436373, 8.39361201926423, 15.0051914245009, 8.142451132105215, 9.513398005500363, 11.261243527735912, 13.065627796996127), # 121
(12.731072870375797, 10.494072046189146, 12.682880967168597, 14.836089386966199, 14.598197201850828, 7.902105299930128, 8.217870718100565, 8.376420015694709, 14.981844390750846, 8.11422184935667, 9.482150619740192, 11.228597577861303, 13.036481093831679), # 122
(12.687691748507607, 10.441415010564684, 12.65490859939465, 14.795635019242972, 14.56642148517387, 7.887724056371495, 8.182587981118376, 8.359873667527177, 14.958784792845258, 8.086223372935942, 9.451185699056563, 11.19600540478619, 13.0068546883346), # 123
(12.643750681116316, 10.389049180143882, 12.62675242420462, 14.754988417055582, 14.533981517663353, 7.873420695019235, 8.147501179429248, 8.343907958478297, 14.935943609526962, 8.058397101098347, 9.420435346497168, 11.163402650013985, 12.976706169481197), # 124
(12.599198756113843, 10.33689001877325, 12.598357265743093, 14.714075402889465, 14.500835126059833, 7.859156570505739, 8.112546652972636, 8.328457872264728, 14.913251819538791, 8.030684432099187, 9.389831665109703, 11.130724955048088, 12.94599312624776), # 125
(12.553985061412101, 10.284852990299292, 12.56966794815466, 14.672821799230077, 14.466940137103851, 7.844893037463395, 8.077660741687978, 8.31345839260313, 14.890640401623585, 8.00302676419378, 9.359306757941859, 11.097907961391908, 12.91467314761061), # 126
(12.508058684923006, 10.232853558568515, 12.540629295583907, 14.63115342856286, 14.432254377535958, 7.830591450524592, 8.042779785514732, 8.298844503210164, 14.86804033452417, 7.975365495637434, 9.32879272804133, 11.064887310548842, 12.88270382254604), # 127
(12.461368714558466, 10.18080718742743, 12.51118613217543, 14.588996113373266, 14.396735674096707, 7.816213164321722, 8.007840124392336, 8.284551187802489, 14.845382596983379, 7.947642024685458, 9.298221678455814, 11.031598644022305, 12.850042740030352), # 128
(12.413864238230394, 10.128629340722538, 12.481283282073816, 14.546275676146736, 14.360341853526638, 7.801719533487173, 7.972778098260239, 8.270513430096765, 14.822598167744045, 7.919797749593164, 9.267525712233, 10.997977603315691, 12.816647489039854), # 129
(12.365494343850713, 10.076235482300353, 12.450865569423652, 14.502917939368722, 14.3230307425663, 7.7870719126533325, 7.937530047057888, 8.256666213809652, 14.799618025549002, 7.89177406861586, 9.236636932420582, 10.963959829932413, 12.78247565855085), # 130
(12.316208119331334, 10.023541076007378, 12.419877818369534, 14.458848725524668, 14.284760167956243, 7.772231656452593, 7.902032310724733, 8.24294452265781, 14.776373149141081, 7.86351238000886, 9.205487442066255, 10.929480965375875, 12.747484837539638), # 131
(12.265954652584163, 9.970461585690122, 12.388264853056045, 14.413993857100023, 14.245487956437017, 7.757160119517344, 7.8662212292002165, 8.229283340357902, 14.752794517263117, 7.834954082027471, 9.17400934421771, 10.894476651149478, 12.711632614982527), # 132
(12.21468303152113, 9.91691247519509, 12.355971497627777, 14.368279156580234, 14.205171934749162, 7.741818656479974, 7.830033142423786, 8.215617650626585, 14.728813108657938, 7.806040572927006, 9.142134741922645, 10.85888252875663, 12.674876579855821), # 133
(12.162342344054133, 9.862809208368793, 12.322942576229327, 14.321630446450746, 14.163769929633231, 7.726168621972872, 7.79340439033489, 8.201882437180522, 14.704359902068381, 7.776713250962773, 9.109795738228751, 10.822634239700733, 12.637174321135817), # 134
(12.108881678095097, 9.808067249057736, 12.289122913005274, 14.273973549197011, 14.12123976782977, 7.710171370628429, 7.756271312872975, 8.18801268373637, 14.679365876237274, 7.746913514390087, 9.07692443618372, 10.785667425485194, 12.59848342779883), # 135
(12.05425012155593, 9.752602061108423, 12.254457332100213, 14.225234287304469, 14.077539276079325, 7.693788257079036, 7.718570249977489, 8.173943374010788, 14.65376200990745, 7.716582761464252, 9.043452938835248, 10.747917727613418, 12.558761488821151), # 136
(11.998396762348548, 9.696329108367367, 12.218890657658735, 14.175338483258576, 14.032626281122448, 7.6769806359570785, 7.6802375415878785, 8.159609491720442, 14.627479281821747, 7.685662390440583, 9.009313349231029, 10.709320787588808, 12.517966093179089), # 137
(11.941270688384867, 9.639163854681073, 12.182367713825425, 14.12421195954477, 13.986458609699687, 7.6597098618949495, 7.6412095276435865, 8.144946020581987, 14.600448670722995, 7.654093799574386, 8.974437770418753, 10.66981224691477, 12.476054829848946), # 138
(11.882820987576796, 9.581021763896047, 12.144833324744877, 14.071780538648504, 13.938994088551583, 7.641937289525037, 7.601422548084064, 8.129887944312085, 14.572601155354022, 7.621818387120976, 8.938758305446116, 10.62932774709471, 12.432985287807028), # 139
(11.822996747836257, 9.521818299858795, 12.106232314561684, 14.017970043055223, 13.890190544418692, 7.623624273479732, 7.560812942848756, 8.114370246627395, 14.543867714457667, 7.588777551335661, 8.902207057360812, 10.58780292963203, 12.38871505602964), # 140
(11.761747057075162, 9.46146892641583, 12.066509507420426, 13.962706295250376, 13.840005804041555, 7.604732168391422, 7.519317051877113, 8.09832791124458, 14.514179326776754, 7.554912690473753, 8.864716129210535, 10.545173436030137, 12.34320172349308), # 141
(11.69902100320542, 9.399889107413653, 12.0256097274657, 13.90591511771941, 13.788397694160723, 7.585222328892499, 7.476871215108577, 8.081695921880296, 14.48346697105412, 7.52016520279056, 8.826217624042977, 10.501374907792433, 12.296402879173653), # 142
(11.634767674138946, 9.336994306698774, 11.983477798842097, 13.847522332947767, 13.735324041516742, 7.56505610961535, 7.4334117724825965, 8.064409262251205, 14.451661626032607, 7.484476486541395, 8.786643644905832, 10.456342986422326, 12.248276112047666), # 143
(11.56893615778766, 9.2726999881177, 11.9400585456942, 13.787453763420901, 13.680742672850162, 7.544194865192366, 7.3888750639386185, 8.04640291607397, 14.418694270455035, 7.4477879399815645, 8.745926294846791, 10.41001331342322, 12.198779011091421), # 144
(11.501475542063469, 9.20692161551694, 11.895296792166606, 13.725635231624254, 13.624611414901528, 7.5225999502559375, 7.343197429416091, 8.027611867065247, 14.384495883064238, 7.410040961366383, 8.703997676913554, 10.36232153029852, 12.14786916528122), # 145
(11.432334914878291, 9.139574652742999, 11.849137362403903, 13.661992560043277, 13.566888094411391, 7.500232719438453, 7.2963152088544625, 8.007971098941699, 14.34899744260305, 7.37117694895116, 8.660789894153808, 10.313203278551628, 12.095504163593366), # 146
(11.361463364144042, 9.070574563642383, 11.801525080550675, 13.596451571163414, 13.507530538120294, 7.477054527372301, 7.2481647421931745, 7.987415595419982, 14.312129927814308, 7.331137300991204, 8.616235049615252, 10.262594199685955, 12.041641595004167), # 147
(11.288809977772631, 8.999836812061604, 11.752404770751518, 13.528938087470117, 13.446496572768787, 7.453026728689875, 7.198682369371678, 7.965880340216761, 14.273824317440841, 7.289863415741826, 8.570265246345576, 10.210429935204898, 11.986239048489919), # 148
(11.214323843675977, 8.927276861847163, 11.701721257151021, 13.459377931448826, 13.38374402509742, 7.42811067802356, 7.147804430329418, 7.943300317048694, 14.234011590225474, 7.247296691458339, 8.522812587392474, 10.156646126611868, 11.929254113026934), # 149
(11.137954049765991, 8.852810176845571, 11.649419363893772, 13.387696925584994, 13.319230721846738, 7.402267730005749, 7.0954672650058415, 7.91961050963244, 14.192622724911054, 7.2033785263960475, 8.473809175803641, 10.101178415410269, 11.870644377591507), # 150
(11.059649683954586, 8.776352220903336, 11.59544391512436, 13.313820892364063, 13.252914489757288, 7.375459239268828, 7.041607213340397, 7.8947459016846615, 14.149588700240406, 7.15805031881027, 8.423187114626767, 10.043962443103501, 11.810367431159946), # 151
(10.979359834153682, 8.697818457866962, 11.539739734987382, 13.237675654271488, 13.184753155569618, 7.34764656044519, 6.986160615272531, 7.8686414769220185, 14.10484049495636, 7.11125346695631, 8.37087850690955, 9.984933851194974, 11.748380862708558), # 152
(10.897033588275185, 8.61712435158296, 11.482251647627416, 13.159187033792707, 13.11470454602428, 7.318791048167222, 6.929063810741687, 7.841232219061167, 14.058309087801755, 7.062929369089481, 8.316815455699683, 9.92402828118809, 11.68464226121364), # 153
(10.81262003423102, 8.534185365897834, 11.422924477189063, 13.078280853413174, 13.042726487861813, 7.288854057067317, 6.87025313968732, 7.8124531118187726, 14.009925457519413, 7.013019423465095, 8.260930064044857, 9.861181374586256, 11.6191092156515), # 154
(10.72606825993309, 8.448916964658093, 11.361703047816906, 12.99488293561833, 12.968776807822776, 7.257796941777861, 6.809664942048866, 7.782239138911491, 13.95962058285218, 6.9614650283384565, 8.203154434992767, 9.796328772892876, 11.551739314998438), # 155
(10.637327353293314, 8.361234611710243, 11.298532183655539, 12.908919102893627, 12.892813332647707, 7.225581056931246, 6.74723555776578, 7.750525284055986, 13.907325442542877, 6.9082075819648825, 8.143420671591107, 9.729406117611353, 11.48249014823076), # 156
(10.546346402223609, 8.271053770900794, 11.233356708849547, 12.820315177724513, 12.81479388907716, 7.19216775715986, 6.6829013267775075, 7.717246530968915, 13.852971015334345, 6.853188482599679, 8.08166087688757, 9.660349050245092, 11.411319304324769), # 157
(10.450553324967336, 8.176634369081162, 11.163028735463298, 12.725677414311741, 12.731153548219398, 7.155434266843955, 6.615149409299001, 7.680115733289122, 13.792326928238738, 6.794712282807602, 8.01583405355452, 9.586639389872076, 11.335080203181485), # 158
(10.335201473769764, 8.06829144743927, 11.069432945764184, 12.605568022303835, 12.62126783369428, 7.103165507209945, 6.535497868740003, 7.626098945870136, 13.700998165711002, 6.723193391738244, 7.934383709866593, 9.493907533156353, 11.235598705688274), # 159
(10.198820932866035, 7.945135419957, 10.950689341138245, 12.458008514572404, 12.482988183885514, 7.034077814466758, 6.443141247737298, 7.553838865338286, 13.576395318120113, 6.637687912608051, 7.8361633120533565, 9.380702728442985, 11.110988852451014), # 160
(10.042510876420344, 7.8079692153126565, 10.808065760674433, 12.28440150525942, 12.317750373994958, 6.94900813819844, 6.338754024409627, 7.464240746353693, 13.420161673798626, 6.5389214704393135, 7.7220383164395905, 9.248074456470599, 10.962523662746737), # 161
(9.8673704785969, 7.657595762184535, 10.642830043461695, 12.086149608506858, 12.126990179224487, 6.848793427989039, 6.223010676875733, 7.358209843576484, 13.233940521079093, 6.427619690254325, 7.592874179350069, 9.09707219797781, 10.791476155852466), # 162
(9.674498913559898, 7.494817989250934, 10.456250028588983, 11.864655438456708, 11.912143374775964, 6.734270633422602, 6.096585683254362, 7.2366514116667755, 13.019375148294069, 6.304508197075376, 7.449536357109572, 8.928745433703247, 10.599119351045232), # 163
(9.464995355473539, 7.320438825190149, 10.249593555145248, 11.621321609250947, 11.674645735851264, 6.606276704083181, 5.960153521664253, 7.100470705284697, 12.778108843776113, 6.170312615924756, 7.292890306042875, 8.744143644385526, 10.386726267602059), # 164
(9.239958978502024, 7.135261198680485, 10.024128462219437, 11.357550735031554, 11.415933037652254, 6.465648589554821, 5.814388670224151, 6.950572979090365, 12.511784895857772, 6.02575857182476, 7.123801482474756, 8.544316310763268, 10.155569924799979), # 165
(9.000488956809557, 6.940088038400237, 9.7811225889005, 11.074745429940503, 11.137441055380801, 6.313223239421572, 5.659965607052801, 6.787863487743908, 12.222046592871603, 5.871571689797677, 6.943135342729992, 8.330312913575103, 9.906923341916015), # 166
(8.747684464560333, 6.735722273027703, 9.521843774277388, 10.774308308119782, 10.840605564238773, 6.149837603267482, 5.497558810268945, 6.613247485905448, 11.91053722315016, 5.7084775948658, 6.751757343133359, 8.103182933559642, 9.642059538227196), # 167
(8.482644675918554, 6.52296683124118, 9.247559857439049, 10.457641983711365, 10.526862339428039, 5.9763286306765995, 5.327842757991326, 6.427630228235103, 11.578900075025999, 5.5372019120514215, 6.550532940009634, 7.863975851455517, 9.362251533010546), # 168
(8.206468765048422, 6.302624641718972, 8.959538677474432, 10.126149070857236, 10.197647156150468, 5.793533271232973, 5.151491928338689, 6.231916969393004, 11.228778436831673, 5.358470266376831, 6.3403275896835956, 7.613741148001342, 9.0687723455431), # 169
(7.9202559061141375, 6.0754986331393726, 8.659048073472489, 9.781232183699368, 9.854395789607928, 5.60228847452065, 4.9691807994297745, 6.027012964039266, 10.861815596899735, 5.173008282864322, 6.122006748480023, 7.353528303935743, 8.762894995101878), # 170
(7.6251052732799005, 5.842391734180682, 8.34735588452217, 9.424293936379751, 9.498544015002288, 5.403431190123678, 4.781583849383328, 5.813823466834017, 10.47965484356274, 4.981541586536184, 5.896435872723688, 7.0843867999973416, 8.445892500963913), # 171
(7.322116040709912, 5.604106873521197, 8.025729949712423, 9.056736943040356, 9.131527607535416, 5.197798367626108, 4.5893755563180925, 5.593253732437379, 10.083939465153241, 4.784795802414712, 5.664480418739371, 6.80736611692476, 8.119037882406225), # 172
(7.012387382568372, 5.3614469798392195, 7.695438108132197, 8.679963817823166, 8.754782342409182, 4.9862269566119855, 4.39323039835281, 5.366209015509473, 9.676312750003792, 4.583496555522195, 5.427005842851849, 6.523515735456615, 7.783604158705848), # 173
(6.697018473019482, 5.115214981813045, 7.357748198870443, 8.295377174870158, 8.369743994825454, 4.76955390666536, 4.193822853606226, 5.133594570710425, 9.25841798644695, 4.3783694708809255, 5.1848776013858995, 6.233885136331535, 7.440864349139807), # 174
(6.377108486227438, 4.866213808120973, 7.013928061016112, 7.904379628323315, 7.977848339986097, 4.54861616737028, 3.9918274001970815, 4.896315652700355, 8.831898462815268, 4.170140173513194, 4.938961150666297, 5.939523800288141, 7.092091472985131), # 175
(6.053756596356447, 4.615246387441302, 6.66524553365815, 7.508373792324615, 7.580531153092983, 4.324250688310793, 3.787918516244121, 4.655277516139389, 8.3983974674413, 3.959534288441294, 4.690121947017822, 5.641481208065051, 6.738558549518844), # 176
(5.7280619775707065, 4.363115648452332, 6.3129684558855095, 7.108762281016037, 7.179228209347984, 4.097294419070949, 3.582770679866088, 4.411385415687646, 7.959558288657599, 3.7472774406875144, 4.43922544676525, 5.340806840400891, 6.381538598017975), # 177
(5.401123804034416, 4.11062451983236, 5.95836466678714, 6.7069477085395635, 6.775375283952959, 3.8685843092347962, 3.3770583691817246, 4.165544606005252, 7.51702421479672, 3.5340952552741505, 4.187137106233358, 5.038550178034279, 6.022304637759553), # 178
(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), # 179
)
passenger_arriving_acc = (
(9, 10, 5, 5, 3, 2, 2, 3, 3, 1, 1, 0, 0, 6, 9, 0, 8, 12, 3, 4, 1, 0, 2, 2, 2, 0), # 0
(14, 20, 14, 16, 9, 4, 2, 8, 4, 2, 2, 0, 0, 17, 14, 5, 14, 18, 4, 6, 3, 1, 6, 2, 2, 0), # 1
(21, 29, 17, 19, 12, 7, 5, 13, 8, 6, 4, 0, 0, 26, 20, 10, 21, 27, 5, 11, 7, 3, 8, 4, 4, 0), # 2
(26, 39, 28, 28, 24, 10, 11, 19, 12, 7, 4, 0, 0, 32, 30, 12, 29, 35, 13, 13, 9, 6, 10, 6, 4, 0), # 3
(37, 48, 34, 36, 31, 13, 15, 24, 16, 8, 4, 0, 0, 40, 42, 15, 34, 45, 16, 13, 13, 7, 11, 6, 7, 0), # 4
(48, 57, 43, 49, 34, 16, 22, 31, 20, 10, 4, 2, 0, 47, 55, 22, 42, 54, 21, 18, 14, 9, 16, 7, 8, 0), # 5
(60, 70, 51, 57, 42, 20, 23, 35, 23, 14, 7, 4, 0, 56, 63, 29, 51, 60, 23, 25, 17, 15, 19, 7, 9, 0), # 6
(72, 78, 59, 68, 55, 23, 26, 36, 27, 15, 8, 4, 0, 68, 70, 40, 55, 69, 27, 28, 19, 18, 21, 8, 10, 0), # 7
(86, 89, 76, 78, 63, 26, 29, 38, 30, 16, 11, 4, 0, 79, 77, 49, 61, 80, 29, 35, 23, 19, 24, 9, 10, 0), # 8
(97, 99, 83, 87, 71, 34, 36, 43, 35, 16, 14, 7, 0, 96, 89, 58, 67, 90, 38, 39, 25, 22, 26, 13, 11, 0), # 9
(107, 111, 94, 97, 78, 37, 42, 46, 42, 19, 16, 9, 0, 114, 102, 70, 76, 102, 44, 41, 28, 28, 28, 16, 13, 0), # 10
(122, 122, 104, 108, 90, 44, 46, 49, 45, 20, 19, 11, 0, 124, 107, 83, 84, 114, 50, 47, 31, 29, 29, 20, 14, 0), # 11
(133, 138, 114, 119, 99, 46, 53, 53, 48, 23, 20, 13, 0, 141, 115, 92, 89, 122, 55, 52, 31, 35, 33, 21, 15, 0), # 12
(144, 155, 124, 129, 105, 53, 57, 55, 54, 24, 23, 14, 0, 155, 127, 96, 92, 127, 61, 56, 36, 38, 40, 24, 16, 0), # 13
(156, 176, 136, 141, 116, 60, 61, 59, 58, 27, 28, 14, 0, 165, 139, 102, 99, 139, 67, 63, 37, 42, 44, 24, 16, 0), # 14
(162, 188, 145, 162, 128, 63, 64, 63, 64, 29, 29, 16, 0, 174, 158, 110, 102, 145, 74, 70, 43, 50, 44, 24, 18, 0), # 15
(169, 200, 155, 175, 140, 70, 69, 67, 68, 32, 31, 19, 0, 186, 166, 114, 108, 159, 84, 74, 45, 54, 48, 25, 19, 0), # 16
(184, 215, 173, 190, 147, 79, 73, 70, 73, 38, 34, 20, 0, 198, 176, 121, 119, 169, 90, 76, 50, 61, 51, 26, 19, 0), # 17
(198, 229, 189, 207, 162, 83, 79, 74, 77, 39, 36, 21, 0, 214, 193, 128, 123, 176, 97, 85, 55, 67, 55, 28, 21, 0), # 18
(221, 245, 201, 220, 168, 89, 85, 77, 84, 39, 37, 22, 0, 231, 211, 139, 134, 191, 110, 91, 58, 72, 61, 32, 23, 0), # 19
(233, 257, 214, 233, 178, 96, 91, 81, 90, 41, 39, 23, 0, 241, 228, 152, 141, 202, 117, 96, 63, 78, 66, 36, 24, 0), # 20
(249, 275, 226, 246, 186, 102, 93, 87, 101, 43, 40, 24, 0, 248, 240, 162, 151, 218, 121, 100, 70, 82, 69, 37, 26, 0), # 21
(263, 288, 234, 257, 193, 109, 95, 90, 110, 47, 42, 24, 0, 266, 249, 168, 163, 230, 128, 103, 73, 85, 77, 37, 29, 0), # 22
(279, 297, 244, 265, 207, 118, 101, 92, 119, 50, 44, 25, 0, 282, 270, 177, 167, 235, 135, 109, 79, 86, 81, 38, 30, 0), # 23
(290, 310, 255, 275, 213, 122, 111, 98, 125, 51, 49, 26, 0, 300, 287, 193, 170, 247, 148, 117, 81, 90, 82, 42, 31, 0), # 24
(301, 326, 272, 282, 225, 127, 119, 103, 131, 53, 49, 28, 0, 310, 301, 203, 177, 267, 153, 129, 85, 93, 85, 45, 33, 0), # 25
(319, 341, 290, 290, 237, 131, 133, 105, 138, 54, 50, 29, 0, 319, 311, 213, 186, 283, 156, 133, 87, 97, 89, 46, 34, 0), # 26
(328, 350, 298, 299, 242, 138, 144, 110, 146, 56, 53, 30, 0, 329, 324, 222, 194, 295, 169, 136, 88, 100, 93, 47, 35, 0), # 27
(346, 364, 315, 315, 259, 140, 151, 117, 153, 63, 55, 32, 0, 349, 337, 234, 202, 302, 170, 140, 90, 106, 94, 49, 37, 0), # 28
(362, 380, 324, 330, 265, 144, 155, 124, 158, 66, 63, 33, 0, 361, 351, 245, 211, 313, 177, 142, 97, 108, 101, 55, 37, 0), # 29
(375, 392, 341, 344, 277, 151, 164, 128, 160, 67, 66, 33, 0, 383, 365, 254, 220, 333, 183, 151, 100, 119, 104, 55, 39, 0), # 30
(392, 401, 351, 366, 291, 157, 168, 130, 163, 72, 69, 33, 0, 402, 378, 263, 227, 348, 186, 153, 103, 124, 106, 56, 40, 0), # 31
(404, 415, 367, 378, 302, 168, 173, 135, 169, 73, 71, 34, 0, 417, 390, 276, 234, 356, 199, 157, 108, 128, 113, 57, 42, 0), # 32
(415, 431, 382, 395, 305, 175, 174, 141, 175, 74, 75, 35, 0, 435, 400, 285, 242, 370, 201, 160, 111, 133, 121, 58, 43, 0), # 33
(423, 442, 394, 410, 323, 184, 178, 147, 180, 76, 79, 35, 0, 448, 413, 290, 246, 381, 208, 166, 116, 135, 123, 59, 43, 0), # 34
(446, 458, 405, 415, 336, 187, 182, 151, 184, 79, 82, 36, 0, 461, 425, 298, 252, 390, 215, 170, 121, 141, 129, 65, 44, 0), # 35
(459, 470, 422, 431, 350, 190, 186, 155, 189, 82, 83, 36, 0, 472, 430, 304, 263, 396, 224, 176, 124, 147, 134, 66, 45, 0), # 36
(474, 479, 435, 443, 358, 195, 195, 163, 197, 83, 84, 37, 0, 494, 448, 315, 270, 410, 235, 184, 126, 152, 141, 69, 45, 0), # 37
(489, 493, 451, 456, 366, 199, 199, 167, 201, 89, 85, 38, 0, 507, 456, 331, 273, 414, 242, 191, 129, 159, 147, 71, 46, 0), # 38
(505, 510, 459, 470, 375, 203, 203, 170, 207, 89, 89, 38, 0, 524, 471, 342, 280, 427, 248, 195, 132, 164, 153, 71, 46, 0), # 39
(516, 523, 470, 477, 384, 206, 204, 176, 215, 92, 92, 38, 0, 539, 478, 348, 292, 438, 254, 200, 139, 169, 159, 74, 47, 0), # 40
(531, 534, 481, 484, 394, 211, 210, 179, 223, 97, 93, 39, 0, 548, 487, 361, 299, 447, 266, 206, 142, 172, 162, 77, 48, 0), # 41
(552, 546, 495, 496, 401, 211, 214, 184, 227, 97, 93, 41, 0, 570, 501, 368, 303, 461, 279, 212, 147, 179, 168, 78, 48, 0), # 42
(569, 562, 503, 508, 414, 212, 221, 188, 233, 98, 95, 41, 0, 585, 506, 377, 311, 474, 283, 221, 151, 180, 171, 80, 49, 0), # 43
(580, 579, 519, 518, 421, 217, 228, 192, 237, 101, 96, 45, 0, 603, 520, 385, 319, 489, 290, 226, 158, 184, 175, 80, 52, 0), # 44
(592, 593, 531, 532, 431, 221, 232, 196, 240, 103, 97, 47, 0, 616, 533, 398, 327, 495, 295, 231, 160, 188, 177, 84, 53, 0), # 45
(610, 614, 541, 548, 443, 225, 236, 202, 246, 106, 98, 47, 0, 624, 538, 405, 334, 508, 303, 236, 164, 198, 179, 84, 56, 0), # 46
(617, 624, 552, 564, 452, 233, 241, 205, 254, 106, 101, 48, 0, 644, 555, 413, 337, 515, 315, 242, 168, 205, 183, 86, 59, 0), # 47
(636, 636, 560, 569, 459, 237, 244, 208, 259, 109, 102, 49, 0, 653, 562, 425, 348, 534, 324, 250, 172, 213, 185, 89, 60, 0), # 48
(645, 643, 574, 589, 476, 239, 251, 211, 263, 112, 106, 52, 0, 666, 573, 435, 357, 547, 331, 254, 175, 216, 191, 90, 61, 0), # 49
(660, 664, 587, 601, 483, 245, 258, 215, 267, 113, 107, 54, 0, 684, 585, 446, 365, 560, 341, 261, 177, 220, 197, 93, 63, 0), # 50
(671, 673, 600, 616, 492, 247, 264, 217, 271, 120, 108, 56, 0, 705, 603, 455, 374, 574, 346, 266, 178, 225, 200, 96, 66, 0), # 51
(686, 688, 611, 626, 500, 251, 267, 222, 277, 121, 109, 57, 0, 712, 610, 467, 385, 588, 351, 271, 180, 229, 200, 97, 69, 0), # 52
(697, 699, 619, 639, 509, 255, 272, 227, 279, 124, 112, 58, 0, 725, 625, 475, 389, 604, 356, 277, 186, 234, 203, 99, 70, 0), # 53
(714, 717, 625, 654, 518, 259, 277, 233, 289, 128, 114, 60, 0, 746, 642, 489, 397, 620, 362, 281, 192, 240, 206, 100, 71, 0), # 54
(724, 729, 643, 664, 529, 266, 278, 240, 296, 131, 115, 60, 0, 760, 649, 504, 404, 627, 369, 286, 195, 241, 216, 100, 71, 0), # 55
(730, 741, 656, 678, 544, 268, 282, 244, 300, 132, 118, 61, 0, 781, 665, 515, 410, 642, 373, 293, 202, 246, 220, 104, 72, 0), # 56
(736, 757, 675, 695, 548, 272, 289, 250, 308, 134, 118, 61, 0, 800, 679, 521, 412, 655, 383, 299, 206, 250, 220, 106, 73, 0), # 57
(751, 770, 690, 714, 556, 275, 295, 256, 313, 134, 120, 63, 0, 814, 688, 529, 418, 669, 386, 308, 212, 257, 224, 110, 74, 0), # 58
(764, 774, 700, 728, 563, 279, 302, 259, 320, 140, 120, 65, 0, 824, 700, 538, 428, 680, 392, 311, 217, 264, 228, 112, 74, 0), # 59
(778, 798, 706, 745, 577, 285, 306, 260, 321, 142, 121, 68, 0, 838, 710, 550, 440, 699, 397, 320, 218, 270, 234, 113, 74, 0), # 60
(791, 818, 715, 755, 588, 292, 311, 269, 330, 143, 122, 70, 0, 854, 722, 561, 447, 715, 410, 323, 224, 276, 238, 113, 75, 0), # 61
(808, 825, 727, 767, 596, 297, 316, 273, 336, 146, 123, 70, 0, 867, 730, 571, 457, 726, 414, 327, 229, 279, 244, 117, 78, 0), # 62
(816, 839, 746, 779, 605, 302, 321, 278, 338, 146, 130, 70, 0, 879, 743, 574, 464, 736, 419, 328, 233, 282, 245, 118, 78, 0), # 63
(832, 849, 757, 787, 617, 304, 328, 286, 343, 147, 134, 70, 0, 893, 759, 582, 475, 750, 426, 333, 237, 290, 249, 119, 79, 0), # 64
(839, 862, 772, 801, 626, 306, 332, 290, 346, 148, 136, 70, 0, 909, 771, 601, 479, 763, 432, 338, 238, 301, 253, 120, 80, 0), # 65
(857, 876, 783, 812, 637, 308, 332, 295, 352, 154, 137, 71, 0, 924, 781, 608, 487, 777, 442, 340, 240, 306, 257, 120, 81, 0), # 66
(872, 893, 792, 824, 652, 312, 339, 302, 360, 154, 139, 74, 0, 941, 791, 614, 498, 786, 446, 352, 242, 307, 265, 123, 81, 0), # 67
(882, 904, 798, 835, 664, 316, 346, 306, 368, 156, 141, 75, 0, 951, 799, 623, 505, 797, 449, 360, 245, 311, 269, 128, 81, 0), # 68
(896, 914, 807, 851, 670, 320, 354, 313, 371, 157, 141, 79, 0, 963, 809, 632, 510, 809, 456, 369, 248, 315, 273, 130, 81, 0), # 69
(915, 925, 815, 869, 683, 326, 361, 317, 375, 157, 146, 80, 0, 979, 817, 642, 516, 820, 462, 375, 250, 321, 277, 131, 83, 0), # 70
(932, 931, 828, 880, 698, 335, 363, 318, 384, 161, 148, 80, 0, 990, 827, 650, 520, 827, 467, 384, 254, 327, 282, 131, 83, 0), # 71
(947, 940, 847, 897, 708, 340, 372, 324, 391, 164, 149, 80, 0, 1006, 838, 662, 537, 836, 469, 392, 261, 334, 286, 133, 86, 0), # 72
(964, 951, 858, 912, 717, 346, 375, 331, 400, 166, 151, 80, 0, 1022, 847, 667, 542, 852, 475, 399, 266, 336, 287, 135, 86, 0), # 73
(973, 959, 866, 926, 729, 357, 378, 333, 403, 169, 151, 80, 0, 1040, 864, 680, 546, 865, 480, 404, 267, 341, 291, 139, 86, 0), # 74
(984, 972, 880, 937, 742, 364, 384, 336, 410, 172, 153, 81, 0, 1054, 878, 689, 555, 872, 485, 410, 268, 349, 295, 142, 87, 0), # 75
(1003, 984, 896, 947, 753, 369, 392, 339, 413, 178, 154, 81, 0, 1061, 890, 699, 563, 891, 494, 417, 270, 354, 301, 146, 87, 0), # 76
(1013, 992, 910, 959, 766, 374, 401, 344, 418, 179, 157, 81, 0, 1079, 911, 708, 574, 897, 496, 419, 274, 362, 303, 149, 88, 0), # 77
(1025, 1006, 916, 976, 781, 380, 405, 348, 424, 181, 159, 81, 0, 1090, 923, 717, 579, 908, 502, 423, 276, 367, 310, 149, 88, 0), # 78
(1037, 1014, 926, 989, 791, 386, 409, 354, 430, 184, 161, 81, 0, 1106, 930, 724, 587, 913, 506, 428, 282, 376, 312, 150, 88, 0), # 79
(1054, 1031, 938, 998, 806, 394, 411, 357, 435, 185, 162, 82, 0, 1116, 945, 737, 592, 926, 510, 434, 286, 383, 315, 151, 88, 0), # 80
(1067, 1042, 950, 1006, 818, 400, 419, 363, 443, 187, 165, 82, 0, 1135, 954, 749, 602, 938, 514, 439, 288, 388, 316, 152, 89, 0), # 81
(1080, 1055, 957, 1021, 829, 407, 425, 369, 448, 189, 165, 89, 0, 1153, 968, 756, 614, 945, 517, 442, 296, 391, 322, 155, 91, 0), # 82
(1092, 1061, 970, 1027, 835, 412, 433, 372, 454, 193, 167, 89, 0, 1170, 977, 764, 622, 957, 524, 447, 299, 398, 326, 157, 91, 0), # 83
(1103, 1074, 984, 1043, 846, 419, 441, 379, 460, 195, 168, 90, 0, 1177, 993, 772, 627, 962, 527, 453, 303, 403, 329, 159, 91, 0), # 84
(1115, 1088, 1005, 1057, 860, 426, 447, 382, 468, 199, 169, 91, 0, 1186, 1008, 782, 629, 975, 530, 459, 307, 409, 332, 162, 91, 0), # 85
(1131, 1099, 1016, 1068, 875, 430, 451, 386, 474, 200, 171, 92, 0, 1197, 1015, 790, 640, 985, 538, 462, 310, 414, 340, 164, 91, 0), # 86
(1148, 1106, 1027, 1080, 881, 433, 455, 388, 479, 202, 172, 92, 0, 1208, 1031, 798, 650, 992, 546, 467, 316, 421, 349, 165, 91, 0), # 87
(1159, 1123, 1037, 1089, 891, 439, 461, 390, 482, 206, 177, 92, 0, 1229, 1043, 807, 660, 1005, 547, 469, 321, 427, 354, 167, 92, 0), # 88
(1174, 1132, 1051, 1104, 898, 443, 465, 395, 486, 207, 180, 93, 0, 1247, 1057, 816, 664, 1014, 553, 478, 325, 432, 358, 169, 92, 0), # 89
(1187, 1140, 1060, 1115, 909, 452, 472, 397, 489, 209, 180, 93, 0, 1260, 1070, 823, 667, 1020, 562, 482, 329, 438, 359, 172, 93, 0), # 90
(1205, 1153, 1067, 1129, 918, 456, 476, 397, 497, 211, 182, 93, 0, 1274, 1080, 834, 672, 1027, 566, 492, 332, 440, 361, 177, 95, 0), # 91
(1217, 1165, 1074, 1142, 931, 463, 477, 405, 502, 215, 187, 94, 0, 1288, 1097, 842, 680, 1038, 570, 497, 335, 445, 366, 179, 96, 0), # 92
(1228, 1170, 1086, 1154, 935, 467, 480, 409, 512, 218, 188, 94, 0, 1301, 1107, 852, 686, 1059, 576, 501, 338, 447, 369, 181, 97, 0), # 93
(1242, 1183, 1098, 1167, 948, 469, 484, 416, 515, 220, 190, 95, 0, 1313, 1120, 856, 693, 1074, 582, 506, 339, 453, 374, 181, 97, 0), # 94
(1251, 1202, 1109, 1178, 955, 474, 486, 420, 518, 224, 190, 98, 0, 1325, 1137, 863, 704, 1085, 588, 511, 341, 456, 377, 181, 99, 0), # 95
(1260, 1210, 1123, 1188, 962, 480, 494, 427, 527, 227, 191, 100, 0, 1335, 1147, 872, 712, 1092, 594, 514, 350, 465, 382, 186, 99, 0), # 96
(1273, 1220, 1131, 1202, 972, 484, 496, 437, 532, 229, 193, 103, 0, 1346, 1150, 880, 720, 1104, 601, 519, 351, 473, 383, 188, 100, 0), # 97
(1290, 1228, 1143, 1214, 984, 491, 500, 439, 536, 233, 193, 105, 0, 1354, 1159, 885, 726, 1114, 606, 522, 352, 480, 387, 192, 102, 0), # 98
(1304, 1238, 1154, 1229, 996, 495, 505, 442, 540, 234, 193, 107, 0, 1368, 1172, 898, 733, 1123, 610, 526, 352, 482, 393, 196, 104, 0), # 99
(1313, 1247, 1165, 1239, 1007, 500, 507, 447, 548, 235, 193, 112, 0, 1380, 1180, 910, 741, 1135, 612, 533, 355, 492, 397, 200, 105, 0), # 100
(1329, 1258, 1175, 1246, 1019, 503, 509, 450, 554, 236, 194, 113, 0, 1393, 1192, 914, 746, 1145, 621, 539, 358, 498, 401, 202, 105, 0), # 101
(1346, 1270, 1183, 1260, 1024, 509, 514, 455, 558, 238, 195, 113, 0, 1408, 1199, 919, 758, 1154, 627, 541, 363, 501, 408, 205, 108, 0), # 102
(1360, 1282, 1191, 1272, 1032, 514, 518, 460, 565, 240, 196, 113, 0, 1428, 1213, 929, 766, 1160, 631, 545, 365, 509, 411, 205, 109, 0), # 103
(1374, 1288, 1202, 1286, 1043, 518, 522, 465, 570, 243, 197, 114, 0, 1438, 1219, 943, 772, 1168, 640, 549, 370, 511, 414, 206, 109, 0), # 104
(1390, 1299, 1211, 1299, 1055, 523, 530, 470, 578, 245, 199, 114, 0, 1455, 1229, 958, 780, 1178, 643, 555, 371, 517, 418, 209, 109, 0), # 105
(1398, 1311, 1224, 1309, 1061, 528, 535, 472, 586, 247, 200, 115, 0, 1474, 1243, 965, 784, 1190, 647, 558, 375, 522, 421, 210, 110, 0), # 106
(1409, 1323, 1240, 1314, 1064, 537, 538, 474, 593, 249, 200, 117, 0, 1489, 1256, 968, 787, 1198, 652, 565, 379, 528, 425, 213, 111, 0), # 107
(1421, 1332, 1247, 1323, 1071, 542, 542, 477, 595, 250, 202, 120, 0, 1513, 1266, 979, 796, 1207, 657, 571, 381, 534, 429, 214, 115, 0), # 108
(1431, 1347, 1261, 1333, 1078, 549, 551, 482, 603, 252, 203, 122, 0, 1530, 1275, 985, 801, 1216, 666, 574, 386, 543, 430, 217, 115, 0), # 109
(1446, 1354, 1271, 1341, 1086, 553, 555, 486, 608, 252, 203, 122, 0, 1543, 1284, 998, 810, 1225, 672, 579, 391, 548, 434, 217, 117, 0), # 110
(1465, 1367, 1280, 1354, 1102, 555, 557, 488, 617, 256, 204, 122, 0, 1551, 1292, 1009, 814, 1235, 673, 584, 393, 554, 436, 220, 117, 0), # 111
(1480, 1385, 1290, 1368, 1106, 557, 560, 490, 626, 256, 205, 122, 0, 1563, 1302, 1015, 825, 1242, 675, 586, 396, 564, 439, 222, 117, 0), # 112
(1489, 1392, 1303, 1385, 1111, 559, 560, 491, 634, 257, 208, 123, 0, 1581, 1311, 1026, 831, 1251, 686, 588, 398, 569, 444, 226, 118, 0), # 113
(1503, 1396, 1315, 1395, 1119, 566, 562, 493, 640, 259, 210, 123, 0, 1594, 1322, 1035, 837, 1261, 687, 594, 401, 573, 447, 228, 119, 0), # 114
(1518, 1403, 1324, 1408, 1129, 569, 569, 494, 644, 259, 212, 125, 0, 1605, 1333, 1050, 841, 1273, 691, 597, 404, 577, 452, 232, 122, 0), # 115
(1522, 1417, 1336, 1421, 1141, 575, 570, 500, 648, 259, 212, 126, 0, 1616, 1342, 1059, 845, 1280, 702, 600, 406, 581, 457, 233, 123, 0), # 116
(1537, 1426, 1349, 1431, 1150, 581, 574, 503, 657, 264, 213, 128, 0, 1626, 1352, 1068, 854, 1292, 703, 603, 410, 586, 459, 234, 123, 0), # 117
(1547, 1436, 1362, 1448, 1160, 587, 577, 506, 661, 265, 215, 130, 0, 1638, 1367, 1078, 863, 1297, 707, 606, 413, 592, 463, 234, 124, 0), # 118
(1552, 1444, 1370, 1455, 1171, 590, 580, 511, 666, 267, 219, 131, 0, 1648, 1376, 1089, 866, 1308, 714, 609, 416, 595, 465, 238, 127, 0), # 119
(1561, 1453, 1379, 1464, 1182, 594, 584, 513, 671, 270, 220, 131, 0, 1659, 1388, 1096, 874, 1316, 722, 612, 419, 603, 467, 242, 129, 0), # 120
(1571, 1468, 1396, 1479, 1197, 599, 588, 517, 681, 273, 223, 131, 0, 1676, 1397, 1102, 881, 1320, 726, 614, 422, 607, 472, 246, 129, 0), # 121
(1594, 1478, 1405, 1487, 1208, 603, 590, 520, 690, 274, 225, 131, 0, 1693, 1409, 1108, 888, 1328, 731, 616, 425, 615, 475, 249, 129, 0), # 122
(1610, 1483, 1410, 1501, 1218, 606, 594, 521, 694, 277, 227, 132, 0, 1710, 1420, 1119, 892, 1337, 734, 621, 430, 618, 477, 253, 130, 0), # 123
(1620, 1502, 1420, 1516, 1223, 612, 599, 523, 699, 279, 227, 132, 0, 1717, 1431, 1125, 898, 1347, 740, 623, 434, 625, 480, 253, 131, 0), # 124
(1627, 1510, 1429, 1522, 1234, 616, 604, 525, 703, 282, 228, 132, 0, 1730, 1442, 1136, 908, 1358, 746, 630, 438, 630, 482, 257, 131, 0), # 125
(1642, 1523, 1435, 1534, 1238, 621, 610, 527, 703, 285, 229, 133, 0, 1749, 1448, 1142, 914, 1366, 750, 634, 441, 634, 485, 258, 132, 0), # 126
(1649, 1531, 1444, 1545, 1250, 625, 614, 529, 709, 287, 229, 133, 0, 1757, 1455, 1146, 917, 1375, 755, 636, 443, 640, 486, 263, 133, 0), # 127
(1664, 1543, 1453, 1554, 1254, 632, 618, 531, 717, 292, 230, 135, 0, 1768, 1460, 1155, 922, 1386, 758, 640, 446, 643, 489, 267, 134, 0), # 128
(1677, 1552, 1467, 1563, 1264, 637, 622, 532, 723, 293, 231, 136, 0, 1782, 1470, 1161, 927, 1396, 767, 645, 448, 644, 497, 267, 134, 0), # 129
(1685, 1564, 1477, 1574, 1275, 642, 624, 538, 728, 294, 233, 137, 0, 1790, 1475, 1166, 933, 1405, 770, 652, 449, 646, 499, 270, 134, 0), # 130
(1690, 1570, 1496, 1581, 1280, 644, 625, 542, 734, 295, 233, 137, 0, 1799, 1485, 1175, 938, 1413, 777, 655, 453, 649, 500, 272, 134, 0), # 131
(1702, 1580, 1506, 1586, 1290, 650, 629, 549, 736, 296, 234, 137, 0, 1816, 1494, 1180, 948, 1426, 780, 657, 456, 650, 504, 279, 135, 0), # 132
(1708, 1590, 1518, 1597, 1295, 654, 633, 553, 739, 297, 236, 140, 0, 1825, 1505, 1186, 952, 1440, 784, 663, 460, 660, 509, 282, 136, 0), # 133
(1723, 1598, 1529, 1613, 1304, 659, 635, 556, 746, 299, 237, 141, 0, 1836, 1510, 1198, 957, 1452, 785, 668, 465, 665, 513, 284, 136, 0), # 134
(1735, 1609, 1542, 1626, 1317, 661, 635, 558, 750, 301, 240, 141, 0, 1846, 1521, 1205, 962, 1467, 792, 674, 467, 668, 516, 285, 139, 0), # 135
(1752, 1616, 1555, 1641, 1324, 667, 640, 560, 755, 302, 240, 142, 0, 1856, 1528, 1213, 966, 1481, 796, 678, 471, 673, 517, 287, 139, 0), # 136
(1762, 1627, 1567, 1653, 1336, 672, 642, 563, 757, 304, 242, 142, 0, 1874, 1539, 1221, 972, 1493, 800, 685, 473, 679, 520, 290, 140, 0), # 137
(1779, 1631, 1572, 1665, 1347, 675, 649, 565, 763, 310, 242, 143, 0, 1885, 1550, 1227, 977, 1501, 802, 688, 476, 686, 526, 293, 141, 0), # 138
(1795, 1643, 1584, 1673, 1355, 681, 655, 568, 767, 311, 245, 144, 0, 1898, 1558, 1235, 984, 1510, 810, 690, 480, 690, 530, 298, 142, 0), # 139
(1808, 1652, 1589, 1687, 1363, 686, 658, 573, 773, 313, 248, 145, 0, 1904, 1567, 1242, 987, 1521, 816, 695, 487, 695, 536, 301, 143, 0), # 140
(1824, 1658, 1600, 1695, 1370, 692, 664, 575, 779, 313, 249, 146, 0, 1918, 1580, 1250, 994, 1531, 818, 699, 488, 700, 538, 302, 143, 0), # 141
(1831, 1663, 1609, 1706, 1378, 697, 666, 581, 784, 315, 249, 148, 0, 1930, 1585, 1254, 996, 1541, 824, 704, 491, 703, 542, 302, 146, 0), # 142
(1848, 1677, 1622, 1716, 1393, 701, 671, 586, 791, 315, 252, 152, 0, 1943, 1595, 1260, 1002, 1556, 829, 710, 494, 705, 547, 303, 147, 0), # 143
(1859, 1688, 1637, 1729, 1398, 705, 677, 592, 792, 319, 257, 152, 0, 1954, 1606, 1267, 1006, 1567, 833, 714, 502, 712, 550, 304, 147, 0), # 144
(1865, 1701, 1648, 1733, 1405, 711, 679, 599, 799, 320, 258, 153, 0, 1963, 1613, 1280, 1011, 1575, 844, 720, 510, 717, 555, 306, 150, 0), # 145
(1880, 1713, 1656, 1743, 1414, 716, 683, 604, 803, 320, 259, 154, 0, 1974, 1622, 1293, 1016, 1586, 848, 725, 512, 720, 558, 307, 150, 0), # 146
(1892, 1725, 1665, 1751, 1421, 720, 685, 609, 805, 321, 261, 155, 0, 1990, 1634, 1299, 1021, 1595, 852, 728, 515, 724, 561, 309, 152, 0), # 147
(1902, 1734, 1680, 1763, 1429, 727, 691, 615, 809, 323, 262, 157, 0, 2004, 1642, 1308, 1027, 1603, 856, 732, 518, 726, 565, 311, 152, 0), # 148
(1920, 1747, 1686, 1778, 1441, 731, 697, 617, 814, 327, 264, 157, 0, 2014, 1649, 1316, 1032, 1611, 858, 735, 522, 733, 567, 314, 154, 0), # 149
(1938, 1750, 1696, 1788, 1445, 736, 699, 620, 816, 328, 266, 157, 0, 2023, 1660, 1320, 1037, 1629, 861, 742, 526, 739, 570, 316, 156, 0), # 150
(1947, 1755, 1700, 1791, 1452, 741, 702, 623, 821, 328, 269, 157, 0, 2033, 1672, 1328, 1043, 1639, 866, 743, 527, 740, 573, 317, 157, 0), # 151
(1956, 1758, 1709, 1803, 1460, 744, 703, 624, 825, 331, 270, 157, 0, 2047, 1678, 1331, 1047, 1648, 870, 746, 534, 743, 578, 317, 157, 0), # 152
(1963, 1763, 1716, 1815, 1465, 750, 706, 627, 829, 334, 272, 157, 0, 2057, 1689, 1336, 1055, 1657, 875, 748, 538, 750, 581, 319, 158, 0), # 153
(1970, 1773, 1724, 1823, 1473, 753, 709, 627, 831, 336, 273, 158, 0, 2066, 1700, 1346, 1062, 1671, 879, 752, 540, 753, 583, 320, 160, 0), # 154
(1987, 1779, 1734, 1836, 1479, 754, 714, 629, 832, 336, 274, 158, 0, 2080, 1703, 1351, 1065, 1678, 882, 754, 544, 758, 587, 321, 160, 0), # 155
(1991, 1784, 1738, 1844, 1483, 760, 717, 633, 835, 336, 275, 159, 0, 2090, 1712, 1356, 1069, 1685, 892, 757, 551, 762, 592, 322, 160, 0), # 156
(1994, 1791, 1744, 1849, 1497, 766, 720, 634, 837, 338, 276, 161, 0, 2103, 1720, 1362, 1074, 1696, 894, 761, 554, 765, 597, 326, 160, 0), # 157
(2003, 1796, 1760, 1857, 1505, 770, 726, 638, 844, 341, 278, 161, 0, 2108, 1729, 1363, 1082, 1708, 899, 765, 556, 768, 598, 330, 160, 0), # 158
(2010, 1802, 1770, 1862, 1513, 775, 730, 643, 850, 342, 279, 161, 0, 2114, 1742, 1370, 1088, 1715, 905, 768, 560, 772, 599, 331, 160, 0), # 159
(2023, 1807, 1782, 1867, 1519, 779, 731, 648, 852, 344, 281, 161, 0, 2125, 1749, 1376, 1093, 1722, 909, 769, 565, 777, 600, 332, 160, 0), # 160
(2034, 1813, 1791, 1874, 1523, 781, 732, 654, 859, 346, 281, 161, 0, 2131, 1760, 1383, 1096, 1728, 916, 776, 568, 783, 603, 334, 161, 0), # 161
(2046, 1823, 1796, 1880, 1532, 787, 734, 659, 866, 347, 282, 161, 0, 2141, 1765, 1393, 1100, 1741, 919, 777, 569, 790, 605, 337, 161, 0), # 162
(2055, 1829, 1808, 1888, 1536, 790, 736, 662, 873, 349, 285, 161, 0, 2153, 1771, 1400, 1101, 1746, 921, 780, 575, 793, 609, 339, 161, 0), # 163
(2064, 1834, 1815, 1897, 1544, 793, 738, 665, 879, 350, 285, 161, 0, 2162, 1776, 1404, 1103, 1754, 924, 783, 579, 798, 612, 340, 162, 0), # 164
(2075, 1842, 1827, 1904, 1549, 797, 744, 666, 885, 353, 286, 162, 0, 2168, 1785, 1407, 1104, 1758, 929, 785, 582, 800, 616, 340, 162, 0), # 165
(2080, 1845, 1840, 1913, 1553, 799, 745, 670, 890, 354, 287, 162, 0, 2180, 1790, 1412, 1109, 1767, 935, 787, 583, 802, 620, 341, 162, 0), # 166
(2086, 1852, 1848, 1921, 1557, 802, 751, 675, 896, 355, 290, 162, 0, 2193, 1796, 1422, 1114, 1772, 939, 788, 586, 807, 621, 341, 163, 0), # 167
(2095, 1857, 1859, 1932, 1562, 805, 754, 678, 898, 357, 291, 164, 0, 2201, 1804, 1428, 1117, 1780, 942, 791, 587, 808, 623, 342, 163, 0), # 168
(2100, 1862, 1867, 1942, 1565, 807, 759, 681, 902, 357, 293, 164, 0, 2214, 1810, 1432, 1119, 1786, 944, 793, 590, 808, 625, 345, 163, 0), # 169
(2111, 1867, 1872, 1948, 1570, 809, 762, 684, 905, 357, 295, 165, 0, 2223, 1816, 1441, 1125, 1793, 947, 796, 594, 814, 626, 347, 165, 0), # 170
(2121, 1871, 1877, 1952, 1581, 813, 763, 688, 907, 358, 296, 166, 0, 2230, 1822, 1452, 1129, 1806, 954, 796, 594, 816, 630, 347, 165, 0), # 171
(2130, 1873, 1881, 1958, 1584, 818, 764, 689, 909, 361, 298, 166, 0, 2234, 1827, 1456, 1132, 1814, 956, 798, 597, 817, 631, 350, 165, 0), # 172
(2138, 1879, 1883, 1962, 1590, 821, 766, 689, 911, 362, 298, 166, 0, 2242, 1834, 1465, 1137, 1818, 957, 801, 599, 820, 637, 350, 166, 0), # 173
(2144, 1884, 1889, 1968, 1597, 824, 768, 689, 913, 364, 298, 166, 0, 2250, 1840, 1468, 1139, 1824, 961, 801, 601, 824, 639, 350, 166, 0), # 174
(2152, 1887, 1894, 1975, 1602, 825, 770, 689, 915, 366, 301, 167, 0, 2256, 1843, 1469, 1144, 1829, 962, 801, 604, 826, 641, 352, 168, 0), # 175
(2157, 1892, 1898, 1982, 1610, 829, 772, 690, 917, 367, 302, 169, 0, 2261, 1843, 1471, 1146, 1834, 965, 802, 605, 828, 644, 352, 168, 0), # 176
(2168, 1896, 1907, 1988, 1615, 832, 775, 692, 918, 369, 302, 170, 0, 2269, 1844, 1475, 1149, 1839, 966, 805, 605, 831, 645, 352, 168, 0), # 177
(2173, 1900, 1911, 1991, 1621, 834, 776, 695, 923, 370, 302, 172, 0, 2278, 1845, 1476, 1151, 1843, 966, 807, 605, 836, 647, 354, 169, 0), # 178
(2173, 1900, 1911, 1991, 1621, 834, 776, 695, 923, 370, 302, 172, 0, 2278, 1845, 1476, 1151, 1843, 966, 807, 605, 836, 647, 354, 169, 0), # 179
)
passenger_arriving_rate = (
(7.029211809720476, 7.090786984939564, 6.079830434547925, 6.525401162556605, 5.184373233768971, 2.563234861163827, 2.9022249307617405, 2.7143527675713304, 2.8420462290117365, 1.3853052554328298, 0.9812285382399741, 0.571423425802387, 0.0, 7.117432297609708, 6.285657683826256, 4.90614269119987, 4.155915766298489, 5.684092458023473, 3.8000938745998627, 2.9022249307617405, 1.8308820436884476, 2.5921866168844856, 2.175133720852202, 1.2159660869095852, 0.6446169986308695, 0.0), # 0
(7.496058012827964, 7.558911224152441, 6.4812376898851785, 6.956401465940448, 5.527657648309288, 2.7325532603014207, 3.093628258884586, 2.893049671694997, 3.0297144856220246, 1.4766432422970026, 1.0460557650564308, 0.6091419437616749, 0.0, 7.587708306415797, 6.700561381378422, 5.230278825282154, 4.429929726891007, 6.059428971244049, 4.050269540372995, 3.093628258884586, 1.9518237573581576, 2.763828824154644, 2.3188004886468163, 1.2962475379770357, 0.687173747650222, 0.0), # 1
(7.9614122125716245, 8.025177635976757, 6.881049333138649, 7.385687089898034, 5.869698775499761, 2.9011961768518306, 3.284272955572493, 3.071031394610912, 3.2166338432095234, 1.5676198212571917, 1.1106254013811399, 0.6467104760728565, 0.0, 8.056110759493567, 7.113815236801421, 5.553127006905699, 4.702859463771574, 6.433267686419047, 4.2994439524552766, 3.284272955572493, 2.0722829834655934, 2.9348493877498805, 2.4618956966326784, 1.37620986662773, 0.7295616032706144, 0.0), # 2
(8.423460910405188, 8.487736310818441, 7.277679347539831, 7.811555227908678, 6.209150897601775, 3.0684948417778424, 3.473402549153569, 3.2475923418717962, 3.4020630750965104, 1.657873944449164, 1.1746812960930562, 0.6839799965752206, 0.0, 8.520781928755916, 7.523779962327425, 5.873406480465281, 4.97362183334749, 6.804126150193021, 4.5466292786205145, 3.473402549153569, 2.191782029841316, 3.1045754488008876, 2.6038517426362264, 1.455535869507966, 0.7716123918925856, 0.0), # 3
(8.880390607782374, 8.94473733908341, 7.669541716320211, 8.232303073451698, 6.5446682968767265, 3.233780486042246, 3.6602605679559215, 3.4220269190303676, 3.585260954605263, 1.7470445640086882, 1.2379672980711345, 0.7208014791080559, 0.0, 8.979864086115745, 7.928816270188614, 6.189836490355671, 5.241133692026064, 7.170521909210526, 4.790837686642515, 3.6602605679559215, 2.30984320431589, 3.2723341484383632, 2.7441010244839, 1.5339083432640421, 0.8131579399166738, 0.0), # 4
(9.330387806156915, 9.394330811177607, 8.055050422711272, 8.646227820006413, 6.874905255585995, 3.396384340607826, 3.844090540307657, 3.593629531639346, 3.765486255058061, 1.8347706320715327, 1.300227256194331, 0.7570258975106506, 0.0, 9.43149950348596, 8.327284872617156, 6.501136280971655, 5.504311896214597, 7.530972510116122, 5.031081344295084, 3.844090540307657, 2.4259888147198754, 3.4374526277929975, 2.8820759400021383, 1.6110100845422546, 0.8540300737434189, 0.0), # 5
(9.771639006982534, 9.834666817506942, 8.43261944994451, 9.051626661052135, 7.198516055990973, 3.5556376364373725, 4.024135994536884, 3.7616945852514516, 3.9419977497771805, 1.920691100773466, 1.3612050193415997, 0.7925042256222944, 0.0, 9.87383045277945, 8.717546481845236, 6.806025096707997, 5.762073302320396, 7.883995499554361, 5.266372419352033, 4.024135994536884, 2.5397411688838374, 3.5992580279954867, 3.017208887017379, 1.6865238899889023, 0.8940606197733586, 0.0), # 6
(10.202330711712957, 10.263895448477353, 8.800662781251408, 9.446796790068186, 7.514154980353052, 3.710871604493673, 4.19964045897171, 3.9255164854194056, 4.1140542120849, 2.004444922250256, 1.4206444363918964, 0.8270874372822752, 0.0, 10.304999205909127, 9.097961810105026, 7.103222181959481, 6.013334766750766, 8.2281084241698, 5.495723079587168, 4.19964045897171, 2.6506225746383376, 3.757077490176526, 3.148932263356063, 1.7601325562502819, 0.9330814044070321, 0.0), # 7
(10.62064942180191, 10.68016679449476, 9.157594399863463, 9.830035400533875, 7.820476310933614, 3.8614174757395103, 4.369847461940239, 4.0843896376959234, 4.280914415303496, 2.0856710486376717, 1.4782893562241752, 0.8606265063298821, 0.0, 10.723148034787885, 9.466891569628702, 7.391446781120876, 6.257013145913014, 8.561828830606991, 5.718145492774292, 4.369847461940239, 2.758155339813936, 3.910238155466807, 3.276678466844626, 1.831518879972693, 0.9709242540449783, 0.0), # 8
(11.02478163870312, 11.081630945965095, 9.501828289012156, 10.199639685928528, 8.116134329994049, 4.006606481137679, 4.534000531770584, 4.237608447633729, 4.441837132755248, 2.1640084320714803, 1.5338836277173917, 0.8929724066044035, 0.0, 11.126419211328628, 9.822696472648436, 7.669418138586958, 6.49202529621444, 8.883674265510496, 5.932651826687221, 4.534000531770584, 2.861861772241199, 4.058067164997024, 3.3998798953095104, 1.9003656578024313, 1.0074209950877362, 0.0), # 9
(11.412913863870306, 11.46643799329428, 9.83177843192898, 10.553906839731454, 8.399783319795748, 4.145769851650964, 4.691343196790848, 4.38446732078554, 4.596081137762433, 2.2390960246874507, 1.5871710997505006, 0.923976111945128, 0.0, 11.512955007444255, 10.163737231396405, 7.935855498752503, 6.717288074062351, 9.192162275524867, 6.138254249099756, 4.691343196790848, 2.961264179750688, 4.199891659897874, 3.517968946577152, 1.9663556863857963, 1.0424034539358438, 0.0), # 10
(11.783232598757209, 11.832738026888249, 10.145858811845418, 10.891134055421968, 8.670077562600099, 4.278238818242151, 4.841118985329142, 4.524260662704076, 4.7429052036473305, 2.3105727786213524, 1.6378956212024585, 0.9534885961913449, 0.0, 11.880897695047656, 10.488374558104791, 8.189478106012292, 6.931718335864056, 9.485810407294661, 6.333964927785706, 4.841118985329142, 3.055884870172965, 4.3350387813000495, 3.63037801847399, 2.0291717623690837, 1.075703456989841, 0.0), # 11
(12.133924344817538, 12.178681137152912, 10.442483411992965, 11.209618526479394, 8.925671340668487, 4.403344611874027, 4.9825714257135685, 4.656282878942054, 4.881568103732217, 2.378077646008951, 1.6858010409522184, 0.9813608331823415, 0.0, 12.22838954605175, 10.794969165005755, 8.429005204761092, 7.134232938026852, 9.763136207464434, 6.518796030518876, 4.9825714257135685, 3.1452461513385908, 4.462835670334243, 3.7365395088264655, 2.0884966823985933, 1.107152830650265, 0.0), # 12
(12.463175603505027, 12.502417414494213, 10.720066215603106, 11.507657446383048, 9.165218936262296, 4.520418463509383, 5.11494404627224, 4.779828375052198, 5.011328611339368, 2.441249578986017, 1.7306312078787365, 1.0074437967574077, 0.0, 12.55357283236943, 11.08188176433148, 8.653156039393682, 7.323748736958049, 10.022657222678736, 6.691759725073078, 5.11494404627224, 3.228870331078131, 4.582609468131148, 3.8358858154610167, 2.1440132431206216, 1.136583401317656, 0.0), # 13
(12.769172876273403, 12.802096949318072, 10.977021205907338, 11.783548008612232, 9.387374631642924, 4.6287916041110035, 5.237480375333263, 4.894191556587227, 5.131445499791063, 2.4997275296883177, 1.7721299708609668, 1.0315884607558323, 0.0, 12.85458982591359, 11.347473068314153, 8.860649854304834, 7.499182589064952, 10.262890999582126, 6.8518681792221185, 5.237480375333263, 3.306279717222145, 4.693687315821462, 3.9278493362040785, 2.195404241181468, 1.1638269953925522, 0.0), # 14
(13.050102664576398, 13.075869832030413, 11.211762366137135, 12.035587406646286, 9.590792709071755, 4.72779526464168, 5.349423941224739, 4.998666829099858, 5.241177542409583, 2.5531504502516222, 1.810041178777865, 1.0536457990169035, 0.0, 13.129582798597134, 11.590103789185937, 9.050205893889325, 7.659451350754866, 10.482355084819165, 6.998133560739801, 5.349423941224739, 3.3769966176011996, 4.795396354535877, 4.0118624688820965, 2.242352473227427, 1.1887154392754924, 0.0), # 15
(13.30415146986772, 13.321886153037171, 11.422703679523998, 12.262072833964503, 9.774127450810177, 4.816760676064193, 5.450018272274784, 5.092548598142811, 5.339783512517201, 2.6011572928116995, 1.8441086805083868, 1.0734667853799098, 0.0, 13.376694022332964, 11.808134639179006, 9.220543402541933, 7.803471878435097, 10.679567025034402, 7.1295680373999355, 5.450018272274784, 3.440543340045852, 4.887063725405088, 4.087357611321502, 2.2845407359047996, 1.2110805593670158, 0.0), # 16
(13.529505793601107, 13.538296002744264, 11.608259129299412, 12.46130148404622, 9.936033139119584, 4.895019069341334, 5.538506896811498, 5.17513126926881, 5.426522183436193, 2.643387009504314, 1.874076324931487, 1.09090239368414, 0.0, 13.594065769033982, 11.999926330525538, 9.370381624657433, 7.9301610285129405, 10.853044366872385, 7.245183776976335, 5.538506896811498, 3.496442192386667, 4.968016569559792, 4.153767161348741, 2.3216518258598824, 1.2307541820676606, 0.0), # 17
(13.724352137230287, 13.723249471557619, 11.766842698694862, 12.631570550370744, 10.07516405626135, 4.961901675435895, 5.6141333431629965, 5.245709248030569, 5.500652328488845, 2.6794785524652385, 1.8996879609261188, 1.1058035977688838, 0.0, 13.779840310613086, 12.163839575457718, 9.498439804630594, 8.038435657395715, 11.00130465697769, 7.343992947242797, 5.6141333431629965, 3.5442154824542103, 5.037582028130675, 4.210523516790249, 2.3533685397389728, 1.2475681337779656, 0.0), # 18
(13.88687700220898, 13.874896649883173, 11.896868370941842, 12.77117722641738, 10.190174484496875, 5.0167397253106545, 5.676141139657377, 5.30357693998081, 5.561432720997431, 2.7090708738302403, 1.9206874373712384, 1.1180213714734282, 0.0, 13.932159918983176, 12.298235086207708, 9.603437186856192, 8.12721262149072, 11.122865441994861, 7.425007715973134, 5.676141139657377, 3.5833855180790386, 5.095087242248438, 4.257059075472461, 2.379373674188369, 1.2613542408984704, 0.0), # 19
(14.015266889990915, 13.991387628126835, 11.996750129271838, 12.87841870566547, 10.279718706087547, 5.058864449928407, 5.723773814622755, 5.348028750672253, 5.608122134284226, 2.731802925735086, 1.936818603145802, 1.1274066886370624, 0.0, 14.049166866057154, 12.401473575007685, 9.68409301572901, 8.195408777205257, 11.216244268568452, 7.487240250941153, 5.723773814622755, 3.6134746070917196, 5.139859353043773, 4.292806235221825, 2.399350025854368, 1.2719443298297126, 0.0), # 20
(14.107708302029813, 14.070872496694552, 12.064901956916339, 12.951592181594311, 10.34245100329475, 5.087607080251938, 5.756274896387231, 5.378359085657614, 5.63997934167151, 2.747313660315545, 1.9478253071287643, 1.133810523099076, 0.0, 14.12900342374791, 12.471915754089835, 9.739126535643821, 8.241940980946634, 11.27995868334302, 7.529702719920659, 5.756274896387231, 3.634005057322813, 5.171225501647375, 4.317197393864771, 2.412980391383268, 1.279170226972232, 0.0), # 21
(14.162387739779412, 14.111501345992236, 12.099737837106835, 12.988994847683228, 10.377025658379871, 5.102298847244033, 5.77288791327892, 5.393862350489618, 5.656263116481561, 2.7552420297073854, 1.9534513981990798, 1.1370838486987573, 0.0, 14.16981186396836, 12.50792233568633, 9.7672569909954, 8.265726089122154, 11.312526232963123, 7.551407290685465, 5.77288791327892, 3.644499176602881, 5.188512829189936, 4.329664949227744, 2.419947567421367, 1.282863758726567, 0.0), # 22
(14.182550708679697, 14.116311945587563, 12.104077046181986, 12.993677353395064, 10.385883252297091, 5.104166666666667, 5.774862801581538, 5.395538065843622, 5.658298909465021, 2.7561772953818022, 1.9541568753377396, 1.1374880506020426, 0.0, 14.175, 12.512368556622466, 9.770784376688697, 8.268531886145405, 11.316597818930042, 7.553753292181072, 5.774862801581538, 3.6458333333333335, 5.192941626148546, 4.331225784465023, 2.4208154092363974, 1.283301085962506, 0.0), # 23
(14.197417378247815, 14.113505864197531, 12.10336728395062, 12.99310104166667, 10.390900439373862, 5.104166666666667, 5.773777668845317, 5.393208333333334, 5.658026111111111, 2.755602716049383, 1.9540790684624023, 1.1373934156378602, 0.0, 14.175, 12.51132757201646, 9.77039534231201, 8.266808148148147, 11.316052222222222, 7.550491666666668, 5.773777668845317, 3.6458333333333335, 5.195450219686931, 4.331033680555557, 2.4206734567901242, 1.2830459876543212, 0.0), # 24
(14.211970122296213, 14.10797467992684, 12.101966163694561, 12.991960841049384, 10.39580728255487, 5.104166666666667, 5.771639231824418, 5.388631687242799, 5.657487139917696, 2.754471593507088, 1.9539247931994848, 1.1372065996037193, 0.0, 14.175, 12.509272595640908, 9.769623965997424, 8.263414780521263, 11.314974279835392, 7.544084362139919, 5.771639231824418, 3.6458333333333335, 5.197903641277435, 4.330653613683129, 2.4203932327389124, 1.2825431527206221, 0.0), # 25
(14.226207826667249, 14.099802892089624, 12.099892889803387, 12.990269714506173, 10.400603610526364, 5.104166666666667, 5.768480702816105, 5.381894547325103, 5.65668890946502, 2.7528027480566992, 1.9536954462318665, 1.136930163084896, 0.0, 14.175, 12.506231793933855, 9.768477231159332, 8.258408244170097, 11.31337781893004, 7.534652366255146, 5.768480702816105, 3.6458333333333335, 5.200301805263182, 4.330089904835392, 2.4199785779606775, 1.2818002629172387, 0.0), # 26
(14.240129377203292, 14.089075, 12.097166666666668, 12.988040625, 10.405289251974601, 5.104166666666667, 5.7643352941176484, 5.3730833333333345, 5.655638333333333, 2.7506150000000003, 1.9533924242424245, 1.1365666666666672, 0.0, 14.175, 12.502233333333336, 9.766962121212122, 8.251845, 11.311276666666666, 7.5223166666666685, 5.7643352941176484, 3.6458333333333335, 5.2026446259873005, 4.329346875000001, 2.4194333333333335, 1.280825, 0.0), # 27
(14.253733659746702, 14.075875502972108, 12.093806698673983, 12.985286535493827, 10.40986403558584, 5.104166666666667, 5.759236218026306, 5.362284465020577, 5.654342325102881, 2.7479271696387753, 1.9530171239140377, 1.1361186709343092, 0.0, 14.175, 12.4973053802774, 9.765085619570188, 8.243781508916324, 11.308684650205763, 7.507198251028808, 5.759236218026306, 3.6458333333333335, 5.20493201779292, 4.32842884516461, 2.418761339734797, 1.2796250457247373, 0.0), # 28
(14.26701956013985, 14.060288900320074, 12.089832190214908, 12.982020408950618, 10.41432779004634, 5.104166666666667, 5.753216686839346, 5.349584362139918, 5.652807798353909, 2.7447580772748066, 1.952570941929584, 1.1355887364730988, 0.0, 14.175, 12.491476101204084, 9.76285470964792, 8.234274231824418, 11.305615596707819, 7.489418106995886, 5.753216686839346, 3.6458333333333335, 5.20716389502317, 4.327340136316874, 2.4179664380429817, 1.2782080818472796, 0.0), # 29
(14.279985964225098, 14.042399691358026, 12.085262345679013, 12.978255208333334, 10.418680344042354, 5.104166666666667, 5.746309912854031, 5.335069444444444, 5.651041666666666, 2.7411265432098775, 1.952055274971942, 1.1349794238683129, 0.0, 14.175, 12.48477366255144, 9.760276374859709, 8.223379629629632, 11.302083333333332, 7.469097222222222, 5.746309912854031, 3.6458333333333335, 5.209340172021177, 4.326085069444446, 2.4170524691358026, 1.276581790123457, 0.0), # 30
(14.292631757844802, 14.022292375400093, 12.080116369455878, 12.97400389660494, 10.422921526260142, 5.104166666666667, 5.7385491083676285, 5.318826131687244, 5.649050843621399, 2.737051387745771, 1.9514715197239891, 1.1342932937052284, 0.0, 14.175, 12.477226230757509, 9.757357598619945, 8.211154163237312, 11.298101687242799, 7.4463565843621415, 5.7385491083676285, 3.6458333333333335, 5.211460763130071, 4.324667965534981, 2.416023273891176, 1.2747538523090995, 0.0), # 31
(14.304955826841338, 14.000051451760402, 12.07441346593507, 12.969279436728398, 10.427051165385956, 5.104166666666667, 5.7299674856774, 5.3009408436214, 5.646842242798354, 2.7325514311842714, 1.950821072868604, 1.1335329065691209, 0.0, 14.175, 12.468861972260328, 9.754105364343019, 8.197654293552812, 11.293684485596708, 7.421317181069961, 5.7299674856774, 3.6458333333333335, 5.213525582692978, 4.3230931455761334, 2.4148826931870144, 1.272731950160037, 0.0), # 32
(14.316957057057056, 13.975761419753086, 12.068172839506175, 12.964094791666666, 10.431069090106059, 5.104166666666667, 5.720598257080611, 5.2815, 5.644422777777778, 2.7276454938271613, 1.9501053310886647, 1.1327008230452675, 0.0, 14.175, 12.459709053497942, 9.750526655443322, 8.182936481481482, 11.288845555555556, 7.394100000000001, 5.720598257080611, 3.6458333333333335, 5.215534545053029, 4.321364930555556, 2.413634567901235, 1.2705237654320989, 0.0), # 33
(14.328634334334335, 13.949506778692271, 12.061413694558757, 12.958462924382715, 10.434975129106702, 5.104166666666667, 5.710474634874527, 5.260590020576132, 5.641799362139919, 2.7223523959762237, 1.9493256910670491, 1.1317996037189455, 0.0, 14.175, 12.449795640908398, 9.746628455335244, 8.16705718792867, 11.283598724279837, 7.3648260288065845, 5.710474634874527, 3.6458333333333335, 5.217487564553351, 4.319487641460906, 2.4122827389117516, 1.2681369798811157, 0.0), # 34
(14.339986544515531, 13.92137202789209, 12.054155235482398, 12.952396797839505, 10.438769111074146, 5.104166666666667, 5.699629831356412, 5.238297325102881, 5.638978909465021, 2.7166909579332423, 1.9484835494866362, 1.1308318091754308, 0.0, 14.175, 12.439149900929737, 9.74241774743318, 8.150072873799726, 11.277957818930043, 7.333616255144034, 5.699629831356412, 3.6458333333333335, 5.219384555537073, 4.317465599279836, 2.41083104709648, 1.2655792752629174, 0.0), # 35
(14.35101257344301, 13.891441666666665, 12.04641666666667, 12.945909375, 10.442450864694647, 5.104166666666667, 5.68809705882353, 5.214708333333334, 5.635968333333333, 2.7106800000000004, 1.9475803030303034, 1.1298000000000004, 0.0, 14.175, 12.427800000000001, 9.737901515151515, 8.13204, 11.271936666666665, 7.300591666666668, 5.68809705882353, 3.6458333333333335, 5.221225432347324, 4.315303125000001, 2.409283333333334, 1.2628583333333334, 0.0), # 36
(14.361711306959135, 13.859800194330132, 12.038217192501145, 12.939013618827161, 10.44602021865446, 5.104166666666667, 5.675909529573146, 5.189909465020577, 5.632774547325103, 2.7043383424782816, 1.9466173483809293, 1.1287067367779304, 0.0, 14.175, 12.415774104557233, 9.733086741904645, 8.113015027434844, 11.265549094650206, 7.265873251028808, 5.675909529573146, 3.6458333333333335, 5.22301010932723, 4.313004539609055, 2.407643438500229, 1.259981835848194, 0.0), # 37
(14.372081630906267, 13.826532110196618, 12.029576017375401, 12.931722492283953, 10.449477001639845, 5.104166666666667, 5.663100455902526, 5.1639871399176975, 5.629404465020576, 2.6976848056698683, 1.9455960822213911, 1.1275545800944982, 0.0, 14.175, 12.403100381039478, 9.727980411106955, 8.093054417009604, 11.258808930041152, 7.229581995884776, 5.663100455902526, 3.6458333333333335, 5.224738500819923, 4.3105741640946516, 2.40591520347508, 1.2569574645633292, 0.0), # 38
(14.382122431126781, 13.791721913580247, 12.020512345679016, 12.924048958333334, 10.452821042337057, 5.104166666666667, 5.649703050108934, 5.137027777777778, 5.625865000000001, 2.690738209876544, 1.9445179012345684, 1.1263460905349796, 0.0, 14.175, 12.389806995884772, 9.722589506172842, 8.07221462962963, 11.251730000000002, 7.191838888888889, 5.649703050108934, 3.6458333333333335, 5.226410521168528, 4.308016319444445, 2.4041024691358035, 1.253792901234568, 0.0), # 39
(14.39183259346303, 13.755454103795152, 12.011045381801555, 12.916005979938273, 10.45605216943235, 5.104166666666667, 5.635750524489632, 5.1091177983539104, 5.622163065843623, 2.6835173754000925, 1.943384202103338, 1.125083828684652, 0.0, 14.175, 12.375922115531171, 9.71692101051669, 8.050552126200277, 11.244326131687245, 7.1527649176954755, 5.635750524489632, 3.6458333333333335, 5.228026084716175, 4.305335326646092, 2.4022090763603114, 1.2504958276177414, 0.0), # 40
(14.40121100375738, 13.717813180155463, 12.001194330132604, 12.90760652006173, 10.459170211611989, 5.104166666666667, 5.621276091341887, 5.080343621399178, 5.618305576131687, 2.676041122542296, 1.9421963815105796, 1.1237703551287916, 0.0, 14.175, 12.361473906416705, 9.710981907552897, 8.028123367626886, 11.236611152263373, 7.112481069958849, 5.621276091341887, 3.6458333333333335, 5.229585105805994, 4.302535506687244, 2.400238866026521, 1.2470739254686787, 0.0), # 41
(14.410256547852201, 13.678883641975311, 11.990978395061731, 12.89886354166667, 10.462174997562222, 5.104166666666667, 5.6063129629629636, 5.050791666666668, 5.614299444444446, 2.668328271604939, 1.9409558361391697, 1.122408230452675, 0.0, 14.175, 12.346490534979424, 9.704779180695848, 8.004984814814815, 11.228598888888891, 7.071108333333335, 5.6063129629629636, 3.6458333333333335, 5.231087498781111, 4.299621180555557, 2.3981956790123466, 1.2435348765432102, 0.0), # 42
(14.418968111589852, 13.638749988568819, 11.980416780978512, 12.889790007716051, 10.46506635596931, 5.104166666666667, 5.5908943516501255, 5.020548353909466, 5.61015158436214, 2.660397642889804, 1.9396639626719878, 1.1210000152415793, 0.0, 14.175, 12.331000167657372, 9.698319813359937, 7.981192928669412, 11.22030316872428, 7.0287676954732525, 5.5908943516501255, 3.6458333333333335, 5.232533177984655, 4.296596669238685, 2.3960833561957027, 1.2398863625971654, 0.0), # 43
(14.427344580812699, 13.597496719250115, 11.969528692272522, 12.880398881172843, 10.467844115519508, 5.104166666666667, 5.575053469700638, 4.98970010288066, 5.605868909465021, 2.652268056698675, 1.938322157791911, 1.1195482700807806, 0.0, 14.175, 12.315030970888586, 9.691610788959554, 7.9568041700960235, 11.211737818930041, 6.985580144032924, 5.575053469700638, 3.6458333333333335, 5.233922057759754, 4.293466293724282, 2.3939057384545044, 1.2361360653863744, 0.0), # 44
(14.435384841363105, 13.555208333333335, 11.958333333333336, 12.870703125000002, 10.470508104899077, 5.104166666666667, 5.558823529411765, 4.958333333333334, 5.601458333333333, 2.6439583333333343, 1.9369318181818187, 1.1180555555555556, 0.0, 14.175, 12.29861111111111, 9.684659090909092, 7.931875000000002, 11.202916666666667, 6.941666666666667, 5.558823529411765, 3.6458333333333335, 5.235254052449538, 4.290234375000002, 2.391666666666667, 1.232291666666667, 0.0), # 45
(14.443087779083434, 13.511969330132603, 11.946849908550526, 12.860715702160494, 10.47305815279427, 5.104166666666667, 5.542237743080772, 4.926534465020577, 5.596926769547324, 2.635487293095565, 1.9354943405245877, 1.1165244322511814, 0.0, 14.175, 12.281768754762993, 9.677471702622938, 7.906461879286693, 11.193853539094649, 6.897148251028808, 5.542237743080772, 3.6458333333333335, 5.236529076397135, 4.286905234053499, 2.3893699817101055, 1.228360848193873, 0.0), # 46
(14.45045227981605, 13.46786420896205, 11.935097622313673, 12.850449575617287, 10.475494087891343, 5.104166666666667, 5.525329323004923, 4.894389917695474, 5.592281131687244, 2.6268737562871523, 1.9340111215030973, 1.1149574607529342, 0.0, 14.175, 12.264532068282275, 9.670055607515485, 7.880621268861455, 11.184562263374488, 6.852145884773663, 5.525329323004923, 3.6458333333333335, 5.237747043945672, 4.283483191872429, 2.387019524462735, 1.2243512917238228, 0.0), # 47
(14.457477229403315, 13.422977469135803, 11.923095679012349, 12.839917708333335, 10.477815738876558, 5.104166666666667, 5.508131481481482, 4.861986111111112, 5.587528333333333, 2.618136543209877, 1.9324835578002246, 1.1133572016460909, 0.0, 14.175, 12.246929218106997, 9.662417789001124, 7.854409629629629, 11.175056666666666, 6.806780555555557, 5.508131481481482, 3.6458333333333335, 5.238907869438279, 4.279972569444446, 2.38461913580247, 1.2202706790123459, 0.0), # 48
(14.464161513687602, 13.377393609967992, 11.910863283036125, 12.829133063271607, 10.480022934436168, 5.104166666666667, 5.490677430807714, 4.829409465020577, 5.582675288065844, 2.6092944741655244, 1.930913046098849, 1.1117262155159278, 0.0, 14.175, 12.228988370675204, 9.654565230494246, 7.827883422496572, 11.165350576131688, 6.761173251028807, 5.490677430807714, 3.6458333333333335, 5.240011467218084, 4.276377687757203, 2.382172656607225, 1.2161266918152722, 0.0), # 49
(14.470504018511264, 13.33119713077275, 11.89841963877458, 12.81810860339506, 10.482115503256427, 5.104166666666667, 5.473000383280885, 4.796746399176955, 5.57772890946502, 2.6003663694558763, 1.9293009830818477, 1.1100670629477218, 0.0, 14.175, 12.210737692424937, 9.646504915409238, 7.8010991083676275, 11.15545781893004, 6.715444958847738, 5.473000383280885, 3.6458333333333335, 5.2410577516282135, 4.272702867798355, 2.379683927754916, 1.211927011888432, 0.0), # 50
(14.476503629716676, 13.284472530864198, 11.885783950617286, 12.806857291666669, 10.484093274023598, 5.104166666666667, 5.455133551198258, 4.764083333333335, 5.572696111111112, 2.5913710493827167, 1.9276487654320995, 1.1083823045267494, 0.0, 14.175, 12.192205349794241, 9.638243827160496, 7.774113148148149, 11.145392222222224, 6.669716666666668, 5.455133551198258, 3.6458333333333335, 5.242046637011799, 4.268952430555557, 2.377156790123457, 1.2076793209876546, 0.0), # 51
(14.482159233146191, 13.237304309556471, 11.87297542295382, 12.795392091049385, 10.485956075423934, 5.104166666666667, 5.437110146857097, 4.731506687242798, 5.567583806584363, 2.582327334247829, 1.9259577898324816, 1.1066745008382872, 0.0, 14.175, 12.173419509221157, 9.629788949162407, 7.746982002743485, 11.135167613168726, 6.624109362139918, 5.437110146857097, 3.6458333333333335, 5.242978037711967, 4.265130697016462, 2.3745950845907644, 1.2033913008687704, 0.0), # 52
(14.487469714642183, 13.189776966163697, 11.860013260173757, 12.783725964506175, 10.487703736143693, 5.104166666666667, 5.418963382554669, 4.699102880658437, 5.5623989094650215, 2.573254044352996, 1.9242294529658732, 1.104946212467612, 0.0, 14.175, 12.15440833714373, 9.621147264829364, 7.719762133058986, 11.124797818930043, 6.578744032921811, 5.418963382554669, 3.6458333333333335, 5.243851868071847, 4.261241988168726, 2.3720026520347517, 1.199070633287609, 0.0), # 53
(14.492433960047004, 13.141975000000002, 11.846916666666667, 12.771871875000002, 10.489336084869135, 5.104166666666667, 5.400726470588236, 4.6669583333333335, 5.557148333333334, 2.5641700000000007, 1.9224651515151516, 1.1032000000000002, 0.0, 14.175, 12.1352, 9.612325757575757, 7.69251, 11.114296666666668, 6.533741666666667, 5.400726470588236, 3.6458333333333335, 5.244668042434568, 4.257290625000001, 2.369383333333334, 1.1947250000000003, 0.0), # 54
(14.497050855203032, 13.093982910379516, 11.833704846822133, 12.759842785493827, 10.490852950286511, 5.104166666666667, 5.382432623255064, 4.6351594650205765, 5.551838991769547, 2.555094021490627, 1.9206662821631961, 1.101438424020729, 0.0, 14.175, 12.115822664228014, 9.603331410815981, 7.66528206447188, 11.103677983539095, 6.4892232510288075, 5.382432623255064, 3.6458333333333335, 5.2454264751432556, 4.253280928497944, 2.3667409693644266, 1.1903620827617745, 0.0), # 55
(14.501319285952622, 13.045885196616371, 11.820397005029724, 12.74765165895062, 10.492254161082082, 5.104166666666667, 5.3641150528524175, 4.603792695473252, 5.5464777983539095, 2.5460449291266585, 1.918834241592884, 1.099664045115074, 0.0, 14.175, 12.096304496265812, 9.59417120796442, 7.638134787379974, 11.092955596707819, 6.445309773662553, 5.3641150528524175, 3.6458333333333335, 5.246127080541041, 4.249217219650207, 2.3640794010059447, 1.1859895633287612, 0.0), # 56
(14.505238138138138, 12.997766358024693, 11.807012345679016, 12.735311458333335, 10.493539545942102, 5.104166666666667, 5.34580697167756, 4.572944444444445, 5.541071666666667, 2.5370415432098774, 1.9169704264870937, 1.097879423868313, 0.0, 14.175, 12.076673662551439, 9.584852132435467, 7.61112462962963, 11.082143333333335, 6.402122222222224, 5.34580697167756, 3.6458333333333335, 5.246769772971051, 4.245103819444446, 2.3614024691358035, 1.1816151234567904, 0.0), # 57
(14.508806297601952, 12.949710893918612, 11.79357007315958, 12.72283514660494, 10.494708933552829, 5.104166666666667, 5.3275415920277585, 4.5427011316872425, 5.535627510288066, 2.5281026840420675, 1.9150762335287033, 1.096087120865722, 0.0, 14.175, 12.05695832952294, 9.575381167643515, 7.584308052126201, 11.071255020576132, 6.35978158436214, 5.3275415920277585, 3.6458333333333335, 5.2473544667764145, 4.240945048868314, 2.3587140146319165, 1.1772464449016922, 0.0), # 58
(14.51202265018642, 12.901803303612255, 11.780089391860999, 12.710235686728396, 10.495762152600523, 5.104166666666667, 5.309352126200275, 4.513149176954733, 5.530152242798355, 2.5192471719250125, 1.9131530594005905, 1.0942896966925775, 0.0, 14.175, 12.037186663618352, 9.565765297002951, 7.557741515775036, 11.06030448559671, 6.3184088477366265, 5.309352126200275, 3.6458333333333335, 5.247881076300262, 4.2367452289094665, 2.3560178783722, 1.172891209419296, 0.0), # 59
(14.51488608173391, 12.854128086419754, 11.76658950617284, 12.697526041666668, 10.496699031771435, 5.104166666666667, 5.291271786492374, 4.484375000000001, 5.524652777777779, 2.5104938271604946, 1.9112023007856345, 1.0924897119341568, 0.0, 14.175, 12.017386831275722, 9.556011503928172, 7.5314814814814826, 11.049305555555557, 6.278125000000001, 5.291271786492374, 3.6458333333333335, 5.248349515885717, 4.232508680555557, 2.353317901234568, 1.1685570987654323, 0.0), # 60
(14.517395478086781, 12.806769741655238, 11.753089620484685, 12.684719174382717, 10.497519399751823, 5.104166666666667, 5.273333785201324, 4.4564650205761325, 5.519136028806585, 2.501861470050298, 1.9092253543667126, 1.0906897271757356, 0.0, 14.175, 11.997586998933091, 9.546126771833563, 7.5055844101508935, 11.03827205761317, 6.2390510288065855, 5.273333785201324, 3.6458333333333335, 5.248759699875912, 4.22823972479424, 2.350617924096937, 1.1642517946959308, 0.0), # 61
(14.519549725087407, 12.759812768632832, 11.739608939186102, 12.671828047839508, 10.498223085227952, 5.104166666666667, 5.255571334624385, 4.429505658436215, 5.513608909465021, 2.4933689208962058, 1.9072236168267036, 1.0888923030025914, 0.0, 14.175, 11.977815333028504, 9.536118084133516, 7.4801067626886155, 11.027217818930042, 6.201307921810701, 5.255571334624385, 3.6458333333333335, 5.249111542613976, 4.2239426826131705, 2.3479217878372207, 1.1599829789666212, 0.0), # 62
(14.521347708578144, 12.713341666666667, 11.72616666666667, 12.658865625, 10.498809916886067, 5.104166666666667, 5.238017647058824, 4.4035833333333345, 5.508078333333334, 2.4850350000000003, 1.9051984848484853, 1.0871000000000002, 0.0, 14.175, 11.9581, 9.525992424242425, 7.455105, 11.016156666666667, 6.165016666666668, 5.238017647058824, 3.6458333333333335, 5.249404958443034, 4.219621875000001, 2.345233333333334, 1.1557583333333337, 0.0), # 63
(14.522788314401359, 12.667440935070873, 11.712782007315958, 12.645844868827162, 10.499279723412432, 5.104166666666667, 5.220705934801905, 4.378784465020577, 5.50255121399177, 2.4768785276634664, 1.9031513551149353, 1.0853153787532392, 0.0, 14.175, 11.938469166285628, 9.515756775574676, 7.430635582990398, 11.00510242798354, 6.130298251028808, 5.220705934801905, 3.6458333333333335, 5.249639861706216, 4.215281622942388, 2.342556401463192, 1.151585539551898, 0.0), # 64
(14.523870428399414, 12.62219507315958, 11.69947416552355, 12.63277874228395, 10.499632333493302, 5.104166666666667, 5.2036694101508925, 4.35519547325103, 5.497034465020577, 2.4689183241883863, 1.9010836243089335, 1.0835409998475842, 0.0, 14.175, 11.918950998323425, 9.505418121544666, 7.406754972565158, 10.994068930041154, 6.097273662551442, 5.2036694101508925, 3.6458333333333335, 5.249816166746651, 4.2109262474279845, 2.3398948331047102, 1.1474722793781438, 0.0), # 65
(14.524592936414676, 12.577688580246916, 11.686262345679015, 12.619680208333333, 10.499867575814935, 5.104166666666667, 5.1869412854030505, 4.332902777777779, 5.491535000000001, 2.4611732098765438, 1.898996689113356, 1.0817794238683132, 0.0, 14.175, 11.899573662551441, 9.49498344556678, 7.38351962962963, 10.983070000000001, 6.06606388888889, 5.1869412854030505, 3.6458333333333335, 5.249933787907468, 4.206560069444445, 2.337252469135803, 1.1434262345679016, 0.0), # 66
(14.524954724289511, 12.534005955647004, 11.673165752171926, 12.606562229938273, 10.499985279063587, 5.104166666666667, 5.1705547728556445, 4.311992798353911, 5.486059732510288, 2.453662005029722, 1.8968919462110825, 1.0800332114007012, 0.0, 14.175, 11.88036532540771, 9.484459731055413, 7.360986015089164, 10.972119465020576, 6.036789917695475, 5.1705547728556445, 3.6458333333333335, 5.2499926395317935, 4.202187409979425, 2.3346331504343856, 1.1394550868770006, 0.0), # 67
(14.524708260273156, 12.491002420461081, 11.660140274919984, 12.593323827495976, 10.499886091610856, 5.104071942793273, 5.154460636380753, 4.292367245846671, 5.480574329370524, 2.446367154576509, 1.894733397326088, 1.078295169221637, 0.0, 14.174825210048013, 11.861246861438005, 9.47366698663044, 7.339101463729525, 10.961148658741047, 6.009314144185339, 5.154460636380753, 3.6457656734237665, 5.249943045805428, 4.197774609165326, 2.3320280549839967, 1.135545674587371, 0.0), # 68
(14.522398389694043, 12.44736508363202, 11.646819830246914, 12.579297690217391, 10.498983297022512, 5.1033231138545965, 5.13818772694263, 4.272974279835392, 5.474838991769548, 2.439082236746551, 1.8923013290802768, 1.0765088802252547, 0.0, 14.17344039351852, 11.8415976824778, 9.461506645401384, 7.317246710239651, 10.949677983539097, 5.982163991769549, 5.13818772694263, 3.6452307956104257, 5.249491648511256, 4.193099230072464, 2.329363966049383, 1.1315786439665476, 0.0), # 69
(14.517840102582454, 12.402893656798973, 11.633146504915409, 12.564391480475042, 10.49719935985368, 5.101848358989992, 5.121662094192959, 4.253638926992837, 5.468821349641823, 2.4317718335619576, 1.8895680735227522, 1.0746659888174948, 0.0, 14.170705268347055, 11.82132587699244, 9.447840367613761, 7.295315500685872, 10.937642699283646, 5.955094497789972, 5.121662094192959, 3.6441773992785653, 5.24859967992684, 4.188130493491681, 2.326629300983082, 1.127535786981725, 0.0), # 70
(14.511097524900102, 12.357614716359132, 11.619125100022863, 12.548627178945251, 10.49455687350386, 5.0996715769953775, 5.104891161677292, 4.234367588782199, 5.462530365035819, 2.4244361257699243, 1.8865437198495683, 1.072767842674817, 0.0, 14.166655842764062, 11.800446269422984, 9.43271859924784, 7.273308377309771, 10.925060730071637, 5.928114624295079, 5.104891161677292, 3.642622554996698, 5.24727843675193, 4.182875726315085, 2.323825020004573, 1.1234195196690122, 0.0), # 71
(14.502234782608697, 12.311554838709677, 11.604760416666666, 12.532026766304348, 10.49107843137255, 5.096816666666667, 5.087882352941177, 4.215166666666667, 5.4559750000000005, 2.4170752941176477, 1.8832383572567788, 1.0708157894736845, 0.0, 14.161328125, 11.778973684210527, 9.416191786283894, 7.251225882352942, 10.911950000000001, 5.901233333333334, 5.087882352941177, 3.6405833333333337, 5.245539215686275, 4.177342255434784, 2.3209520833333337, 1.1192322580645162, 0.0), # 72
(14.491316001669949, 12.264740600247798, 11.590057255944217, 12.514612223228664, 10.486786626859248, 5.0933075267997765, 5.070643091530164, 4.196042562109436, 5.4491642165828384, 2.409689519352323, 1.8796620749404376, 1.0688111768905575, 0.0, 14.154758123285324, 11.75692294579613, 9.398310374702186, 7.229068558056968, 10.898328433165677, 5.8744595869532095, 5.070643091530164, 3.638076804856983, 5.243393313429624, 4.171537407742889, 2.3180114511888434, 1.1149764182043456, 0.0), # 73
(14.478405308045566, 12.21719857737068, 11.575020418952905, 12.496405530394526, 10.481704053363458, 5.089168056190623, 5.053180800989806, 4.177001676573693, 5.4421069768328, 2.402278982221147, 1.8758249620965999, 1.0667553526018982, 0.0, 14.146981845850483, 11.734308878620878, 9.379124810482999, 7.20683694666344, 10.8842139536656, 5.84780234720317, 5.053180800989806, 3.635120040136159, 5.240852026681729, 4.165468510131509, 2.315004083790581, 1.1106544161246077, 0.0), # 74
(14.463566827697262, 12.168955346475506, 11.559654706790123, 12.477428668478263, 10.475853304284678, 5.084422153635118, 5.03550290486565, 4.158050411522635, 5.434812242798353, 2.394843863471315, 1.8717371079213185, 1.0646496642841674, 0.0, 14.138035300925928, 11.711146307125839, 9.358685539606592, 7.184531590413944, 10.869624485596706, 5.821270576131688, 5.03550290486565, 3.63173010973937, 5.237926652142339, 4.159142889492755, 2.311930941358025, 1.10626866786141, 0.0), # 75
(14.44686468658675, 12.12003748395947, 11.543964920553272, 12.457703618156202, 10.469256973022405, 5.079093717929179, 5.017616826703247, 4.139195168419449, 5.427288976527969, 2.3873843438500235, 1.8674086016106486, 1.0624954596138265, 0.0, 14.127954496742113, 11.68745005575209, 9.337043008053241, 7.162153031550069, 10.854577953055937, 5.794873235787229, 5.017616826703247, 3.6279240842351275, 5.234628486511203, 4.152567872718735, 2.3087929841106543, 1.101821589450861, 0.0), # 76
(14.428363010675731, 12.070471566219748, 11.527955861339734, 12.43725236010467, 10.461937652976141, 5.07320664786872, 4.9995299900481465, 4.120442348727329, 5.4195461400701115, 2.3799006041044684, 1.8628495323606438, 1.0602940862673376, 0.0, 14.116775441529496, 11.663234948940712, 9.314247661803218, 7.139701812313404, 10.839092280140223, 5.768619288218261, 4.9995299900481465, 3.623719034191943, 5.230968826488071, 4.145750786701558, 2.305591172267947, 1.0973155969290682, 0.0), # 77
(14.408125925925928, 12.020284169653527, 11.511632330246915, 12.416096875000001, 10.45391793754539, 5.066784842249657, 4.981249818445898, 4.101798353909466, 5.41159269547325, 2.372392824981845, 1.8580699893673582, 1.0580468919211612, 0.0, 14.10453414351852, 11.638515811132772, 9.29034994683679, 7.1171784749455345, 10.8231853909465, 5.742517695473253, 4.981249818445898, 3.6191320301783265, 5.226958968772695, 4.138698958333334, 2.3023264660493834, 1.092753106332139, 0.0), # 78
(14.386217558299041, 11.969501870657995, 11.494999128372202, 12.394259143518521, 10.445220420129644, 5.0598521998679065, 4.962783735442051, 4.0832695854290515, 5.403437604785855, 2.3648611872293506, 1.8530800618268455, 1.0557552242517592, 0.0, 14.091266610939643, 11.613307466769347, 9.265400309134227, 7.094583561688051, 10.80687520957171, 5.716577419600672, 4.962783735442051, 3.61418014276279, 5.222610210064822, 4.131419714506174, 2.2989998256744406, 1.0881365336961817, 0.0), # 79
(14.362702033756786, 11.918151245630337, 11.478061056812987, 12.371761146336556, 10.435867694128408, 5.052432619519382, 4.9441391645821575, 4.064862444749277, 5.395089830056394, 2.35730587159418, 1.847889838935161, 1.0534204309355928, 0.0, 14.07700885202332, 11.587624740291517, 9.239449194675805, 7.071917614782539, 10.790179660112788, 5.690807422648988, 4.9441391645821575, 3.6088804425138443, 5.217933847064204, 4.123920382112186, 2.2956122113625974, 1.0834682950573036, 0.0), # 80
(14.337643478260873, 11.866258870967743, 11.460822916666668, 12.348624864130437, 10.425882352941176, 5.04455, 4.925323529411765, 4.046583333333334, 5.386558333333333, 2.34972705882353, 1.8425094098883579, 1.0510438596491232, 0.0, 14.061796875, 11.561482456140352, 9.212547049441788, 7.049181176470589, 10.773116666666667, 5.665216666666669, 4.925323529411765, 3.60325, 5.212941176470588, 4.11620828804348, 2.2921645833333337, 1.0787508064516131, 0.0), # 81
(14.311106017773009, 11.813851323067393, 11.443289509030638, 12.32487227757649, 10.415286989967456, 5.036228240105676, 4.906344253476426, 4.0284386526444145, 5.3778520766651425, 2.342124929664596, 1.83694886388249, 1.048626858068812, 0.0, 14.045666688100141, 11.53489543875693, 9.18474431941245, 7.026374788993786, 10.755704153330285, 5.63981411370218, 4.906344253476426, 3.5973058857897686, 5.207643494983728, 4.1082907591921645, 2.2886579018061277, 1.0739864839152178, 0.0), # 82
(14.283153778254908, 11.760955178326475, 11.425465635002288, 12.300525367351046, 10.40410419860674, 5.027491238632323, 4.887208760321688, 4.01043480414571, 5.368980022100289, 2.3344996648645746, 1.8312182901136123, 1.0461707738711208, 0.0, 14.028654299554185, 11.507878512582325, 9.156091450568061, 7.0034989945937225, 10.737960044200578, 5.614608725803994, 4.887208760321688, 3.5910651704516594, 5.20205209930337, 4.1001751224503495, 2.2850931270004575, 1.0691777434842251, 0.0), # 83
(14.253850885668278, 11.707597013142175, 11.407356095679013, 12.275606114130436, 10.392356572258533, 5.0183628943758585, 4.867924473493101, 3.9925781893004118, 5.359951131687243, 2.3268514451706617, 1.825327777777778, 1.0436769547325107, 0.0, 14.010795717592593, 11.480446502057614, 9.12663888888889, 6.980554335511984, 10.719902263374486, 5.589609465020577, 4.867924473493101, 3.5845449245541845, 5.196178286129267, 4.091868704710146, 2.281471219135803, 1.0643270011947434, 0.0), # 84
(14.223261465974833, 11.653803403911677, 11.388965692158209, 12.250136498590983, 10.380066704322333, 5.008867106132196, 4.8484988165362175, 3.974875209571713, 5.35077436747447, 2.3191804513300527, 1.8192874160710422, 1.041146748329443, 0.0, 13.992126950445819, 11.452614231623869, 9.09643708035521, 6.957541353990157, 10.70154873494894, 5.564825293400398, 4.8484988165362175, 3.577762218665854, 5.190033352161167, 4.083378832863662, 2.2777931384316417, 1.05943667308288, 0.0), # 85
(14.191449645136279, 11.59960092703217, 11.370299225537268, 12.224138501409021, 10.367257188197637, 4.999027772697253, 4.828939212996585, 3.9573322664228017, 5.341458691510441, 2.311486864089944, 1.8131072941894584, 1.0385815023383795, 0.0, 13.97268400634431, 11.424396525722173, 9.065536470947292, 6.934460592269831, 10.682917383020882, 5.540265172991923, 4.828939212996585, 3.57073412335518, 5.183628594098819, 4.074712833803008, 2.274059845107454, 1.0545091751847429, 0.0), # 86
(14.15847954911433, 11.545016158900838, 11.35136149691358, 12.19763410326087, 10.353950617283953, 4.988868792866941, 4.809253086419753, 3.939955761316873, 5.332013065843622, 2.3037708641975314, 1.8067975013290805, 1.035982564435781, 0.0, 13.95250289351852, 11.39580820879359, 9.033987506645403, 6.9113125925925925, 10.664026131687244, 5.515938065843622, 4.809253086419753, 3.563477709190672, 5.1769753086419765, 4.065878034420291, 2.2702722993827162, 1.0495469235364399, 0.0), # 87
(14.124415303870702, 11.490075675914863, 11.332157307384547, 12.170645284822868, 10.340169584980769, 4.97841406543718, 4.789447860351274, 3.9227520957171165, 5.322446452522482, 2.296032632400011, 1.8003681266859632, 1.0333512822981095, 0.0, 13.931619620198905, 11.366864105279202, 9.001840633429817, 6.888097897200032, 10.644892905044964, 5.491852934003963, 4.789447860351274, 3.556010046740843, 5.1700847924903846, 4.056881761607624, 2.2664314614769094, 1.0445523341740786, 0.0), # 88
(14.089321035367092, 11.434806054471437, 11.312691458047555, 12.143194026771337, 10.325936684687594, 4.967687489203883, 4.769530958336696, 3.905727671086725, 5.312767813595489, 2.2882723494445796, 1.7938292594561607, 1.030689003601826, 0.0, 13.910070194615912, 11.337579039620083, 8.969146297280803, 6.864817048333737, 10.625535627190978, 5.4680187395214155, 4.769530958336696, 3.548348206574202, 5.162968342343797, 4.047731342257113, 2.2625382916095114, 1.0395278231337672, 0.0), # 89
(14.053260869565218, 11.379233870967743, 11.292968750000002, 12.115302309782612, 10.311274509803923, 4.956712962962964, 4.749509803921569, 3.8888888888888893, 5.302986111111112, 2.280490196078432, 1.787190988835726, 1.027997076023392, 0.0, 13.887890625, 11.30796783625731, 8.93595494417863, 6.841470588235294, 10.605972222222224, 5.4444444444444455, 4.749509803921569, 3.54050925925926, 5.155637254901961, 4.0384341032608715, 2.2585937500000006, 1.0344758064516133, 0.0), # 90
(14.016298932426789, 11.323385701800964, 11.272993984339278, 12.086992114533015, 10.296205653729254, 4.945514385510339, 4.729391820651443, 3.8722421505868017, 5.293110307117818, 2.2726863530487647, 1.7804634040207143, 1.025276847239269, 0.0, 13.865116919581618, 11.278045319631957, 8.902317020103572, 6.818059059146293, 10.586220614235636, 5.4211390108215225, 4.729391820651443, 3.5325102753645283, 5.148102826864627, 4.0289973715110055, 2.254598796867856, 1.0293987001637241, 0.0), # 91
(13.978499349913523, 11.267288123368292, 11.252771962162782, 12.058285421698875, 10.280752709863094, 4.934115655641925, 4.709184432071869, 3.8557938576436523, 5.2831493636640765, 2.2648610011027737, 1.7736565942071794, 1.0225296649259181, 0.0, 13.841785086591221, 11.247826314185097, 8.868282971035896, 6.79458300330832, 10.566298727328153, 5.398111400701113, 4.709184432071869, 3.524368325458518, 5.140376354931547, 4.019428473899626, 2.2505543924325564, 1.0242989203062085, 0.0), # 92
(13.939926247987117, 11.210967712066907, 11.232307484567903, 12.029204211956525, 10.264938271604938, 4.9225406721536356, 4.688895061728395, 3.839550411522634, 5.273112242798354, 2.2570143209876545, 1.7667806485911755, 1.019756876759801, 0.0, 13.81793113425926, 11.217325644357809, 8.833903242955877, 6.771042962962962, 10.546224485596708, 5.375370576131688, 4.688895061728395, 3.5161004801097393, 5.132469135802469, 4.009734737318842, 2.246461496913581, 1.0191788829151736, 0.0), # 93
(13.900643752609293, 11.154451044293994, 11.211605352652038, 11.999770465982289, 10.248784932354287, 4.910813333841387, 4.6685311331665735, 3.8235182136869392, 5.263007906569121, 2.2491464934506045, 1.7598456563687561, 1.016959830417379, 0.0, 13.793591070816188, 11.186558134591166, 8.79922828184378, 6.747439480351812, 10.526015813138242, 5.3529254991617155, 4.6685311331665735, 3.5077238098867047, 5.124392466177143, 3.9999234886607637, 2.2423210705304077, 1.014041004026727, 0.0), # 94
(13.860715989741754, 11.097764696446747, 11.190670367512576, 11.970006164452498, 10.232315285510639, 4.898957539501094, 4.648100069931951, 3.807703665599757, 5.252845317024844, 2.241257699238818, 1.752861706735976, 1.014139873575113, 0.0, 13.768800904492457, 11.155538609326241, 8.764308533679879, 6.723773097716453, 10.505690634049689, 5.33078513183966, 4.648100069931951, 3.499255385357924, 5.1161576427553195, 3.9900020548175, 2.2381340735025153, 1.0088876996769771, 0.0), # 95
(13.820207085346219, 11.040935244922345, 11.169507330246915, 11.93993328804348, 10.215551924473493, 4.88699718792867, 4.62760929557008, 3.7921131687242804, 5.242633436213992, 2.2333481190994924, 1.7458388888888892, 1.0112983539094653, 0.0, 13.74359664351852, 11.124281893004117, 8.729194444444445, 6.700044357298475, 10.485266872427983, 5.3089584362139925, 4.62760929557008, 3.490712277091907, 5.1077759622367465, 3.9799777626811608, 2.2339014660493834, 1.0037213859020315, 0.0), # 96
(13.779181165384388, 10.983989266117973, 11.148121041952448, 11.909573817431562, 10.198517442642354, 4.8749561779200326, 4.60706623362651, 3.7767531245237014, 5.2323812261850335, 2.2254179337798226, 1.7387872920235496, 1.0084366190968967, 0.0, 13.718014296124831, 11.09280281006586, 8.693936460117747, 6.676253801339467, 10.464762452370067, 5.287454374333182, 4.60706623362651, 3.482111555657166, 5.099258721321177, 3.969857939143855, 2.2296242083904896, 0.9985444787379977, 0.0), # 97
(13.737702355817978, 10.926953336430817, 11.126516303726566, 11.878949733293078, 10.181234433416716, 4.862858408271099, 4.58647830764679, 3.7616299344612103, 5.222097648986434, 2.2174673240270053, 1.7317170053360116, 1.0055560168138682, 0.0, 13.69208987054184, 11.06111618495255, 8.658585026680058, 6.652401972081014, 10.444195297972868, 5.266281908245695, 4.58647830764679, 3.4734702916222133, 5.090617216708358, 3.9596499110976935, 2.2253032607453136, 0.9933593942209834, 0.0), # 98
(13.695834782608697, 10.869854032258065, 11.10469791666667, 11.848083016304349, 10.163725490196079, 4.850727777777779, 4.5658529411764714, 3.7467500000000005, 5.211791666666667, 2.2094964705882356, 1.724638118022329, 1.0026578947368423, 0.0, 13.665859375000002, 11.029236842105265, 8.623190590111644, 6.628489411764706, 10.423583333333333, 5.245450000000001, 4.5658529411764714, 3.4648055555555564, 5.081862745098039, 3.949361005434784, 2.220939583333334, 0.988168548387097, 0.0), # 99
(13.653642571718258, 10.8127179299969, 11.082670681870143, 11.816995647141708, 10.146013206379946, 4.8385881852359915, 4.545197557761102, 3.732119722603262, 5.201472241274196, 2.201505554210711, 1.717560719278556, 0.9997436005422796, 0.0, 13.639358817729768, 10.997179605965075, 8.58780359639278, 6.6045166626321326, 10.402944482548392, 5.224967611644567, 4.545197557761102, 3.456134418025708, 5.073006603189973, 3.938998549047237, 2.2165341363740287, 0.9829743572724456, 0.0), # 100
(13.611189849108369, 10.755571606044516, 11.060439400434387, 11.785709606481484, 10.128120175367815, 4.82646352944165, 4.524519580946234, 3.7177455037341867, 5.191148334857491, 2.1934947556416264, 1.7104948983007466, 0.9968144819066413, 0.0, 13.612624206961591, 10.964959300973053, 8.552474491503732, 6.580484266924878, 10.382296669714982, 5.204843705227861, 4.524519580946234, 3.4474739496011786, 5.064060087683908, 3.928569868827162, 2.2120878800868775, 0.977779236913138, 0.0), # 101
(13.568540740740744, 10.698441636798089, 11.038008873456791, 11.754246875000002, 10.110068990559187, 4.814377709190674, 4.503826434277415, 3.7036337448559675, 5.180828909465021, 2.1854642556281783, 1.7034507442849551, 0.9938718865063897, 0.0, 13.585691550925928, 10.932590751570284, 8.517253721424776, 6.556392766884533, 10.361657818930041, 5.185087242798355, 4.503826434277415, 3.438841220850481, 5.055034495279593, 3.918082291666668, 2.207601774691358, 0.972585603345281, 0.0), # 102
(13.525759372577088, 10.641354598654807, 11.015383902034753, 11.722629433373593, 10.09188224535356, 4.802354623278973, 4.483125541300197, 3.689790847431795, 5.170522927145252, 2.1774142349175616, 1.696438346427236, 0.9909171620179854, 0.0, 13.558596857853223, 10.900088782197837, 8.482191732136178, 6.532242704752683, 10.341045854290504, 5.1657071864045125, 4.483125541300197, 3.4302533023421233, 5.04594112267678, 3.907543144457865, 2.2030767804069504, 0.9673958726049827, 0.0), # 103
(13.482909870579116, 10.58433706801186, 10.992569287265662, 11.690879262278584, 10.073582533150434, 4.790418170502465, 4.462424325560129, 3.6762232129248593, 5.160239349946655, 2.1693448742569736, 1.689467793923642, 0.9879516561178898, 0.0, 13.53137613597394, 10.867468217296787, 8.447338969618208, 6.50803462277092, 10.32047869989331, 5.146712498094804, 4.462424325560129, 3.421727264644618, 5.036791266575217, 3.896959754092862, 2.1985138574531327, 0.9622124607283511, 0.0), # 104
(13.440056360708535, 10.527415621266428, 10.969569830246915, 11.659018342391304, 10.05519244734931, 4.778592249657065, 4.441730210602761, 3.662937242798354, 5.1499871399176955, 2.1612563543936103, 1.682549175970229, 0.9849767164825647, 0.0, 13.50406539351852, 10.83474388130821, 8.412745879851144, 6.48376906318083, 10.299974279835391, 5.128112139917696, 4.441730210602761, 3.4132801783264752, 5.027596223674655, 3.886339447463769, 2.1939139660493834, 0.9570377837514936, 0.0), # 105
(13.39726296892706, 10.470616834815702, 10.946390332075904, 11.627068654388085, 10.036734581349688, 4.766900759538689, 4.4210506199736415, 3.6499393385154706, 5.139775259106843, 2.153148856074666, 1.67569258176305, 0.9819936907884712, 0.0, 13.476700638717421, 10.801930598673183, 8.378462908815248, 6.459446568223997, 10.279550518213686, 5.109915073921659, 4.4210506199736415, 3.4049291139562063, 5.018367290674844, 3.875689551462696, 2.189278066415181, 0.9518742577105185, 0.0), # 106
(13.3545938211964, 10.413967285056863, 10.923035593850026, 11.59505217894525, 10.018231528551063, 4.755367598943252, 4.400392977218323, 3.6372359015394005, 5.129612669562567, 2.145022560047339, 1.6689081004981592, 0.9790039267120707, 0.0, 13.449317879801098, 10.769043193832776, 8.344540502490794, 6.435067680142016, 10.259225339125134, 5.092130262155161, 4.400392977218323, 3.3966911421023225, 5.009115764275531, 3.865017392981751, 2.1846071187700056, 0.9467242986415331, 0.0), # 107
(13.312113043478263, 10.357493548387097, 10.899510416666669, 11.562990896739132, 9.999705882352941, 4.744016666666668, 4.379764705882353, 3.6248333333333345, 5.119508333333334, 2.1368776470588244, 1.662205821371611, 0.9760087719298248, 0.0, 13.421953125000002, 10.736096491228071, 8.311029106858054, 6.4106329411764715, 10.239016666666668, 5.074766666666668, 4.379764705882353, 3.3885833333333344, 4.999852941176471, 3.854330298913045, 2.179902083333334, 0.9415903225806455, 0.0), # 108
(13.26988476173436, 10.301222201203595, 10.87581960162323, 11.530906788446053, 9.98118023615482, 4.732871861504853, 4.359173229511284, 3.612738035360464, 5.109471212467612, 2.1287142978563174, 1.6555958335794598, 0.9730095741181947, 0.0, 13.394642382544584, 10.70310531530014, 8.277979167897298, 6.386142893568951, 10.218942424935223, 5.05783324950465, 4.359173229511284, 3.3806227582177515, 4.99059011807741, 3.8436355961486854, 2.1751639203246462, 0.9364747455639633, 0.0), # 109
(13.227973101926404, 10.245179819903537, 10.851967949817103, 11.498821834742351, 9.962677183356197, 4.721957082253722, 4.3386259716506625, 3.6009564090839814, 5.099510269013869, 2.1205326931870148, 1.6490882263177586, 0.9700076809536419, 0.0, 13.367421660665297, 10.670084490490058, 8.245441131588793, 6.361598079561043, 10.199020538027739, 5.041338972717574, 4.3386259716506625, 3.372826487324087, 4.981338591678099, 3.832940611580785, 2.170393589963421, 0.9313799836275944, 0.0), # 110
(13.186442190016104, 10.189392980884113, 10.827960262345682, 11.46675801630435, 9.944219317356573, 4.711296227709192, 4.318130355846042, 3.5894948559670787, 5.089634465020577, 2.1123330137981124, 1.6426930887825626, 0.9670044401126275, 0.0, 13.340326967592594, 10.6370488412389, 8.213465443912813, 6.336999041394336, 10.179268930041154, 5.02529279835391, 4.318130355846042, 3.3652115912208513, 4.972109658678287, 3.8222526721014507, 2.1655920524691368, 0.9263084528076467, 0.0), # 111
(13.14535615196517, 10.133888260542502, 10.803801340306359, 11.434737313808373, 9.925829231555449, 4.700913196667176, 4.297693805642971, 3.5783597774729468, 5.079852762536198, 2.1041154404368063, 1.6364205101699256, 0.9640011992716131, 0.0, 13.313394311556928, 10.604013191987741, 8.182102550849628, 6.312346321310418, 10.159705525072397, 5.0097036884621255, 4.297693805642971, 3.357795140476554, 4.962914615777724, 3.8115791046027923, 2.160760268061272, 0.9212625691402275, 0.0), # 112
(13.104705913184263, 10.078784894108638, 10.779554132960747, 11.402825576616644, 9.907497301495457, 4.690826978191853, 4.277368174559739, 3.5675806651220205, 5.07019931192069, 2.095906657814456, 1.6302822447690024, 0.9610058425921835, 0.0, 13.286621461180511, 10.571064268514016, 8.151411223845011, 6.287719973443367, 10.14039862384138, 4.9946129311708285, 4.277368174559739, 3.3505906987084666, 4.953748650747729, 3.8009418588722155, 2.15591082659215, 0.9162531721916946, 0.0), # 113
(13.064073257060091, 10.024626385524439, 10.755553287525224, 11.371278892341204, 9.88903379759524, 4.681014596966087, 4.257412745887406, 3.557289901377987, 5.060822216666095, 2.0878603087694745, 1.6242903453264128, 0.9580564200798471, 0.0, 13.25978557982405, 10.538620620878318, 8.121451726632063, 6.263580926308422, 10.12164443333219, 4.980205861929182, 4.257412745887406, 3.3435818549757763, 4.94451689879762, 3.790426297447069, 2.1511106575050447, 0.9113296714113127, 0.0), # 114
(13.023338864205595, 9.97143223830991, 10.731813088158539, 11.340088730440868, 9.870380499362694, 4.671450535207326, 4.2378417551340934, 3.547484881662581, 5.051724990045435, 2.0799888647958276, 1.6184360526663222, 0.9551543846318662, 0.0, 13.232809284324528, 10.506698230950526, 8.09218026333161, 6.239966594387481, 10.10344998009087, 4.966478834327614, 4.2378417551340934, 3.336750382290947, 4.935190249681347, 3.780029576813624, 2.146362617631708, 0.9064938398463556, 0.0), # 115
(12.982451822532688, 9.919124960991017, 10.708287554981187, 11.309199457779725, 9.851509291291528, 4.662112249784464, 4.218623372269525, 3.5381385158577467, 5.042884624972988, 2.072277675457342, 1.6127080506300124, 0.9522943730401906, 0.0, 13.205650163658248, 10.475238103442095, 8.063540253150062, 6.216833026372026, 10.085769249945976, 4.953393922200846, 4.218623372269525, 3.330080178417474, 4.925754645645764, 3.7697331525932425, 2.1416575109962372, 0.9017386328173653, 0.0), # 116
(12.941361219953283, 9.867627062093726, 10.68493070811365, 11.278555441221856, 9.832392057875436, 4.652977197566394, 4.199725767263427, 3.529223713845425, 5.034278114363028, 2.0647120903178457, 1.6070950230587664, 0.949471022096771, 0.0, 13.178265806801516, 10.44418124306448, 8.035475115293831, 6.1941362709535355, 10.068556228726056, 4.940913199383595, 4.199725767263427, 3.3235551411188533, 4.916196028937718, 3.7595184804072863, 2.1369861416227303, 0.8970570056448843, 0.0), # 117
(12.900016144379297, 9.816861050144, 10.66169656767643, 11.248101047631351, 9.81300068360812, 4.644022835422014, 4.181117110085521, 3.5207133855075567, 5.025882451129837, 2.0572774589411664, 1.6015856537938657, 0.9466789685935577, 0.0, 13.150613802730636, 10.413468654529133, 8.007928268969328, 6.171832376823498, 10.051764902259674, 4.92899873971058, 4.181117110085521, 3.317159168158581, 4.90650034180406, 3.7493670158771177, 2.132339313535286, 0.8924419136494547, 0.0), # 118
(12.858365683722639, 9.766749433667803, 10.638539153790012, 11.217780643872292, 9.793307052983273, 4.635226620220214, 4.162765570705529, 3.512580440726085, 5.017674628187687, 2.0499591308911307, 1.5961686266765933, 0.9439128493225009, 0.0, 13.122651740421906, 10.383041342547507, 7.980843133382966, 6.149877392673391, 10.035349256375374, 4.91761261701652, 4.162765570705529, 3.310876157300153, 4.896653526491637, 3.7392602146240983, 2.1277078307580024, 0.8878863121516185, 0.0), # 119
(12.816358925895228, 9.717214721191104, 10.61541248657489, 11.187538596808764, 9.773283050494598, 4.626566008829889, 4.144639319093177, 3.5047977893829505, 5.009631638450861, 2.0427424557315677, 1.5908326255482306, 0.9411673010755515, 0.0, 13.094337208851638, 10.352840311831065, 7.954163127741153, 6.128227367194702, 10.019263276901722, 4.906716905136131, 4.144639319093177, 3.3046900063070637, 4.886641525247299, 3.729179532269589, 2.1230824973149782, 0.8833831564719186, 0.0), # 120
(12.773944958808976, 9.668179421239865, 10.592270586151553, 11.157319273304857, 9.75290056063579, 4.618018458119934, 4.126706525218187, 3.4973383413600962, 5.001730474833633, 2.035612783026304, 1.5855663342500608, 0.9384369606446594, 0.0, 13.065627796996127, 10.322806567091252, 7.927831671250303, 6.106838349078911, 10.003460949667266, 4.8962736779041345, 4.126706525218187, 3.29858461294281, 4.876450280317895, 3.719106424434953, 2.118454117230311, 0.878925401930897, 0.0), # 121
(12.731072870375797, 9.61956604234005, 10.569067472640498, 11.127067040224649, 9.732131467900551, 4.609561424959241, 4.108935359050283, 3.490175006539462, 4.993948130250281, 2.0285554623391677, 1.5803584366233656, 0.9357164648217753, 0.0, 13.036481093831679, 10.292881113039527, 7.901792183116827, 6.085666387017502, 9.987896260500563, 4.886245009155247, 4.108935359050283, 3.2925438749708866, 4.8660657339502755, 3.7090223467415506, 2.1138134945280997, 0.8745060038490956, 0.0), # 122
(12.687691748507607, 9.571297093017627, 10.54575716616221, 11.09672626443223, 9.71094765678258, 4.601172366216706, 4.091293990559188, 3.4832806948029904, 4.986261597615085, 2.021555843233986, 1.5751976165094272, 0.9330004503988493, 0.0, 13.0068546883346, 10.263004954387341, 7.875988082547136, 6.064667529701957, 9.97252319523017, 4.876592972724187, 4.091293990559188, 3.28655169015479, 4.85547382839129, 3.698908754810744, 2.109151433232442, 0.8701179175470571, 0.0), # 123
(12.643750681116316, 9.523295081798558, 10.522293686837184, 11.066241312791686, 9.689321011775569, 4.592828738761221, 4.073750589714624, 3.476628316032624, 4.97864786984232, 2.014599275274587, 1.5700725577495283, 0.9302835541678323, 0.0, 12.976706169481197, 10.233119095846153, 7.85036278874764, 6.04379782582376, 9.95729573968464, 4.8672796424456735, 4.073750589714624, 3.280591956258015, 4.844660505887784, 3.6887471042638964, 2.104458737367437, 0.8657540983453236, 0.0), # 124
(12.599198756113843, 9.475482517208812, 10.498631054785912, 11.0355565521671, 9.667223417373222, 4.584507999461682, 4.056273326486318, 3.4701907801103036, 4.971083939846263, 2.0076711080247973, 1.5649719441849508, 0.927560412920674, 0.0, 12.94599312624776, 10.203164542127412, 7.824859720924753, 6.023013324074391, 9.942167879692526, 4.858267092154425, 4.056273326486318, 3.2746485710440583, 4.833611708686611, 3.678518850722367, 2.0997262109571824, 0.8614075015644376, 0.0), # 125
(12.553985061412101, 9.427781907774351, 10.474723290128884, 11.004616349422557, 9.644626758069233, 4.5761876051869805, 4.038830370843989, 3.463940996917971, 4.963546800541195, 2.0007566910484456, 1.5598844596569765, 0.9248256634493257, 0.0, 12.91467314761061, 10.173082297942582, 7.799422298284883, 6.002270073145335, 9.92709360108239, 4.849517395685159, 4.038830370843989, 3.268705432276415, 4.822313379034616, 3.66820544980752, 2.094944658025777, 0.8570710825249411, 0.0), # 126
(12.508058684923006, 9.380115762021138, 10.450524412986589, 10.973365071422144, 9.621502918357304, 4.567845012806012, 4.021389892757366, 3.4578518763375685, 4.95601344484139, 1.993841373909359, 1.5547987880068885, 0.9220739425457369, 0.0, 12.88270382254604, 10.142813368003106, 7.773993940034442, 5.981524121728076, 9.91202688968278, 4.8409926268725965, 4.021389892757366, 3.26274643771858, 4.810751459178652, 3.6577883571407157, 2.090104882597318, 0.8527377965473764, 0.0), # 127
(12.461368714558466, 9.332406588475143, 10.425988443479525, 10.941747085029949, 9.597823782731137, 4.5594576791876715, 4.003920062196168, 3.451896328251037, 4.948460865661126, 1.986910506171365, 1.5497036130759692, 0.9192998870018588, 0.0, 12.850042740030352, 10.112298757020445, 7.748518065379845, 5.960731518514094, 9.896921731322252, 4.832654859551452, 4.003920062196168, 3.2567554851340508, 4.798911891365568, 3.6472490283433174, 2.085197688695905, 0.8484005989522859, 0.0), # 128
(12.413864238230394, 9.284576895662326, 10.401069401728181, 10.909706757110053, 9.573561235684425, 4.551003061200851, 3.9863890491301195, 3.446047262540319, 4.9408660559146815, 1.9799494373982915, 1.5445876187055003, 0.916498133609641, 0.0, 12.816647489039854, 10.08147946970605, 7.7229380935275005, 5.939848312194873, 9.881732111829363, 4.824466167556446, 3.9863890491301195, 3.250716472286322, 4.786780617842212, 3.636568919036685, 2.0802138803456365, 0.8440524450602116, 0.0), # 129
(12.365494343850713, 9.236549192108656, 10.375721307853043, 10.877188454526541, 9.548687161710866, 4.542458615714445, 3.968765023528944, 3.440277589087355, 4.933206008516334, 1.9729435171539655, 1.539439488736764, 0.9136633191610346, 0.0, 12.78247565855085, 10.050296510771378, 7.697197443683819, 5.9188305514618955, 9.866412017032667, 4.816388624722297, 3.968765023528944, 3.244613296938889, 4.774343580855433, 3.6257294848421813, 2.075144261570609, 0.8396862901916962, 0.0), # 130
(12.316208119331334, 9.188245986340096, 10.349898181974611, 10.8441365441435, 9.523173445304161, 4.533801799597346, 3.9510161553623666, 3.4345602177740875, 4.92545771638036, 1.9658780950022154, 1.5342479070110426, 0.9107900804479897, 0.0, 12.747484837539638, 10.018690884927885, 7.671239535055213, 5.897634285006645, 9.85091543276072, 4.808384304883723, 3.9510161553623666, 3.238429856855247, 4.761586722652081, 3.614712181381168, 2.0699796363949226, 0.8352950896672816, 0.0), # 131
(12.265954652584163, 9.139589786882611, 10.32355404421337, 10.810495392825016, 9.49699197095801, 4.525010069718451, 3.9331106146001082, 3.4288680584824593, 4.917598172421039, 1.9587385205068681, 1.5290015573696185, 0.9078730542624567, 0.0, 12.711632614982527, 9.986603596887022, 7.645007786848092, 5.876215561520603, 9.835196344842078, 4.800415281875443, 3.9331106146001082, 3.2321500497988938, 4.748495985479005, 3.6034984642750065, 2.0647108088426744, 0.8308717988075103, 0.0), # 132
(12.21468303152113, 9.090503102262165, 10.296642914689816, 10.776209367435175, 9.470114623166108, 4.516060882946651, 3.915016571211893, 3.4231740210944106, 4.909604369552646, 1.9515101432317519, 1.5236891236537742, 0.904906877396386, 0.0, 12.674876579855821, 9.953975651360244, 7.618445618268871, 5.854530429695254, 9.819208739105292, 4.792443629532175, 3.915016571211893, 3.2257577735333225, 4.735057311583054, 3.5920697891450595, 2.059328582937963, 0.8264093729329243, 0.0), # 133
(12.162342344054133, 9.040908441004726, 10.26911881352444, 10.741222834838059, 9.442513286422153, 4.5069316961508425, 3.896702195167445, 3.4174510154918845, 4.90145330068946, 1.9441783127406937, 1.518299289704792, 0.9018861866417278, 0.0, 12.637174321135817, 9.920748053059004, 7.5914964485239596, 5.83253493822208, 9.80290660137892, 4.784431421688638, 3.896702195167445, 3.21923692582203, 4.721256643211077, 3.5804076116126873, 2.053823762704888, 0.8219007673640661, 0.0), # 134
(12.108881678095097, 8.990728311636257, 10.24093576083773, 10.705480161897759, 9.414159845219846, 4.4975999661999175, 3.8781356564364877, 3.4116719515568206, 4.893121958745757, 1.9367283785975222, 1.5128207393639534, 0.898805618790433, 0.0, 12.59848342779883, 9.88686180669476, 7.5641036968197675, 5.810185135792565, 9.786243917491515, 4.776340732179549, 3.8781356564364877, 3.212571404428512, 4.707079922609923, 3.5684933872992537, 2.048187152167546, 0.817338937421478, 0.0), # 135
(12.05425012155593, 8.93988522268272, 10.212047776750177, 10.668925715478352, 9.385026184052883, 4.488043149962771, 3.8592851249887445, 3.4058097391711617, 4.884587336635816, 1.9291456903660635, 1.5072421564725416, 0.8956598106344515, 0.0, 12.558761488821151, 9.852257916978965, 7.536210782362707, 5.787437071098189, 9.769174673271632, 4.768133634839627, 3.8592851249887445, 3.205745107116265, 4.6925130920264415, 3.556308571826118, 2.042409555350036, 0.812716838425702, 0.0), # 136
(11.998396762348548, 8.888301682670086, 10.18240888138228, 10.631503862443932, 9.355084187414965, 4.478238704308296, 3.8401187707939393, 3.399837288216851, 4.875826427273916, 1.9214155976101461, 1.5015522248718383, 0.8924433989657341, 0.0, 12.517966093179089, 9.816877388623073, 7.507761124359191, 5.764246792830437, 9.751652854547832, 4.759772203503592, 3.8401187707939393, 3.1987419316487826, 4.6775420937074825, 3.543834620814645, 2.036481776276456, 0.8080274256972807, 0.0), # 137
(11.941270688384867, 8.835900200124316, 10.15197309485452, 10.593158969658578, 9.32430573979979, 4.4681640861053875, 3.8206047638217933, 3.393727508575828, 4.8668162235743315, 1.913523449893597, 1.4957396284031257, 0.889151020576231, 0.0, 12.476054829848946, 9.78066122633854, 7.478698142015627, 5.740570349680789, 9.733632447148663, 4.751218512006159, 3.8206047638217933, 3.1915457757895624, 4.662152869899895, 3.5310529898861933, 2.0303946189709046, 0.8032636545567561, 0.0), # 138
(11.882820987576796, 8.782603283571376, 10.120694437287398, 10.553835403986378, 9.292662725701055, 4.457796752222938, 3.800711274042032, 3.3874533101300353, 4.85753371845134, 1.9054545967802445, 1.4897930509076862, 0.8857773122578926, 0.0, 12.432985287807028, 9.743550434836816, 7.448965254538431, 5.716363790340733, 9.71506743690268, 4.742434634182049, 3.800711274042032, 3.184140537302099, 4.646331362850527, 3.517945134662127, 2.0241388874574797, 0.7984184803246707, 0.0), # 139
(11.822996747836257, 8.72833344153723, 10.088526928801404, 10.513477532291418, 9.26012702961246, 4.447114159529844, 3.780406471424378, 3.3809876027614147, 4.847955904819222, 1.8971943878339157, 1.4837011762268022, 0.8823169108026693, 0.0, 12.38871505602964, 9.70548601882936, 7.41850588113401, 5.691583163501746, 9.695911809638444, 4.733382643865981, 3.780406471424378, 3.176510113949888, 4.63006351480623, 3.5044925107638067, 2.017705385760281, 0.7934848583215663, 0.0), # 140
(11.761747057075162, 8.673013182547843, 10.055424589517022, 10.472029721437782, 9.226670536027703, 4.436093764894997, 3.7596585259385567, 3.374303296351908, 4.838059775592251, 1.8887281726184386, 1.477452688201756, 0.8787644530025115, 0.0, 12.34320172349308, 9.666408983027624, 7.38726344100878, 5.6661845178553145, 9.676119551184502, 4.724024614892672, 3.7596585259385567, 3.168638403496426, 4.613335268013851, 3.490676573812595, 2.0110849179034047, 0.7884557438679859, 0.0), # 141
(11.69902100320542, 8.616565015129181, 10.02134143955475, 10.429436338289557, 9.192265129440482, 4.424713025187291, 3.7384356075542886, 3.367373300783457, 4.827822323684707, 1.8800413006976404, 1.4710362706738296, 0.8751145756493696, 0.0, 12.296402879173653, 9.626260332143064, 7.355181353369148, 5.64012390209292, 9.655644647369414, 4.71432262109684, 3.7384356075542886, 3.160509303705208, 4.596132564720241, 3.4764787794298533, 2.0042682879109504, 0.7833240922844712, 0.0), # 142
(11.634767674138946, 8.558911447807208, 9.986231499035082, 10.385641749710825, 9.156882694344494, 4.412949397275621, 3.7167058862412983, 3.360170525938002, 4.817220542010869, 1.871119121635349, 1.4644406074843055, 0.8713619155351939, 0.0, 12.248276112047666, 9.584981070887132, 7.322203037421526, 5.6133573649060455, 9.634441084021738, 4.704238736313203, 3.7167058862412983, 3.1521067123397293, 4.578441347172247, 3.4618805832369426, 1.9972462998070164, 0.7780828588915646, 0.0), # 143
(11.56893615778766, 8.499974989107892, 9.950048788078501, 10.340590322565676, 9.12049511523344, 4.400780338028881, 3.6944375319693092, 3.3526678816974873, 4.806231423485011, 1.8619469849953916, 1.4576543824744654, 0.867501109451935, 0.0, 12.198779011091421, 9.542512203971285, 7.288271912372326, 5.585840954986173, 9.612462846970022, 4.693735034376482, 3.6944375319693092, 3.1434145271634857, 4.56024755761672, 3.446863440855226, 1.9900097576157, 0.7727249990098085, 0.0), # 144
(11.501475542063469, 8.439678147557194, 9.912747326805505, 10.294226423718191, 9.083074276601018, 4.388183304315964, 3.6715987147080456, 3.344838277943853, 4.794831961021412, 1.8525102403415963, 1.4506662794855925, 0.8635267941915434, 0.0, 12.14786916528122, 9.498794736106976, 7.253331397427962, 5.557530721024787, 9.589663922042824, 4.682773589121394, 3.6715987147080456, 3.1344166459399743, 4.541537138300509, 3.4314088079060645, 1.9825494653611013, 0.7672434679597451, 0.0), # 145
(11.432334914878291, 8.377943431681082, 9.874281135336586, 10.246494420032459, 9.044592062940927, 4.375135753005765, 3.6481576044272312, 3.336654624559041, 4.782999147534349, 1.8427942372377903, 1.4434649823589683, 0.8594336065459691, 0.0, 12.095504163593366, 9.453769672005658, 7.21732491179484, 5.52838271171337, 9.565998295068699, 4.671316474382658, 3.6481576044272312, 3.125096966432689, 4.522296031470463, 3.41549814001082, 1.9748562270673173, 0.7616312210619166, 0.0), # 146
(11.361463364144042, 8.314693350005518, 9.83460423379223, 10.19733867837256, 9.005020358746862, 4.361615140967176, 3.6240823710965873, 3.3280898314249927, 4.770709975938102, 1.8327843252478015, 1.4360391749358754, 0.855216183307163, 0.0, 12.041641595004167, 9.407378016378791, 7.180195874679377, 5.498352975743403, 9.541419951876204, 4.65932576399499, 3.6240823710965873, 3.1154393864051255, 4.502510179373431, 3.3991128927908543, 1.966920846758446, 0.7558812136368653, 0.0), # 147
(11.288809977772631, 8.24985041105647, 9.793670642292932, 10.146703565602587, 8.964331048512523, 4.347598925069094, 3.599341184685839, 3.3191168084236504, 4.757941439146947, 1.822465853935457, 1.428377541057596, 0.8508691612670749, 0.0, 11.986239048489919, 9.359560773937822, 7.141887705287981, 5.4673975618063695, 9.515882878293894, 4.646763531793111, 3.599341184685839, 3.105427803620781, 4.482165524256262, 3.38223452186753, 1.9587341284585866, 0.7499864010051337, 0.0), # 148
(11.214323843675977, 8.1833371233599, 9.751434380959186, 10.094533448586619, 8.922496016731612, 4.33306456218041, 3.573902215164709, 3.3097084654369557, 4.744670530075158, 1.8118241728645852, 1.4204687645654126, 0.8463871772176558, 0.0, 11.929254113026934, 9.310258949394212, 7.102343822827062, 5.4354725185937545, 9.489341060150316, 4.6335918516117385, 3.573902215164709, 3.09504611584315, 4.461248008365806, 3.3648444828622073, 1.950286876191837, 0.7439397384872637, 0.0), # 149
(11.137954049765991, 8.115075995441773, 9.707849469911476, 10.040772694188746, 8.879487147897825, 4.317989509170021, 3.5477336325029207, 3.29983771234685, 4.730874241637018, 1.8008446315990123, 1.412301529300607, 0.8417648679508558, 0.0, 11.870644377591507, 9.259413547459413, 7.061507646503035, 5.402533894797036, 9.461748483274036, 4.61977279728559, 3.5477336325029207, 3.084278220835729, 4.439743573948912, 3.3469242313962493, 1.9415698939822956, 0.7377341814037977, 0.0), # 150
(11.059649683954586, 8.044989535828057, 9.6628699292703, 9.985365669273047, 8.835276326504857, 4.302351222906816, 3.5208036066701984, 3.2894774590352758, 4.716529566746802, 1.789512579702568, 1.4038645191044614, 0.8369968702586252, 0.0, 11.810367431159946, 9.206965572844876, 7.019322595522306, 5.368537739107703, 9.433059133493604, 4.605268442649386, 3.5208036066701984, 3.0731080163620117, 4.417638163252429, 3.3284552230910167, 1.9325739858540603, 0.731362685075278, 0.0), # 151
(10.979359834153682, 7.973000253044715, 9.616449779156152, 9.928256740703617, 8.789835437046412, 4.286127160259694, 3.4930803076362653, 3.2786006153841747, 4.701613498318786, 1.7778133667390779, 1.3951464178182584, 0.8320778209329146, 0.0, 11.748380862708558, 9.15285603026206, 6.975732089091292, 5.333440100217232, 9.403226996637573, 4.590040861537845, 3.4930803076362653, 3.061519400185496, 4.394917718523206, 3.309418913567873, 1.9232899558312306, 0.7248182048222469, 0.0), # 152
(10.897033588275185, 7.899030655617714, 9.568543039689514, 9.86939027534453, 8.743136364016186, 4.269294778097547, 3.4645319053708437, 3.2671800912754865, 4.686103029267251, 1.7657323422723707, 1.3861359092832806, 0.8270023567656742, 0.0, 11.68464226121364, 9.097025924422415, 6.930679546416402, 5.297197026817111, 9.372206058534502, 4.574052127785681, 3.4645319053708437, 3.049496270069676, 4.371568182008093, 3.2897967584481775, 1.9137086079379029, 0.7180936959652467, 0.0), # 153
(10.81262003423102, 7.823003252073014, 9.519103730990887, 9.80871064005988, 8.695150991907875, 4.251831533289268, 3.43512656984366, 3.2551887965911552, 4.6699751525064706, 1.7532548558662742, 1.3768216773408095, 0.8217651145488547, 0.0, 11.6191092156515, 9.0394162600374, 6.884108386704048, 5.259764567598821, 9.339950305012941, 4.557264315227617, 3.43512656984366, 3.037022523778049, 4.347575495953937, 3.2695702133532945, 1.9038207461981775, 0.7111821138248196, 0.0), # 154
(10.72606825993309, 7.744840550936584, 9.468085873180756, 9.746162201713748, 8.645851205215184, 4.233714882703753, 3.404832471024433, 3.2425996412131215, 4.653206860950727, 1.7403662570846146, 1.3671924058321279, 0.8163607310744064, 0.0, 11.551739314998438, 8.97996804181847, 6.8359620291606396, 5.221098771253843, 9.306413721901453, 4.53963949769837, 3.404832471024433, 3.0240820590741087, 4.322925602607592, 3.2487207339045834, 1.8936171746361512, 0.7040764137215078, 0.0), # 155
(10.637327353293314, 7.664465060734389, 9.415443486379615, 9.68168932717022, 8.595208888431804, 4.214922283209894, 3.37361777888289, 3.2293855350233276, 4.635775147514292, 1.727051895491221, 1.357236778598518, 0.8107838431342794, 0.0, 11.48249014823076, 8.918622274477073, 6.7861838929925895, 5.181155686473662, 9.271550295028584, 4.521139749032659, 3.37361777888289, 3.0106587737213526, 4.297604444215902, 3.2272297757234076, 1.8830886972759233, 0.6967695509758537, 0.0), # 156
(10.546346402223609, 7.581799289992394, 9.361130590707957, 9.615236383293386, 8.543195926051439, 4.195431191676585, 3.3414506633887537, 3.215519387903715, 4.6176570051114485, 1.7132971206499201, 1.3469434794812618, 0.8050290875204243, 0.0, 11.411319304324769, 8.855319962724668, 6.734717397406309, 5.1398913619497595, 9.235314010222897, 4.501727143065201, 3.3414506633887537, 2.996736565483275, 4.2715979630257195, 3.205078794431129, 1.8722261181415913, 0.6892544809083996, 0.0), # 157
(10.450553324967336, 7.495248171657732, 9.302523946219415, 9.544258060733807, 8.48743569881293, 4.174003322325641, 3.3075747046495003, 3.200048222203801, 4.597442309412912, 1.698678070701901, 1.335972342259087, 0.7988866158226731, 0.0, 11.335080203181485, 8.787752774049402, 6.679861711295434, 5.096034212105701, 9.194884618825824, 4.480067511085322, 3.3075747046495003, 2.9814309445183147, 4.243717849406465, 3.1814193535779363, 1.8605047892438833, 0.6813861974234302, 0.0), # 158
(10.335201473769764, 7.395933826819331, 9.224527454803487, 9.454176016727876, 8.414178555796186, 4.143513212539135, 3.2677489343700015, 3.17754122744589, 4.566999388570334, 1.6807983479345614, 1.3223972849777657, 0.7911589610963629, 0.0, 11.235598705688274, 8.70274857205999, 6.611986424888827, 5.042395043803683, 9.133998777140668, 4.448557718424246, 3.2677489343700015, 2.9596522946708106, 4.207089277898093, 3.1513920055759597, 1.8449054909606977, 0.6723576206199392, 0.0), # 159
(10.198820932866035, 7.28304080162725, 9.125574450948537, 9.343506385929302, 8.321992122590341, 4.103212058438943, 3.221570623868649, 3.147432860557619, 4.525465106040038, 1.6594219781520132, 1.3060272186755595, 0.7817252273702489, 0.0, 11.110988852451014, 8.598977501072737, 6.530136093377798, 4.978265934456038, 9.050930212080075, 4.406406004780667, 3.221570623868649, 2.9308657560278157, 4.160996061295171, 3.114502128643102, 1.8251148901897079, 0.6620946183297501, 0.0), # 160
(10.042510876420344, 7.1573051140366015, 9.006721467228694, 9.213301128944565, 8.211833582663305, 4.053588080615757, 3.1693770122048135, 3.1101003109807053, 4.473387224599541, 1.6347303676098288, 1.2870063860732652, 0.77067287137255, 0.0, 10.962523662746737, 8.477401585098049, 6.435031930366326, 4.904191102829485, 8.946774449199083, 4.354140435372988, 3.1693770122048135, 2.8954200575826836, 4.105916791331652, 3.071100376314856, 1.801344293445739, 0.6506641012760548, 0.0), # 161
(9.8673704785969, 7.01946278200249, 8.86902503621808, 9.064612206380144, 8.08466011948299, 3.9951294996602726, 3.1115053384378664, 3.0659207681568685, 4.411313507026364, 1.6069049225635816, 1.2654790298916783, 0.7580893498314843, 0.0, 10.791476155852466, 8.338982848146326, 6.3273951494583915, 4.820714767690744, 8.822627014052728, 4.292289075419616, 3.1115053384378664, 2.8536639283287664, 4.042330059741495, 3.0215374021267154, 1.773805007243616, 0.6381329801820447, 0.0), # 162
(9.674498913559898, 6.870249823480022, 8.71354169049082, 8.898491578842531, 7.941428916517308, 3.928324536163185, 3.048292841627181, 3.015271421527823, 4.339791716098023, 1.5761270492688444, 1.2415893928515955, 0.7440621194752707, 0.0, 10.599119351045232, 8.184683314227977, 6.207946964257977, 4.728381147806532, 8.679583432196045, 4.221379990138953, 3.048292841627181, 2.8059460972594175, 3.970714458258654, 2.9661638596141775, 1.742708338098164, 0.6245681657709112, 0.0), # 163
(9.464995355473539, 6.710402256424303, 8.54132796262104, 8.71599120693821, 7.783097157234176, 3.853661410715189, 2.9800767608321266, 2.9585294605352903, 4.259369614592037, 1.5425781539811894, 1.2154817176738126, 0.7286786370321272, 0.0, 10.386726267602059, 8.015465007353399, 6.077408588369063, 4.627734461943566, 8.518739229184074, 4.141941244749407, 2.9800767608321266, 2.752615293367992, 3.891548578617088, 2.905330402312737, 1.7082655925242083, 0.6100365687658459, 0.0), # 164
(9.239958978502024, 6.5406560987904445, 8.353440385182864, 8.518163051273666, 7.610622025101502, 3.771628343906979, 2.9071943351120755, 2.8960720746209856, 4.1705949652859235, 1.5064396429561904, 1.1873002470791263, 0.7120263592302724, 0.0, 10.155569924799979, 7.832289951532995, 5.936501235395631, 4.51931892886857, 8.341189930571847, 4.05450090446938, 2.9071943351120755, 2.694020245647842, 3.805311012550751, 2.839387683757889, 1.670688077036573, 0.5946050998900405, 0.0), # 165
(9.000488956809557, 6.361747368533551, 8.150935490750417, 8.306059072455376, 7.4249607035872005, 3.682713556329251, 2.8299828035264003, 2.8282764532266285, 4.074015530957201, 1.4678929224494195, 1.157189223788332, 0.6941927427979253, 0.0, 9.906923341916015, 7.636120170777177, 5.78594611894166, 4.403678767348258, 8.148031061914402, 3.95958703451728, 2.8299828035264003, 2.630509683092322, 3.7124803517936003, 2.768686357485126, 1.6301870981500834, 0.5783406698666865, 0.0), # 166
(8.747684464560333, 6.174412083608727, 7.934869811897824, 8.080731231089835, 7.2270703761591815, 3.5874052685726983, 2.7487794051344725, 2.7555197857939366, 3.9701790743833865, 1.4271193987164503, 1.1252928905222266, 0.6752652444633036, 0.0, 9.642059538227196, 7.427917689096338, 5.626464452611132, 4.28135819614935, 7.940358148766773, 3.8577277001115116, 2.7487794051344725, 2.562432334694784, 3.6135351880795907, 2.693577077029946, 1.5869739623795647, 0.5613101894189753, 0.0), # 167
(8.482644675918554, 5.979386261971081, 7.706299881199207, 7.843231487783524, 7.017908226285359, 3.4861917012280164, 2.663921378995663, 2.6781792617646265, 3.8596333583419993, 1.3843004780128556, 1.0917554900016058, 0.6553313209546264, 0.0, 9.362251533010546, 7.20864453050089, 5.458777450008029, 4.152901434038566, 7.7192667166839986, 3.7494509664704774, 2.663921378995663, 2.490136929448583, 3.5089541131426794, 2.614410495927842, 1.5412599762398416, 0.5435805692700985, 0.0), # 168
(8.206468765048422, 5.777405921575724, 7.466282231228694, 7.594611803142927, 6.798431437433646, 3.3795610748859013, 2.5757459641693443, 2.5966320705804184, 3.7429261456105576, 1.339617566594208, 1.0567212649472661, 0.6344784290001119, 0.0, 9.0687723455431, 6.9792627190012295, 5.28360632473633, 4.018852699782624, 7.485852291221115, 3.635284898812586, 2.5757459641693443, 2.413972196347072, 3.399215718716823, 2.5315372677143095, 1.493256446245739, 0.5252187201432478, 0.0), # 169
(7.9202559061141375, 5.569207080377758, 7.215873394560408, 7.335924137774526, 6.569597193071951, 3.268001610137046, 2.4845903997148873, 2.5112554016830275, 3.620605198966578, 1.2932520707160806, 1.020334458080004, 0.6127940253279787, 0.0, 8.762894995101878, 6.740734278607764, 5.101672290400019, 3.879756212148241, 7.241210397933156, 3.5157575623562387, 2.4845903997148873, 2.3342868643836043, 3.2847985965359756, 2.4453080459248424, 1.4431746789120816, 0.5062915527616144, 0.0), # 170
(7.6251052732799005, 5.355525756332291, 6.956129903768475, 7.068220452284813, 6.3323626766681915, 3.152001527572146, 2.390791924691664, 2.4224264445141737, 3.4932182811875796, 1.2453853966340462, 0.9827393121206148, 0.5903655666664452, 0.0, 8.445892500963913, 6.494021233330896, 4.913696560603074, 3.736156189902138, 6.986436562375159, 3.3913970223198433, 2.390791924691664, 2.2514296625515327, 3.1661813383340958, 2.356073484094938, 1.391225980753695, 0.4868659778483902, 0.0), # 171
(7.322116040709912, 5.137097967394431, 6.688108291427019, 6.792552707280267, 6.087685071690277, 3.0320490477818964, 2.2946877781590462, 2.3305223885155746, 3.3613131550510804, 1.1961989506036783, 0.9440800697898953, 0.56728050974373, 0.0, 8.119037882406225, 6.24008560718103, 4.720400348949476, 3.588596851811034, 6.722626310102161, 3.2627313439218044, 2.2946877781590462, 2.165749319844212, 3.0438425358451386, 2.2641842357600894, 1.337621658285404, 0.4670089061267665, 0.0), # 172
(7.012387382568372, 4.914659731519285, 6.412865090110164, 6.509972863367375, 5.836521561606121, 2.9086323913569916, 2.196615199176405, 2.235920423128947, 3.225437583334597, 1.145874138880549, 0.9045009738086416, 0.5436263112880514, 0.0, 7.783604158705848, 5.979889424168563, 4.522504869043208, 3.437622416641646, 6.450875166669194, 3.130288592380526, 2.196615199176405, 2.077594565254994, 2.9182607808030605, 2.169990954455792, 1.282573018022033, 0.446787248319935, 0.0), # 173
(6.697018473019482, 4.6889470666619575, 6.131456832392036, 6.221532881152618, 5.579829329883635, 2.7822397788881266, 2.096911426803113, 2.1389977377960108, 3.08613932881565, 1.0945923677202316, 0.8641462668976501, 0.519490428027628, 0.0, 7.440864349139807, 5.7143947083039075, 4.32073133448825, 3.283777103160694, 6.1722786576313, 2.994596832914415, 2.096911426803113, 1.9873141277772333, 2.7899146649418176, 2.07384429371754, 1.2262913664784072, 0.42626791515108714, 0.0), # 174
(6.377108486227438, 4.460695990777558, 5.84494005084676, 5.928284721242486, 5.318565559990731, 2.653359430965997, 1.9959137000985407, 2.040131521958481, 2.943966154271756, 1.0425350433782987, 0.8231601917777163, 0.49496031669067847, 0.0, 7.092091472985131, 5.444563483597462, 4.115800958888581, 3.1276051301348957, 5.887932308543512, 2.8561841307418736, 1.9959137000985407, 1.8952567364042836, 2.6592827799953653, 1.9760949070808291, 1.1689880101693522, 0.40551781734341447, 0.0), # 175
(6.053756596356447, 4.230642521821194, 5.554371278048459, 5.631280344243462, 5.053687435395322, 2.5224795681812964, 1.8939592581220606, 1.9396989650580787, 2.7994658224804327, 0.9898835721103237, 0.781686991169637, 0.470123434005421, 0.0, 6.738558549518844, 5.17135777405963, 3.9084349558481852, 2.9696507163309707, 5.5989316449608655, 2.71557855108131, 1.8939592581220606, 1.8017711201294973, 2.526843717697661, 1.8770934480811543, 1.1108742556096918, 0.38460386562010856, 0.0), # 176
(5.7280619775707065, 3.9995226777479713, 5.260807046571258, 5.331571710762027, 4.786152139565322, 2.3900884111247205, 1.791385339933044, 1.8380772565365193, 2.6531860962191995, 0.9368193601718788, 0.7398709077942084, 0.4450672367000743, 0.0, 6.381538598017975, 4.895739603700816, 3.699354538971042, 2.8104580805156356, 5.306372192438399, 2.5733081591511273, 1.791385339933044, 1.707206007946229, 2.393076069782661, 1.7771905702540096, 1.0521614093142517, 0.3635929707043611, 0.0), # 177
(5.401123804034416, 3.7680724765129963, 4.9653038889892835, 5.030210781404673, 4.516916855968639, 2.2566741803869648, 1.6885291845908623, 1.7356435858355217, 2.505674738265573, 0.8835238138185378, 0.6978561843722264, 0.41987918150285664, 0.0, 6.022304637759553, 4.618670996531422, 3.489280921861132, 2.6505714414556127, 5.011349476531146, 2.4299010201697304, 1.6885291845908623, 1.611910128847832, 2.2584584279843196, 1.6767369271348913, 0.9930607777978567, 0.34255204331936334, 0.0), # 178
(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), # 179
)
passenger_allighting_rate = (
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 0
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 1
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 2
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 3
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 4
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 5
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 6
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 7
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 8
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 9
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 10
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 11
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 12
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 13
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 14
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 15
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 16
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 17
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 18
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 19
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 20
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 21
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 22
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 23
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 24
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 25
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 26
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 27
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 28
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 29
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 30
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 31
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 32
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 33
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 34
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 35
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 36
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 37
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 38
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 39
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 40
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 41
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 42
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 43
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 44
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 45
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 46
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 47
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 48
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 49
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 50
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 51
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 52
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 53
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 54
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 55
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 56
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 57
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 58
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 59
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 60
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 61
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 62
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 63
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 64
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 65
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 66
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 67
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 68
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 69
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 70
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 71
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 72
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 73
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 74
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 75
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 76
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 77
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 78
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 79
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 80
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 81
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 82
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 83
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 84
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 85
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 86
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 87
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 88
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 89
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 90
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 91
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 92
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 93
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 94
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 95
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 96
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 97
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 98
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 99
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 100
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 101
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 102
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 103
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 104
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 105
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 106
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 107
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 108
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 109
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 110
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 111
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 112
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 113
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 114
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 115
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 116
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 117
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 118
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 119
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 120
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 121
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 122
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 123
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 124
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 125
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 126
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 127
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 128
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 129
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 130
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 131
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 132
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 133
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 134
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 135
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 136
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 137
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 138
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 139
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 140
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 141
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 142
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 143
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 144
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 145
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 146
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 147
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 148
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 149
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 150
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 151
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 152
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 153
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 154
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 155
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 156
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 157
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 158
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 159
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 160
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 161
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 162
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 163
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 164
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 165
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 166
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 167
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 168
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 169
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 170
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 171
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 172
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 173
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 174
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 175
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 176
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 177
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 178
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 179
)
"""
parameters for reproducibiliy. More information: https://numpy.org/doc/stable/reference/random/parallel.html
"""
#initial entropy
entropy = 8991598675325360468762009371570610170
#index for seed sequence child
child_seed_index = (
1, # 0
47, # 1
)
| 278.913369 | 492 | 0.77175 |
numPassengers = 26645
passenger_arriving = (
(9, 10, 5, 5, 3, 2, 2, 3, 3, 1, 1, 0, 0, 6, 9, 0, 8, 12, 3, 4, 1, 0, 2, 2, 2, 0),
(5, 10, 9, 11, 6, 2, 0, 5, 1, 1, 1, 0, 0, 11, 5, 5, 6, 6, 1, 2, 2, 1, 4, 0, 0, 0),
(7, 9, 3, 3, 3, 3, 3, 5, 4, 4, 2, 0, 0, 9, 6, 5, 7, 9, 1, 5, 4, 2, 2, 2, 2, 0),
(5, 10, 11, 9, 12, 3, 6, 6, 4, 1, 0, 0, 0, 6, 10, 2, 8, 8, 8, 2, 2, 3, 2, 2, 0, 0),
(11, 9, 6, 8, 7, 3, 4, 5, 4, 1, 0, 0, 0, 8, 12, 3, 5, 10, 3, 0, 4, 1, 1, 0, 3, 0),
(11, 9, 9, 13, 3, 3, 7, 7, 4, 2, 0, 2, 0, 7, 13, 7, 8, 9, 5, 5, 1, 2, 5, 1, 1, 0),
(12, 13, 8, 8, 8, 4, 1, 4, 3, 4, 3, 2, 0, 9, 8, 7, 9, 6, 2, 7, 3, 6, 3, 0, 1, 0),
(12, 8, 8, 11, 13, 3, 3, 1, 4, 1, 1, 0, 0, 12, 7, 11, 4, 9, 4, 3, 2, 3, 2, 1, 1, 0),
(14, 11, 17, 10, 8, 3, 3, 2, 3, 1, 3, 0, 0, 11, 7, 9, 6, 11, 2, 7, 4, 1, 3, 1, 0, 0),
(11, 10, 7, 9, 8, 8, 7, 5, 5, 0, 3, 3, 0, 17, 12, 9, 6, 10, 9, 4, 2, 3, 2, 4, 1, 0),
(10, 12, 11, 10, 7, 3, 6, 3, 7, 3, 2, 2, 0, 18, 13, 12, 9, 12, 6, 2, 3, 6, 2, 3, 2, 0),
(15, 11, 10, 11, 12, 7, 4, 3, 3, 1, 3, 2, 0, 10, 5, 13, 8, 12, 6, 6, 3, 1, 1, 4, 1, 0),
(11, 16, 10, 11, 9, 2, 7, 4, 3, 3, 1, 2, 0, 17, 8, 9, 5, 8, 5, 5, 0, 6, 4, 1, 1, 0),
(11, 17, 10, 10, 6, 7, 4, 2, 6, 1, 3, 1, 0, 14, 12, 4, 3, 5, 6, 4, 5, 3, 7, 3, 1, 0),
(12, 21, 12, 12, 11, 7, 4, 4, 4, 3, 5, 0, 0, 10, 12, 6, 7, 12, 6, 7, 1, 4, 4, 0, 0, 0),
(6, 12, 9, 21, 12, 3, 3, 4, 6, 2, 1, 2, 0, 9, 19, 8, 3, 6, 7, 7, 6, 8, 0, 0, 2, 0),
(7, 12, 10, 13, 12, 7, 5, 4, 4, 3, 2, 3, 0, 12, 8, 4, 6, 14, 10, 4, 2, 4, 4, 1, 1, 0),
(15, 15, 18, 15, 7, 9, 4, 3, 5, 6, 3, 1, 0, 12, 10, 7, 11, 10, 6, 2, 5, 7, 3, 1, 0, 0),
(14, 14, 16, 17, 15, 4, 6, 4, 4, 1, 2, 1, 0, 16, 17, 7, 4, 7, 7, 9, 5, 6, 4, 2, 2, 0),
(23, 16, 12, 13, 6, 6, 6, 3, 7, 0, 1, 1, 0, 17, 18, 11, 11, 15, 13, 6, 3, 5, 6, 4, 2, 0),
(12, 12, 13, 13, 10, 7, 6, 4, 6, 2, 2, 1, 0, 10, 17, 13, 7, 11, 7, 5, 5, 6, 5, 4, 1, 0),
(16, 18, 12, 13, 8, 6, 2, 6, 11, 2, 1, 1, 0, 7, 12, 10, 10, 16, 4, 4, 7, 4, 3, 1, 2, 0),
(14, 13, 8, 11, 7, 7, 2, 3, 9, 4, 2, 0, 0, 18, 9, 6, 12, 12, 7, 3, 3, 3, 8, 0, 3, 0),
(16, 9, 10, 8, 14, 9, 6, 2, 9, 3, 2, 1, 0, 16, 21, 9, 4, 5, 7, 6, 6, 1, 4, 1, 1, 0),
(11, 13, 11, 10, 6, 4, 10, 6, 6, 1, 5, 1, 0, 18, 17, 16, 3, 12, 13, 8, 2, 4, 1, 4, 1, 0),
(11, 16, 17, 7, 12, 5, 8, 5, 6, 2, 0, 2, 0, 10, 14, 10, 7, 20, 5, 12, 4, 3, 3, 3, 2, 0),
(18, 15, 18, 8, 12, 4, 14, 2, 7, 1, 1, 1, 0, 9, 10, 10, 9, 16, 3, 4, 2, 4, 4, 1, 1, 0),
(9, 9, 8, 9, 5, 7, 11, 5, 8, 2, 3, 1, 0, 10, 13, 9, 8, 12, 13, 3, 1, 3, 4, 1, 1, 0),
(18, 14, 17, 16, 17, 2, 7, 7, 7, 7, 2, 2, 0, 20, 13, 12, 8, 7, 1, 4, 2, 6, 1, 2, 2, 0),
(16, 16, 9, 15, 6, 4, 4, 7, 5, 3, 8, 1, 0, 12, 14, 11, 9, 11, 7, 2, 7, 2, 7, 6, 0, 0),
(13, 12, 17, 14, 12, 7, 9, 4, 2, 1, 3, 0, 0, 22, 14, 9, 9, 20, 6, 9, 3, 11, 3, 0, 2, 0),
(17, 9, 10, 22, 14, 6, 4, 2, 3, 5, 3, 0, 0, 19, 13, 9, 7, 15, 3, 2, 3, 5, 2, 1, 1, 0),
(12, 14, 16, 12, 11, 11, 5, 5, 6, 1, 2, 1, 0, 15, 12, 13, 7, 8, 13, 4, 5, 4, 7, 1, 2, 0),
(11, 16, 15, 17, 3, 7, 1, 6, 6, 1, 4, 1, 0, 18, 10, 9, 8, 14, 2, 3, 3, 5, 8, 1, 1, 0),
(8, 11, 12, 15, 18, 9, 4, 6, 5, 2, 4, 0, 0, 13, 13, 5, 4, 11, 7, 6, 5, 2, 2, 1, 0, 0),
(23, 16, 11, 5, 13, 3, 4, 4, 4, 3, 3, 1, 0, 13, 12, 8, 6, 9, 7, 4, 5, 6, 6, 6, 1, 0),
(13, 12, 17, 16, 14, 3, 4, 4, 5, 3, 1, 0, 0, 11, 5, 6, 11, 6, 9, 6, 3, 6, 5, 1, 1, 0),
(15, 9, 13, 12, 8, 5, 9, 8, 8, 1, 1, 1, 0, 22, 18, 11, 7, 14, 11, 8, 2, 5, 7, 3, 0, 0),
(15, 14, 16, 13, 8, 4, 4, 4, 4, 6, 1, 1, 0, 13, 8, 16, 3, 4, 7, 7, 3, 7, 6, 2, 1, 0),
(16, 17, 8, 14, 9, 4, 4, 3, 6, 0, 4, 0, 0, 17, 15, 11, 7, 13, 6, 4, 3, 5, 6, 0, 0, 0),
(11, 13, 11, 7, 9, 3, 1, 6, 8, 3, 3, 0, 0, 15, 7, 6, 12, 11, 6, 5, 7, 5, 6, 3, 1, 0),
(15, 11, 11, 7, 10, 5, 6, 3, 8, 5, 1, 1, 0, 9, 9, 13, 7, 9, 12, 6, 3, 3, 3, 3, 1, 0),
(21, 12, 14, 12, 7, 0, 4, 5, 4, 0, 0, 2, 0, 22, 14, 7, 4, 14, 13, 6, 5, 7, 6, 1, 0, 0),
(17, 16, 8, 12, 13, 1, 7, 4, 6, 1, 2, 0, 0, 15, 5, 9, 8, 13, 4, 9, 4, 1, 3, 2, 1, 0),
(11, 17, 16, 10, 7, 5, 7, 4, 4, 3, 1, 4, 0, 18, 14, 8, 8, 15, 7, 5, 7, 4, 4, 0, 3, 0),
(12, 14, 12, 14, 10, 4, 4, 4, 3, 2, 1, 2, 0, 13, 13, 13, 8, 6, 5, 5, 2, 4, 2, 4, 1, 0),
(18, 21, 10, 16, 12, 4, 4, 6, 6, 3, 1, 0, 0, 8, 5, 7, 7, 13, 8, 5, 4, 10, 2, 0, 3, 0),
(7, 10, 11, 16, 9, 8, 5, 3, 8, 0, 3, 1, 0, 20, 17, 8, 3, 7, 12, 6, 4, 7, 4, 2, 3, 0),
(19, 12, 8, 5, 7, 4, 3, 3, 5, 3, 1, 1, 0, 9, 7, 12, 11, 19, 9, 8, 4, 8, 2, 3, 1, 0),
(9, 7, 14, 20, 17, 2, 7, 3, 4, 3, 4, 3, 0, 13, 11, 10, 9, 13, 7, 4, 3, 3, 6, 1, 1, 0),
(15, 21, 13, 12, 7, 6, 7, 4, 4, 1, 1, 2, 0, 18, 12, 11, 8, 13, 10, 7, 2, 4, 6, 3, 2, 0),
(11, 9, 13, 15, 9, 2, 6, 2, 4, 7, 1, 2, 0, 21, 18, 9, 9, 14, 5, 5, 1, 5, 3, 3, 3, 0),
(15, 15, 11, 10, 8, 4, 3, 5, 6, 1, 1, 1, 0, 7, 7, 12, 11, 14, 5, 5, 2, 4, 0, 1, 3, 0),
(11, 11, 8, 13, 9, 4, 5, 5, 2, 3, 3, 1, 0, 13, 15, 8, 4, 16, 5, 6, 6, 5, 3, 2, 1, 0),
(17, 18, 6, 15, 9, 4, 5, 6, 10, 4, 2, 2, 0, 21, 17, 14, 8, 16, 6, 4, 6, 6, 3, 1, 1, 0),
(10, 12, 18, 10, 11, 7, 1, 7, 7, 3, 1, 0, 0, 14, 7, 15, 7, 7, 7, 5, 3, 1, 10, 0, 0, 0),
(6, 12, 13, 14, 15, 2, 4, 4, 4, 1, 3, 1, 0, 21, 16, 11, 6, 15, 4, 7, 7, 5, 4, 4, 1, 0),
(6, 16, 19, 17, 4, 4, 7, 6, 8, 2, 0, 0, 0, 19, 14, 6, 2, 13, 10, 6, 4, 4, 0, 2, 1, 0),
(15, 13, 15, 19, 8, 3, 6, 6, 5, 0, 2, 2, 0, 14, 9, 8, 6, 14, 3, 9, 6, 7, 4, 4, 1, 0),
(13, 4, 10, 14, 7, 4, 7, 3, 7, 6, 0, 2, 0, 10, 12, 9, 10, 11, 6, 3, 5, 7, 4, 2, 0, 0),
(14, 24, 6, 17, 14, 6, 4, 1, 1, 2, 1, 3, 0, 14, 10, 12, 12, 19, 5, 9, 1, 6, 6, 1, 0, 0),
(13, 20, 9, 10, 11, 7, 5, 9, 9, 1, 1, 2, 0, 16, 12, 11, 7, 16, 13, 3, 6, 6, 4, 0, 1, 0),
(17, 7, 12, 12, 8, 5, 5, 4, 6, 3, 1, 0, 0, 13, 8, 10, 10, 11, 4, 4, 5, 3, 6, 4, 3, 0),
(8, 14, 19, 12, 9, 5, 5, 5, 2, 0, 7, 0, 0, 12, 13, 3, 7, 10, 5, 1, 4, 3, 1, 1, 0, 0),
(16, 10, 11, 8, 12, 2, 7, 8, 5, 1, 4, 0, 0, 14, 16, 8, 11, 14, 7, 5, 4, 8, 4, 1, 1, 0),
(7, 13, 15, 14, 9, 2, 4, 4, 3, 1, 2, 0, 0, 16, 12, 19, 4, 13, 6, 5, 1, 11, 4, 1, 1, 0),
(18, 14, 11, 11, 11, 2, 0, 5, 6, 6, 1, 1, 0, 15, 10, 7, 8, 14, 10, 2, 2, 5, 4, 0, 1, 0),
(15, 17, 9, 12, 15, 4, 7, 7, 8, 0, 2, 3, 0, 17, 10, 6, 11, 9, 4, 12, 2, 1, 8, 3, 0, 0),
(10, 11, 6, 11, 12, 4, 7, 4, 8, 2, 2, 1, 0, 10, 8, 9, 7, 11, 3, 8, 3, 4, 4, 5, 0, 0),
(14, 10, 9, 16, 6, 4, 8, 7, 3, 1, 0, 4, 0, 12, 10, 9, 5, 12, 7, 9, 3, 4, 4, 2, 0, 0),
(19, 11, 8, 18, 13, 6, 7, 4, 4, 0, 5, 1, 0, 16, 8, 10, 6, 11, 6, 6, 2, 6, 4, 1, 2, 0),
(17, 6, 13, 11, 15, 9, 2, 1, 9, 4, 2, 0, 0, 11, 10, 8, 4, 7, 5, 9, 4, 6, 5, 0, 0, 0),
(15, 9, 19, 17, 10, 5, 9, 6, 7, 3, 1, 0, 0, 16, 11, 12, 17, 9, 2, 8, 7, 7, 4, 2, 3, 0),
(17, 11, 11, 15, 9, 6, 3, 7, 9, 2, 2, 0, 0, 16, 9, 5, 5, 16, 6, 7, 5, 2, 1, 2, 0, 0),
(9, 8, 8, 14, 12, 11, 3, 2, 3, 3, 0, 0, 0, 18, 17, 13, 4, 13, 5, 5, 1, 5, 4, 4, 0, 0),
(11, 13, 14, 11, 13, 7, 6, 3, 7, 3, 2, 1, 0, 14, 14, 9, 9, 7, 5, 6, 1, 8, 4, 3, 1, 0),
(19, 12, 16, 10, 11, 5, 8, 3, 3, 6, 1, 0, 0, 7, 12, 10, 8, 19, 9, 7, 2, 5, 6, 4, 0, 0),
(10, 8, 14, 12, 13, 5, 9, 5, 5, 1, 3, 0, 0, 18, 21, 9, 11, 6, 2, 2, 4, 8, 2, 3, 1, 0),
(12, 14, 6, 17, 15, 6, 4, 4, 6, 2, 2, 0, 0, 11, 12, 9, 5, 11, 6, 4, 2, 5, 7, 0, 0, 0),
(12, 8, 10, 13, 10, 6, 4, 6, 6, 3, 2, 0, 0, 16, 7, 7, 8, 5, 4, 5, 6, 9, 2, 1, 0, 0),
(17, 17, 12, 9, 15, 8, 2, 3, 5, 1, 1, 1, 0, 10, 15, 13, 5, 13, 4, 6, 4, 7, 3, 1, 0, 0),
(13, 11, 12, 8, 12, 6, 8, 6, 8, 2, 3, 0, 0, 19, 9, 12, 10, 12, 4, 5, 2, 5, 1, 1, 1, 0),
(13, 13, 7, 15, 11, 7, 6, 6, 5, 2, 0, 7, 0, 18, 14, 7, 12, 7, 3, 3, 8, 3, 6, 3, 2, 0),
(12, 6, 13, 6, 6, 5, 8, 3, 6, 4, 2, 0, 0, 17, 9, 8, 8, 12, 7, 5, 3, 7, 4, 2, 0, 0),
(11, 13, 14, 16, 11, 7, 8, 7, 6, 2, 1, 1, 0, 7, 16, 8, 5, 5, 3, 6, 4, 5, 3, 2, 0, 0),
(12, 14, 21, 14, 14, 7, 6, 3, 8, 4, 1, 1, 0, 9, 15, 10, 2, 13, 3, 6, 4, 6, 3, 3, 0, 0),
(16, 11, 11, 11, 15, 4, 4, 4, 6, 1, 2, 1, 0, 11, 7, 8, 11, 10, 8, 3, 3, 5, 8, 2, 0, 0),
(17, 7, 11, 12, 6, 3, 4, 2, 5, 2, 1, 0, 0, 11, 16, 8, 10, 7, 8, 5, 6, 7, 9, 1, 0, 0),
(11, 17, 10, 9, 10, 6, 6, 2, 3, 4, 5, 0, 0, 21, 12, 9, 10, 13, 1, 2, 5, 6, 5, 2, 1, 0),
(15, 9, 14, 15, 7, 4, 4, 5, 4, 1, 3, 1, 0, 18, 14, 9, 4, 9, 6, 9, 4, 5, 4, 2, 0, 0),
(13, 8, 9, 11, 11, 9, 7, 2, 3, 2, 0, 0, 0, 13, 13, 7, 3, 6, 9, 4, 4, 6, 1, 3, 1, 0),
(18, 13, 7, 14, 9, 4, 4, 0, 8, 2, 2, 0, 0, 14, 10, 11, 5, 7, 4, 10, 3, 2, 2, 5, 2, 0),
(12, 12, 7, 13, 13, 7, 1, 8, 5, 4, 5, 1, 0, 14, 17, 8, 8, 11, 4, 5, 3, 5, 5, 2, 1, 0),
(11, 5, 12, 12, 4, 4, 3, 4, 10, 3, 1, 0, 0, 13, 10, 10, 6, 21, 6, 4, 3, 2, 3, 2, 1, 0),
(14, 13, 12, 13, 13, 2, 4, 7, 3, 2, 2, 1, 0, 12, 13, 4, 7, 15, 6, 5, 1, 6, 5, 0, 0, 0),
(9, 19, 11, 11, 7, 5, 2, 4, 3, 4, 0, 3, 0, 12, 17, 7, 11, 11, 6, 5, 2, 3, 3, 0, 2, 0),
(9, 8, 14, 10, 7, 6, 8, 7, 9, 3, 1, 2, 0, 10, 10, 9, 8, 7, 6, 3, 9, 9, 5, 5, 0, 0),
(13, 10, 8, 14, 10, 4, 2, 10, 5, 2, 2, 3, 0, 11, 3, 8, 8, 12, 7, 5, 1, 8, 1, 2, 1, 0),
(17, 8, 12, 12, 12, 7, 4, 2, 4, 4, 0, 2, 0, 8, 9, 5, 6, 10, 5, 3, 1, 7, 4, 4, 2, 0),
(14, 10, 11, 15, 12, 4, 5, 3, 4, 1, 0, 2, 0, 14, 13, 13, 7, 9, 4, 4, 0, 2, 6, 4, 2, 0),
(9, 9, 11, 10, 11, 5, 2, 5, 8, 1, 0, 5, 0, 12, 8, 12, 8, 12, 2, 7, 3, 10, 4, 4, 1, 0),
(16, 11, 10, 7, 12, 3, 2, 3, 6, 1, 1, 1, 0, 13, 12, 4, 5, 10, 9, 6, 3, 6, 4, 2, 0, 0),
(17, 12, 8, 14, 5, 6, 5, 5, 4, 2, 1, 0, 0, 15, 7, 5, 12, 9, 6, 2, 5, 3, 7, 3, 3, 0),
(14, 12, 8, 12, 8, 5, 4, 5, 7, 2, 1, 0, 0, 20, 14, 10, 8, 6, 4, 4, 2, 8, 3, 0, 1, 0),
(14, 6, 11, 14, 11, 4, 4, 5, 5, 3, 1, 1, 0, 10, 6, 14, 6, 8, 9, 4, 5, 2, 3, 1, 0, 0),
(16, 11, 9, 13, 12, 5, 8, 5, 8, 2, 2, 0, 0, 17, 10, 15, 8, 10, 3, 6, 1, 6, 4, 3, 0, 0),
(8, 12, 13, 10, 6, 5, 5, 2, 8, 2, 1, 1, 0, 19, 14, 7, 4, 12, 4, 3, 4, 5, 3, 1, 1, 0),
(11, 12, 16, 5, 3, 9, 3, 2, 7, 2, 0, 2, 0, 15, 13, 3, 3, 8, 5, 7, 4, 6, 4, 3, 1, 0),
(12, 9, 7, 9, 7, 5, 4, 3, 2, 1, 2, 3, 0, 24, 10, 11, 9, 9, 5, 6, 2, 6, 4, 1, 4, 0),
(10, 15, 14, 10, 7, 7, 9, 5, 8, 2, 1, 2, 0, 17, 9, 6, 5, 9, 9, 3, 5, 9, 1, 3, 0, 0),
(15, 7, 10, 8, 8, 4, 4, 4, 5, 0, 0, 0, 0, 13, 9, 13, 9, 9, 6, 5, 5, 5, 4, 0, 2, 0),
(19, 13, 9, 13, 16, 2, 2, 2, 9, 4, 1, 0, 0, 8, 8, 11, 4, 10, 1, 5, 2, 6, 2, 3, 0, 0),
(15, 18, 10, 14, 4, 2, 3, 2, 9, 0, 1, 0, 0, 12, 10, 6, 11, 7, 2, 2, 3, 10, 3, 2, 0, 0),
(9, 7, 13, 17, 5, 2, 0, 1, 8, 1, 3, 1, 0, 18, 9, 11, 6, 9, 11, 2, 2, 5, 5, 4, 1, 0),
(14, 4, 12, 10, 8, 7, 2, 2, 6, 2, 2, 0, 0, 13, 11, 9, 6, 10, 1, 6, 3, 4, 3, 2, 1, 0),
(15, 7, 9, 13, 10, 3, 7, 1, 4, 0, 2, 2, 0, 11, 11, 15, 4, 12, 4, 3, 3, 4, 5, 4, 3, 0),
(4, 14, 12, 13, 12, 6, 1, 6, 4, 0, 0, 1, 0, 11, 9, 9, 4, 7, 11, 3, 2, 4, 5, 1, 1, 0),
(15, 9, 13, 10, 9, 6, 4, 3, 9, 5, 1, 2, 0, 10, 10, 9, 9, 12, 1, 3, 4, 5, 2, 1, 0, 0),
(10, 10, 13, 17, 10, 6, 3, 3, 4, 1, 2, 2, 0, 12, 15, 10, 9, 5, 4, 3, 3, 6, 4, 0, 1, 0),
(5, 8, 8, 7, 11, 3, 3, 5, 5, 2, 4, 1, 0, 10, 9, 11, 3, 11, 7, 3, 3, 3, 2, 4, 3, 0),
(9, 9, 9, 9, 11, 4, 4, 2, 5, 3, 1, 0, 0, 11, 12, 7, 8, 8, 8, 3, 3, 8, 2, 4, 2, 0),
(10, 15, 17, 15, 15, 5, 4, 4, 10, 3, 3, 0, 0, 17, 9, 6, 7, 4, 4, 2, 3, 4, 5, 4, 0, 0),
(23, 10, 9, 8, 11, 4, 2, 3, 9, 1, 2, 0, 0, 17, 12, 6, 7, 8, 5, 2, 3, 8, 3, 3, 0, 0),
(16, 5, 5, 14, 10, 3, 4, 1, 4, 3, 2, 1, 0, 17, 11, 11, 4, 9, 3, 5, 5, 3, 2, 4, 1, 0),
(10, 19, 10, 15, 5, 6, 5, 2, 5, 2, 0, 0, 0, 7, 11, 6, 6, 10, 6, 2, 4, 7, 3, 0, 1, 0),
(7, 8, 9, 6, 11, 4, 5, 2, 4, 3, 1, 0, 0, 13, 11, 11, 10, 11, 6, 7, 4, 5, 2, 4, 0, 0),
(15, 13, 6, 12, 4, 5, 6, 2, 0, 3, 1, 1, 0, 19, 6, 6, 6, 8, 4, 4, 3, 4, 3, 1, 1, 0),
(7, 8, 9, 11, 12, 4, 4, 2, 6, 2, 0, 0, 0, 8, 7, 4, 3, 9, 5, 2, 2, 6, 1, 5, 1, 0),
(15, 12, 9, 9, 4, 7, 4, 2, 8, 5, 1, 2, 0, 11, 5, 9, 5, 11, 3, 4, 3, 3, 3, 4, 1, 0),
(13, 9, 14, 9, 10, 5, 4, 1, 6, 1, 1, 1, 0, 14, 10, 6, 5, 10, 9, 5, 2, 1, 8, 0, 0, 0),
(8, 12, 10, 11, 11, 5, 2, 6, 5, 1, 2, 1, 0, 8, 5, 5, 6, 9, 3, 7, 1, 2, 2, 3, 0, 0),
(5, 6, 19, 7, 5, 2, 1, 4, 6, 1, 0, 0, 0, 9, 10, 9, 5, 8, 7, 3, 4, 3, 1, 2, 0, 0),
(12, 10, 10, 5, 10, 6, 4, 7, 2, 1, 1, 0, 0, 17, 9, 5, 10, 13, 3, 2, 3, 1, 4, 7, 1, 0),
(6, 10, 12, 11, 5, 4, 4, 4, 3, 1, 2, 3, 0, 9, 11, 6, 4, 14, 4, 6, 4, 10, 5, 3, 1, 0),
(15, 8, 11, 16, 9, 5, 2, 3, 7, 2, 1, 1, 0, 11, 5, 12, 5, 12, 1, 5, 5, 5, 4, 2, 0, 0),
(12, 11, 13, 13, 13, 2, 0, 2, 4, 2, 3, 0, 0, 10, 11, 7, 5, 15, 7, 6, 2, 3, 3, 1, 3, 0),
(17, 7, 13, 15, 7, 6, 5, 2, 5, 1, 0, 1, 0, 10, 7, 8, 4, 14, 4, 4, 4, 5, 1, 2, 0, 0),
(10, 11, 12, 12, 12, 5, 2, 3, 2, 2, 2, 0, 0, 18, 11, 8, 6, 12, 4, 7, 2, 6, 3, 3, 1, 0),
(17, 4, 5, 12, 11, 3, 7, 2, 6, 6, 0, 1, 0, 11, 11, 6, 5, 8, 2, 3, 3, 7, 6, 3, 1, 0),
(16, 12, 12, 8, 8, 6, 6, 3, 4, 1, 3, 1, 0, 13, 8, 8, 7, 9, 8, 2, 4, 4, 4, 5, 1, 0),
(13, 9, 5, 14, 8, 5, 3, 5, 6, 2, 3, 1, 0, 6, 9, 7, 3, 11, 6, 5, 7, 5, 6, 3, 1, 0),
(16, 6, 11, 8, 7, 6, 6, 2, 6, 0, 1, 1, 0, 14, 13, 8, 7, 10, 2, 4, 1, 5, 2, 1, 0, 0),
(7, 5, 9, 11, 8, 5, 2, 6, 5, 2, 0, 2, 0, 12, 5, 4, 2, 10, 6, 5, 3, 3, 4, 0, 3, 0),
(17, 14, 13, 10, 15, 4, 5, 5, 7, 0, 3, 4, 0, 13, 10, 6, 6, 15, 5, 6, 3, 2, 5, 1, 1, 0),
(11, 11, 15, 13, 5, 4, 6, 6, 1, 4, 5, 0, 0, 11, 11, 7, 4, 11, 4, 4, 8, 7, 3, 1, 0, 0),
(6, 13, 11, 4, 7, 6, 2, 7, 7, 1, 1, 1, 0, 9, 7, 13, 5, 8, 11, 6, 8, 5, 5, 2, 3, 0),
(15, 12, 8, 10, 9, 5, 4, 5, 4, 0, 1, 1, 0, 11, 9, 13, 5, 11, 4, 5, 2, 3, 3, 1, 0, 0),
(12, 12, 9, 8, 7, 4, 2, 5, 2, 1, 2, 1, 0, 16, 12, 6, 5, 9, 4, 3, 3, 4, 3, 2, 2, 0),
(10, 9, 15, 12, 8, 7, 6, 6, 4, 2, 1, 2, 0, 14, 8, 9, 6, 8, 4, 4, 3, 2, 4, 2, 0, 0),
(18, 13, 6, 15, 12, 4, 6, 2, 5, 4, 2, 0, 0, 10, 7, 8, 5, 8, 2, 3, 4, 7, 2, 3, 2, 0),
(18, 3, 10, 10, 4, 5, 2, 3, 2, 1, 2, 0, 0, 9, 11, 4, 5, 18, 3, 7, 4, 6, 3, 2, 2, 0),
(9, 5, 4, 3, 7, 5, 3, 3, 5, 0, 3, 0, 0, 10, 12, 8, 6, 10, 5, 1, 1, 1, 3, 1, 1, 0),
(9, 3, 9, 12, 8, 3, 1, 1, 4, 3, 1, 0, 0, 14, 6, 3, 4, 9, 4, 3, 7, 3, 5, 0, 0, 0),
(7, 5, 7, 12, 5, 6, 3, 3, 4, 3, 2, 0, 0, 10, 11, 5, 8, 9, 5, 2, 4, 7, 3, 2, 1, 0),
(7, 10, 8, 8, 8, 3, 3, 0, 2, 2, 1, 1, 0, 9, 11, 10, 7, 14, 4, 4, 2, 3, 2, 1, 2, 0),
(17, 6, 10, 13, 6, 1, 5, 2, 1, 0, 1, 0, 0, 14, 3, 5, 3, 7, 3, 2, 4, 5, 4, 1, 0, 0),
(4, 5, 4, 8, 4, 6, 3, 4, 3, 0, 1, 1, 0, 10, 9, 5, 4, 7, 10, 3, 7, 4, 5, 1, 0, 0),
(3, 7, 6, 5, 14, 6, 3, 1, 2, 2, 1, 2, 0, 13, 8, 6, 5, 11, 2, 4, 3, 3, 5, 4, 0, 0),
(9, 5, 16, 8, 8, 4, 6, 4, 7, 3, 2, 0, 0, 5, 9, 1, 8, 12, 5, 4, 2, 3, 1, 4, 0, 0),
(7, 6, 10, 5, 8, 5, 4, 5, 6, 1, 1, 0, 0, 6, 13, 7, 6, 7, 6, 3, 4, 4, 1, 1, 0, 0),
(13, 5, 12, 5, 6, 4, 1, 5, 2, 2, 2, 0, 0, 11, 7, 6, 5, 7, 4, 1, 5, 5, 1, 1, 0, 0),
(11, 6, 9, 7, 4, 2, 1, 6, 7, 2, 0, 0, 0, 6, 11, 7, 3, 6, 7, 7, 3, 6, 3, 2, 1, 0),
(12, 10, 5, 6, 9, 6, 2, 5, 7, 1, 1, 0, 0, 10, 5, 10, 4, 13, 3, 1, 1, 7, 2, 3, 0, 0),
(9, 6, 12, 8, 4, 3, 2, 3, 7, 2, 3, 0, 0, 12, 6, 7, 1, 5, 2, 3, 6, 3, 4, 2, 0, 0),
(9, 5, 7, 9, 8, 3, 2, 3, 6, 1, 0, 0, 0, 9, 5, 4, 2, 8, 3, 3, 4, 5, 3, 1, 1, 0),
(11, 8, 12, 7, 5, 4, 6, 1, 6, 3, 1, 1, 0, 6, 9, 3, 1, 4, 5, 2, 3, 2, 4, 0, 0, 0),
(5, 3, 13, 9, 4, 2, 1, 4, 5, 1, 1, 0, 0, 12, 5, 5, 5, 9, 6, 2, 1, 2, 4, 1, 0, 0),
(6, 7, 8, 8, 4, 3, 6, 5, 6, 1, 3, 0, 0, 13, 6, 10, 5, 5, 4, 1, 3, 5, 1, 0, 1, 0),
(9, 5, 11, 11, 5, 3, 3, 3, 2, 2, 1, 2, 0, 8, 8, 6, 3, 8, 3, 3, 1, 1, 2, 1, 0, 0),
(5, 5, 8, 10, 3, 2, 5, 3, 4, 0, 2, 0, 0, 13, 6, 4, 2, 6, 2, 2, 3, 0, 2, 3, 0, 0),
(11, 5, 5, 6, 5, 2, 3, 3, 3, 0, 2, 1, 0, 9, 6, 9, 6, 7, 3, 3, 4, 6, 1, 2, 2, 0),
(10, 4, 5, 4, 11, 4, 1, 4, 2, 1, 1, 1, 0, 7, 6, 11, 4, 13, 7, 0, 0, 2, 4, 0, 0, 0),
(9, 2, 4, 6, 3, 5, 1, 1, 2, 3, 2, 0, 0, 4, 5, 4, 3, 8, 2, 2, 3, 1, 1, 3, 0, 0),
(8, 6, 2, 4, 6, 3, 2, 0, 2, 1, 0, 0, 0, 8, 7, 9, 5, 4, 1, 3, 2, 3, 6, 0, 1, 0),
(6, 5, 6, 6, 7, 3, 2, 0, 2, 2, 0, 0, 0, 8, 6, 3, 2, 6, 4, 0, 2, 4, 2, 0, 0, 0),
(8, 3, 5, 7, 5, 1, 2, 0, 2, 2, 3, 1, 0, 6, 3, 1, 5, 5, 1, 0, 3, 2, 2, 2, 2, 0),
(5, 5, 4, 7, 8, 4, 2, 1, 2, 1, 1, 2, 0, 5, 0, 2, 2, 5, 3, 1, 1, 2, 3, 0, 0, 0),
(11, 4, 9, 6, 5, 3, 3, 2, 1, 2, 0, 1, 0, 8, 1, 4, 3, 5, 1, 3, 0, 3, 1, 0, 0, 0),
(5, 4, 4, 3, 6, 2, 1, 3, 5, 1, 0, 2, 0, 9, 1, 1, 2, 4, 0, 2, 0, 5, 2, 2, 1, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
)
station_arriving_intensity = (
(7.029211809720476, 7.735403983570434, 7.29579652145751, 8.700534883408807, 7.776559850653457, 4.394116904852274, 5.804449861523481, 6.514446642171193, 8.52613868703521, 5.541221021731318, 5.887371229439844, 6.857081109628643, 7.117432297609708),
(7.496058012827964, 8.246084971802663, 7.777485227862214, 9.275201954587263, 8.291486472463932, 4.684377017659578, 6.187256517769172, 6.943319212067992, 9.089143456866074, 5.90657296918801, 6.2763345903385845, 7.309703325140097, 7.587708306415797),
(7.9614122125716245, 8.754739239247371, 8.257259199766379, 9.847582786530712, 8.804548163249642, 4.9734791603174235, 6.568545911144986, 7.370475347066188, 9.64990152962857, 6.270479285028765, 6.663752408286839, 7.760525712874277, 8.056110759493567),
(8.423460910405188, 9.259348702711026, 8.733215217047796, 10.415406970544904, 9.313726346402664, 5.260276871619158, 6.946805098307138, 7.79422162049231, 10.206189225289531, 6.631495777796654, 7.0480877765583365, 8.207759958902646, 8.520781928755916),
(8.880390607782374, 9.757895279000085, 9.203450059584252, 10.976404097935598, 9.81700244531509, 5.543623690358135, 7.320521135911843, 8.212864605672882, 10.75578286381579, 6.988178256034751, 7.4278037884268056, 8.64961774929667, 8.979864086115745),
(9.330387806156915, 10.248360884921025, 9.666060507253526, 11.528303760008551, 10.312357883378994, 5.822373155327701, 7.688181080615314, 8.62471087593443, 11.296458765174183, 7.339082528286129, 7.801363537165986, 9.084310770127807, 9.43149950348596),
(9.771639006982534, 10.728727437280302, 10.119143339933412, 12.068835548069513, 10.79777408398646, 6.09537880532121, 8.048271989073768, 9.028067004603484, 11.825993249331543, 7.682764403093862, 8.167230116049597, 9.510050707467531, 9.87383045277945),
(10.202330711712957, 11.196976852884385, 10.56079533750169, 12.595729053424249, 11.271232470529577, 6.36149417913201, 8.39928091794342, 9.421239565006573, 12.342162636254702, 8.017779689001022, 8.523866618351377, 9.925049247387301, 10.304999205909127),
(10.62064942180191, 11.651091048539739, 10.989113279836156, 13.1067138673785, 11.730714466400421, 6.619572815553446, 8.739694923880478, 9.802535130470215, 12.842743245910489, 8.342684194550685, 8.86973613734505, 10.327518075958585, 10.723148034787885),
(11.02478163870312, 12.089051941052832, 11.402193946814586, 13.599519581238038, 12.174201494991074, 6.868468253378878, 9.068001063541168, 10.170260274320949, 13.325511398265744, 8.65603372828592, 9.20330176630435, 10.71566887925284, 11.126419211328628),
(11.412913863870306, 12.508841447230123, 11.798134118314776, 14.071875786308604, 12.599674979693622, 7.107034031401651, 9.382686393581697, 10.522721569885295, 13.7882434132873, 8.956384098749801, 9.523026598503003, 11.087713343341534, 11.512955007444255),
(11.783232598757209, 12.90844148387809, 12.175030574214501, 14.521512073895957, 13.005116343900148, 7.334123688415116, 9.682237970658283, 10.85822559048978, 14.228715610941991, 9.242291114485408, 9.82737372721475, 11.441863154296136, 11.880897695047656),
(12.133924344817538, 13.285833967803178, 12.530980094391557, 14.946158035305858, 13.38850701100273, 7.5485907632126175, 9.965142851427137, 11.17507890946093, 14.644704311196652, 9.512310584035802, 10.114806245713309, 11.776329998188096, 12.22838954605175),
(12.463175603505027, 13.639000815811869, 12.864079458723728, 15.343543261844063, 13.747828404393443, 7.749288794587514, 10.22988809254448, 11.471588100125276, 15.033985834018106, 9.764998315944066, 10.383787247272418, 12.08932556108889, 12.55357283236943),
(12.769172876273403, 13.965923944710624, 13.172425447088806, 15.71139734481631, 14.081061947464386, 7.935071321333148, 10.474960750666526, 11.746059735809345, 15.39433649937319, 9.998910118753269, 10.6327798251658, 12.379061529069986, 12.85458982591359),
(13.050102664576398, 14.264585271305906, 13.45411483936456, 16.047449875528383, 14.386189063607633, 8.104791882242878, 10.698847882449478, 11.99680038983966, 15.723532627228748, 10.212601801006487, 10.860247072667189, 12.64374958820284, 13.129582798597134),
(13.30415146986772, 14.532966712404187, 13.707244415428796, 16.349430445286004, 14.661191176215267, 8.257304016110044, 10.900036544549568, 12.222116635542745, 16.019350537551603, 10.404629171246796, 11.06465208305032, 12.881601424558916, 13.376694022332964),
(13.529505793601107, 14.769050184811926, 13.929910955159293, 16.61506864539496, 14.904049708679375, 8.391461261728, 11.077013793622996, 12.420315046245145, 16.27956655030858, 10.573548038017254, 11.24445794958892, 13.090828724209679, 13.594065769033982),
(13.724352137230287, 14.970817605335585, 14.120211238433834, 16.842094067160993, 15.112746084392025, 8.506117157890104, 11.228266686325993, 12.589702195273366, 16.501956985466535, 10.717914209860952, 11.398127765556712, 13.269643173226603, 13.779840310613086),
(13.88687700220898, 15.136250890781643, 14.27624204513021, 17.02823630188984, 15.285261726745313, 8.600125243389693, 11.352282279314753, 12.728584655953943, 16.68429816299229, 10.83628349532096, 11.52412462422743, 13.416256457681136, 13.932159918983176),
(14.015266889990915, 15.263331957956549, 14.396100155126206, 17.171224940887296, 15.419578059131322, 8.672339057020126, 11.44754762924551, 12.835269001613405, 16.82436640285268, 10.927211702940342, 11.62091161887481, 13.528880263644748, 14.049166866057154),
(14.107708302029813, 15.350042723666784, 14.477882348299607, 17.26878957545908, 15.513676504942126, 8.72161213757475, 11.512549792774463, 12.908061805578273, 16.91993802501453, 10.989254641262178, 11.686951842772585, 13.60572627718891, 14.12900342374791),
(14.162387739779412, 15.394365104718803, 14.5196854045282, 17.31865979691097, 15.565538487569807, 8.746798023846914, 11.54577582655784, 12.945269641175082, 16.968789349444684, 11.02096811882954, 11.720708389194478, 13.645006184385087, 14.16981186396836),
(14.182550708679697, 15.39961303155007, 14.524892455418383, 17.324903137860087, 15.578824878445637, 8.75, 11.549725603163076, 12.949291358024693, 16.974896728395063, 11.024709181527207, 11.724941252026436, 13.649856607224509, 14.175),
(14.197417378247815, 15.396551851851854, 14.524040740740743, 17.324134722222226, 15.586350659060795, 8.75, 11.547555337690634, 12.943700000000002, 16.974078333333335, 11.02241086419753, 11.724474410774413, 13.648720987654322, 14.175),
(14.211970122296213, 15.390517832647463, 14.522359396433473, 17.322614454732513, 15.593710923832306, 8.75, 11.543278463648836, 12.932716049382718, 16.97246141975309, 11.01788637402835, 11.723548759196907, 13.646479195244629, 14.175),
(14.226207826667249, 15.381603155006863, 14.519871467764064, 17.320359619341563, 15.600905415789548, 8.75, 11.53696140563221, 12.916546913580248, 16.97006672839506, 11.011210992226795, 11.722172677391198, 13.643161957018751, 14.175),
(14.240129377203292, 15.3699, 14.5166, 17.3173875, 15.607933877961901, 8.75, 11.528670588235297, 12.895400000000002, 16.966915, 11.00246, 11.720354545454546, 13.638800000000003, 14.175),
(14.253733659746702, 15.355500548696845, 14.51256803840878, 17.313715380658437, 15.614796053378763, 8.75, 11.518472436052612, 12.869482716049385, 16.963026975308644, 10.9917086785551, 11.718102743484225, 13.633424051211708, 14.175),
(14.26701956013985, 15.338496982167355, 14.50779862825789, 17.30936054526749, 15.62149168506951, 8.75, 11.506433373678693, 12.839002469135803, 16.95842339506173, 10.979032309099225, 11.715425651577503, 13.627064837677183, 14.175),
(14.279985964225098, 15.318981481481483, 14.502314814814815, 17.30434027777778, 15.628020516063533, 8.75, 11.492619825708061, 12.804166666666665, 16.953125, 10.964506172839508, 11.71233164983165, 13.619753086419752, 14.175),
(14.292631757844802, 15.297046227709194, 14.496139643347053, 17.29867186213992, 15.634382289390214, 8.75, 11.477098216735257, 12.765182716049384, 16.947152530864198, 10.948205550983083, 11.708829118343933, 13.611519524462738, 14.175),
(14.304955826841338, 15.27278340192044, 14.489296159122084, 17.29237258230453, 15.640576748078935, 8.75, 11.4599349713548, 12.72225802469136, 16.940526728395064, 10.930205724737084, 11.704926437211622, 13.602394878829449, 14.175),
(14.316957057057056, 15.246285185185185, 14.481807407407409, 17.28545972222222, 15.646603635159089, 8.75, 11.441196514161222, 12.675600000000001, 16.933268333333334, 10.910581975308643, 11.700631986531986, 13.59240987654321, 14.175),
(14.328634334334335, 15.217643758573388, 14.473696433470508, 17.27795056584362, 15.652462693660054, 8.75, 11.420949269749054, 12.625416049382716, 16.925398086419758, 10.889409583904893, 11.695954146402293, 13.581595244627344, 14.175),
(14.339986544515531, 15.186951303155007, 14.464986282578877, 17.26986239711934, 15.65815366661122, 8.75, 11.399259662712824, 12.571913580246914, 16.916936728395065, 10.866763831732968, 11.690901296919815, 13.569981710105168, 14.175),
(14.35101257344301, 15.1543, 14.455700000000002, 17.2612125, 15.663676297041972, 8.75, 11.37619411764706, 12.515300000000002, 16.907905, 10.84272, 11.685481818181819, 13.557600000000003, 14.175),
(14.361711306959135, 15.119782030178326, 14.445860631001374, 17.252018158436215, 15.669030327981691, 8.75, 11.351819059146292, 12.455782716049384, 16.89832364197531, 10.817353369913125, 11.679704090285574, 13.544480841335163, 14.175),
(14.372081630906267, 15.083489574759948, 14.43549122085048, 17.242296656378603, 15.674215502459768, 8.75, 11.326200911805053, 12.393569135802473, 16.88821339506173, 10.790739222679472, 11.673576493328346, 13.530654961133976, 14.175),
(14.382122431126781, 15.045514814814815, 14.424614814814818, 17.232065277777778, 15.679231563505585, 8.75, 11.299406100217867, 12.328866666666666, 16.877595000000003, 10.762952839506175, 11.667107407407409, 13.516153086419752, 14.175),
(14.39183259346303, 15.005949931412895, 14.413254458161866, 17.221341306584364, 15.684078254148528, 8.75, 11.271501048979264, 12.261882716049385, 16.866489197530868, 10.734069501600368, 11.660305212620028, 13.501005944215823, 14.175),
(14.40121100375738, 14.964887105624143, 14.401433196159124, 17.210142026748972, 15.688755317417984, 8.75, 11.242552182683774, 12.192824691358027, 16.85491672839506, 10.704164490169182, 11.653178289063476, 13.485244261545498, 14.175),
(14.410256547852201, 14.922418518518521, 14.389174074074077, 17.198484722222226, 15.693262496343333, 8.75, 11.212625925925927, 12.121900000000002, 16.842898333333338, 10.673313086419753, 11.645735016835017, 13.4688987654321, 14.175),
(14.418968111589852, 14.878636351165984, 14.376500137174213, 17.186386676954736, 15.697599533953966, 8.75, 11.181788703300251, 12.049316049382718, 16.83045475308642, 10.641590571559215, 11.637983776031925, 13.452000182898951, 14.175),
(14.427344580812699, 14.83363278463649, 14.363434430727025, 17.173865174897124, 15.701766173279264, 8.75, 11.150106939401276, 11.975280246913583, 16.817606728395063, 10.609072226794698, 11.629932946751465, 13.434579240969367, 14.175),
(14.435384841363105, 14.787500000000001, 14.350000000000001, 17.160937500000003, 15.705762157348616, 8.75, 11.11764705882353, 11.9, 16.804375, 10.575833333333335, 11.62159090909091, 13.416666666666666, 14.175),
(14.443087779083434, 14.740330178326476, 14.336219890260631, 17.147620936213993, 15.709587229191404, 8.75, 11.084475486161544, 11.823682716049385, 16.790780308641974, 10.541949172382258, 11.612966043147525, 13.398293187014175, 14.175),
(14.45045227981605, 14.692215500685872, 14.322117146776408, 17.133932767489714, 15.713241131837016, 8.75, 11.050658646009847, 11.746535802469136, 16.776843395061732, 10.507495025148607, 11.604066729018582, 13.37948952903521, 14.175),
(14.457477229403315, 14.64324814814815, 14.307714814814817, 17.11989027777778, 15.716723608314837, 8.75, 11.016262962962964, 11.668766666666668, 16.762585, 10.472546172839506, 11.594901346801347, 13.360286419753088, 14.175),
(14.464161513687602, 14.593520301783265, 14.29303593964335, 17.10551075102881, 15.720034401654251, 8.75, 10.981354861615428, 11.590582716049383, 16.748025864197533, 10.437177896662096, 11.585478276593093, 13.340714586191131, 14.175),
(14.470504018511264, 14.543124142661183, 14.278103566529495, 17.090811471193415, 15.723173254884642, 8.75, 10.94600076656177, 11.512191358024692, 16.73318672839506, 10.401465477823503, 11.575805898491085, 13.32080475537266, 14.175),
(14.476503629716676, 14.492151851851853, 14.262940740740742, 17.075809722222225, 15.726139911035398, 8.75, 10.910267102396515, 11.433800000000002, 16.718088333333338, 10.365484197530865, 11.565892592592595, 13.30058765432099, 14.175),
(14.482159233146191, 14.440695610425243, 14.247570507544584, 17.060522788065846, 15.728934113135901, 8.75, 10.874220293714194, 11.355616049382716, 16.70275141975309, 10.329309336991313, 11.555746738994888, 13.280094010059445, 14.175),
(14.487469714642183, 14.388847599451307, 14.232015912208508, 17.0449679526749, 15.731555604215542, 8.75, 10.837926765109337, 11.277846913580248, 16.687196728395065, 10.293016177411982, 11.545376717795238, 13.259354549611341, 14.175),
(14.492433960047004, 14.336700000000002, 14.2163, 17.0291625, 15.734004127303704, 8.75, 10.801452941176471, 11.2007, 16.671445000000002, 10.256680000000001, 11.534790909090908, 13.2384, 14.175),
(14.497050855203032, 14.284344993141291, 14.200445816186559, 17.01312371399177, 15.736279425429768, 8.75, 10.764865246510128, 11.124382716049384, 16.655516975308643, 10.220376085962506, 11.523997692979176, 13.217261088248744, 14.175),
(14.501319285952622, 14.231874759945132, 14.184476406035667, 16.996868878600825, 15.738381241623124, 8.75, 10.728230105704835, 11.049102469135804, 16.63943339506173, 10.184179716506632, 11.513005449557303, 13.195968541380887, 14.175),
(14.505238138138138, 14.179381481481483, 14.168414814814819, 16.98041527777778, 15.740309318913155, 8.75, 10.69161394335512, 10.975066666666669, 16.623215000000002, 10.148166172839508, 11.50182255892256, 13.174553086419753, 14.175),
(14.508806297601952, 14.126957338820304, 14.152284087791497, 16.96378019547325, 15.742063400329245, 8.75, 10.655083184055517, 10.902482716049382, 16.606882530864198, 10.112410736168268, 11.490457401172218, 13.153045450388662, 14.175),
(14.51202265018642, 14.07469451303155, 14.136107270233198, 16.946980915637862, 15.743643228900785, 8.75, 10.61870425240055, 10.83155802469136, 16.590456728395065, 10.076988687700048, 11.478918356403542, 13.131476360310929, 14.175),
(14.51488608173391, 14.022685185185187, 14.119907407407407, 16.930034722222224, 15.745048547657152, 8.75, 10.582543572984749, 10.762500000000001, 16.573958333333337, 10.041975308641977, 11.467213804713806, 13.109876543209879, 14.175),
(14.517395478086781, 13.971021536351168, 14.10370754458162, 16.912958899176957, 15.746279099627737, 8.75, 10.546667570402647, 10.695516049382718, 16.557408086419755, 10.00744588020119, 11.455352126200275, 13.088276726108827, 14.175),
(14.519549725087407, 13.919795747599453, 14.087530727023323, 16.89577073045268, 15.74733462784193, 8.75, 10.51114266924877, 10.630813580246915, 16.540826728395064, 9.973475683584821, 11.44334170096022, 13.066707636031095, 14.175),
(14.521347708578144, 13.869100000000001, 14.071400000000002, 16.878487500000002, 15.7482148753291, 8.75, 10.476035294117647, 10.568600000000002, 16.524235, 9.94014, 11.43119090909091, 13.045200000000001, 14.175),
(14.522788314401359, 13.819026474622772, 14.05533840877915, 16.86112649176955, 15.74891958511865, 8.75, 10.44141186960381, 10.509082716049384, 16.50765364197531, 9.907514110653864, 11.41890813068961, 13.023784545038868, 14.175),
(14.523870428399414, 13.769667352537724, 14.03936899862826, 16.843704989711934, 15.749448500239955, 8.75, 10.407338820301785, 10.45246913580247, 16.49110339506173, 9.875673296753543, 11.4065017458536, 13.00249199817101, 14.175),
(14.524592936414676, 13.721114814814818, 14.023514814814817, 16.826240277777778, 15.749801363722403, 8.75, 10.373882570806101, 10.398966666666668, 16.474605000000004, 9.844692839506173, 11.393980134680135, 12.981353086419755, 14.175),
(14.524954724289511, 13.673461042524005, 14.00779890260631, 16.808749639917696, 15.749977918595382, 8.75, 10.341109545711289, 10.348782716049385, 16.458179197530864, 9.814648020118886, 11.381351677266494, 12.960398536808412, 14.175),
(14.524708260273156, 13.626548095048452, 13.99216832990398, 16.7910984366613, 15.749829137416285, 8.74983761621704, 10.308921272761506, 10.301681390032009, 16.44172298811157, 9.785468618306034, 11.368400383956526, 12.939542030659641, 14.174825210048013),
(14.522398389694043, 13.578943727598569, 13.976183796296295, 16.772396920289854, 15.748474945533768, 8.748553909465022, 10.27637545388526, 10.25513827160494, 16.424516975308645, 9.756328946986201, 11.35380797448166, 12.918106562703056, 14.17344039351852),
(14.517840102582454, 13.5304294437807, 13.95977580589849, 16.752521973966722, 15.74579903978052, 8.746025758268557, 10.243324188385918, 10.208733424782809, 16.40646404892547, 9.727087334247829, 11.337408441136512, 12.895991865809934, 14.170705268347055),
(14.511097524900102, 13.481034236028144, 13.942950120027435, 16.731502905260335, 15.74183531025579, 8.742294131992075, 10.209782323354585, 10.162482213077277, 16.387591095107457, 9.697744503079695, 11.319262319097408, 12.873214112097802, 14.166655842764062),
(14.502234782608697, 13.430787096774193, 13.9257125, 16.709369021739132, 15.736617647058825, 8.737400000000001, 10.175764705882354, 10.1164, 16.367925000000003, 9.668301176470589, 11.299430143540672, 12.849789473684211, 14.161328125),
(14.491316001669949, 13.379717018452144, 13.90806870713306, 16.686149630971553, 15.730179940288872, 8.73138433165676, 10.141286183060329, 10.070502149062644, 16.347492649748517, 9.63875807740929, 11.277972449642624, 12.825734122686688, 14.154758123285324),
(14.478405308045566, 13.32785299349529, 13.890024502743485, 16.661874040526033, 15.722556080045187, 8.72428809632678, 10.106361601979613, 10.024804023776863, 16.3263209304984, 9.609115928884586, 11.254949772579598, 12.801064231222776, 14.146981845850483),
(14.463566827697262, 13.275224014336917, 13.871585648148148, 16.636571557971017, 15.713779956427018, 8.716152263374488, 10.0710058097313, 9.979320987654322, 16.30443672839506, 9.579375453885259, 11.23042264752791, 12.775795971410007, 14.138035300925928),
(14.44686468658675, 13.22185907341033, 13.852757904663925, 16.610271490874936, 15.703885459533609, 8.707017802164305, 10.035233653406493, 9.934068404206677, 16.281866929583906, 9.549537375400092, 11.20445160966389, 12.749945515365916, 14.127954496742113),
(14.428363010675731, 13.167787163148816, 13.833547033607681, 16.583003146806227, 15.692906479464213, 8.696925682060662, 9.999059980096293, 9.88906163694559, 16.258638420210335, 9.519602416417872, 11.177097194163862, 12.723529035208049, 14.116775441529496),
(14.408125925925928, 13.113037275985667, 13.813958796296298, 16.554795833333333, 15.680876906318085, 8.685916872427983, 9.962499636891796, 9.844316049382718, 16.23477808641975, 9.489571299927379, 11.148419936204148, 12.696562703053933, 14.10453414351852),
(14.386217558299041, 13.057638404354178, 13.793998954046641, 16.525678858024694, 15.667830630194468, 8.674032342630696, 9.925567470884102, 9.799847005029722, 16.210312814357568, 9.4594447489174, 11.118480370961072, 12.669062691021107, 14.091266610939643),
(14.362702033756786, 13.001619540687642, 13.773673268175584, 16.495681528448742, 15.653801541192612, 8.661313062033226, 9.888278329164315, 9.755669867398264, 16.185269490169183, 9.429223486376719, 11.087339033610965, 12.64104517122711, 14.07700885202332),
(14.337643478260873, 12.945009677419357, 13.752987500000001, 16.464833152173917, 15.638823529411765, 8.6478, 9.85064705882353, 9.711800000000002, 16.159675, 9.398908235294119, 11.055056459330146, 12.612526315789475, 14.061796875),
(14.311106017773009, 12.887837806982612, 13.731947410836765, 16.433163036768654, 15.622930484951183, 8.633534125895444, 9.812688506952853, 9.668252766346594, 16.133556229995428, 9.368499718658382, 11.02169318329494, 12.583522296825743, 14.045666688100141),
(14.283153778254908, 12.8301329218107, 13.710558762002744, 16.400700489801395, 15.606156297910111, 8.618556409083983, 9.774417520643375, 9.625043529949703, 16.10694006630087, 9.337998659458297, 10.987309740681672, 12.554049286453447, 14.028654299554185),
(14.253850885668278, 12.77192401433692, 13.688827314814816, 16.36747481884058, 15.588534858387801, 8.602907818930042, 9.735848946986202, 9.582187654320988, 16.07985339506173, 9.307405780682645, 10.951966666666667, 12.524123456790125, 14.010795717592593),
(14.223261465974833, 12.713240076994557, 13.666758830589849, 16.333515331454645, 15.5701000564835, 8.58662932479805, 9.696997633072435, 9.53970050297211, 16.05232310242341, 9.276721805320209, 10.915724496426252, 12.493760979953313, 13.992126950445819),
(14.191449645136279, 12.654110102216913, 13.644359070644722, 16.298851335212028, 15.550885782296458, 8.569761896052432, 9.65787842599317, 9.497597439414724, 16.024376074531325, 9.245947456359774, 10.878643765136749, 12.462978028060553, 13.97268400634431),
(14.15847954911433, 12.594563082437277, 13.621633796296296, 16.26351213768116, 15.53092592592593, 8.552346502057613, 9.618506172839506, 9.455893827160494, 15.996039197530868, 9.215083456790124, 10.840785007974482, 12.43179077322937, 13.95250289351852),
(14.124415303870702, 12.534628010088941, 13.598588768861456, 16.22752704643049, 15.510254377471155, 8.534424112178023, 9.578895720702548, 9.414605029721079, 15.967339357567447, 9.184130529600042, 10.802208760115779, 12.400215387577312, 13.931619620198905),
(14.089321035367092, 12.474333877605204, 13.575229749657066, 16.19092536902845, 15.488905027031391, 8.516035695778085, 9.539061916673392, 9.37374641060814, 15.938303440786468, 9.153089397778317, 10.762975556736963, 12.36826804322191, 13.910070194615912),
(14.053260869565218, 12.413709677419357, 13.551562500000001, 16.153736413043482, 15.466911764705886, 8.497222222222224, 9.499019607843138, 9.333333333333334, 15.908958333333336, 9.121960784313726, 10.723145933014354, 12.335964912280703, 13.887890625),
(14.016298932426789, 12.352784401964689, 13.527592781207133, 16.11598948604402, 15.444308480593882, 8.478024660874867, 9.458783641302887, 9.293381161408323, 15.879330921353455, 9.090745412195057, 10.682780424124285, 12.303322166871226, 13.865116919581618),
(13.978499349913523, 12.2915870436745, 13.503326354595337, 16.0777138955985, 15.421129064794641, 8.458483981100443, 9.418368864143739, 9.253905258344766, 15.84944809099223, 9.059444004411093, 10.641939565243074, 12.270355979111017, 13.841785086591221),
(13.939926247987117, 12.230146594982081, 13.478768981481483, 16.038938949275366, 15.397407407407409, 8.438641152263374, 9.37779012345679, 9.214920987654322, 15.819336728395063, 9.028057283950616, 10.600683891547051, 12.23708252111761, 13.81793113425926),
(13.900643752609293, 12.168492048320722, 13.453926423182445, 15.999693954643051, 15.37317739853143, 8.418537143728091, 9.337062266333147, 9.176443712848654, 15.789023719707364, 8.996585973802416, 10.559073938212535, 12.203517965008546, 13.793591070816188),
(13.860715989741754, 12.106652396123724, 13.42880444101509, 15.960008219269996, 15.34847292826596, 8.398212924859017, 9.296200139863902, 9.138488797439416, 15.758535951074533, 8.96503079695527, 10.517170240415854, 12.169678482901354, 13.768800904492457),
(13.820207085346219, 12.044656630824377, 13.403408796296299, 15.91991105072464, 15.32332788671024, 8.377709465020576, 9.25521859114016, 9.101071604938273, 15.727900308641976, 8.933392476397968, 10.475033333333334, 12.135580246913582, 13.74359664351852),
(13.779181165384388, 11.98253374485597, 13.377745250342937, 15.879431756575416, 15.297776163963531, 8.357067733577198, 9.21413246725302, 9.064207498856883, 15.6971436785551, 8.901671735119288, 10.432723752141296, 12.101239429162758, 13.718014296124831),
(13.737702355817978, 11.9203127306518, 13.35181956447188, 15.83859964439077, 15.271851650125074, 8.336328699893311, 9.17295661529358, 9.027911842706905, 15.666292946959304, 8.86986929610802, 10.390302032016068, 12.066672201766417, 13.69208987054184),
(13.695834782608697, 11.858022580645162, 13.325637500000003, 15.797444021739132, 15.24558823529412, 8.315533333333335, 9.131705882352943, 8.9922, 15.635375000000002, 8.83798588235294, 10.347828708133973, 12.031894736842107, 13.665859375000002),
(13.653642571718258, 11.795692287269347, 13.29920481824417, 15.755994196188944, 15.21901980956992, 8.294722603261699, 9.090395115522204, 8.957087334247829, 15.60441672382259, 8.806022216842843, 10.305364315671335, 11.996923206507354, 13.639358817729768),
(13.611189849108369, 11.733350842957654, 13.272527280521263, 15.714279475308645, 15.192180263051725, 8.273937479042829, 9.049039161892468, 8.922589208962048, 15.573445004572475, 8.773979022566504, 10.262969389804478, 11.961773782879694, 13.612624206961591),
(13.568540740740744, 11.67102724014337, 13.245610648148148, 15.67232916666667, 15.165103485838781, 8.253218930041154, 9.00765286855483, 8.888720987654322, 15.542486728395062, 8.741857022512711, 10.22070446570973, 11.926462638076675, 13.585691550925928),
(13.525759372577088, 11.60875047125979, 13.218460682441702, 15.630172577831457, 15.137823368030341, 8.232607925621096, 8.966251082600394, 8.855498033836307, 15.511568781435757, 8.709656939670245, 10.178630078563414, 11.891005944215824, 13.558596857853223),
(13.482909870579116, 11.546549528740211, 13.191083144718794, 15.587839016371445, 15.110373799725652, 8.212145435147082, 8.924848651120257, 8.822935711019662, 15.480718049839965, 8.677379497027893, 10.13680676354185, 11.855419873414677, 13.53137613597394),
(13.440056360708535, 11.484453405017922, 13.163483796296298, 15.545357789855073, 15.082788671023966, 8.19187242798354, 8.883460421205521, 8.79104938271605, 15.449961419753087, 8.64502541757444, 10.095295055821373, 11.819720597790775, 13.50406539351852),
(13.39726296892706, 11.42249109252622, 13.135668398491084, 15.50275820585078, 15.055101872024531, 8.171829873494895, 8.842101239947283, 8.759854412437129, 15.41932577732053, 8.612595424298663, 10.054155490578298, 11.783924289461654, 13.476700638717421),
(13.3545938211964, 11.360691583698395, 13.10764271262003, 15.460069571927, 15.027347292826596, 8.152058741045574, 8.800785954436646, 8.72936616369456, 15.388838008687703, 8.580090240189355, 10.013448602988953, 11.748047120544847, 13.449317879801098),
(13.312113043478263, 11.299083870967744, 13.079412500000002, 15.417321195652177, 14.999558823529412, 8.132600000000002, 8.759529411764706, 8.699600000000002, 15.358525000000002, 8.547510588235296, 9.973234928229665, 11.712105263157897, 13.421953125000002),
(13.26988476173436, 11.237696946767558, 13.050983521947876, 15.374542384594738, 14.97177035423223, 8.113494619722603, 8.718346459022568, 8.670571284865114, 15.328413637402836, 8.514857191425268, 9.933575001476758, 11.676114889418335, 13.394642382544584),
(13.227973101926404, 11.176559803531132, 13.022361539780524, 15.331762446323136, 14.944015775034297, 8.094783569577809, 8.677251943301325, 8.642295381801555, 15.29853080704161, 8.482130772748057, 9.894529357906551, 11.640092171443701, 13.367421660665297),
(13.186442190016104, 11.11570143369176, 12.993552314814819, 15.2890106884058, 14.91632897603486, 8.076507818930043, 8.636260711692085, 8.614787654320988, 15.26890339506173, 8.449332055192448, 9.856158532695375, 11.60405328135153, 13.340326967592594),
(13.14535615196517, 11.055150829682729, 12.96456160836763, 15.246316418411165, 14.888743847333174, 8.05870833714373, 8.595387611285942, 8.588063465935072, 15.239558287608595, 8.416461761747223, 9.818523061019553, 11.568014391259355, 13.313394311556928),
(13.104705913184263, 10.995038066300333, 12.935464959552897, 15.203767435488858, 14.861245952243188, 8.04141767690032, 8.554736349119478, 8.562193596292849, 15.21059793576207, 8.383626631257822, 9.781693468614014, 11.5320701111062, 13.286621461180511),
(13.064073257060091, 10.935956056935751, 12.906663945030267, 15.161705189788272, 14.833550696392859, 8.024596451941862, 8.514825491774811, 8.537495763307168, 15.182466649998286, 8.351441235077896, 9.745742071958476, 11.496677040958165, 13.25978557982405),
(13.023338864205595, 10.877926078156266, 12.878175705790246, 15.120118307254492, 14.805570749044042, 8.008200917498272, 8.475683510268187, 8.513963715990194, 15.155174970136306, 8.319955459183308, 9.710616315997932, 11.461852615582393, 13.232809284324528),
(12.982451822532688, 10.820863593808383, 12.849945065977423, 15.078932610372966, 14.777263936937292, 7.992192428201937, 8.43724674453905, 8.491532438058591, 15.128653874918964, 8.289110701829367, 9.676248303780074, 11.427532476482286, 13.205650163658248),
(12.941361219953283, 10.76468406773861, 12.82191684973638, 15.038073921629142, 14.748588086813156, 7.976532338685248, 8.399451534526854, 8.47013691322902, 15.102834343089086, 8.258848361271381, 9.642570138352598, 11.39365226516125, 13.178265806801516),
(12.900016144379297, 10.709302963793455, 12.794035881211714, 14.997468063508467, 14.71950102541218, 7.9611820035805945, 8.362234220171041, 8.449712125218136, 15.07764735338951, 8.229109835764664, 9.609513922763194, 11.36014762312269, 13.150613802730636),
(12.858365683722639, 10.654635745819421, 12.766246984548014, 14.95704085849639, 14.689960579474912, 7.946102777520366, 8.325531141411059, 8.430193057742605, 15.053023884563062, 8.199836523564521, 9.577011760059559, 11.326954191870009, 13.122651740421906),
(12.816358925895228, 10.600597877663022, 12.738494983889867, 14.916718129078353, 14.659924575741897, 7.931256015136952, 8.289278638186355, 8.41151469451908, 15.028894915352582, 8.170969822926269, 9.544995753289383, 11.294007612906617, 13.094337208851638),
(12.773944958808976, 10.547104823170763, 12.710724703381864, 14.876425697739808, 14.629350840953688, 7.9166030710627435, 8.253413050436373, 8.39361201926423, 15.0051914245009, 8.142451132105215, 9.513398005500363, 11.261243527735912, 13.065627796996127),
(12.731072870375797, 10.494072046189146, 12.682880967168597, 14.836089386966199, 14.598197201850828, 7.902105299930128, 8.217870718100565, 8.376420015694709, 14.981844390750846, 8.11422184935667, 9.482150619740192, 11.228597577861303, 13.036481093831679),
(12.687691748507607, 10.441415010564684, 12.65490859939465, 14.795635019242972, 14.56642148517387, 7.887724056371495, 8.182587981118376, 8.359873667527177, 14.958784792845258, 8.086223372935942, 9.451185699056563, 11.19600540478619, 13.0068546883346),
(12.643750681116316, 10.389049180143882, 12.62675242420462, 14.754988417055582, 14.533981517663353, 7.873420695019235, 8.147501179429248, 8.343907958478297, 14.935943609526962, 8.058397101098347, 9.420435346497168, 11.163402650013985, 12.976706169481197),
(12.599198756113843, 10.33689001877325, 12.598357265743093, 14.714075402889465, 14.500835126059833, 7.859156570505739, 8.112546652972636, 8.328457872264728, 14.913251819538791, 8.030684432099187, 9.389831665109703, 11.130724955048088, 12.94599312624776),
(12.553985061412101, 10.284852990299292, 12.56966794815466, 14.672821799230077, 14.466940137103851, 7.844893037463395, 8.077660741687978, 8.31345839260313, 14.890640401623585, 8.00302676419378, 9.359306757941859, 11.097907961391908, 12.91467314761061),
(12.508058684923006, 10.232853558568515, 12.540629295583907, 14.63115342856286, 14.432254377535958, 7.830591450524592, 8.042779785514732, 8.298844503210164, 14.86804033452417, 7.975365495637434, 9.32879272804133, 11.064887310548842, 12.88270382254604),
(12.461368714558466, 10.18080718742743, 12.51118613217543, 14.588996113373266, 14.396735674096707, 7.816213164321722, 8.007840124392336, 8.284551187802489, 14.845382596983379, 7.947642024685458, 9.298221678455814, 11.031598644022305, 12.850042740030352),
(12.413864238230394, 10.128629340722538, 12.481283282073816, 14.546275676146736, 14.360341853526638, 7.801719533487173, 7.972778098260239, 8.270513430096765, 14.822598167744045, 7.919797749593164, 9.267525712233, 10.997977603315691, 12.816647489039854),
(12.365494343850713, 10.076235482300353, 12.450865569423652, 14.502917939368722, 14.3230307425663, 7.7870719126533325, 7.937530047057888, 8.256666213809652, 14.799618025549002, 7.89177406861586, 9.236636932420582, 10.963959829932413, 12.78247565855085),
(12.316208119331334, 10.023541076007378, 12.419877818369534, 14.458848725524668, 14.284760167956243, 7.772231656452593, 7.902032310724733, 8.24294452265781, 14.776373149141081, 7.86351238000886, 9.205487442066255, 10.929480965375875, 12.747484837539638),
(12.265954652584163, 9.970461585690122, 12.388264853056045, 14.413993857100023, 14.245487956437017, 7.757160119517344, 7.8662212292002165, 8.229283340357902, 14.752794517263117, 7.834954082027471, 9.17400934421771, 10.894476651149478, 12.711632614982527),
(12.21468303152113, 9.91691247519509, 12.355971497627777, 14.368279156580234, 14.205171934749162, 7.741818656479974, 7.830033142423786, 8.215617650626585, 14.728813108657938, 7.806040572927006, 9.142134741922645, 10.85888252875663, 12.674876579855821),
(12.162342344054133, 9.862809208368793, 12.322942576229327, 14.321630446450746, 14.163769929633231, 7.726168621972872, 7.79340439033489, 8.201882437180522, 14.704359902068381, 7.776713250962773, 9.109795738228751, 10.822634239700733, 12.637174321135817),
(12.108881678095097, 9.808067249057736, 12.289122913005274, 14.273973549197011, 14.12123976782977, 7.710171370628429, 7.756271312872975, 8.18801268373637, 14.679365876237274, 7.746913514390087, 9.07692443618372, 10.785667425485194, 12.59848342779883),
(12.05425012155593, 9.752602061108423, 12.254457332100213, 14.225234287304469, 14.077539276079325, 7.693788257079036, 7.718570249977489, 8.173943374010788, 14.65376200990745, 7.716582761464252, 9.043452938835248, 10.747917727613418, 12.558761488821151),
(11.998396762348548, 9.696329108367367, 12.218890657658735, 14.175338483258576, 14.032626281122448, 7.6769806359570785, 7.6802375415878785, 8.159609491720442, 14.627479281821747, 7.685662390440583, 9.009313349231029, 10.709320787588808, 12.517966093179089),
(11.941270688384867, 9.639163854681073, 12.182367713825425, 14.12421195954477, 13.986458609699687, 7.6597098618949495, 7.6412095276435865, 8.144946020581987, 14.600448670722995, 7.654093799574386, 8.974437770418753, 10.66981224691477, 12.476054829848946),
(11.882820987576796, 9.581021763896047, 12.144833324744877, 14.071780538648504, 13.938994088551583, 7.641937289525037, 7.601422548084064, 8.129887944312085, 14.572601155354022, 7.621818387120976, 8.938758305446116, 10.62932774709471, 12.432985287807028),
(11.822996747836257, 9.521818299858795, 12.106232314561684, 14.017970043055223, 13.890190544418692, 7.623624273479732, 7.560812942848756, 8.114370246627395, 14.543867714457667, 7.588777551335661, 8.902207057360812, 10.58780292963203, 12.38871505602964),
(11.761747057075162, 9.46146892641583, 12.066509507420426, 13.962706295250376, 13.840005804041555, 7.604732168391422, 7.519317051877113, 8.09832791124458, 14.514179326776754, 7.554912690473753, 8.864716129210535, 10.545173436030137, 12.34320172349308),
(11.69902100320542, 9.399889107413653, 12.0256097274657, 13.90591511771941, 13.788397694160723, 7.585222328892499, 7.476871215108577, 8.081695921880296, 14.48346697105412, 7.52016520279056, 8.826217624042977, 10.501374907792433, 12.296402879173653),
(11.634767674138946, 9.336994306698774, 11.983477798842097, 13.847522332947767, 13.735324041516742, 7.56505610961535, 7.4334117724825965, 8.064409262251205, 14.451661626032607, 7.484476486541395, 8.786643644905832, 10.456342986422326, 12.248276112047666),
(11.56893615778766, 9.2726999881177, 11.9400585456942, 13.787453763420901, 13.680742672850162, 7.544194865192366, 7.3888750639386185, 8.04640291607397, 14.418694270455035, 7.4477879399815645, 8.745926294846791, 10.41001331342322, 12.198779011091421),
(11.501475542063469, 9.20692161551694, 11.895296792166606, 13.725635231624254, 13.624611414901528, 7.5225999502559375, 7.343197429416091, 8.027611867065247, 14.384495883064238, 7.410040961366383, 8.703997676913554, 10.36232153029852, 12.14786916528122),
(11.432334914878291, 9.139574652742999, 11.849137362403903, 13.661992560043277, 13.566888094411391, 7.500232719438453, 7.2963152088544625, 8.007971098941699, 14.34899744260305, 7.37117694895116, 8.660789894153808, 10.313203278551628, 12.095504163593366),
(11.361463364144042, 9.070574563642383, 11.801525080550675, 13.596451571163414, 13.507530538120294, 7.477054527372301, 7.2481647421931745, 7.987415595419982, 14.312129927814308, 7.331137300991204, 8.616235049615252, 10.262594199685955, 12.041641595004167),
(11.288809977772631, 8.999836812061604, 11.752404770751518, 13.528938087470117, 13.446496572768787, 7.453026728689875, 7.198682369371678, 7.965880340216761, 14.273824317440841, 7.289863415741826, 8.570265246345576, 10.210429935204898, 11.986239048489919),
(11.214323843675977, 8.927276861847163, 11.701721257151021, 13.459377931448826, 13.38374402509742, 7.42811067802356, 7.147804430329418, 7.943300317048694, 14.234011590225474, 7.247296691458339, 8.522812587392474, 10.156646126611868, 11.929254113026934),
(11.137954049765991, 8.852810176845571, 11.649419363893772, 13.387696925584994, 13.319230721846738, 7.402267730005749, 7.0954672650058415, 7.91961050963244, 14.192622724911054, 7.2033785263960475, 8.473809175803641, 10.101178415410269, 11.870644377591507),
(11.059649683954586, 8.776352220903336, 11.59544391512436, 13.313820892364063, 13.252914489757288, 7.375459239268828, 7.041607213340397, 7.8947459016846615, 14.149588700240406, 7.15805031881027, 8.423187114626767, 10.043962443103501, 11.810367431159946),
(10.979359834153682, 8.697818457866962, 11.539739734987382, 13.237675654271488, 13.184753155569618, 7.34764656044519, 6.986160615272531, 7.8686414769220185, 14.10484049495636, 7.11125346695631, 8.37087850690955, 9.984933851194974, 11.748380862708558),
(10.897033588275185, 8.61712435158296, 11.482251647627416, 13.159187033792707, 13.11470454602428, 7.318791048167222, 6.929063810741687, 7.841232219061167, 14.058309087801755, 7.062929369089481, 8.316815455699683, 9.92402828118809, 11.68464226121364),
(10.81262003423102, 8.534185365897834, 11.422924477189063, 13.078280853413174, 13.042726487861813, 7.288854057067317, 6.87025313968732, 7.8124531118187726, 14.009925457519413, 7.013019423465095, 8.260930064044857, 9.861181374586256, 11.6191092156515),
(10.72606825993309, 8.448916964658093, 11.361703047816906, 12.99488293561833, 12.968776807822776, 7.257796941777861, 6.809664942048866, 7.782239138911491, 13.95962058285218, 6.9614650283384565, 8.203154434992767, 9.796328772892876, 11.551739314998438),
(10.637327353293314, 8.361234611710243, 11.298532183655539, 12.908919102893627, 12.892813332647707, 7.225581056931246, 6.74723555776578, 7.750525284055986, 13.907325442542877, 6.9082075819648825, 8.143420671591107, 9.729406117611353, 11.48249014823076),
(10.546346402223609, 8.271053770900794, 11.233356708849547, 12.820315177724513, 12.81479388907716, 7.19216775715986, 6.6829013267775075, 7.717246530968915, 13.852971015334345, 6.853188482599679, 8.08166087688757, 9.660349050245092, 11.411319304324769),
(10.450553324967336, 8.176634369081162, 11.163028735463298, 12.725677414311741, 12.731153548219398, 7.155434266843955, 6.615149409299001, 7.680115733289122, 13.792326928238738, 6.794712282807602, 8.01583405355452, 9.586639389872076, 11.335080203181485),
(10.335201473769764, 8.06829144743927, 11.069432945764184, 12.605568022303835, 12.62126783369428, 7.103165507209945, 6.535497868740003, 7.626098945870136, 13.700998165711002, 6.723193391738244, 7.934383709866593, 9.493907533156353, 11.235598705688274),
(10.198820932866035, 7.945135419957, 10.950689341138245, 12.458008514572404, 12.482988183885514, 7.034077814466758, 6.443141247737298, 7.553838865338286, 13.576395318120113, 6.637687912608051, 7.8361633120533565, 9.380702728442985, 11.110988852451014),
(10.042510876420344, 7.8079692153126565, 10.808065760674433, 12.28440150525942, 12.317750373994958, 6.94900813819844, 6.338754024409627, 7.464240746353693, 13.420161673798626, 6.5389214704393135, 7.7220383164395905, 9.248074456470599, 10.962523662746737),
(9.8673704785969, 7.657595762184535, 10.642830043461695, 12.086149608506858, 12.126990179224487, 6.848793427989039, 6.223010676875733, 7.358209843576484, 13.233940521079093, 6.427619690254325, 7.592874179350069, 9.09707219797781, 10.791476155852466),
(9.674498913559898, 7.494817989250934, 10.456250028588983, 11.864655438456708, 11.912143374775964, 6.734270633422602, 6.096585683254362, 7.2366514116667755, 13.019375148294069, 6.304508197075376, 7.449536357109572, 8.928745433703247, 10.599119351045232),
(9.464995355473539, 7.320438825190149, 10.249593555145248, 11.621321609250947, 11.674645735851264, 6.606276704083181, 5.960153521664253, 7.100470705284697, 12.778108843776113, 6.170312615924756, 7.292890306042875, 8.744143644385526, 10.386726267602059),
(9.239958978502024, 7.135261198680485, 10.024128462219437, 11.357550735031554, 11.415933037652254, 6.465648589554821, 5.814388670224151, 6.950572979090365, 12.511784895857772, 6.02575857182476, 7.123801482474756, 8.544316310763268, 10.155569924799979),
(9.000488956809557, 6.940088038400237, 9.7811225889005, 11.074745429940503, 11.137441055380801, 6.313223239421572, 5.659965607052801, 6.787863487743908, 12.222046592871603, 5.871571689797677, 6.943135342729992, 8.330312913575103, 9.906923341916015),
(8.747684464560333, 6.735722273027703, 9.521843774277388, 10.774308308119782, 10.840605564238773, 6.149837603267482, 5.497558810268945, 6.613247485905448, 11.91053722315016, 5.7084775948658, 6.751757343133359, 8.103182933559642, 9.642059538227196),
(8.482644675918554, 6.52296683124118, 9.247559857439049, 10.457641983711365, 10.526862339428039, 5.9763286306765995, 5.327842757991326, 6.427630228235103, 11.578900075025999, 5.5372019120514215, 6.550532940009634, 7.863975851455517, 9.362251533010546),
(8.206468765048422, 6.302624641718972, 8.959538677474432, 10.126149070857236, 10.197647156150468, 5.793533271232973, 5.151491928338689, 6.231916969393004, 11.228778436831673, 5.358470266376831, 6.3403275896835956, 7.613741148001342, 9.0687723455431),
(7.9202559061141375, 6.0754986331393726, 8.659048073472489, 9.781232183699368, 9.854395789607928, 5.60228847452065, 4.9691807994297745, 6.027012964039266, 10.861815596899735, 5.173008282864322, 6.122006748480023, 7.353528303935743, 8.762894995101878),
(7.6251052732799005, 5.842391734180682, 8.34735588452217, 9.424293936379751, 9.498544015002288, 5.403431190123678, 4.781583849383328, 5.813823466834017, 10.47965484356274, 4.981541586536184, 5.896435872723688, 7.0843867999973416, 8.445892500963913),
(7.322116040709912, 5.604106873521197, 8.025729949712423, 9.056736943040356, 9.131527607535416, 5.197798367626108, 4.5893755563180925, 5.593253732437379, 10.083939465153241, 4.784795802414712, 5.664480418739371, 6.80736611692476, 8.119037882406225),
(7.012387382568372, 5.3614469798392195, 7.695438108132197, 8.679963817823166, 8.754782342409182, 4.9862269566119855, 4.39323039835281, 5.366209015509473, 9.676312750003792, 4.583496555522195, 5.427005842851849, 6.523515735456615, 7.783604158705848),
(6.697018473019482, 5.115214981813045, 7.357748198870443, 8.295377174870158, 8.369743994825454, 4.76955390666536, 4.193822853606226, 5.133594570710425, 9.25841798644695, 4.3783694708809255, 5.1848776013858995, 6.233885136331535, 7.440864349139807),
(6.377108486227438, 4.866213808120973, 7.013928061016112, 7.904379628323315, 7.977848339986097, 4.54861616737028, 3.9918274001970815, 4.896315652700355, 8.831898462815268, 4.170140173513194, 4.938961150666297, 5.939523800288141, 7.092091472985131),
(6.053756596356447, 4.615246387441302, 6.66524553365815, 7.508373792324615, 7.580531153092983, 4.324250688310793, 3.787918516244121, 4.655277516139389, 8.3983974674413, 3.959534288441294, 4.690121947017822, 5.641481208065051, 6.738558549518844),
(5.7280619775707065, 4.363115648452332, 6.3129684558855095, 7.108762281016037, 7.179228209347984, 4.097294419070949, 3.582770679866088, 4.411385415687646, 7.959558288657599, 3.7472774406875144, 4.43922544676525, 5.340806840400891, 6.381538598017975),
(5.401123804034416, 4.11062451983236, 5.95836466678714, 6.7069477085395635, 6.775375283952959, 3.8685843092347962, 3.3770583691817246, 4.165544606005252, 7.51702421479672, 3.5340952552741505, 4.187137106233358, 5.038550178034279, 6.022304637759553),
(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
)
passenger_arriving_acc = (
(9, 10, 5, 5, 3, 2, 2, 3, 3, 1, 1, 0, 0, 6, 9, 0, 8, 12, 3, 4, 1, 0, 2, 2, 2, 0),
(14, 20, 14, 16, 9, 4, 2, 8, 4, 2, 2, 0, 0, 17, 14, 5, 14, 18, 4, 6, 3, 1, 6, 2, 2, 0),
(21, 29, 17, 19, 12, 7, 5, 13, 8, 6, 4, 0, 0, 26, 20, 10, 21, 27, 5, 11, 7, 3, 8, 4, 4, 0),
(26, 39, 28, 28, 24, 10, 11, 19, 12, 7, 4, 0, 0, 32, 30, 12, 29, 35, 13, 13, 9, 6, 10, 6, 4, 0),
(37, 48, 34, 36, 31, 13, 15, 24, 16, 8, 4, 0, 0, 40, 42, 15, 34, 45, 16, 13, 13, 7, 11, 6, 7, 0),
(48, 57, 43, 49, 34, 16, 22, 31, 20, 10, 4, 2, 0, 47, 55, 22, 42, 54, 21, 18, 14, 9, 16, 7, 8, 0),
(60, 70, 51, 57, 42, 20, 23, 35, 23, 14, 7, 4, 0, 56, 63, 29, 51, 60, 23, 25, 17, 15, 19, 7, 9, 0),
(72, 78, 59, 68, 55, 23, 26, 36, 27, 15, 8, 4, 0, 68, 70, 40, 55, 69, 27, 28, 19, 18, 21, 8, 10, 0),
(86, 89, 76, 78, 63, 26, 29, 38, 30, 16, 11, 4, 0, 79, 77, 49, 61, 80, 29, 35, 23, 19, 24, 9, 10, 0),
(97, 99, 83, 87, 71, 34, 36, 43, 35, 16, 14, 7, 0, 96, 89, 58, 67, 90, 38, 39, 25, 22, 26, 13, 11, 0),
(107, 111, 94, 97, 78, 37, 42, 46, 42, 19, 16, 9, 0, 114, 102, 70, 76, 102, 44, 41, 28, 28, 28, 16, 13, 0),
(122, 122, 104, 108, 90, 44, 46, 49, 45, 20, 19, 11, 0, 124, 107, 83, 84, 114, 50, 47, 31, 29, 29, 20, 14, 0),
(133, 138, 114, 119, 99, 46, 53, 53, 48, 23, 20, 13, 0, 141, 115, 92, 89, 122, 55, 52, 31, 35, 33, 21, 15, 0),
(144, 155, 124, 129, 105, 53, 57, 55, 54, 24, 23, 14, 0, 155, 127, 96, 92, 127, 61, 56, 36, 38, 40, 24, 16, 0),
(156, 176, 136, 141, 116, 60, 61, 59, 58, 27, 28, 14, 0, 165, 139, 102, 99, 139, 67, 63, 37, 42, 44, 24, 16, 0),
(162, 188, 145, 162, 128, 63, 64, 63, 64, 29, 29, 16, 0, 174, 158, 110, 102, 145, 74, 70, 43, 50, 44, 24, 18, 0),
(169, 200, 155, 175, 140, 70, 69, 67, 68, 32, 31, 19, 0, 186, 166, 114, 108, 159, 84, 74, 45, 54, 48, 25, 19, 0),
(184, 215, 173, 190, 147, 79, 73, 70, 73, 38, 34, 20, 0, 198, 176, 121, 119, 169, 90, 76, 50, 61, 51, 26, 19, 0),
(198, 229, 189, 207, 162, 83, 79, 74, 77, 39, 36, 21, 0, 214, 193, 128, 123, 176, 97, 85, 55, 67, 55, 28, 21, 0),
(221, 245, 201, 220, 168, 89, 85, 77, 84, 39, 37, 22, 0, 231, 211, 139, 134, 191, 110, 91, 58, 72, 61, 32, 23, 0),
(233, 257, 214, 233, 178, 96, 91, 81, 90, 41, 39, 23, 0, 241, 228, 152, 141, 202, 117, 96, 63, 78, 66, 36, 24, 0),
(249, 275, 226, 246, 186, 102, 93, 87, 101, 43, 40, 24, 0, 248, 240, 162, 151, 218, 121, 100, 70, 82, 69, 37, 26, 0),
(263, 288, 234, 257, 193, 109, 95, 90, 110, 47, 42, 24, 0, 266, 249, 168, 163, 230, 128, 103, 73, 85, 77, 37, 29, 0),
(279, 297, 244, 265, 207, 118, 101, 92, 119, 50, 44, 25, 0, 282, 270, 177, 167, 235, 135, 109, 79, 86, 81, 38, 30, 0),
(290, 310, 255, 275, 213, 122, 111, 98, 125, 51, 49, 26, 0, 300, 287, 193, 170, 247, 148, 117, 81, 90, 82, 42, 31, 0),
(301, 326, 272, 282, 225, 127, 119, 103, 131, 53, 49, 28, 0, 310, 301, 203, 177, 267, 153, 129, 85, 93, 85, 45, 33, 0),
(319, 341, 290, 290, 237, 131, 133, 105, 138, 54, 50, 29, 0, 319, 311, 213, 186, 283, 156, 133, 87, 97, 89, 46, 34, 0),
(328, 350, 298, 299, 242, 138, 144, 110, 146, 56, 53, 30, 0, 329, 324, 222, 194, 295, 169, 136, 88, 100, 93, 47, 35, 0),
(346, 364, 315, 315, 259, 140, 151, 117, 153, 63, 55, 32, 0, 349, 337, 234, 202, 302, 170, 140, 90, 106, 94, 49, 37, 0),
(362, 380, 324, 330, 265, 144, 155, 124, 158, 66, 63, 33, 0, 361, 351, 245, 211, 313, 177, 142, 97, 108, 101, 55, 37, 0),
(375, 392, 341, 344, 277, 151, 164, 128, 160, 67, 66, 33, 0, 383, 365, 254, 220, 333, 183, 151, 100, 119, 104, 55, 39, 0),
(392, 401, 351, 366, 291, 157, 168, 130, 163, 72, 69, 33, 0, 402, 378, 263, 227, 348, 186, 153, 103, 124, 106, 56, 40, 0),
(404, 415, 367, 378, 302, 168, 173, 135, 169, 73, 71, 34, 0, 417, 390, 276, 234, 356, 199, 157, 108, 128, 113, 57, 42, 0),
(415, 431, 382, 395, 305, 175, 174, 141, 175, 74, 75, 35, 0, 435, 400, 285, 242, 370, 201, 160, 111, 133, 121, 58, 43, 0),
(423, 442, 394, 410, 323, 184, 178, 147, 180, 76, 79, 35, 0, 448, 413, 290, 246, 381, 208, 166, 116, 135, 123, 59, 43, 0),
(446, 458, 405, 415, 336, 187, 182, 151, 184, 79, 82, 36, 0, 461, 425, 298, 252, 390, 215, 170, 121, 141, 129, 65, 44, 0),
(459, 470, 422, 431, 350, 190, 186, 155, 189, 82, 83, 36, 0, 472, 430, 304, 263, 396, 224, 176, 124, 147, 134, 66, 45, 0),
(474, 479, 435, 443, 358, 195, 195, 163, 197, 83, 84, 37, 0, 494, 448, 315, 270, 410, 235, 184, 126, 152, 141, 69, 45, 0),
(489, 493, 451, 456, 366, 199, 199, 167, 201, 89, 85, 38, 0, 507, 456, 331, 273, 414, 242, 191, 129, 159, 147, 71, 46, 0),
(505, 510, 459, 470, 375, 203, 203, 170, 207, 89, 89, 38, 0, 524, 471, 342, 280, 427, 248, 195, 132, 164, 153, 71, 46, 0),
(516, 523, 470, 477, 384, 206, 204, 176, 215, 92, 92, 38, 0, 539, 478, 348, 292, 438, 254, 200, 139, 169, 159, 74, 47, 0),
(531, 534, 481, 484, 394, 211, 210, 179, 223, 97, 93, 39, 0, 548, 487, 361, 299, 447, 266, 206, 142, 172, 162, 77, 48, 0),
(552, 546, 495, 496, 401, 211, 214, 184, 227, 97, 93, 41, 0, 570, 501, 368, 303, 461, 279, 212, 147, 179, 168, 78, 48, 0),
(569, 562, 503, 508, 414, 212, 221, 188, 233, 98, 95, 41, 0, 585, 506, 377, 311, 474, 283, 221, 151, 180, 171, 80, 49, 0),
(580, 579, 519, 518, 421, 217, 228, 192, 237, 101, 96, 45, 0, 603, 520, 385, 319, 489, 290, 226, 158, 184, 175, 80, 52, 0),
(592, 593, 531, 532, 431, 221, 232, 196, 240, 103, 97, 47, 0, 616, 533, 398, 327, 495, 295, 231, 160, 188, 177, 84, 53, 0),
(610, 614, 541, 548, 443, 225, 236, 202, 246, 106, 98, 47, 0, 624, 538, 405, 334, 508, 303, 236, 164, 198, 179, 84, 56, 0),
(617, 624, 552, 564, 452, 233, 241, 205, 254, 106, 101, 48, 0, 644, 555, 413, 337, 515, 315, 242, 168, 205, 183, 86, 59, 0),
(636, 636, 560, 569, 459, 237, 244, 208, 259, 109, 102, 49, 0, 653, 562, 425, 348, 534, 324, 250, 172, 213, 185, 89, 60, 0),
(645, 643, 574, 589, 476, 239, 251, 211, 263, 112, 106, 52, 0, 666, 573, 435, 357, 547, 331, 254, 175, 216, 191, 90, 61, 0),
(660, 664, 587, 601, 483, 245, 258, 215, 267, 113, 107, 54, 0, 684, 585, 446, 365, 560, 341, 261, 177, 220, 197, 93, 63, 0),
(671, 673, 600, 616, 492, 247, 264, 217, 271, 120, 108, 56, 0, 705, 603, 455, 374, 574, 346, 266, 178, 225, 200, 96, 66, 0),
(686, 688, 611, 626, 500, 251, 267, 222, 277, 121, 109, 57, 0, 712, 610, 467, 385, 588, 351, 271, 180, 229, 200, 97, 69, 0),
(697, 699, 619, 639, 509, 255, 272, 227, 279, 124, 112, 58, 0, 725, 625, 475, 389, 604, 356, 277, 186, 234, 203, 99, 70, 0),
(714, 717, 625, 654, 518, 259, 277, 233, 289, 128, 114, 60, 0, 746, 642, 489, 397, 620, 362, 281, 192, 240, 206, 100, 71, 0),
(724, 729, 643, 664, 529, 266, 278, 240, 296, 131, 115, 60, 0, 760, 649, 504, 404, 627, 369, 286, 195, 241, 216, 100, 71, 0),
(730, 741, 656, 678, 544, 268, 282, 244, 300, 132, 118, 61, 0, 781, 665, 515, 410, 642, 373, 293, 202, 246, 220, 104, 72, 0),
(736, 757, 675, 695, 548, 272, 289, 250, 308, 134, 118, 61, 0, 800, 679, 521, 412, 655, 383, 299, 206, 250, 220, 106, 73, 0),
(751, 770, 690, 714, 556, 275, 295, 256, 313, 134, 120, 63, 0, 814, 688, 529, 418, 669, 386, 308, 212, 257, 224, 110, 74, 0),
(764, 774, 700, 728, 563, 279, 302, 259, 320, 140, 120, 65, 0, 824, 700, 538, 428, 680, 392, 311, 217, 264, 228, 112, 74, 0),
(778, 798, 706, 745, 577, 285, 306, 260, 321, 142, 121, 68, 0, 838, 710, 550, 440, 699, 397, 320, 218, 270, 234, 113, 74, 0),
(791, 818, 715, 755, 588, 292, 311, 269, 330, 143, 122, 70, 0, 854, 722, 561, 447, 715, 410, 323, 224, 276, 238, 113, 75, 0),
(808, 825, 727, 767, 596, 297, 316, 273, 336, 146, 123, 70, 0, 867, 730, 571, 457, 726, 414, 327, 229, 279, 244, 117, 78, 0),
(816, 839, 746, 779, 605, 302, 321, 278, 338, 146, 130, 70, 0, 879, 743, 574, 464, 736, 419, 328, 233, 282, 245, 118, 78, 0),
(832, 849, 757, 787, 617, 304, 328, 286, 343, 147, 134, 70, 0, 893, 759, 582, 475, 750, 426, 333, 237, 290, 249, 119, 79, 0),
(839, 862, 772, 801, 626, 306, 332, 290, 346, 148, 136, 70, 0, 909, 771, 601, 479, 763, 432, 338, 238, 301, 253, 120, 80, 0),
(857, 876, 783, 812, 637, 308, 332, 295, 352, 154, 137, 71, 0, 924, 781, 608, 487, 777, 442, 340, 240, 306, 257, 120, 81, 0),
(872, 893, 792, 824, 652, 312, 339, 302, 360, 154, 139, 74, 0, 941, 791, 614, 498, 786, 446, 352, 242, 307, 265, 123, 81, 0),
(882, 904, 798, 835, 664, 316, 346, 306, 368, 156, 141, 75, 0, 951, 799, 623, 505, 797, 449, 360, 245, 311, 269, 128, 81, 0),
(896, 914, 807, 851, 670, 320, 354, 313, 371, 157, 141, 79, 0, 963, 809, 632, 510, 809, 456, 369, 248, 315, 273, 130, 81, 0),
(915, 925, 815, 869, 683, 326, 361, 317, 375, 157, 146, 80, 0, 979, 817, 642, 516, 820, 462, 375, 250, 321, 277, 131, 83, 0),
(932, 931, 828, 880, 698, 335, 363, 318, 384, 161, 148, 80, 0, 990, 827, 650, 520, 827, 467, 384, 254, 327, 282, 131, 83, 0),
(947, 940, 847, 897, 708, 340, 372, 324, 391, 164, 149, 80, 0, 1006, 838, 662, 537, 836, 469, 392, 261, 334, 286, 133, 86, 0),
(964, 951, 858, 912, 717, 346, 375, 331, 400, 166, 151, 80, 0, 1022, 847, 667, 542, 852, 475, 399, 266, 336, 287, 135, 86, 0),
(973, 959, 866, 926, 729, 357, 378, 333, 403, 169, 151, 80, 0, 1040, 864, 680, 546, 865, 480, 404, 267, 341, 291, 139, 86, 0),
(984, 972, 880, 937, 742, 364, 384, 336, 410, 172, 153, 81, 0, 1054, 878, 689, 555, 872, 485, 410, 268, 349, 295, 142, 87, 0),
(1003, 984, 896, 947, 753, 369, 392, 339, 413, 178, 154, 81, 0, 1061, 890, 699, 563, 891, 494, 417, 270, 354, 301, 146, 87, 0),
(1013, 992, 910, 959, 766, 374, 401, 344, 418, 179, 157, 81, 0, 1079, 911, 708, 574, 897, 496, 419, 274, 362, 303, 149, 88, 0),
(1025, 1006, 916, 976, 781, 380, 405, 348, 424, 181, 159, 81, 0, 1090, 923, 717, 579, 908, 502, 423, 276, 367, 310, 149, 88, 0),
(1037, 1014, 926, 989, 791, 386, 409, 354, 430, 184, 161, 81, 0, 1106, 930, 724, 587, 913, 506, 428, 282, 376, 312, 150, 88, 0),
(1054, 1031, 938, 998, 806, 394, 411, 357, 435, 185, 162, 82, 0, 1116, 945, 737, 592, 926, 510, 434, 286, 383, 315, 151, 88, 0),
(1067, 1042, 950, 1006, 818, 400, 419, 363, 443, 187, 165, 82, 0, 1135, 954, 749, 602, 938, 514, 439, 288, 388, 316, 152, 89, 0),
(1080, 1055, 957, 1021, 829, 407, 425, 369, 448, 189, 165, 89, 0, 1153, 968, 756, 614, 945, 517, 442, 296, 391, 322, 155, 91, 0),
(1092, 1061, 970, 1027, 835, 412, 433, 372, 454, 193, 167, 89, 0, 1170, 977, 764, 622, 957, 524, 447, 299, 398, 326, 157, 91, 0),
(1103, 1074, 984, 1043, 846, 419, 441, 379, 460, 195, 168, 90, 0, 1177, 993, 772, 627, 962, 527, 453, 303, 403, 329, 159, 91, 0),
(1115, 1088, 1005, 1057, 860, 426, 447, 382, 468, 199, 169, 91, 0, 1186, 1008, 782, 629, 975, 530, 459, 307, 409, 332, 162, 91, 0),
(1131, 1099, 1016, 1068, 875, 430, 451, 386, 474, 200, 171, 92, 0, 1197, 1015, 790, 640, 985, 538, 462, 310, 414, 340, 164, 91, 0),
(1148, 1106, 1027, 1080, 881, 433, 455, 388, 479, 202, 172, 92, 0, 1208, 1031, 798, 650, 992, 546, 467, 316, 421, 349, 165, 91, 0),
(1159, 1123, 1037, 1089, 891, 439, 461, 390, 482, 206, 177, 92, 0, 1229, 1043, 807, 660, 1005, 547, 469, 321, 427, 354, 167, 92, 0),
(1174, 1132, 1051, 1104, 898, 443, 465, 395, 486, 207, 180, 93, 0, 1247, 1057, 816, 664, 1014, 553, 478, 325, 432, 358, 169, 92, 0),
(1187, 1140, 1060, 1115, 909, 452, 472, 397, 489, 209, 180, 93, 0, 1260, 1070, 823, 667, 1020, 562, 482, 329, 438, 359, 172, 93, 0),
(1205, 1153, 1067, 1129, 918, 456, 476, 397, 497, 211, 182, 93, 0, 1274, 1080, 834, 672, 1027, 566, 492, 332, 440, 361, 177, 95, 0),
(1217, 1165, 1074, 1142, 931, 463, 477, 405, 502, 215, 187, 94, 0, 1288, 1097, 842, 680, 1038, 570, 497, 335, 445, 366, 179, 96, 0),
(1228, 1170, 1086, 1154, 935, 467, 480, 409, 512, 218, 188, 94, 0, 1301, 1107, 852, 686, 1059, 576, 501, 338, 447, 369, 181, 97, 0),
(1242, 1183, 1098, 1167, 948, 469, 484, 416, 515, 220, 190, 95, 0, 1313, 1120, 856, 693, 1074, 582, 506, 339, 453, 374, 181, 97, 0),
(1251, 1202, 1109, 1178, 955, 474, 486, 420, 518, 224, 190, 98, 0, 1325, 1137, 863, 704, 1085, 588, 511, 341, 456, 377, 181, 99, 0),
(1260, 1210, 1123, 1188, 962, 480, 494, 427, 527, 227, 191, 100, 0, 1335, 1147, 872, 712, 1092, 594, 514, 350, 465, 382, 186, 99, 0),
(1273, 1220, 1131, 1202, 972, 484, 496, 437, 532, 229, 193, 103, 0, 1346, 1150, 880, 720, 1104, 601, 519, 351, 473, 383, 188, 100, 0),
(1290, 1228, 1143, 1214, 984, 491, 500, 439, 536, 233, 193, 105, 0, 1354, 1159, 885, 726, 1114, 606, 522, 352, 480, 387, 192, 102, 0),
(1304, 1238, 1154, 1229, 996, 495, 505, 442, 540, 234, 193, 107, 0, 1368, 1172, 898, 733, 1123, 610, 526, 352, 482, 393, 196, 104, 0),
(1313, 1247, 1165, 1239, 1007, 500, 507, 447, 548, 235, 193, 112, 0, 1380, 1180, 910, 741, 1135, 612, 533, 355, 492, 397, 200, 105, 0),
(1329, 1258, 1175, 1246, 1019, 503, 509, 450, 554, 236, 194, 113, 0, 1393, 1192, 914, 746, 1145, 621, 539, 358, 498, 401, 202, 105, 0),
(1346, 1270, 1183, 1260, 1024, 509, 514, 455, 558, 238, 195, 113, 0, 1408, 1199, 919, 758, 1154, 627, 541, 363, 501, 408, 205, 108, 0),
(1360, 1282, 1191, 1272, 1032, 514, 518, 460, 565, 240, 196, 113, 0, 1428, 1213, 929, 766, 1160, 631, 545, 365, 509, 411, 205, 109, 0),
(1374, 1288, 1202, 1286, 1043, 518, 522, 465, 570, 243, 197, 114, 0, 1438, 1219, 943, 772, 1168, 640, 549, 370, 511, 414, 206, 109, 0),
(1390, 1299, 1211, 1299, 1055, 523, 530, 470, 578, 245, 199, 114, 0, 1455, 1229, 958, 780, 1178, 643, 555, 371, 517, 418, 209, 109, 0),
(1398, 1311, 1224, 1309, 1061, 528, 535, 472, 586, 247, 200, 115, 0, 1474, 1243, 965, 784, 1190, 647, 558, 375, 522, 421, 210, 110, 0),
(1409, 1323, 1240, 1314, 1064, 537, 538, 474, 593, 249, 200, 117, 0, 1489, 1256, 968, 787, 1198, 652, 565, 379, 528, 425, 213, 111, 0),
(1421, 1332, 1247, 1323, 1071, 542, 542, 477, 595, 250, 202, 120, 0, 1513, 1266, 979, 796, 1207, 657, 571, 381, 534, 429, 214, 115, 0),
(1431, 1347, 1261, 1333, 1078, 549, 551, 482, 603, 252, 203, 122, 0, 1530, 1275, 985, 801, 1216, 666, 574, 386, 543, 430, 217, 115, 0),
(1446, 1354, 1271, 1341, 1086, 553, 555, 486, 608, 252, 203, 122, 0, 1543, 1284, 998, 810, 1225, 672, 579, 391, 548, 434, 217, 117, 0),
(1465, 1367, 1280, 1354, 1102, 555, 557, 488, 617, 256, 204, 122, 0, 1551, 1292, 1009, 814, 1235, 673, 584, 393, 554, 436, 220, 117, 0),
(1480, 1385, 1290, 1368, 1106, 557, 560, 490, 626, 256, 205, 122, 0, 1563, 1302, 1015, 825, 1242, 675, 586, 396, 564, 439, 222, 117, 0),
(1489, 1392, 1303, 1385, 1111, 559, 560, 491, 634, 257, 208, 123, 0, 1581, 1311, 1026, 831, 1251, 686, 588, 398, 569, 444, 226, 118, 0),
(1503, 1396, 1315, 1395, 1119, 566, 562, 493, 640, 259, 210, 123, 0, 1594, 1322, 1035, 837, 1261, 687, 594, 401, 573, 447, 228, 119, 0),
(1518, 1403, 1324, 1408, 1129, 569, 569, 494, 644, 259, 212, 125, 0, 1605, 1333, 1050, 841, 1273, 691, 597, 404, 577, 452, 232, 122, 0),
(1522, 1417, 1336, 1421, 1141, 575, 570, 500, 648, 259, 212, 126, 0, 1616, 1342, 1059, 845, 1280, 702, 600, 406, 581, 457, 233, 123, 0),
(1537, 1426, 1349, 1431, 1150, 581, 574, 503, 657, 264, 213, 128, 0, 1626, 1352, 1068, 854, 1292, 703, 603, 410, 586, 459, 234, 123, 0),
(1547, 1436, 1362, 1448, 1160, 587, 577, 506, 661, 265, 215, 130, 0, 1638, 1367, 1078, 863, 1297, 707, 606, 413, 592, 463, 234, 124, 0),
(1552, 1444, 1370, 1455, 1171, 590, 580, 511, 666, 267, 219, 131, 0, 1648, 1376, 1089, 866, 1308, 714, 609, 416, 595, 465, 238, 127, 0),
(1561, 1453, 1379, 1464, 1182, 594, 584, 513, 671, 270, 220, 131, 0, 1659, 1388, 1096, 874, 1316, 722, 612, 419, 603, 467, 242, 129, 0),
(1571, 1468, 1396, 1479, 1197, 599, 588, 517, 681, 273, 223, 131, 0, 1676, 1397, 1102, 881, 1320, 726, 614, 422, 607, 472, 246, 129, 0),
(1594, 1478, 1405, 1487, 1208, 603, 590, 520, 690, 274, 225, 131, 0, 1693, 1409, 1108, 888, 1328, 731, 616, 425, 615, 475, 249, 129, 0),
(1610, 1483, 1410, 1501, 1218, 606, 594, 521, 694, 277, 227, 132, 0, 1710, 1420, 1119, 892, 1337, 734, 621, 430, 618, 477, 253, 130, 0),
(1620, 1502, 1420, 1516, 1223, 612, 599, 523, 699, 279, 227, 132, 0, 1717, 1431, 1125, 898, 1347, 740, 623, 434, 625, 480, 253, 131, 0),
(1627, 1510, 1429, 1522, 1234, 616, 604, 525, 703, 282, 228, 132, 0, 1730, 1442, 1136, 908, 1358, 746, 630, 438, 630, 482, 257, 131, 0),
(1642, 1523, 1435, 1534, 1238, 621, 610, 527, 703, 285, 229, 133, 0, 1749, 1448, 1142, 914, 1366, 750, 634, 441, 634, 485, 258, 132, 0),
(1649, 1531, 1444, 1545, 1250, 625, 614, 529, 709, 287, 229, 133, 0, 1757, 1455, 1146, 917, 1375, 755, 636, 443, 640, 486, 263, 133, 0),
(1664, 1543, 1453, 1554, 1254, 632, 618, 531, 717, 292, 230, 135, 0, 1768, 1460, 1155, 922, 1386, 758, 640, 446, 643, 489, 267, 134, 0),
(1677, 1552, 1467, 1563, 1264, 637, 622, 532, 723, 293, 231, 136, 0, 1782, 1470, 1161, 927, 1396, 767, 645, 448, 644, 497, 267, 134, 0),
(1685, 1564, 1477, 1574, 1275, 642, 624, 538, 728, 294, 233, 137, 0, 1790, 1475, 1166, 933, 1405, 770, 652, 449, 646, 499, 270, 134, 0),
(1690, 1570, 1496, 1581, 1280, 644, 625, 542, 734, 295, 233, 137, 0, 1799, 1485, 1175, 938, 1413, 777, 655, 453, 649, 500, 272, 134, 0),
(1702, 1580, 1506, 1586, 1290, 650, 629, 549, 736, 296, 234, 137, 0, 1816, 1494, 1180, 948, 1426, 780, 657, 456, 650, 504, 279, 135, 0),
(1708, 1590, 1518, 1597, 1295, 654, 633, 553, 739, 297, 236, 140, 0, 1825, 1505, 1186, 952, 1440, 784, 663, 460, 660, 509, 282, 136, 0),
(1723, 1598, 1529, 1613, 1304, 659, 635, 556, 746, 299, 237, 141, 0, 1836, 1510, 1198, 957, 1452, 785, 668, 465, 665, 513, 284, 136, 0),
(1735, 1609, 1542, 1626, 1317, 661, 635, 558, 750, 301, 240, 141, 0, 1846, 1521, 1205, 962, 1467, 792, 674, 467, 668, 516, 285, 139, 0),
(1752, 1616, 1555, 1641, 1324, 667, 640, 560, 755, 302, 240, 142, 0, 1856, 1528, 1213, 966, 1481, 796, 678, 471, 673, 517, 287, 139, 0),
(1762, 1627, 1567, 1653, 1336, 672, 642, 563, 757, 304, 242, 142, 0, 1874, 1539, 1221, 972, 1493, 800, 685, 473, 679, 520, 290, 140, 0),
(1779, 1631, 1572, 1665, 1347, 675, 649, 565, 763, 310, 242, 143, 0, 1885, 1550, 1227, 977, 1501, 802, 688, 476, 686, 526, 293, 141, 0),
(1795, 1643, 1584, 1673, 1355, 681, 655, 568, 767, 311, 245, 144, 0, 1898, 1558, 1235, 984, 1510, 810, 690, 480, 690, 530, 298, 142, 0),
(1808, 1652, 1589, 1687, 1363, 686, 658, 573, 773, 313, 248, 145, 0, 1904, 1567, 1242, 987, 1521, 816, 695, 487, 695, 536, 301, 143, 0),
(1824, 1658, 1600, 1695, 1370, 692, 664, 575, 779, 313, 249, 146, 0, 1918, 1580, 1250, 994, 1531, 818, 699, 488, 700, 538, 302, 143, 0),
(1831, 1663, 1609, 1706, 1378, 697, 666, 581, 784, 315, 249, 148, 0, 1930, 1585, 1254, 996, 1541, 824, 704, 491, 703, 542, 302, 146, 0),
(1848, 1677, 1622, 1716, 1393, 701, 671, 586, 791, 315, 252, 152, 0, 1943, 1595, 1260, 1002, 1556, 829, 710, 494, 705, 547, 303, 147, 0),
(1859, 1688, 1637, 1729, 1398, 705, 677, 592, 792, 319, 257, 152, 0, 1954, 1606, 1267, 1006, 1567, 833, 714, 502, 712, 550, 304, 147, 0),
(1865, 1701, 1648, 1733, 1405, 711, 679, 599, 799, 320, 258, 153, 0, 1963, 1613, 1280, 1011, 1575, 844, 720, 510, 717, 555, 306, 150, 0),
(1880, 1713, 1656, 1743, 1414, 716, 683, 604, 803, 320, 259, 154, 0, 1974, 1622, 1293, 1016, 1586, 848, 725, 512, 720, 558, 307, 150, 0),
(1892, 1725, 1665, 1751, 1421, 720, 685, 609, 805, 321, 261, 155, 0, 1990, 1634, 1299, 1021, 1595, 852, 728, 515, 724, 561, 309, 152, 0),
(1902, 1734, 1680, 1763, 1429, 727, 691, 615, 809, 323, 262, 157, 0, 2004, 1642, 1308, 1027, 1603, 856, 732, 518, 726, 565, 311, 152, 0),
(1920, 1747, 1686, 1778, 1441, 731, 697, 617, 814, 327, 264, 157, 0, 2014, 1649, 1316, 1032, 1611, 858, 735, 522, 733, 567, 314, 154, 0),
(1938, 1750, 1696, 1788, 1445, 736, 699, 620, 816, 328, 266, 157, 0, 2023, 1660, 1320, 1037, 1629, 861, 742, 526, 739, 570, 316, 156, 0),
(1947, 1755, 1700, 1791, 1452, 741, 702, 623, 821, 328, 269, 157, 0, 2033, 1672, 1328, 1043, 1639, 866, 743, 527, 740, 573, 317, 157, 0),
(1956, 1758, 1709, 1803, 1460, 744, 703, 624, 825, 331, 270, 157, 0, 2047, 1678, 1331, 1047, 1648, 870, 746, 534, 743, 578, 317, 157, 0),
(1963, 1763, 1716, 1815, 1465, 750, 706, 627, 829, 334, 272, 157, 0, 2057, 1689, 1336, 1055, 1657, 875, 748, 538, 750, 581, 319, 158, 0),
(1970, 1773, 1724, 1823, 1473, 753, 709, 627, 831, 336, 273, 158, 0, 2066, 1700, 1346, 1062, 1671, 879, 752, 540, 753, 583, 320, 160, 0),
(1987, 1779, 1734, 1836, 1479, 754, 714, 629, 832, 336, 274, 158, 0, 2080, 1703, 1351, 1065, 1678, 882, 754, 544, 758, 587, 321, 160, 0),
(1991, 1784, 1738, 1844, 1483, 760, 717, 633, 835, 336, 275, 159, 0, 2090, 1712, 1356, 1069, 1685, 892, 757, 551, 762, 592, 322, 160, 0),
(1994, 1791, 1744, 1849, 1497, 766, 720, 634, 837, 338, 276, 161, 0, 2103, 1720, 1362, 1074, 1696, 894, 761, 554, 765, 597, 326, 160, 0),
(2003, 1796, 1760, 1857, 1505, 770, 726, 638, 844, 341, 278, 161, 0, 2108, 1729, 1363, 1082, 1708, 899, 765, 556, 768, 598, 330, 160, 0),
(2010, 1802, 1770, 1862, 1513, 775, 730, 643, 850, 342, 279, 161, 0, 2114, 1742, 1370, 1088, 1715, 905, 768, 560, 772, 599, 331, 160, 0),
(2023, 1807, 1782, 1867, 1519, 779, 731, 648, 852, 344, 281, 161, 0, 2125, 1749, 1376, 1093, 1722, 909, 769, 565, 777, 600, 332, 160, 0),
(2034, 1813, 1791, 1874, 1523, 781, 732, 654, 859, 346, 281, 161, 0, 2131, 1760, 1383, 1096, 1728, 916, 776, 568, 783, 603, 334, 161, 0),
(2046, 1823, 1796, 1880, 1532, 787, 734, 659, 866, 347, 282, 161, 0, 2141, 1765, 1393, 1100, 1741, 919, 777, 569, 790, 605, 337, 161, 0),
(2055, 1829, 1808, 1888, 1536, 790, 736, 662, 873, 349, 285, 161, 0, 2153, 1771, 1400, 1101, 1746, 921, 780, 575, 793, 609, 339, 161, 0),
(2064, 1834, 1815, 1897, 1544, 793, 738, 665, 879, 350, 285, 161, 0, 2162, 1776, 1404, 1103, 1754, 924, 783, 579, 798, 612, 340, 162, 0),
(2075, 1842, 1827, 1904, 1549, 797, 744, 666, 885, 353, 286, 162, 0, 2168, 1785, 1407, 1104, 1758, 929, 785, 582, 800, 616, 340, 162, 0),
(2080, 1845, 1840, 1913, 1553, 799, 745, 670, 890, 354, 287, 162, 0, 2180, 1790, 1412, 1109, 1767, 935, 787, 583, 802, 620, 341, 162, 0),
(2086, 1852, 1848, 1921, 1557, 802, 751, 675, 896, 355, 290, 162, 0, 2193, 1796, 1422, 1114, 1772, 939, 788, 586, 807, 621, 341, 163, 0),
(2095, 1857, 1859, 1932, 1562, 805, 754, 678, 898, 357, 291, 164, 0, 2201, 1804, 1428, 1117, 1780, 942, 791, 587, 808, 623, 342, 163, 0),
(2100, 1862, 1867, 1942, 1565, 807, 759, 681, 902, 357, 293, 164, 0, 2214, 1810, 1432, 1119, 1786, 944, 793, 590, 808, 625, 345, 163, 0),
(2111, 1867, 1872, 1948, 1570, 809, 762, 684, 905, 357, 295, 165, 0, 2223, 1816, 1441, 1125, 1793, 947, 796, 594, 814, 626, 347, 165, 0),
(2121, 1871, 1877, 1952, 1581, 813, 763, 688, 907, 358, 296, 166, 0, 2230, 1822, 1452, 1129, 1806, 954, 796, 594, 816, 630, 347, 165, 0),
(2130, 1873, 1881, 1958, 1584, 818, 764, 689, 909, 361, 298, 166, 0, 2234, 1827, 1456, 1132, 1814, 956, 798, 597, 817, 631, 350, 165, 0),
(2138, 1879, 1883, 1962, 1590, 821, 766, 689, 911, 362, 298, 166, 0, 2242, 1834, 1465, 1137, 1818, 957, 801, 599, 820, 637, 350, 166, 0),
(2144, 1884, 1889, 1968, 1597, 824, 768, 689, 913, 364, 298, 166, 0, 2250, 1840, 1468, 1139, 1824, 961, 801, 601, 824, 639, 350, 166, 0),
(2152, 1887, 1894, 1975, 1602, 825, 770, 689, 915, 366, 301, 167, 0, 2256, 1843, 1469, 1144, 1829, 962, 801, 604, 826, 641, 352, 168, 0),
(2157, 1892, 1898, 1982, 1610, 829, 772, 690, 917, 367, 302, 169, 0, 2261, 1843, 1471, 1146, 1834, 965, 802, 605, 828, 644, 352, 168, 0),
(2168, 1896, 1907, 1988, 1615, 832, 775, 692, 918, 369, 302, 170, 0, 2269, 1844, 1475, 1149, 1839, 966, 805, 605, 831, 645, 352, 168, 0),
(2173, 1900, 1911, 1991, 1621, 834, 776, 695, 923, 370, 302, 172, 0, 2278, 1845, 1476, 1151, 1843, 966, 807, 605, 836, 647, 354, 169, 0),
(2173, 1900, 1911, 1991, 1621, 834, 776, 695, 923, 370, 302, 172, 0, 2278, 1845, 1476, 1151, 1843, 966, 807, 605, 836, 647, 354, 169, 0),
)
passenger_arriving_rate = (
(7.029211809720476, 7.090786984939564, 6.079830434547925, 6.525401162556605, 5.184373233768971, 2.563234861163827, 2.9022249307617405, 2.7143527675713304, 2.8420462290117365, 1.3853052554328298, 0.9812285382399741, 0.571423425802387, 0.0, 7.117432297609708, 6.285657683826256, 4.90614269119987, 4.155915766298489, 5.684092458023473, 3.8000938745998627, 2.9022249307617405, 1.8308820436884476, 2.5921866168844856, 2.175133720852202, 1.2159660869095852, 0.6446169986308695, 0.0),
(7.496058012827964, 7.558911224152441, 6.4812376898851785, 6.956401465940448, 5.527657648309288, 2.7325532603014207, 3.093628258884586, 2.893049671694997, 3.0297144856220246, 1.4766432422970026, 1.0460557650564308, 0.6091419437616749, 0.0, 7.587708306415797, 6.700561381378422, 5.230278825282154, 4.429929726891007, 6.059428971244049, 4.050269540372995, 3.093628258884586, 1.9518237573581576, 2.763828824154644, 2.3188004886468163, 1.2962475379770357, 0.687173747650222, 0.0),
(7.9614122125716245, 8.025177635976757, 6.881049333138649, 7.385687089898034, 5.869698775499761, 2.9011961768518306, 3.284272955572493, 3.071031394610912, 3.2166338432095234, 1.5676198212571917, 1.1106254013811399, 0.6467104760728565, 0.0, 8.056110759493567, 7.113815236801421, 5.553127006905699, 4.702859463771574, 6.433267686419047, 4.2994439524552766, 3.284272955572493, 2.0722829834655934, 2.9348493877498805, 2.4618956966326784, 1.37620986662773, 0.7295616032706144, 0.0),
(8.423460910405188, 8.487736310818441, 7.277679347539831, 7.811555227908678, 6.209150897601775, 3.0684948417778424, 3.473402549153569, 3.2475923418717962, 3.4020630750965104, 1.657873944449164, 1.1746812960930562, 0.6839799965752206, 0.0, 8.520781928755916, 7.523779962327425, 5.873406480465281, 4.97362183334749, 6.804126150193021, 4.5466292786205145, 3.473402549153569, 2.191782029841316, 3.1045754488008876, 2.6038517426362264, 1.455535869507966, 0.7716123918925856, 0.0),
(8.880390607782374, 8.94473733908341, 7.669541716320211, 8.232303073451698, 6.5446682968767265, 3.233780486042246, 3.6602605679559215, 3.4220269190303676, 3.585260954605263, 1.7470445640086882, 1.2379672980711345, 0.7208014791080559, 0.0, 8.979864086115745, 7.928816270188614, 6.189836490355671, 5.241133692026064, 7.170521909210526, 4.790837686642515, 3.6602605679559215, 2.30984320431589, 3.2723341484383632, 2.7441010244839, 1.5339083432640421, 0.8131579399166738, 0.0),
(9.330387806156915, 9.394330811177607, 8.055050422711272, 8.646227820006413, 6.874905255585995, 3.396384340607826, 3.844090540307657, 3.593629531639346, 3.765486255058061, 1.8347706320715327, 1.300227256194331, 0.7570258975106506, 0.0, 9.43149950348596, 8.327284872617156, 6.501136280971655, 5.504311896214597, 7.530972510116122, 5.031081344295084, 3.844090540307657, 2.4259888147198754, 3.4374526277929975, 2.8820759400021383, 1.6110100845422546, 0.8540300737434189, 0.0),
(9.771639006982534, 9.834666817506942, 8.43261944994451, 9.051626661052135, 7.198516055990973, 3.5556376364373725, 4.024135994536884, 3.7616945852514516, 3.9419977497771805, 1.920691100773466, 1.3612050193415997, 0.7925042256222944, 0.0, 9.87383045277945, 8.717546481845236, 6.806025096707997, 5.762073302320396, 7.883995499554361, 5.266372419352033, 4.024135994536884, 2.5397411688838374, 3.5992580279954867, 3.017208887017379, 1.6865238899889023, 0.8940606197733586, 0.0),
(10.202330711712957, 10.263895448477353, 8.800662781251408, 9.446796790068186, 7.514154980353052, 3.710871604493673, 4.19964045897171, 3.9255164854194056, 4.1140542120849, 2.004444922250256, 1.4206444363918964, 0.8270874372822752, 0.0, 10.304999205909127, 9.097961810105026, 7.103222181959481, 6.013334766750766, 8.2281084241698, 5.495723079587168, 4.19964045897171, 2.6506225746383376, 3.757077490176526, 3.148932263356063, 1.7601325562502819, 0.9330814044070321, 0.0),
(10.62064942180191, 10.68016679449476, 9.157594399863463, 9.830035400533875, 7.820476310933614, 3.8614174757395103, 4.369847461940239, 4.0843896376959234, 4.280914415303496, 2.0856710486376717, 1.4782893562241752, 0.8606265063298821, 0.0, 10.723148034787885, 9.466891569628702, 7.391446781120876, 6.257013145913014, 8.561828830606991, 5.718145492774292, 4.369847461940239, 2.758155339813936, 3.910238155466807, 3.276678466844626, 1.831518879972693, 0.9709242540449783, 0.0),
(11.02478163870312, 11.081630945965095, 9.501828289012156, 10.199639685928528, 8.116134329994049, 4.006606481137679, 4.534000531770584, 4.237608447633729, 4.441837132755248, 2.1640084320714803, 1.5338836277173917, 0.8929724066044035, 0.0, 11.126419211328628, 9.822696472648436, 7.669418138586958, 6.49202529621444, 8.883674265510496, 5.932651826687221, 4.534000531770584, 2.861861772241199, 4.058067164997024, 3.3998798953095104, 1.9003656578024313, 1.0074209950877362, 0.0),
(11.412913863870306, 11.46643799329428, 9.83177843192898, 10.553906839731454, 8.399783319795748, 4.145769851650964, 4.691343196790848, 4.38446732078554, 4.596081137762433, 2.2390960246874507, 1.5871710997505006, 0.923976111945128, 0.0, 11.512955007444255, 10.163737231396405, 7.935855498752503, 6.717288074062351, 9.192162275524867, 6.138254249099756, 4.691343196790848, 2.961264179750688, 4.199891659897874, 3.517968946577152, 1.9663556863857963, 1.0424034539358438, 0.0),
(11.783232598757209, 11.832738026888249, 10.145858811845418, 10.891134055421968, 8.670077562600099, 4.278238818242151, 4.841118985329142, 4.524260662704076, 4.7429052036473305, 2.3105727786213524, 1.6378956212024585, 0.9534885961913449, 0.0, 11.880897695047656, 10.488374558104791, 8.189478106012292, 6.931718335864056, 9.485810407294661, 6.333964927785706, 4.841118985329142, 3.055884870172965, 4.3350387813000495, 3.63037801847399, 2.0291717623690837, 1.075703456989841, 0.0),
(12.133924344817538, 12.178681137152912, 10.442483411992965, 11.209618526479394, 8.925671340668487, 4.403344611874027, 4.9825714257135685, 4.656282878942054, 4.881568103732217, 2.378077646008951, 1.6858010409522184, 0.9813608331823415, 0.0, 12.22838954605175, 10.794969165005755, 8.429005204761092, 7.134232938026852, 9.763136207464434, 6.518796030518876, 4.9825714257135685, 3.1452461513385908, 4.462835670334243, 3.7365395088264655, 2.0884966823985933, 1.107152830650265, 0.0),
(12.463175603505027, 12.502417414494213, 10.720066215603106, 11.507657446383048, 9.165218936262296, 4.520418463509383, 5.11494404627224, 4.779828375052198, 5.011328611339368, 2.441249578986017, 1.7306312078787365, 1.0074437967574077, 0.0, 12.55357283236943, 11.08188176433148, 8.653156039393682, 7.323748736958049, 10.022657222678736, 6.691759725073078, 5.11494404627224, 3.228870331078131, 4.582609468131148, 3.8358858154610167, 2.1440132431206216, 1.136583401317656, 0.0),
(12.769172876273403, 12.802096949318072, 10.977021205907338, 11.783548008612232, 9.387374631642924, 4.6287916041110035, 5.237480375333263, 4.894191556587227, 5.131445499791063, 2.4997275296883177, 1.7721299708609668, 1.0315884607558323, 0.0, 12.85458982591359, 11.347473068314153, 8.860649854304834, 7.499182589064952, 10.262890999582126, 6.8518681792221185, 5.237480375333263, 3.306279717222145, 4.693687315821462, 3.9278493362040785, 2.195404241181468, 1.1638269953925522, 0.0),
(13.050102664576398, 13.075869832030413, 11.211762366137135, 12.035587406646286, 9.590792709071755, 4.72779526464168, 5.349423941224739, 4.998666829099858, 5.241177542409583, 2.5531504502516222, 1.810041178777865, 1.0536457990169035, 0.0, 13.129582798597134, 11.590103789185937, 9.050205893889325, 7.659451350754866, 10.482355084819165, 6.998133560739801, 5.349423941224739, 3.3769966176011996, 4.795396354535877, 4.0118624688820965, 2.242352473227427, 1.1887154392754924, 0.0),
(13.30415146986772, 13.321886153037171, 11.422703679523998, 12.262072833964503, 9.774127450810177, 4.816760676064193, 5.450018272274784, 5.092548598142811, 5.339783512517201, 2.6011572928116995, 1.8441086805083868, 1.0734667853799098, 0.0, 13.376694022332964, 11.808134639179006, 9.220543402541933, 7.803471878435097, 10.679567025034402, 7.1295680373999355, 5.450018272274784, 3.440543340045852, 4.887063725405088, 4.087357611321502, 2.2845407359047996, 1.2110805593670158, 0.0),
(13.529505793601107, 13.538296002744264, 11.608259129299412, 12.46130148404622, 9.936033139119584, 4.895019069341334, 5.538506896811498, 5.17513126926881, 5.426522183436193, 2.643387009504314, 1.874076324931487, 1.09090239368414, 0.0, 13.594065769033982, 11.999926330525538, 9.370381624657433, 7.9301610285129405, 10.853044366872385, 7.245183776976335, 5.538506896811498, 3.496442192386667, 4.968016569559792, 4.153767161348741, 2.3216518258598824, 1.2307541820676606, 0.0),
(13.724352137230287, 13.723249471557619, 11.766842698694862, 12.631570550370744, 10.07516405626135, 4.961901675435895, 5.6141333431629965, 5.245709248030569, 5.500652328488845, 2.6794785524652385, 1.8996879609261188, 1.1058035977688838, 0.0, 13.779840310613086, 12.163839575457718, 9.498439804630594, 8.038435657395715, 11.00130465697769, 7.343992947242797, 5.6141333431629965, 3.5442154824542103, 5.037582028130675, 4.210523516790249, 2.3533685397389728, 1.2475681337779656, 0.0),
(13.88687700220898, 13.874896649883173, 11.896868370941842, 12.77117722641738, 10.190174484496875, 5.0167397253106545, 5.676141139657377, 5.30357693998081, 5.561432720997431, 2.7090708738302403, 1.9206874373712384, 1.1180213714734282, 0.0, 13.932159918983176, 12.298235086207708, 9.603437186856192, 8.12721262149072, 11.122865441994861, 7.425007715973134, 5.676141139657377, 3.5833855180790386, 5.095087242248438, 4.257059075472461, 2.379373674188369, 1.2613542408984704, 0.0),
(14.015266889990915, 13.991387628126835, 11.996750129271838, 12.87841870566547, 10.279718706087547, 5.058864449928407, 5.723773814622755, 5.348028750672253, 5.608122134284226, 2.731802925735086, 1.936818603145802, 1.1274066886370624, 0.0, 14.049166866057154, 12.401473575007685, 9.68409301572901, 8.195408777205257, 11.216244268568452, 7.487240250941153, 5.723773814622755, 3.6134746070917196, 5.139859353043773, 4.292806235221825, 2.399350025854368, 1.2719443298297126, 0.0),
(14.107708302029813, 14.070872496694552, 12.064901956916339, 12.951592181594311, 10.34245100329475, 5.087607080251938, 5.756274896387231, 5.378359085657614, 5.63997934167151, 2.747313660315545, 1.9478253071287643, 1.133810523099076, 0.0, 14.12900342374791, 12.471915754089835, 9.739126535643821, 8.241940980946634, 11.27995868334302, 7.529702719920659, 5.756274896387231, 3.634005057322813, 5.171225501647375, 4.317197393864771, 2.412980391383268, 1.279170226972232, 0.0),
(14.162387739779412, 14.111501345992236, 12.099737837106835, 12.988994847683228, 10.377025658379871, 5.102298847244033, 5.77288791327892, 5.393862350489618, 5.656263116481561, 2.7552420297073854, 1.9534513981990798, 1.1370838486987573, 0.0, 14.16981186396836, 12.50792233568633, 9.7672569909954, 8.265726089122154, 11.312526232963123, 7.551407290685465, 5.77288791327892, 3.644499176602881, 5.188512829189936, 4.329664949227744, 2.419947567421367, 1.282863758726567, 0.0),
(14.182550708679697, 14.116311945587563, 12.104077046181986, 12.993677353395064, 10.385883252297091, 5.104166666666667, 5.774862801581538, 5.395538065843622, 5.658298909465021, 2.7561772953818022, 1.9541568753377396, 1.1374880506020426, 0.0, 14.175, 12.512368556622466, 9.770784376688697, 8.268531886145405, 11.316597818930042, 7.553753292181072, 5.774862801581538, 3.6458333333333335, 5.192941626148546, 4.331225784465023, 2.4208154092363974, 1.283301085962506, 0.0),
(14.197417378247815, 14.113505864197531, 12.10336728395062, 12.99310104166667, 10.390900439373862, 5.104166666666667, 5.773777668845317, 5.393208333333334, 5.658026111111111, 2.755602716049383, 1.9540790684624023, 1.1373934156378602, 0.0, 14.175, 12.51132757201646, 9.77039534231201, 8.266808148148147, 11.316052222222222, 7.550491666666668, 5.773777668845317, 3.6458333333333335, 5.195450219686931, 4.331033680555557, 2.4206734567901242, 1.2830459876543212, 0.0),
(14.211970122296213, 14.10797467992684, 12.101966163694561, 12.991960841049384, 10.39580728255487, 5.104166666666667, 5.771639231824418, 5.388631687242799, 5.657487139917696, 2.754471593507088, 1.9539247931994848, 1.1372065996037193, 0.0, 14.175, 12.509272595640908, 9.769623965997424, 8.263414780521263, 11.314974279835392, 7.544084362139919, 5.771639231824418, 3.6458333333333335, 5.197903641277435, 4.330653613683129, 2.4203932327389124, 1.2825431527206221, 0.0),
(14.226207826667249, 14.099802892089624, 12.099892889803387, 12.990269714506173, 10.400603610526364, 5.104166666666667, 5.768480702816105, 5.381894547325103, 5.65668890946502, 2.7528027480566992, 1.9536954462318665, 1.136930163084896, 0.0, 14.175, 12.506231793933855, 9.768477231159332, 8.258408244170097, 11.31337781893004, 7.534652366255146, 5.768480702816105, 3.6458333333333335, 5.200301805263182, 4.330089904835392, 2.4199785779606775, 1.2818002629172387, 0.0),
(14.240129377203292, 14.089075, 12.097166666666668, 12.988040625, 10.405289251974601, 5.104166666666667, 5.7643352941176484, 5.3730833333333345, 5.655638333333333, 2.7506150000000003, 1.9533924242424245, 1.1365666666666672, 0.0, 14.175, 12.502233333333336, 9.766962121212122, 8.251845, 11.311276666666666, 7.5223166666666685, 5.7643352941176484, 3.6458333333333335, 5.2026446259873005, 4.329346875000001, 2.4194333333333335, 1.280825, 0.0),
(14.253733659746702, 14.075875502972108, 12.093806698673983, 12.985286535493827, 10.40986403558584, 5.104166666666667, 5.759236218026306, 5.362284465020577, 5.654342325102881, 2.7479271696387753, 1.9530171239140377, 1.1361186709343092, 0.0, 14.175, 12.4973053802774, 9.765085619570188, 8.243781508916324, 11.308684650205763, 7.507198251028808, 5.759236218026306, 3.6458333333333335, 5.20493201779292, 4.32842884516461, 2.418761339734797, 1.2796250457247373, 0.0),
(14.26701956013985, 14.060288900320074, 12.089832190214908, 12.982020408950618, 10.41432779004634, 5.104166666666667, 5.753216686839346, 5.349584362139918, 5.652807798353909, 2.7447580772748066, 1.952570941929584, 1.1355887364730988, 0.0, 14.175, 12.491476101204084, 9.76285470964792, 8.234274231824418, 11.305615596707819, 7.489418106995886, 5.753216686839346, 3.6458333333333335, 5.20716389502317, 4.327340136316874, 2.4179664380429817, 1.2782080818472796, 0.0),
(14.279985964225098, 14.042399691358026, 12.085262345679013, 12.978255208333334, 10.418680344042354, 5.104166666666667, 5.746309912854031, 5.335069444444444, 5.651041666666666, 2.7411265432098775, 1.952055274971942, 1.1349794238683129, 0.0, 14.175, 12.48477366255144, 9.760276374859709, 8.223379629629632, 11.302083333333332, 7.469097222222222, 5.746309912854031, 3.6458333333333335, 5.209340172021177, 4.326085069444446, 2.4170524691358026, 1.276581790123457, 0.0),
(14.292631757844802, 14.022292375400093, 12.080116369455878, 12.97400389660494, 10.422921526260142, 5.104166666666667, 5.7385491083676285, 5.318826131687244, 5.649050843621399, 2.737051387745771, 1.9514715197239891, 1.1342932937052284, 0.0, 14.175, 12.477226230757509, 9.757357598619945, 8.211154163237312, 11.298101687242799, 7.4463565843621415, 5.7385491083676285, 3.6458333333333335, 5.211460763130071, 4.324667965534981, 2.416023273891176, 1.2747538523090995, 0.0),
(14.304955826841338, 14.000051451760402, 12.07441346593507, 12.969279436728398, 10.427051165385956, 5.104166666666667, 5.7299674856774, 5.3009408436214, 5.646842242798354, 2.7325514311842714, 1.950821072868604, 1.1335329065691209, 0.0, 14.175, 12.468861972260328, 9.754105364343019, 8.197654293552812, 11.293684485596708, 7.421317181069961, 5.7299674856774, 3.6458333333333335, 5.213525582692978, 4.3230931455761334, 2.4148826931870144, 1.272731950160037, 0.0),
(14.316957057057056, 13.975761419753086, 12.068172839506175, 12.964094791666666, 10.431069090106059, 5.104166666666667, 5.720598257080611, 5.2815, 5.644422777777778, 2.7276454938271613, 1.9501053310886647, 1.1327008230452675, 0.0, 14.175, 12.459709053497942, 9.750526655443322, 8.182936481481482, 11.288845555555556, 7.394100000000001, 5.720598257080611, 3.6458333333333335, 5.215534545053029, 4.321364930555556, 2.413634567901235, 1.2705237654320989, 0.0),
(14.328634334334335, 13.949506778692271, 12.061413694558757, 12.958462924382715, 10.434975129106702, 5.104166666666667, 5.710474634874527, 5.260590020576132, 5.641799362139919, 2.7223523959762237, 1.9493256910670491, 1.1317996037189455, 0.0, 14.175, 12.449795640908398, 9.746628455335244, 8.16705718792867, 11.283598724279837, 7.3648260288065845, 5.710474634874527, 3.6458333333333335, 5.217487564553351, 4.319487641460906, 2.4122827389117516, 1.2681369798811157, 0.0),
(14.339986544515531, 13.92137202789209, 12.054155235482398, 12.952396797839505, 10.438769111074146, 5.104166666666667, 5.699629831356412, 5.238297325102881, 5.638978909465021, 2.7166909579332423, 1.9484835494866362, 1.1308318091754308, 0.0, 14.175, 12.439149900929737, 9.74241774743318, 8.150072873799726, 11.277957818930043, 7.333616255144034, 5.699629831356412, 3.6458333333333335, 5.219384555537073, 4.317465599279836, 2.41083104709648, 1.2655792752629174, 0.0),
(14.35101257344301, 13.891441666666665, 12.04641666666667, 12.945909375, 10.442450864694647, 5.104166666666667, 5.68809705882353, 5.214708333333334, 5.635968333333333, 2.7106800000000004, 1.9475803030303034, 1.1298000000000004, 0.0, 14.175, 12.427800000000001, 9.737901515151515, 8.13204, 11.271936666666665, 7.300591666666668, 5.68809705882353, 3.6458333333333335, 5.221225432347324, 4.315303125000001, 2.409283333333334, 1.2628583333333334, 0.0),
(14.361711306959135, 13.859800194330132, 12.038217192501145, 12.939013618827161, 10.44602021865446, 5.104166666666667, 5.675909529573146, 5.189909465020577, 5.632774547325103, 2.7043383424782816, 1.9466173483809293, 1.1287067367779304, 0.0, 14.175, 12.415774104557233, 9.733086741904645, 8.113015027434844, 11.265549094650206, 7.265873251028808, 5.675909529573146, 3.6458333333333335, 5.22301010932723, 4.313004539609055, 2.407643438500229, 1.259981835848194, 0.0),
(14.372081630906267, 13.826532110196618, 12.029576017375401, 12.931722492283953, 10.449477001639845, 5.104166666666667, 5.663100455902526, 5.1639871399176975, 5.629404465020576, 2.6976848056698683, 1.9455960822213911, 1.1275545800944982, 0.0, 14.175, 12.403100381039478, 9.727980411106955, 8.093054417009604, 11.258808930041152, 7.229581995884776, 5.663100455902526, 3.6458333333333335, 5.224738500819923, 4.3105741640946516, 2.40591520347508, 1.2569574645633292, 0.0),
(14.382122431126781, 13.791721913580247, 12.020512345679016, 12.924048958333334, 10.452821042337057, 5.104166666666667, 5.649703050108934, 5.137027777777778, 5.625865000000001, 2.690738209876544, 1.9445179012345684, 1.1263460905349796, 0.0, 14.175, 12.389806995884772, 9.722589506172842, 8.07221462962963, 11.251730000000002, 7.191838888888889, 5.649703050108934, 3.6458333333333335, 5.226410521168528, 4.308016319444445, 2.4041024691358035, 1.253792901234568, 0.0),
(14.39183259346303, 13.755454103795152, 12.011045381801555, 12.916005979938273, 10.45605216943235, 5.104166666666667, 5.635750524489632, 5.1091177983539104, 5.622163065843623, 2.6835173754000925, 1.943384202103338, 1.125083828684652, 0.0, 14.175, 12.375922115531171, 9.71692101051669, 8.050552126200277, 11.244326131687245, 7.1527649176954755, 5.635750524489632, 3.6458333333333335, 5.228026084716175, 4.305335326646092, 2.4022090763603114, 1.2504958276177414, 0.0),
(14.40121100375738, 13.717813180155463, 12.001194330132604, 12.90760652006173, 10.459170211611989, 5.104166666666667, 5.621276091341887, 5.080343621399178, 5.618305576131687, 2.676041122542296, 1.9421963815105796, 1.1237703551287916, 0.0, 14.175, 12.361473906416705, 9.710981907552897, 8.028123367626886, 11.236611152263373, 7.112481069958849, 5.621276091341887, 3.6458333333333335, 5.229585105805994, 4.302535506687244, 2.400238866026521, 1.2470739254686787, 0.0),
(14.410256547852201, 13.678883641975311, 11.990978395061731, 12.89886354166667, 10.462174997562222, 5.104166666666667, 5.6063129629629636, 5.050791666666668, 5.614299444444446, 2.668328271604939, 1.9409558361391697, 1.122408230452675, 0.0, 14.175, 12.346490534979424, 9.704779180695848, 8.004984814814815, 11.228598888888891, 7.071108333333335, 5.6063129629629636, 3.6458333333333335, 5.231087498781111, 4.299621180555557, 2.3981956790123466, 1.2435348765432102, 0.0),
(14.418968111589852, 13.638749988568819, 11.980416780978512, 12.889790007716051, 10.46506635596931, 5.104166666666667, 5.5908943516501255, 5.020548353909466, 5.61015158436214, 2.660397642889804, 1.9396639626719878, 1.1210000152415793, 0.0, 14.175, 12.331000167657372, 9.698319813359937, 7.981192928669412, 11.22030316872428, 7.0287676954732525, 5.5908943516501255, 3.6458333333333335, 5.232533177984655, 4.296596669238685, 2.3960833561957027, 1.2398863625971654, 0.0),
(14.427344580812699, 13.597496719250115, 11.969528692272522, 12.880398881172843, 10.467844115519508, 5.104166666666667, 5.575053469700638, 4.98970010288066, 5.605868909465021, 2.652268056698675, 1.938322157791911, 1.1195482700807806, 0.0, 14.175, 12.315030970888586, 9.691610788959554, 7.9568041700960235, 11.211737818930041, 6.985580144032924, 5.575053469700638, 3.6458333333333335, 5.233922057759754, 4.293466293724282, 2.3939057384545044, 1.2361360653863744, 0.0),
(14.435384841363105, 13.555208333333335, 11.958333333333336, 12.870703125000002, 10.470508104899077, 5.104166666666667, 5.558823529411765, 4.958333333333334, 5.601458333333333, 2.6439583333333343, 1.9369318181818187, 1.1180555555555556, 0.0, 14.175, 12.29861111111111, 9.684659090909092, 7.931875000000002, 11.202916666666667, 6.941666666666667, 5.558823529411765, 3.6458333333333335, 5.235254052449538, 4.290234375000002, 2.391666666666667, 1.232291666666667, 0.0),
(14.443087779083434, 13.511969330132603, 11.946849908550526, 12.860715702160494, 10.47305815279427, 5.104166666666667, 5.542237743080772, 4.926534465020577, 5.596926769547324, 2.635487293095565, 1.9354943405245877, 1.1165244322511814, 0.0, 14.175, 12.281768754762993, 9.677471702622938, 7.906461879286693, 11.193853539094649, 6.897148251028808, 5.542237743080772, 3.6458333333333335, 5.236529076397135, 4.286905234053499, 2.3893699817101055, 1.228360848193873, 0.0),
(14.45045227981605, 13.46786420896205, 11.935097622313673, 12.850449575617287, 10.475494087891343, 5.104166666666667, 5.525329323004923, 4.894389917695474, 5.592281131687244, 2.6268737562871523, 1.9340111215030973, 1.1149574607529342, 0.0, 14.175, 12.264532068282275, 9.670055607515485, 7.880621268861455, 11.184562263374488, 6.852145884773663, 5.525329323004923, 3.6458333333333335, 5.237747043945672, 4.283483191872429, 2.387019524462735, 1.2243512917238228, 0.0),
(14.457477229403315, 13.422977469135803, 11.923095679012349, 12.839917708333335, 10.477815738876558, 5.104166666666667, 5.508131481481482, 4.861986111111112, 5.587528333333333, 2.618136543209877, 1.9324835578002246, 1.1133572016460909, 0.0, 14.175, 12.246929218106997, 9.662417789001124, 7.854409629629629, 11.175056666666666, 6.806780555555557, 5.508131481481482, 3.6458333333333335, 5.238907869438279, 4.279972569444446, 2.38461913580247, 1.2202706790123459, 0.0),
(14.464161513687602, 13.377393609967992, 11.910863283036125, 12.829133063271607, 10.480022934436168, 5.104166666666667, 5.490677430807714, 4.829409465020577, 5.582675288065844, 2.6092944741655244, 1.930913046098849, 1.1117262155159278, 0.0, 14.175, 12.228988370675204, 9.654565230494246, 7.827883422496572, 11.165350576131688, 6.761173251028807, 5.490677430807714, 3.6458333333333335, 5.240011467218084, 4.276377687757203, 2.382172656607225, 1.2161266918152722, 0.0),
(14.470504018511264, 13.33119713077275, 11.89841963877458, 12.81810860339506, 10.482115503256427, 5.104166666666667, 5.473000383280885, 4.796746399176955, 5.57772890946502, 2.6003663694558763, 1.9293009830818477, 1.1100670629477218, 0.0, 14.175, 12.210737692424937, 9.646504915409238, 7.8010991083676275, 11.15545781893004, 6.715444958847738, 5.473000383280885, 3.6458333333333335, 5.2410577516282135, 4.272702867798355, 2.379683927754916, 1.211927011888432, 0.0),
(14.476503629716676, 13.284472530864198, 11.885783950617286, 12.806857291666669, 10.484093274023598, 5.104166666666667, 5.455133551198258, 4.764083333333335, 5.572696111111112, 2.5913710493827167, 1.9276487654320995, 1.1083823045267494, 0.0, 14.175, 12.192205349794241, 9.638243827160496, 7.774113148148149, 11.145392222222224, 6.669716666666668, 5.455133551198258, 3.6458333333333335, 5.242046637011799, 4.268952430555557, 2.377156790123457, 1.2076793209876546, 0.0),
(14.482159233146191, 13.237304309556471, 11.87297542295382, 12.795392091049385, 10.485956075423934, 5.104166666666667, 5.437110146857097, 4.731506687242798, 5.567583806584363, 2.582327334247829, 1.9259577898324816, 1.1066745008382872, 0.0, 14.175, 12.173419509221157, 9.629788949162407, 7.746982002743485, 11.135167613168726, 6.624109362139918, 5.437110146857097, 3.6458333333333335, 5.242978037711967, 4.265130697016462, 2.3745950845907644, 1.2033913008687704, 0.0),
(14.487469714642183, 13.189776966163697, 11.860013260173757, 12.783725964506175, 10.487703736143693, 5.104166666666667, 5.418963382554669, 4.699102880658437, 5.5623989094650215, 2.573254044352996, 1.9242294529658732, 1.104946212467612, 0.0, 14.175, 12.15440833714373, 9.621147264829364, 7.719762133058986, 11.124797818930043, 6.578744032921811, 5.418963382554669, 3.6458333333333335, 5.243851868071847, 4.261241988168726, 2.3720026520347517, 1.199070633287609, 0.0),
(14.492433960047004, 13.141975000000002, 11.846916666666667, 12.771871875000002, 10.489336084869135, 5.104166666666667, 5.400726470588236, 4.6669583333333335, 5.557148333333334, 2.5641700000000007, 1.9224651515151516, 1.1032000000000002, 0.0, 14.175, 12.1352, 9.612325757575757, 7.69251, 11.114296666666668, 6.533741666666667, 5.400726470588236, 3.6458333333333335, 5.244668042434568, 4.257290625000001, 2.369383333333334, 1.1947250000000003, 0.0),
(14.497050855203032, 13.093982910379516, 11.833704846822133, 12.759842785493827, 10.490852950286511, 5.104166666666667, 5.382432623255064, 4.6351594650205765, 5.551838991769547, 2.555094021490627, 1.9206662821631961, 1.101438424020729, 0.0, 14.175, 12.115822664228014, 9.603331410815981, 7.66528206447188, 11.103677983539095, 6.4892232510288075, 5.382432623255064, 3.6458333333333335, 5.2454264751432556, 4.253280928497944, 2.3667409693644266, 1.1903620827617745, 0.0),
(14.501319285952622, 13.045885196616371, 11.820397005029724, 12.74765165895062, 10.492254161082082, 5.104166666666667, 5.3641150528524175, 4.603792695473252, 5.5464777983539095, 2.5460449291266585, 1.918834241592884, 1.099664045115074, 0.0, 14.175, 12.096304496265812, 9.59417120796442, 7.638134787379974, 11.092955596707819, 6.445309773662553, 5.3641150528524175, 3.6458333333333335, 5.246127080541041, 4.249217219650207, 2.3640794010059447, 1.1859895633287612, 0.0),
(14.505238138138138, 12.997766358024693, 11.807012345679016, 12.735311458333335, 10.493539545942102, 5.104166666666667, 5.34580697167756, 4.572944444444445, 5.541071666666667, 2.5370415432098774, 1.9169704264870937, 1.097879423868313, 0.0, 14.175, 12.076673662551439, 9.584852132435467, 7.61112462962963, 11.082143333333335, 6.402122222222224, 5.34580697167756, 3.6458333333333335, 5.246769772971051, 4.245103819444446, 2.3614024691358035, 1.1816151234567904, 0.0),
(14.508806297601952, 12.949710893918612, 11.79357007315958, 12.72283514660494, 10.494708933552829, 5.104166666666667, 5.3275415920277585, 4.5427011316872425, 5.535627510288066, 2.5281026840420675, 1.9150762335287033, 1.096087120865722, 0.0, 14.175, 12.05695832952294, 9.575381167643515, 7.584308052126201, 11.071255020576132, 6.35978158436214, 5.3275415920277585, 3.6458333333333335, 5.2473544667764145, 4.240945048868314, 2.3587140146319165, 1.1772464449016922, 0.0),
(14.51202265018642, 12.901803303612255, 11.780089391860999, 12.710235686728396, 10.495762152600523, 5.104166666666667, 5.309352126200275, 4.513149176954733, 5.530152242798355, 2.5192471719250125, 1.9131530594005905, 1.0942896966925775, 0.0, 14.175, 12.037186663618352, 9.565765297002951, 7.557741515775036, 11.06030448559671, 6.3184088477366265, 5.309352126200275, 3.6458333333333335, 5.247881076300262, 4.2367452289094665, 2.3560178783722, 1.172891209419296, 0.0),
(14.51488608173391, 12.854128086419754, 11.76658950617284, 12.697526041666668, 10.496699031771435, 5.104166666666667, 5.291271786492374, 4.484375000000001, 5.524652777777779, 2.5104938271604946, 1.9112023007856345, 1.0924897119341568, 0.0, 14.175, 12.017386831275722, 9.556011503928172, 7.5314814814814826, 11.049305555555557, 6.278125000000001, 5.291271786492374, 3.6458333333333335, 5.248349515885717, 4.232508680555557, 2.353317901234568, 1.1685570987654323, 0.0),
(14.517395478086781, 12.806769741655238, 11.753089620484685, 12.684719174382717, 10.497519399751823, 5.104166666666667, 5.273333785201324, 4.4564650205761325, 5.519136028806585, 2.501861470050298, 1.9092253543667126, 1.0906897271757356, 0.0, 14.175, 11.997586998933091, 9.546126771833563, 7.5055844101508935, 11.03827205761317, 6.2390510288065855, 5.273333785201324, 3.6458333333333335, 5.248759699875912, 4.22823972479424, 2.350617924096937, 1.1642517946959308, 0.0),
(14.519549725087407, 12.759812768632832, 11.739608939186102, 12.671828047839508, 10.498223085227952, 5.104166666666667, 5.255571334624385, 4.429505658436215, 5.513608909465021, 2.4933689208962058, 1.9072236168267036, 1.0888923030025914, 0.0, 14.175, 11.977815333028504, 9.536118084133516, 7.4801067626886155, 11.027217818930042, 6.201307921810701, 5.255571334624385, 3.6458333333333335, 5.249111542613976, 4.2239426826131705, 2.3479217878372207, 1.1599829789666212, 0.0),
(14.521347708578144, 12.713341666666667, 11.72616666666667, 12.658865625, 10.498809916886067, 5.104166666666667, 5.238017647058824, 4.4035833333333345, 5.508078333333334, 2.4850350000000003, 1.9051984848484853, 1.0871000000000002, 0.0, 14.175, 11.9581, 9.525992424242425, 7.455105, 11.016156666666667, 6.165016666666668, 5.238017647058824, 3.6458333333333335, 5.249404958443034, 4.219621875000001, 2.345233333333334, 1.1557583333333337, 0.0),
(14.522788314401359, 12.667440935070873, 11.712782007315958, 12.645844868827162, 10.499279723412432, 5.104166666666667, 5.220705934801905, 4.378784465020577, 5.50255121399177, 2.4768785276634664, 1.9031513551149353, 1.0853153787532392, 0.0, 14.175, 11.938469166285628, 9.515756775574676, 7.430635582990398, 11.00510242798354, 6.130298251028808, 5.220705934801905, 3.6458333333333335, 5.249639861706216, 4.215281622942388, 2.342556401463192, 1.151585539551898, 0.0),
(14.523870428399414, 12.62219507315958, 11.69947416552355, 12.63277874228395, 10.499632333493302, 5.104166666666667, 5.2036694101508925, 4.35519547325103, 5.497034465020577, 2.4689183241883863, 1.9010836243089335, 1.0835409998475842, 0.0, 14.175, 11.918950998323425, 9.505418121544666, 7.406754972565158, 10.994068930041154, 6.097273662551442, 5.2036694101508925, 3.6458333333333335, 5.249816166746651, 4.2109262474279845, 2.3398948331047102, 1.1474722793781438, 0.0),
(14.524592936414676, 12.577688580246916, 11.686262345679015, 12.619680208333333, 10.499867575814935, 5.104166666666667, 5.1869412854030505, 4.332902777777779, 5.491535000000001, 2.4611732098765438, 1.898996689113356, 1.0817794238683132, 0.0, 14.175, 11.899573662551441, 9.49498344556678, 7.38351962962963, 10.983070000000001, 6.06606388888889, 5.1869412854030505, 3.6458333333333335, 5.249933787907468, 4.206560069444445, 2.337252469135803, 1.1434262345679016, 0.0),
(14.524954724289511, 12.534005955647004, 11.673165752171926, 12.606562229938273, 10.499985279063587, 5.104166666666667, 5.1705547728556445, 4.311992798353911, 5.486059732510288, 2.453662005029722, 1.8968919462110825, 1.0800332114007012, 0.0, 14.175, 11.88036532540771, 9.484459731055413, 7.360986015089164, 10.972119465020576, 6.036789917695475, 5.1705547728556445, 3.6458333333333335, 5.2499926395317935, 4.202187409979425, 2.3346331504343856, 1.1394550868770006, 0.0),
(14.524708260273156, 12.491002420461081, 11.660140274919984, 12.593323827495976, 10.499886091610856, 5.104071942793273, 5.154460636380753, 4.292367245846671, 5.480574329370524, 2.446367154576509, 1.894733397326088, 1.078295169221637, 0.0, 14.174825210048013, 11.861246861438005, 9.47366698663044, 7.339101463729525, 10.961148658741047, 6.009314144185339, 5.154460636380753, 3.6457656734237665, 5.249943045805428, 4.197774609165326, 2.3320280549839967, 1.135545674587371, 0.0),
(14.522398389694043, 12.44736508363202, 11.646819830246914, 12.579297690217391, 10.498983297022512, 5.1033231138545965, 5.13818772694263, 4.272974279835392, 5.474838991769548, 2.439082236746551, 1.8923013290802768, 1.0765088802252547, 0.0, 14.17344039351852, 11.8415976824778, 9.461506645401384, 7.317246710239651, 10.949677983539097, 5.982163991769549, 5.13818772694263, 3.6452307956104257, 5.249491648511256, 4.193099230072464, 2.329363966049383, 1.1315786439665476, 0.0),
(14.517840102582454, 12.402893656798973, 11.633146504915409, 12.564391480475042, 10.49719935985368, 5.101848358989992, 5.121662094192959, 4.253638926992837, 5.468821349641823, 2.4317718335619576, 1.8895680735227522, 1.0746659888174948, 0.0, 14.170705268347055, 11.82132587699244, 9.447840367613761, 7.295315500685872, 10.937642699283646, 5.955094497789972, 5.121662094192959, 3.6441773992785653, 5.24859967992684, 4.188130493491681, 2.326629300983082, 1.127535786981725, 0.0),
(14.511097524900102, 12.357614716359132, 11.619125100022863, 12.548627178945251, 10.49455687350386, 5.0996715769953775, 5.104891161677292, 4.234367588782199, 5.462530365035819, 2.4244361257699243, 1.8865437198495683, 1.072767842674817, 0.0, 14.166655842764062, 11.800446269422984, 9.43271859924784, 7.273308377309771, 10.925060730071637, 5.928114624295079, 5.104891161677292, 3.642622554996698, 5.24727843675193, 4.182875726315085, 2.323825020004573, 1.1234195196690122, 0.0),
(14.502234782608697, 12.311554838709677, 11.604760416666666, 12.532026766304348, 10.49107843137255, 5.096816666666667, 5.087882352941177, 4.215166666666667, 5.4559750000000005, 2.4170752941176477, 1.8832383572567788, 1.0708157894736845, 0.0, 14.161328125, 11.778973684210527, 9.416191786283894, 7.251225882352942, 10.911950000000001, 5.901233333333334, 5.087882352941177, 3.6405833333333337, 5.245539215686275, 4.177342255434784, 2.3209520833333337, 1.1192322580645162, 0.0),
(14.491316001669949, 12.264740600247798, 11.590057255944217, 12.514612223228664, 10.486786626859248, 5.0933075267997765, 5.070643091530164, 4.196042562109436, 5.4491642165828384, 2.409689519352323, 1.8796620749404376, 1.0688111768905575, 0.0, 14.154758123285324, 11.75692294579613, 9.398310374702186, 7.229068558056968, 10.898328433165677, 5.8744595869532095, 5.070643091530164, 3.638076804856983, 5.243393313429624, 4.171537407742889, 2.3180114511888434, 1.1149764182043456, 0.0),
(14.478405308045566, 12.21719857737068, 11.575020418952905, 12.496405530394526, 10.481704053363458, 5.089168056190623, 5.053180800989806, 4.177001676573693, 5.4421069768328, 2.402278982221147, 1.8758249620965999, 1.0667553526018982, 0.0, 14.146981845850483, 11.734308878620878, 9.379124810482999, 7.20683694666344, 10.8842139536656, 5.84780234720317, 5.053180800989806, 3.635120040136159, 5.240852026681729, 4.165468510131509, 2.315004083790581, 1.1106544161246077, 0.0),
(14.463566827697262, 12.168955346475506, 11.559654706790123, 12.477428668478263, 10.475853304284678, 5.084422153635118, 5.03550290486565, 4.158050411522635, 5.434812242798353, 2.394843863471315, 1.8717371079213185, 1.0646496642841674, 0.0, 14.138035300925928, 11.711146307125839, 9.358685539606592, 7.184531590413944, 10.869624485596706, 5.821270576131688, 5.03550290486565, 3.63173010973937, 5.237926652142339, 4.159142889492755, 2.311930941358025, 1.10626866786141, 0.0),
(14.44686468658675, 12.12003748395947, 11.543964920553272, 12.457703618156202, 10.469256973022405, 5.079093717929179, 5.017616826703247, 4.139195168419449, 5.427288976527969, 2.3873843438500235, 1.8674086016106486, 1.0624954596138265, 0.0, 14.127954496742113, 11.68745005575209, 9.337043008053241, 7.162153031550069, 10.854577953055937, 5.794873235787229, 5.017616826703247, 3.6279240842351275, 5.234628486511203, 4.152567872718735, 2.3087929841106543, 1.101821589450861, 0.0),
(14.428363010675731, 12.070471566219748, 11.527955861339734, 12.43725236010467, 10.461937652976141, 5.07320664786872, 4.9995299900481465, 4.120442348727329, 5.4195461400701115, 2.3799006041044684, 1.8628495323606438, 1.0602940862673376, 0.0, 14.116775441529496, 11.663234948940712, 9.314247661803218, 7.139701812313404, 10.839092280140223, 5.768619288218261, 4.9995299900481465, 3.623719034191943, 5.230968826488071, 4.145750786701558, 2.305591172267947, 1.0973155969290682, 0.0),
(14.408125925925928, 12.020284169653527, 11.511632330246915, 12.416096875000001, 10.45391793754539, 5.066784842249657, 4.981249818445898, 4.101798353909466, 5.41159269547325, 2.372392824981845, 1.8580699893673582, 1.0580468919211612, 0.0, 14.10453414351852, 11.638515811132772, 9.29034994683679, 7.1171784749455345, 10.8231853909465, 5.742517695473253, 4.981249818445898, 3.6191320301783265, 5.226958968772695, 4.138698958333334, 2.3023264660493834, 1.092753106332139, 0.0),
(14.386217558299041, 11.969501870657995, 11.494999128372202, 12.394259143518521, 10.445220420129644, 5.0598521998679065, 4.962783735442051, 4.0832695854290515, 5.403437604785855, 2.3648611872293506, 1.8530800618268455, 1.0557552242517592, 0.0, 14.091266610939643, 11.613307466769347, 9.265400309134227, 7.094583561688051, 10.80687520957171, 5.716577419600672, 4.962783735442051, 3.61418014276279, 5.222610210064822, 4.131419714506174, 2.2989998256744406, 1.0881365336961817, 0.0),
(14.362702033756786, 11.918151245630337, 11.478061056812987, 12.371761146336556, 10.435867694128408, 5.052432619519382, 4.9441391645821575, 4.064862444749277, 5.395089830056394, 2.35730587159418, 1.847889838935161, 1.0534204309355928, 0.0, 14.07700885202332, 11.587624740291517, 9.239449194675805, 7.071917614782539, 10.790179660112788, 5.690807422648988, 4.9441391645821575, 3.6088804425138443, 5.217933847064204, 4.123920382112186, 2.2956122113625974, 1.0834682950573036, 0.0),
(14.337643478260873, 11.866258870967743, 11.460822916666668, 12.348624864130437, 10.425882352941176, 5.04455, 4.925323529411765, 4.046583333333334, 5.386558333333333, 2.34972705882353, 1.8425094098883579, 1.0510438596491232, 0.0, 14.061796875, 11.561482456140352, 9.212547049441788, 7.049181176470589, 10.773116666666667, 5.665216666666669, 4.925323529411765, 3.60325, 5.212941176470588, 4.11620828804348, 2.2921645833333337, 1.0787508064516131, 0.0),
(14.311106017773009, 11.813851323067393, 11.443289509030638, 12.32487227757649, 10.415286989967456, 5.036228240105676, 4.906344253476426, 4.0284386526444145, 5.3778520766651425, 2.342124929664596, 1.83694886388249, 1.048626858068812, 0.0, 14.045666688100141, 11.53489543875693, 9.18474431941245, 7.026374788993786, 10.755704153330285, 5.63981411370218, 4.906344253476426, 3.5973058857897686, 5.207643494983728, 4.1082907591921645, 2.2886579018061277, 1.0739864839152178, 0.0),
(14.283153778254908, 11.760955178326475, 11.425465635002288, 12.300525367351046, 10.40410419860674, 5.027491238632323, 4.887208760321688, 4.01043480414571, 5.368980022100289, 2.3344996648645746, 1.8312182901136123, 1.0461707738711208, 0.0, 14.028654299554185, 11.507878512582325, 9.156091450568061, 7.0034989945937225, 10.737960044200578, 5.614608725803994, 4.887208760321688, 3.5910651704516594, 5.20205209930337, 4.1001751224503495, 2.2850931270004575, 1.0691777434842251, 0.0),
(14.253850885668278, 11.707597013142175, 11.407356095679013, 12.275606114130436, 10.392356572258533, 5.0183628943758585, 4.867924473493101, 3.9925781893004118, 5.359951131687243, 2.3268514451706617, 1.825327777777778, 1.0436769547325107, 0.0, 14.010795717592593, 11.480446502057614, 9.12663888888889, 6.980554335511984, 10.719902263374486, 5.589609465020577, 4.867924473493101, 3.5845449245541845, 5.196178286129267, 4.091868704710146, 2.281471219135803, 1.0643270011947434, 0.0),
(14.223261465974833, 11.653803403911677, 11.388965692158209, 12.250136498590983, 10.380066704322333, 5.008867106132196, 4.8484988165362175, 3.974875209571713, 5.35077436747447, 2.3191804513300527, 1.8192874160710422, 1.041146748329443, 0.0, 13.992126950445819, 11.452614231623869, 9.09643708035521, 6.957541353990157, 10.70154873494894, 5.564825293400398, 4.8484988165362175, 3.577762218665854, 5.190033352161167, 4.083378832863662, 2.2777931384316417, 1.05943667308288, 0.0),
(14.191449645136279, 11.59960092703217, 11.370299225537268, 12.224138501409021, 10.367257188197637, 4.999027772697253, 4.828939212996585, 3.9573322664228017, 5.341458691510441, 2.311486864089944, 1.8131072941894584, 1.0385815023383795, 0.0, 13.97268400634431, 11.424396525722173, 9.065536470947292, 6.934460592269831, 10.682917383020882, 5.540265172991923, 4.828939212996585, 3.57073412335518, 5.183628594098819, 4.074712833803008, 2.274059845107454, 1.0545091751847429, 0.0),
(14.15847954911433, 11.545016158900838, 11.35136149691358, 12.19763410326087, 10.353950617283953, 4.988868792866941, 4.809253086419753, 3.939955761316873, 5.332013065843622, 2.3037708641975314, 1.8067975013290805, 1.035982564435781, 0.0, 13.95250289351852, 11.39580820879359, 9.033987506645403, 6.9113125925925925, 10.664026131687244, 5.515938065843622, 4.809253086419753, 3.563477709190672, 5.1769753086419765, 4.065878034420291, 2.2702722993827162, 1.0495469235364399, 0.0),
(14.124415303870702, 11.490075675914863, 11.332157307384547, 12.170645284822868, 10.340169584980769, 4.97841406543718, 4.789447860351274, 3.9227520957171165, 5.322446452522482, 2.296032632400011, 1.8003681266859632, 1.0333512822981095, 0.0, 13.931619620198905, 11.366864105279202, 9.001840633429817, 6.888097897200032, 10.644892905044964, 5.491852934003963, 4.789447860351274, 3.556010046740843, 5.1700847924903846, 4.056881761607624, 2.2664314614769094, 1.0445523341740786, 0.0),
(14.089321035367092, 11.434806054471437, 11.312691458047555, 12.143194026771337, 10.325936684687594, 4.967687489203883, 4.769530958336696, 3.905727671086725, 5.312767813595489, 2.2882723494445796, 1.7938292594561607, 1.030689003601826, 0.0, 13.910070194615912, 11.337579039620083, 8.969146297280803, 6.864817048333737, 10.625535627190978, 5.4680187395214155, 4.769530958336696, 3.548348206574202, 5.162968342343797, 4.047731342257113, 2.2625382916095114, 1.0395278231337672, 0.0),
(14.053260869565218, 11.379233870967743, 11.292968750000002, 12.115302309782612, 10.311274509803923, 4.956712962962964, 4.749509803921569, 3.8888888888888893, 5.302986111111112, 2.280490196078432, 1.787190988835726, 1.027997076023392, 0.0, 13.887890625, 11.30796783625731, 8.93595494417863, 6.841470588235294, 10.605972222222224, 5.4444444444444455, 4.749509803921569, 3.54050925925926, 5.155637254901961, 4.0384341032608715, 2.2585937500000006, 1.0344758064516133, 0.0),
(14.016298932426789, 11.323385701800964, 11.272993984339278, 12.086992114533015, 10.296205653729254, 4.945514385510339, 4.729391820651443, 3.8722421505868017, 5.293110307117818, 2.2726863530487647, 1.7804634040207143, 1.025276847239269, 0.0, 13.865116919581618, 11.278045319631957, 8.902317020103572, 6.818059059146293, 10.586220614235636, 5.4211390108215225, 4.729391820651443, 3.5325102753645283, 5.148102826864627, 4.0289973715110055, 2.254598796867856, 1.0293987001637241, 0.0),
(13.978499349913523, 11.267288123368292, 11.252771962162782, 12.058285421698875, 10.280752709863094, 4.934115655641925, 4.709184432071869, 3.8557938576436523, 5.2831493636640765, 2.2648610011027737, 1.7736565942071794, 1.0225296649259181, 0.0, 13.841785086591221, 11.247826314185097, 8.868282971035896, 6.79458300330832, 10.566298727328153, 5.398111400701113, 4.709184432071869, 3.524368325458518, 5.140376354931547, 4.019428473899626, 2.2505543924325564, 1.0242989203062085, 0.0),
(13.939926247987117, 11.210967712066907, 11.232307484567903, 12.029204211956525, 10.264938271604938, 4.9225406721536356, 4.688895061728395, 3.839550411522634, 5.273112242798354, 2.2570143209876545, 1.7667806485911755, 1.019756876759801, 0.0, 13.81793113425926, 11.217325644357809, 8.833903242955877, 6.771042962962962, 10.546224485596708, 5.375370576131688, 4.688895061728395, 3.5161004801097393, 5.132469135802469, 4.009734737318842, 2.246461496913581, 1.0191788829151736, 0.0),
(13.900643752609293, 11.154451044293994, 11.211605352652038, 11.999770465982289, 10.248784932354287, 4.910813333841387, 4.6685311331665735, 3.8235182136869392, 5.263007906569121, 2.2491464934506045, 1.7598456563687561, 1.016959830417379, 0.0, 13.793591070816188, 11.186558134591166, 8.79922828184378, 6.747439480351812, 10.526015813138242, 5.3529254991617155, 4.6685311331665735, 3.5077238098867047, 5.124392466177143, 3.9999234886607637, 2.2423210705304077, 1.014041004026727, 0.0),
(13.860715989741754, 11.097764696446747, 11.190670367512576, 11.970006164452498, 10.232315285510639, 4.898957539501094, 4.648100069931951, 3.807703665599757, 5.252845317024844, 2.241257699238818, 1.752861706735976, 1.014139873575113, 0.0, 13.768800904492457, 11.155538609326241, 8.764308533679879, 6.723773097716453, 10.505690634049689, 5.33078513183966, 4.648100069931951, 3.499255385357924, 5.1161576427553195, 3.9900020548175, 2.2381340735025153, 1.0088876996769771, 0.0),
(13.820207085346219, 11.040935244922345, 11.169507330246915, 11.93993328804348, 10.215551924473493, 4.88699718792867, 4.62760929557008, 3.7921131687242804, 5.242633436213992, 2.2333481190994924, 1.7458388888888892, 1.0112983539094653, 0.0, 13.74359664351852, 11.124281893004117, 8.729194444444445, 6.700044357298475, 10.485266872427983, 5.3089584362139925, 4.62760929557008, 3.490712277091907, 5.1077759622367465, 3.9799777626811608, 2.2339014660493834, 1.0037213859020315, 0.0),
(13.779181165384388, 10.983989266117973, 11.148121041952448, 11.909573817431562, 10.198517442642354, 4.8749561779200326, 4.60706623362651, 3.7767531245237014, 5.2323812261850335, 2.2254179337798226, 1.7387872920235496, 1.0084366190968967, 0.0, 13.718014296124831, 11.09280281006586, 8.693936460117747, 6.676253801339467, 10.464762452370067, 5.287454374333182, 4.60706623362651, 3.482111555657166, 5.099258721321177, 3.969857939143855, 2.2296242083904896, 0.9985444787379977, 0.0),
(13.737702355817978, 10.926953336430817, 11.126516303726566, 11.878949733293078, 10.181234433416716, 4.862858408271099, 4.58647830764679, 3.7616299344612103, 5.222097648986434, 2.2174673240270053, 1.7317170053360116, 1.0055560168138682, 0.0, 13.69208987054184, 11.06111618495255, 8.658585026680058, 6.652401972081014, 10.444195297972868, 5.266281908245695, 4.58647830764679, 3.4734702916222133, 5.090617216708358, 3.9596499110976935, 2.2253032607453136, 0.9933593942209834, 0.0),
(13.695834782608697, 10.869854032258065, 11.10469791666667, 11.848083016304349, 10.163725490196079, 4.850727777777779, 4.5658529411764714, 3.7467500000000005, 5.211791666666667, 2.2094964705882356, 1.724638118022329, 1.0026578947368423, 0.0, 13.665859375000002, 11.029236842105265, 8.623190590111644, 6.628489411764706, 10.423583333333333, 5.245450000000001, 4.5658529411764714, 3.4648055555555564, 5.081862745098039, 3.949361005434784, 2.220939583333334, 0.988168548387097, 0.0),
(13.653642571718258, 10.8127179299969, 11.082670681870143, 11.816995647141708, 10.146013206379946, 4.8385881852359915, 4.545197557761102, 3.732119722603262, 5.201472241274196, 2.201505554210711, 1.717560719278556, 0.9997436005422796, 0.0, 13.639358817729768, 10.997179605965075, 8.58780359639278, 6.6045166626321326, 10.402944482548392, 5.224967611644567, 4.545197557761102, 3.456134418025708, 5.073006603189973, 3.938998549047237, 2.2165341363740287, 0.9829743572724456, 0.0),
(13.611189849108369, 10.755571606044516, 11.060439400434387, 11.785709606481484, 10.128120175367815, 4.82646352944165, 4.524519580946234, 3.7177455037341867, 5.191148334857491, 2.1934947556416264, 1.7104948983007466, 0.9968144819066413, 0.0, 13.612624206961591, 10.964959300973053, 8.552474491503732, 6.580484266924878, 10.382296669714982, 5.204843705227861, 4.524519580946234, 3.4474739496011786, 5.064060087683908, 3.928569868827162, 2.2120878800868775, 0.977779236913138, 0.0),
(13.568540740740744, 10.698441636798089, 11.038008873456791, 11.754246875000002, 10.110068990559187, 4.814377709190674, 4.503826434277415, 3.7036337448559675, 5.180828909465021, 2.1854642556281783, 1.7034507442849551, 0.9938718865063897, 0.0, 13.585691550925928, 10.932590751570284, 8.517253721424776, 6.556392766884533, 10.361657818930041, 5.185087242798355, 4.503826434277415, 3.438841220850481, 5.055034495279593, 3.918082291666668, 2.207601774691358, 0.972585603345281, 0.0),
(13.525759372577088, 10.641354598654807, 11.015383902034753, 11.722629433373593, 10.09188224535356, 4.802354623278973, 4.483125541300197, 3.689790847431795, 5.170522927145252, 2.1774142349175616, 1.696438346427236, 0.9909171620179854, 0.0, 13.558596857853223, 10.900088782197837, 8.482191732136178, 6.532242704752683, 10.341045854290504, 5.1657071864045125, 4.483125541300197, 3.4302533023421233, 5.04594112267678, 3.907543144457865, 2.2030767804069504, 0.9673958726049827, 0.0),
(13.482909870579116, 10.58433706801186, 10.992569287265662, 11.690879262278584, 10.073582533150434, 4.790418170502465, 4.462424325560129, 3.6762232129248593, 5.160239349946655, 2.1693448742569736, 1.689467793923642, 0.9879516561178898, 0.0, 13.53137613597394, 10.867468217296787, 8.447338969618208, 6.50803462277092, 10.32047869989331, 5.146712498094804, 4.462424325560129, 3.421727264644618, 5.036791266575217, 3.896959754092862, 2.1985138574531327, 0.9622124607283511, 0.0),
(13.440056360708535, 10.527415621266428, 10.969569830246915, 11.659018342391304, 10.05519244734931, 4.778592249657065, 4.441730210602761, 3.662937242798354, 5.1499871399176955, 2.1612563543936103, 1.682549175970229, 0.9849767164825647, 0.0, 13.50406539351852, 10.83474388130821, 8.412745879851144, 6.48376906318083, 10.299974279835391, 5.128112139917696, 4.441730210602761, 3.4132801783264752, 5.027596223674655, 3.886339447463769, 2.1939139660493834, 0.9570377837514936, 0.0),
(13.39726296892706, 10.470616834815702, 10.946390332075904, 11.627068654388085, 10.036734581349688, 4.766900759538689, 4.4210506199736415, 3.6499393385154706, 5.139775259106843, 2.153148856074666, 1.67569258176305, 0.9819936907884712, 0.0, 13.476700638717421, 10.801930598673183, 8.378462908815248, 6.459446568223997, 10.279550518213686, 5.109915073921659, 4.4210506199736415, 3.4049291139562063, 5.018367290674844, 3.875689551462696, 2.189278066415181, 0.9518742577105185, 0.0),
(13.3545938211964, 10.413967285056863, 10.923035593850026, 11.59505217894525, 10.018231528551063, 4.755367598943252, 4.400392977218323, 3.6372359015394005, 5.129612669562567, 2.145022560047339, 1.6689081004981592, 0.9790039267120707, 0.0, 13.449317879801098, 10.769043193832776, 8.344540502490794, 6.435067680142016, 10.259225339125134, 5.092130262155161, 4.400392977218323, 3.3966911421023225, 5.009115764275531, 3.865017392981751, 2.1846071187700056, 0.9467242986415331, 0.0),
(13.312113043478263, 10.357493548387097, 10.899510416666669, 11.562990896739132, 9.999705882352941, 4.744016666666668, 4.379764705882353, 3.6248333333333345, 5.119508333333334, 2.1368776470588244, 1.662205821371611, 0.9760087719298248, 0.0, 13.421953125000002, 10.736096491228071, 8.311029106858054, 6.4106329411764715, 10.239016666666668, 5.074766666666668, 4.379764705882353, 3.3885833333333344, 4.999852941176471, 3.854330298913045, 2.179902083333334, 0.9415903225806455, 0.0),
(13.26988476173436, 10.301222201203595, 10.87581960162323, 11.530906788446053, 9.98118023615482, 4.732871861504853, 4.359173229511284, 3.612738035360464, 5.109471212467612, 2.1287142978563174, 1.6555958335794598, 0.9730095741181947, 0.0, 13.394642382544584, 10.70310531530014, 8.277979167897298, 6.386142893568951, 10.218942424935223, 5.05783324950465, 4.359173229511284, 3.3806227582177515, 4.99059011807741, 3.8436355961486854, 2.1751639203246462, 0.9364747455639633, 0.0),
(13.227973101926404, 10.245179819903537, 10.851967949817103, 11.498821834742351, 9.962677183356197, 4.721957082253722, 4.3386259716506625, 3.6009564090839814, 5.099510269013869, 2.1205326931870148, 1.6490882263177586, 0.9700076809536419, 0.0, 13.367421660665297, 10.670084490490058, 8.245441131588793, 6.361598079561043, 10.199020538027739, 5.041338972717574, 4.3386259716506625, 3.372826487324087, 4.981338591678099, 3.832940611580785, 2.170393589963421, 0.9313799836275944, 0.0),
(13.186442190016104, 10.189392980884113, 10.827960262345682, 11.46675801630435, 9.944219317356573, 4.711296227709192, 4.318130355846042, 3.5894948559670787, 5.089634465020577, 2.1123330137981124, 1.6426930887825626, 0.9670044401126275, 0.0, 13.340326967592594, 10.6370488412389, 8.213465443912813, 6.336999041394336, 10.179268930041154, 5.02529279835391, 4.318130355846042, 3.3652115912208513, 4.972109658678287, 3.8222526721014507, 2.1655920524691368, 0.9263084528076467, 0.0),
(13.14535615196517, 10.133888260542502, 10.803801340306359, 11.434737313808373, 9.925829231555449, 4.700913196667176, 4.297693805642971, 3.5783597774729468, 5.079852762536198, 2.1041154404368063, 1.6364205101699256, 0.9640011992716131, 0.0, 13.313394311556928, 10.604013191987741, 8.182102550849628, 6.312346321310418, 10.159705525072397, 5.0097036884621255, 4.297693805642971, 3.357795140476554, 4.962914615777724, 3.8115791046027923, 2.160760268061272, 0.9212625691402275, 0.0),
(13.104705913184263, 10.078784894108638, 10.779554132960747, 11.402825576616644, 9.907497301495457, 4.690826978191853, 4.277368174559739, 3.5675806651220205, 5.07019931192069, 2.095906657814456, 1.6302822447690024, 0.9610058425921835, 0.0, 13.286621461180511, 10.571064268514016, 8.151411223845011, 6.287719973443367, 10.14039862384138, 4.9946129311708285, 4.277368174559739, 3.3505906987084666, 4.953748650747729, 3.8009418588722155, 2.15591082659215, 0.9162531721916946, 0.0),
(13.064073257060091, 10.024626385524439, 10.755553287525224, 11.371278892341204, 9.88903379759524, 4.681014596966087, 4.257412745887406, 3.557289901377987, 5.060822216666095, 2.0878603087694745, 1.6242903453264128, 0.9580564200798471, 0.0, 13.25978557982405, 10.538620620878318, 8.121451726632063, 6.263580926308422, 10.12164443333219, 4.980205861929182, 4.257412745887406, 3.3435818549757763, 4.94451689879762, 3.790426297447069, 2.1511106575050447, 0.9113296714113127, 0.0),
(13.023338864205595, 9.97143223830991, 10.731813088158539, 11.340088730440868, 9.870380499362694, 4.671450535207326, 4.2378417551340934, 3.547484881662581, 5.051724990045435, 2.0799888647958276, 1.6184360526663222, 0.9551543846318662, 0.0, 13.232809284324528, 10.506698230950526, 8.09218026333161, 6.239966594387481, 10.10344998009087, 4.966478834327614, 4.2378417551340934, 3.336750382290947, 4.935190249681347, 3.780029576813624, 2.146362617631708, 0.9064938398463556, 0.0),
(12.982451822532688, 9.919124960991017, 10.708287554981187, 11.309199457779725, 9.851509291291528, 4.662112249784464, 4.218623372269525, 3.5381385158577467, 5.042884624972988, 2.072277675457342, 1.6127080506300124, 0.9522943730401906, 0.0, 13.205650163658248, 10.475238103442095, 8.063540253150062, 6.216833026372026, 10.085769249945976, 4.953393922200846, 4.218623372269525, 3.330080178417474, 4.925754645645764, 3.7697331525932425, 2.1416575109962372, 0.9017386328173653, 0.0),
(12.941361219953283, 9.867627062093726, 10.68493070811365, 11.278555441221856, 9.832392057875436, 4.652977197566394, 4.199725767263427, 3.529223713845425, 5.034278114363028, 2.0647120903178457, 1.6070950230587664, 0.949471022096771, 0.0, 13.178265806801516, 10.44418124306448, 8.035475115293831, 6.1941362709535355, 10.068556228726056, 4.940913199383595, 4.199725767263427, 3.3235551411188533, 4.916196028937718, 3.7595184804072863, 2.1369861416227303, 0.8970570056448843, 0.0),
(12.900016144379297, 9.816861050144, 10.66169656767643, 11.248101047631351, 9.81300068360812, 4.644022835422014, 4.181117110085521, 3.5207133855075567, 5.025882451129837, 2.0572774589411664, 1.6015856537938657, 0.9466789685935577, 0.0, 13.150613802730636, 10.413468654529133, 8.007928268969328, 6.171832376823498, 10.051764902259674, 4.92899873971058, 4.181117110085521, 3.317159168158581, 4.90650034180406, 3.7493670158771177, 2.132339313535286, 0.8924419136494547, 0.0),
(12.858365683722639, 9.766749433667803, 10.638539153790012, 11.217780643872292, 9.793307052983273, 4.635226620220214, 4.162765570705529, 3.512580440726085, 5.017674628187687, 2.0499591308911307, 1.5961686266765933, 0.9439128493225009, 0.0, 13.122651740421906, 10.383041342547507, 7.980843133382966, 6.149877392673391, 10.035349256375374, 4.91761261701652, 4.162765570705529, 3.310876157300153, 4.896653526491637, 3.7392602146240983, 2.1277078307580024, 0.8878863121516185, 0.0),
(12.816358925895228, 9.717214721191104, 10.61541248657489, 11.187538596808764, 9.773283050494598, 4.626566008829889, 4.144639319093177, 3.5047977893829505, 5.009631638450861, 2.0427424557315677, 1.5908326255482306, 0.9411673010755515, 0.0, 13.094337208851638, 10.352840311831065, 7.954163127741153, 6.128227367194702, 10.019263276901722, 4.906716905136131, 4.144639319093177, 3.3046900063070637, 4.886641525247299, 3.729179532269589, 2.1230824973149782, 0.8833831564719186, 0.0),
(12.773944958808976, 9.668179421239865, 10.592270586151553, 11.157319273304857, 9.75290056063579, 4.618018458119934, 4.126706525218187, 3.4973383413600962, 5.001730474833633, 2.035612783026304, 1.5855663342500608, 0.9384369606446594, 0.0, 13.065627796996127, 10.322806567091252, 7.927831671250303, 6.106838349078911, 10.003460949667266, 4.8962736779041345, 4.126706525218187, 3.29858461294281, 4.876450280317895, 3.719106424434953, 2.118454117230311, 0.878925401930897, 0.0),
(12.731072870375797, 9.61956604234005, 10.569067472640498, 11.127067040224649, 9.732131467900551, 4.609561424959241, 4.108935359050283, 3.490175006539462, 4.993948130250281, 2.0285554623391677, 1.5803584366233656, 0.9357164648217753, 0.0, 13.036481093831679, 10.292881113039527, 7.901792183116827, 6.085666387017502, 9.987896260500563, 4.886245009155247, 4.108935359050283, 3.2925438749708866, 4.8660657339502755, 3.7090223467415506, 2.1138134945280997, 0.8745060038490956, 0.0),
(12.687691748507607, 9.571297093017627, 10.54575716616221, 11.09672626443223, 9.71094765678258, 4.601172366216706, 4.091293990559188, 3.4832806948029904, 4.986261597615085, 2.021555843233986, 1.5751976165094272, 0.9330004503988493, 0.0, 13.0068546883346, 10.263004954387341, 7.875988082547136, 6.064667529701957, 9.97252319523017, 4.876592972724187, 4.091293990559188, 3.28655169015479, 4.85547382839129, 3.698908754810744, 2.109151433232442, 0.8701179175470571, 0.0),
(12.643750681116316, 9.523295081798558, 10.522293686837184, 11.066241312791686, 9.689321011775569, 4.592828738761221, 4.073750589714624, 3.476628316032624, 4.97864786984232, 2.014599275274587, 1.5700725577495283, 0.9302835541678323, 0.0, 12.976706169481197, 10.233119095846153, 7.85036278874764, 6.04379782582376, 9.95729573968464, 4.8672796424456735, 4.073750589714624, 3.280591956258015, 4.844660505887784, 3.6887471042638964, 2.104458737367437, 0.8657540983453236, 0.0),
(12.599198756113843, 9.475482517208812, 10.498631054785912, 11.0355565521671, 9.667223417373222, 4.584507999461682, 4.056273326486318, 3.4701907801103036, 4.971083939846263, 2.0076711080247973, 1.5649719441849508, 0.927560412920674, 0.0, 12.94599312624776, 10.203164542127412, 7.824859720924753, 6.023013324074391, 9.942167879692526, 4.858267092154425, 4.056273326486318, 3.2746485710440583, 4.833611708686611, 3.678518850722367, 2.0997262109571824, 0.8614075015644376, 0.0),
(12.553985061412101, 9.427781907774351, 10.474723290128884, 11.004616349422557, 9.644626758069233, 4.5761876051869805, 4.038830370843989, 3.463940996917971, 4.963546800541195, 2.0007566910484456, 1.5598844596569765, 0.9248256634493257, 0.0, 12.91467314761061, 10.173082297942582, 7.799422298284883, 6.002270073145335, 9.92709360108239, 4.849517395685159, 4.038830370843989, 3.268705432276415, 4.822313379034616, 3.66820544980752, 2.094944658025777, 0.8570710825249411, 0.0),
(12.508058684923006, 9.380115762021138, 10.450524412986589, 10.973365071422144, 9.621502918357304, 4.567845012806012, 4.021389892757366, 3.4578518763375685, 4.95601344484139, 1.993841373909359, 1.5547987880068885, 0.9220739425457369, 0.0, 12.88270382254604, 10.142813368003106, 7.773993940034442, 5.981524121728076, 9.91202688968278, 4.8409926268725965, 4.021389892757366, 3.26274643771858, 4.810751459178652, 3.6577883571407157, 2.090104882597318, 0.8527377965473764, 0.0),
(12.461368714558466, 9.332406588475143, 10.425988443479525, 10.941747085029949, 9.597823782731137, 4.5594576791876715, 4.003920062196168, 3.451896328251037, 4.948460865661126, 1.986910506171365, 1.5497036130759692, 0.9192998870018588, 0.0, 12.850042740030352, 10.112298757020445, 7.748518065379845, 5.960731518514094, 9.896921731322252, 4.832654859551452, 4.003920062196168, 3.2567554851340508, 4.798911891365568, 3.6472490283433174, 2.085197688695905, 0.8484005989522859, 0.0),
(12.413864238230394, 9.284576895662326, 10.401069401728181, 10.909706757110053, 9.573561235684425, 4.551003061200851, 3.9863890491301195, 3.446047262540319, 4.9408660559146815, 1.9799494373982915, 1.5445876187055003, 0.916498133609641, 0.0, 12.816647489039854, 10.08147946970605, 7.7229380935275005, 5.939848312194873, 9.881732111829363, 4.824466167556446, 3.9863890491301195, 3.250716472286322, 4.786780617842212, 3.636568919036685, 2.0802138803456365, 0.8440524450602116, 0.0),
(12.365494343850713, 9.236549192108656, 10.375721307853043, 10.877188454526541, 9.548687161710866, 4.542458615714445, 3.968765023528944, 3.440277589087355, 4.933206008516334, 1.9729435171539655, 1.539439488736764, 0.9136633191610346, 0.0, 12.78247565855085, 10.050296510771378, 7.697197443683819, 5.9188305514618955, 9.866412017032667, 4.816388624722297, 3.968765023528944, 3.244613296938889, 4.774343580855433, 3.6257294848421813, 2.075144261570609, 0.8396862901916962, 0.0),
(12.316208119331334, 9.188245986340096, 10.349898181974611, 10.8441365441435, 9.523173445304161, 4.533801799597346, 3.9510161553623666, 3.4345602177740875, 4.92545771638036, 1.9658780950022154, 1.5342479070110426, 0.9107900804479897, 0.0, 12.747484837539638, 10.018690884927885, 7.671239535055213, 5.897634285006645, 9.85091543276072, 4.808384304883723, 3.9510161553623666, 3.238429856855247, 4.761586722652081, 3.614712181381168, 2.0699796363949226, 0.8352950896672816, 0.0),
(12.265954652584163, 9.139589786882611, 10.32355404421337, 10.810495392825016, 9.49699197095801, 4.525010069718451, 3.9331106146001082, 3.4288680584824593, 4.917598172421039, 1.9587385205068681, 1.5290015573696185, 0.9078730542624567, 0.0, 12.711632614982527, 9.986603596887022, 7.645007786848092, 5.876215561520603, 9.835196344842078, 4.800415281875443, 3.9331106146001082, 3.2321500497988938, 4.748495985479005, 3.6034984642750065, 2.0647108088426744, 0.8308717988075103, 0.0),
(12.21468303152113, 9.090503102262165, 10.296642914689816, 10.776209367435175, 9.470114623166108, 4.516060882946651, 3.915016571211893, 3.4231740210944106, 4.909604369552646, 1.9515101432317519, 1.5236891236537742, 0.904906877396386, 0.0, 12.674876579855821, 9.953975651360244, 7.618445618268871, 5.854530429695254, 9.819208739105292, 4.792443629532175, 3.915016571211893, 3.2257577735333225, 4.735057311583054, 3.5920697891450595, 2.059328582937963, 0.8264093729329243, 0.0),
(12.162342344054133, 9.040908441004726, 10.26911881352444, 10.741222834838059, 9.442513286422153, 4.5069316961508425, 3.896702195167445, 3.4174510154918845, 4.90145330068946, 1.9441783127406937, 1.518299289704792, 0.9018861866417278, 0.0, 12.637174321135817, 9.920748053059004, 7.5914964485239596, 5.83253493822208, 9.80290660137892, 4.784431421688638, 3.896702195167445, 3.21923692582203, 4.721256643211077, 3.5804076116126873, 2.053823762704888, 0.8219007673640661, 0.0),
(12.108881678095097, 8.990728311636257, 10.24093576083773, 10.705480161897759, 9.414159845219846, 4.4975999661999175, 3.8781356564364877, 3.4116719515568206, 4.893121958745757, 1.9367283785975222, 1.5128207393639534, 0.898805618790433, 0.0, 12.59848342779883, 9.88686180669476, 7.5641036968197675, 5.810185135792565, 9.786243917491515, 4.776340732179549, 3.8781356564364877, 3.212571404428512, 4.707079922609923, 3.5684933872992537, 2.048187152167546, 0.817338937421478, 0.0),
(12.05425012155593, 8.93988522268272, 10.212047776750177, 10.668925715478352, 9.385026184052883, 4.488043149962771, 3.8592851249887445, 3.4058097391711617, 4.884587336635816, 1.9291456903660635, 1.5072421564725416, 0.8956598106344515, 0.0, 12.558761488821151, 9.852257916978965, 7.536210782362707, 5.787437071098189, 9.769174673271632, 4.768133634839627, 3.8592851249887445, 3.205745107116265, 4.6925130920264415, 3.556308571826118, 2.042409555350036, 0.812716838425702, 0.0),
(11.998396762348548, 8.888301682670086, 10.18240888138228, 10.631503862443932, 9.355084187414965, 4.478238704308296, 3.8401187707939393, 3.399837288216851, 4.875826427273916, 1.9214155976101461, 1.5015522248718383, 0.8924433989657341, 0.0, 12.517966093179089, 9.816877388623073, 7.507761124359191, 5.764246792830437, 9.751652854547832, 4.759772203503592, 3.8401187707939393, 3.1987419316487826, 4.6775420937074825, 3.543834620814645, 2.036481776276456, 0.8080274256972807, 0.0),
(11.941270688384867, 8.835900200124316, 10.15197309485452, 10.593158969658578, 9.32430573979979, 4.4681640861053875, 3.8206047638217933, 3.393727508575828, 4.8668162235743315, 1.913523449893597, 1.4957396284031257, 0.889151020576231, 0.0, 12.476054829848946, 9.78066122633854, 7.478698142015627, 5.740570349680789, 9.733632447148663, 4.751218512006159, 3.8206047638217933, 3.1915457757895624, 4.662152869899895, 3.5310529898861933, 2.0303946189709046, 0.8032636545567561, 0.0),
(11.882820987576796, 8.782603283571376, 10.120694437287398, 10.553835403986378, 9.292662725701055, 4.457796752222938, 3.800711274042032, 3.3874533101300353, 4.85753371845134, 1.9054545967802445, 1.4897930509076862, 0.8857773122578926, 0.0, 12.432985287807028, 9.743550434836816, 7.448965254538431, 5.716363790340733, 9.71506743690268, 4.742434634182049, 3.800711274042032, 3.184140537302099, 4.646331362850527, 3.517945134662127, 2.0241388874574797, 0.7984184803246707, 0.0),
(11.822996747836257, 8.72833344153723, 10.088526928801404, 10.513477532291418, 9.26012702961246, 4.447114159529844, 3.780406471424378, 3.3809876027614147, 4.847955904819222, 1.8971943878339157, 1.4837011762268022, 0.8823169108026693, 0.0, 12.38871505602964, 9.70548601882936, 7.41850588113401, 5.691583163501746, 9.695911809638444, 4.733382643865981, 3.780406471424378, 3.176510113949888, 4.63006351480623, 3.5044925107638067, 2.017705385760281, 0.7934848583215663, 0.0),
(11.761747057075162, 8.673013182547843, 10.055424589517022, 10.472029721437782, 9.226670536027703, 4.436093764894997, 3.7596585259385567, 3.374303296351908, 4.838059775592251, 1.8887281726184386, 1.477452688201756, 0.8787644530025115, 0.0, 12.34320172349308, 9.666408983027624, 7.38726344100878, 5.6661845178553145, 9.676119551184502, 4.724024614892672, 3.7596585259385567, 3.168638403496426, 4.613335268013851, 3.490676573812595, 2.0110849179034047, 0.7884557438679859, 0.0),
(11.69902100320542, 8.616565015129181, 10.02134143955475, 10.429436338289557, 9.192265129440482, 4.424713025187291, 3.7384356075542886, 3.367373300783457, 4.827822323684707, 1.8800413006976404, 1.4710362706738296, 0.8751145756493696, 0.0, 12.296402879173653, 9.626260332143064, 7.355181353369148, 5.64012390209292, 9.655644647369414, 4.71432262109684, 3.7384356075542886, 3.160509303705208, 4.596132564720241, 3.4764787794298533, 2.0042682879109504, 0.7833240922844712, 0.0),
(11.634767674138946, 8.558911447807208, 9.986231499035082, 10.385641749710825, 9.156882694344494, 4.412949397275621, 3.7167058862412983, 3.360170525938002, 4.817220542010869, 1.871119121635349, 1.4644406074843055, 0.8713619155351939, 0.0, 12.248276112047666, 9.584981070887132, 7.322203037421526, 5.6133573649060455, 9.634441084021738, 4.704238736313203, 3.7167058862412983, 3.1521067123397293, 4.578441347172247, 3.4618805832369426, 1.9972462998070164, 0.7780828588915646, 0.0),
(11.56893615778766, 8.499974989107892, 9.950048788078501, 10.340590322565676, 9.12049511523344, 4.400780338028881, 3.6944375319693092, 3.3526678816974873, 4.806231423485011, 1.8619469849953916, 1.4576543824744654, 0.867501109451935, 0.0, 12.198779011091421, 9.542512203971285, 7.288271912372326, 5.585840954986173, 9.612462846970022, 4.693735034376482, 3.6944375319693092, 3.1434145271634857, 4.56024755761672, 3.446863440855226, 1.9900097576157, 0.7727249990098085, 0.0),
(11.501475542063469, 8.439678147557194, 9.912747326805505, 10.294226423718191, 9.083074276601018, 4.388183304315964, 3.6715987147080456, 3.344838277943853, 4.794831961021412, 1.8525102403415963, 1.4506662794855925, 0.8635267941915434, 0.0, 12.14786916528122, 9.498794736106976, 7.253331397427962, 5.557530721024787, 9.589663922042824, 4.682773589121394, 3.6715987147080456, 3.1344166459399743, 4.541537138300509, 3.4314088079060645, 1.9825494653611013, 0.7672434679597451, 0.0),
(11.432334914878291, 8.377943431681082, 9.874281135336586, 10.246494420032459, 9.044592062940927, 4.375135753005765, 3.6481576044272312, 3.336654624559041, 4.782999147534349, 1.8427942372377903, 1.4434649823589683, 0.8594336065459691, 0.0, 12.095504163593366, 9.453769672005658, 7.21732491179484, 5.52838271171337, 9.565998295068699, 4.671316474382658, 3.6481576044272312, 3.125096966432689, 4.522296031470463, 3.41549814001082, 1.9748562270673173, 0.7616312210619166, 0.0),
(11.361463364144042, 8.314693350005518, 9.83460423379223, 10.19733867837256, 9.005020358746862, 4.361615140967176, 3.6240823710965873, 3.3280898314249927, 4.770709975938102, 1.8327843252478015, 1.4360391749358754, 0.855216183307163, 0.0, 12.041641595004167, 9.407378016378791, 7.180195874679377, 5.498352975743403, 9.541419951876204, 4.65932576399499, 3.6240823710965873, 3.1154393864051255, 4.502510179373431, 3.3991128927908543, 1.966920846758446, 0.7558812136368653, 0.0),
(11.288809977772631, 8.24985041105647, 9.793670642292932, 10.146703565602587, 8.964331048512523, 4.347598925069094, 3.599341184685839, 3.3191168084236504, 4.757941439146947, 1.822465853935457, 1.428377541057596, 0.8508691612670749, 0.0, 11.986239048489919, 9.359560773937822, 7.141887705287981, 5.4673975618063695, 9.515882878293894, 4.646763531793111, 3.599341184685839, 3.105427803620781, 4.482165524256262, 3.38223452186753, 1.9587341284585866, 0.7499864010051337, 0.0),
(11.214323843675977, 8.1833371233599, 9.751434380959186, 10.094533448586619, 8.922496016731612, 4.33306456218041, 3.573902215164709, 3.3097084654369557, 4.744670530075158, 1.8118241728645852, 1.4204687645654126, 0.8463871772176558, 0.0, 11.929254113026934, 9.310258949394212, 7.102343822827062, 5.4354725185937545, 9.489341060150316, 4.6335918516117385, 3.573902215164709, 3.09504611584315, 4.461248008365806, 3.3648444828622073, 1.950286876191837, 0.7439397384872637, 0.0),
(11.137954049765991, 8.115075995441773, 9.707849469911476, 10.040772694188746, 8.879487147897825, 4.317989509170021, 3.5477336325029207, 3.29983771234685, 4.730874241637018, 1.8008446315990123, 1.412301529300607, 0.8417648679508558, 0.0, 11.870644377591507, 9.259413547459413, 7.061507646503035, 5.402533894797036, 9.461748483274036, 4.61977279728559, 3.5477336325029207, 3.084278220835729, 4.439743573948912, 3.3469242313962493, 1.9415698939822956, 0.7377341814037977, 0.0),
(11.059649683954586, 8.044989535828057, 9.6628699292703, 9.985365669273047, 8.835276326504857, 4.302351222906816, 3.5208036066701984, 3.2894774590352758, 4.716529566746802, 1.789512579702568, 1.4038645191044614, 0.8369968702586252, 0.0, 11.810367431159946, 9.206965572844876, 7.019322595522306, 5.368537739107703, 9.433059133493604, 4.605268442649386, 3.5208036066701984, 3.0731080163620117, 4.417638163252429, 3.3284552230910167, 1.9325739858540603, 0.731362685075278, 0.0),
(10.979359834153682, 7.973000253044715, 9.616449779156152, 9.928256740703617, 8.789835437046412, 4.286127160259694, 3.4930803076362653, 3.2786006153841747, 4.701613498318786, 1.7778133667390779, 1.3951464178182584, 0.8320778209329146, 0.0, 11.748380862708558, 9.15285603026206, 6.975732089091292, 5.333440100217232, 9.403226996637573, 4.590040861537845, 3.4930803076362653, 3.061519400185496, 4.394917718523206, 3.309418913567873, 1.9232899558312306, 0.7248182048222469, 0.0),
(10.897033588275185, 7.899030655617714, 9.568543039689514, 9.86939027534453, 8.743136364016186, 4.269294778097547, 3.4645319053708437, 3.2671800912754865, 4.686103029267251, 1.7657323422723707, 1.3861359092832806, 0.8270023567656742, 0.0, 11.68464226121364, 9.097025924422415, 6.930679546416402, 5.297197026817111, 9.372206058534502, 4.574052127785681, 3.4645319053708437, 3.049496270069676, 4.371568182008093, 3.2897967584481775, 1.9137086079379029, 0.7180936959652467, 0.0),
(10.81262003423102, 7.823003252073014, 9.519103730990887, 9.80871064005988, 8.695150991907875, 4.251831533289268, 3.43512656984366, 3.2551887965911552, 4.6699751525064706, 1.7532548558662742, 1.3768216773408095, 0.8217651145488547, 0.0, 11.6191092156515, 9.0394162600374, 6.884108386704048, 5.259764567598821, 9.339950305012941, 4.557264315227617, 3.43512656984366, 3.037022523778049, 4.347575495953937, 3.2695702133532945, 1.9038207461981775, 0.7111821138248196, 0.0),
(10.72606825993309, 7.744840550936584, 9.468085873180756, 9.746162201713748, 8.645851205215184, 4.233714882703753, 3.404832471024433, 3.2425996412131215, 4.653206860950727, 1.7403662570846146, 1.3671924058321279, 0.8163607310744064, 0.0, 11.551739314998438, 8.97996804181847, 6.8359620291606396, 5.221098771253843, 9.306413721901453, 4.53963949769837, 3.404832471024433, 3.0240820590741087, 4.322925602607592, 3.2487207339045834, 1.8936171746361512, 0.7040764137215078, 0.0),
(10.637327353293314, 7.664465060734389, 9.415443486379615, 9.68168932717022, 8.595208888431804, 4.214922283209894, 3.37361777888289, 3.2293855350233276, 4.635775147514292, 1.727051895491221, 1.357236778598518, 0.8107838431342794, 0.0, 11.48249014823076, 8.918622274477073, 6.7861838929925895, 5.181155686473662, 9.271550295028584, 4.521139749032659, 3.37361777888289, 3.0106587737213526, 4.297604444215902, 3.2272297757234076, 1.8830886972759233, 0.6967695509758537, 0.0),
(10.546346402223609, 7.581799289992394, 9.361130590707957, 9.615236383293386, 8.543195926051439, 4.195431191676585, 3.3414506633887537, 3.215519387903715, 4.6176570051114485, 1.7132971206499201, 1.3469434794812618, 0.8050290875204243, 0.0, 11.411319304324769, 8.855319962724668, 6.734717397406309, 5.1398913619497595, 9.235314010222897, 4.501727143065201, 3.3414506633887537, 2.996736565483275, 4.2715979630257195, 3.205078794431129, 1.8722261181415913, 0.6892544809083996, 0.0),
(10.450553324967336, 7.495248171657732, 9.302523946219415, 9.544258060733807, 8.48743569881293, 4.174003322325641, 3.3075747046495003, 3.200048222203801, 4.597442309412912, 1.698678070701901, 1.335972342259087, 0.7988866158226731, 0.0, 11.335080203181485, 8.787752774049402, 6.679861711295434, 5.096034212105701, 9.194884618825824, 4.480067511085322, 3.3075747046495003, 2.9814309445183147, 4.243717849406465, 3.1814193535779363, 1.8605047892438833, 0.6813861974234302, 0.0),
(10.335201473769764, 7.395933826819331, 9.224527454803487, 9.454176016727876, 8.414178555796186, 4.143513212539135, 3.2677489343700015, 3.17754122744589, 4.566999388570334, 1.6807983479345614, 1.3223972849777657, 0.7911589610963629, 0.0, 11.235598705688274, 8.70274857205999, 6.611986424888827, 5.042395043803683, 9.133998777140668, 4.448557718424246, 3.2677489343700015, 2.9596522946708106, 4.207089277898093, 3.1513920055759597, 1.8449054909606977, 0.6723576206199392, 0.0),
(10.198820932866035, 7.28304080162725, 9.125574450948537, 9.343506385929302, 8.321992122590341, 4.103212058438943, 3.221570623868649, 3.147432860557619, 4.525465106040038, 1.6594219781520132, 1.3060272186755595, 0.7817252273702489, 0.0, 11.110988852451014, 8.598977501072737, 6.530136093377798, 4.978265934456038, 9.050930212080075, 4.406406004780667, 3.221570623868649, 2.9308657560278157, 4.160996061295171, 3.114502128643102, 1.8251148901897079, 0.6620946183297501, 0.0),
(10.042510876420344, 7.1573051140366015, 9.006721467228694, 9.213301128944565, 8.211833582663305, 4.053588080615757, 3.1693770122048135, 3.1101003109807053, 4.473387224599541, 1.6347303676098288, 1.2870063860732652, 0.77067287137255, 0.0, 10.962523662746737, 8.477401585098049, 6.435031930366326, 4.904191102829485, 8.946774449199083, 4.354140435372988, 3.1693770122048135, 2.8954200575826836, 4.105916791331652, 3.071100376314856, 1.801344293445739, 0.6506641012760548, 0.0),
(9.8673704785969, 7.01946278200249, 8.86902503621808, 9.064612206380144, 8.08466011948299, 3.9951294996602726, 3.1115053384378664, 3.0659207681568685, 4.411313507026364, 1.6069049225635816, 1.2654790298916783, 0.7580893498314843, 0.0, 10.791476155852466, 8.338982848146326, 6.3273951494583915, 4.820714767690744, 8.822627014052728, 4.292289075419616, 3.1115053384378664, 2.8536639283287664, 4.042330059741495, 3.0215374021267154, 1.773805007243616, 0.6381329801820447, 0.0),
(9.674498913559898, 6.870249823480022, 8.71354169049082, 8.898491578842531, 7.941428916517308, 3.928324536163185, 3.048292841627181, 3.015271421527823, 4.339791716098023, 1.5761270492688444, 1.2415893928515955, 0.7440621194752707, 0.0, 10.599119351045232, 8.184683314227977, 6.207946964257977, 4.728381147806532, 8.679583432196045, 4.221379990138953, 3.048292841627181, 2.8059460972594175, 3.970714458258654, 2.9661638596141775, 1.742708338098164, 0.6245681657709112, 0.0),
(9.464995355473539, 6.710402256424303, 8.54132796262104, 8.71599120693821, 7.783097157234176, 3.853661410715189, 2.9800767608321266, 2.9585294605352903, 4.259369614592037, 1.5425781539811894, 1.2154817176738126, 0.7286786370321272, 0.0, 10.386726267602059, 8.015465007353399, 6.077408588369063, 4.627734461943566, 8.518739229184074, 4.141941244749407, 2.9800767608321266, 2.752615293367992, 3.891548578617088, 2.905330402312737, 1.7082655925242083, 0.6100365687658459, 0.0),
(9.239958978502024, 6.5406560987904445, 8.353440385182864, 8.518163051273666, 7.610622025101502, 3.771628343906979, 2.9071943351120755, 2.8960720746209856, 4.1705949652859235, 1.5064396429561904, 1.1873002470791263, 0.7120263592302724, 0.0, 10.155569924799979, 7.832289951532995, 5.936501235395631, 4.51931892886857, 8.341189930571847, 4.05450090446938, 2.9071943351120755, 2.694020245647842, 3.805311012550751, 2.839387683757889, 1.670688077036573, 0.5946050998900405, 0.0),
(9.000488956809557, 6.361747368533551, 8.150935490750417, 8.306059072455376, 7.4249607035872005, 3.682713556329251, 2.8299828035264003, 2.8282764532266285, 4.074015530957201, 1.4678929224494195, 1.157189223788332, 0.6941927427979253, 0.0, 9.906923341916015, 7.636120170777177, 5.78594611894166, 4.403678767348258, 8.148031061914402, 3.95958703451728, 2.8299828035264003, 2.630509683092322, 3.7124803517936003, 2.768686357485126, 1.6301870981500834, 0.5783406698666865, 0.0),
(8.747684464560333, 6.174412083608727, 7.934869811897824, 8.080731231089835, 7.2270703761591815, 3.5874052685726983, 2.7487794051344725, 2.7555197857939366, 3.9701790743833865, 1.4271193987164503, 1.1252928905222266, 0.6752652444633036, 0.0, 9.642059538227196, 7.427917689096338, 5.626464452611132, 4.28135819614935, 7.940358148766773, 3.8577277001115116, 2.7487794051344725, 2.562432334694784, 3.6135351880795907, 2.693577077029946, 1.5869739623795647, 0.5613101894189753, 0.0),
(8.482644675918554, 5.979386261971081, 7.706299881199207, 7.843231487783524, 7.017908226285359, 3.4861917012280164, 2.663921378995663, 2.6781792617646265, 3.8596333583419993, 1.3843004780128556, 1.0917554900016058, 0.6553313209546264, 0.0, 9.362251533010546, 7.20864453050089, 5.458777450008029, 4.152901434038566, 7.7192667166839986, 3.7494509664704774, 2.663921378995663, 2.490136929448583, 3.5089541131426794, 2.614410495927842, 1.5412599762398416, 0.5435805692700985, 0.0),
(8.206468765048422, 5.777405921575724, 7.466282231228694, 7.594611803142927, 6.798431437433646, 3.3795610748859013, 2.5757459641693443, 2.5966320705804184, 3.7429261456105576, 1.339617566594208, 1.0567212649472661, 0.6344784290001119, 0.0, 9.0687723455431, 6.9792627190012295, 5.28360632473633, 4.018852699782624, 7.485852291221115, 3.635284898812586, 2.5757459641693443, 2.413972196347072, 3.399215718716823, 2.5315372677143095, 1.493256446245739, 0.5252187201432478, 0.0),
(7.9202559061141375, 5.569207080377758, 7.215873394560408, 7.335924137774526, 6.569597193071951, 3.268001610137046, 2.4845903997148873, 2.5112554016830275, 3.620605198966578, 1.2932520707160806, 1.020334458080004, 0.6127940253279787, 0.0, 8.762894995101878, 6.740734278607764, 5.101672290400019, 3.879756212148241, 7.241210397933156, 3.5157575623562387, 2.4845903997148873, 2.3342868643836043, 3.2847985965359756, 2.4453080459248424, 1.4431746789120816, 0.5062915527616144, 0.0),
(7.6251052732799005, 5.355525756332291, 6.956129903768475, 7.068220452284813, 6.3323626766681915, 3.152001527572146, 2.390791924691664, 2.4224264445141737, 3.4932182811875796, 1.2453853966340462, 0.9827393121206148, 0.5903655666664452, 0.0, 8.445892500963913, 6.494021233330896, 4.913696560603074, 3.736156189902138, 6.986436562375159, 3.3913970223198433, 2.390791924691664, 2.2514296625515327, 3.1661813383340958, 2.356073484094938, 1.391225980753695, 0.4868659778483902, 0.0),
(7.322116040709912, 5.137097967394431, 6.688108291427019, 6.792552707280267, 6.087685071690277, 3.0320490477818964, 2.2946877781590462, 2.3305223885155746, 3.3613131550510804, 1.1961989506036783, 0.9440800697898953, 0.56728050974373, 0.0, 8.119037882406225, 6.24008560718103, 4.720400348949476, 3.588596851811034, 6.722626310102161, 3.2627313439218044, 2.2946877781590462, 2.165749319844212, 3.0438425358451386, 2.2641842357600894, 1.337621658285404, 0.4670089061267665, 0.0),
(7.012387382568372, 4.914659731519285, 6.412865090110164, 6.509972863367375, 5.836521561606121, 2.9086323913569916, 2.196615199176405, 2.235920423128947, 3.225437583334597, 1.145874138880549, 0.9045009738086416, 0.5436263112880514, 0.0, 7.783604158705848, 5.979889424168563, 4.522504869043208, 3.437622416641646, 6.450875166669194, 3.130288592380526, 2.196615199176405, 2.077594565254994, 2.9182607808030605, 2.169990954455792, 1.282573018022033, 0.446787248319935, 0.0),
(6.697018473019482, 4.6889470666619575, 6.131456832392036, 6.221532881152618, 5.579829329883635, 2.7822397788881266, 2.096911426803113, 2.1389977377960108, 3.08613932881565, 1.0945923677202316, 0.8641462668976501, 0.519490428027628, 0.0, 7.440864349139807, 5.7143947083039075, 4.32073133448825, 3.283777103160694, 6.1722786576313, 2.994596832914415, 2.096911426803113, 1.9873141277772333, 2.7899146649418176, 2.07384429371754, 1.2262913664784072, 0.42626791515108714, 0.0),
(6.377108486227438, 4.460695990777558, 5.84494005084676, 5.928284721242486, 5.318565559990731, 2.653359430965997, 1.9959137000985407, 2.040131521958481, 2.943966154271756, 1.0425350433782987, 0.8231601917777163, 0.49496031669067847, 0.0, 7.092091472985131, 5.444563483597462, 4.115800958888581, 3.1276051301348957, 5.887932308543512, 2.8561841307418736, 1.9959137000985407, 1.8952567364042836, 2.6592827799953653, 1.9760949070808291, 1.1689880101693522, 0.40551781734341447, 0.0),
(6.053756596356447, 4.230642521821194, 5.554371278048459, 5.631280344243462, 5.053687435395322, 2.5224795681812964, 1.8939592581220606, 1.9396989650580787, 2.7994658224804327, 0.9898835721103237, 0.781686991169637, 0.470123434005421, 0.0, 6.738558549518844, 5.17135777405963, 3.9084349558481852, 2.9696507163309707, 5.5989316449608655, 2.71557855108131, 1.8939592581220606, 1.8017711201294973, 2.526843717697661, 1.8770934480811543, 1.1108742556096918, 0.38460386562010856, 0.0),
(5.7280619775707065, 3.9995226777479713, 5.260807046571258, 5.331571710762027, 4.786152139565322, 2.3900884111247205, 1.791385339933044, 1.8380772565365193, 2.6531860962191995, 0.9368193601718788, 0.7398709077942084, 0.4450672367000743, 0.0, 6.381538598017975, 4.895739603700816, 3.699354538971042, 2.8104580805156356, 5.306372192438399, 2.5733081591511273, 1.791385339933044, 1.707206007946229, 2.393076069782661, 1.7771905702540096, 1.0521614093142517, 0.3635929707043611, 0.0),
(5.401123804034416, 3.7680724765129963, 4.9653038889892835, 5.030210781404673, 4.516916855968639, 2.2566741803869648, 1.6885291845908623, 1.7356435858355217, 2.505674738265573, 0.8835238138185378, 0.6978561843722264, 0.41987918150285664, 0.0, 6.022304637759553, 4.618670996531422, 3.489280921861132, 2.6505714414556127, 5.011349476531146, 2.4299010201697304, 1.6885291845908623, 1.611910128847832, 2.2584584279843196, 1.6767369271348913, 0.9930607777978567, 0.34255204331936334, 0.0),
(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
)
passenger_allighting_rate = (
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
)
entropy = 8991598675325360468762009371570610170
child_seed_index = (
1,
47,
)
| true | true |
f716a1a5f632f06075f249c2221bcd21beac3b38 | 657 | py | Python | odc_gee/setup.py | admariner/data_cube_notebooks | 984a84b2f92114040e36a533d3f476dcf384695e | [
"Apache-2.0"
] | null | null | null | odc_gee/setup.py | admariner/data_cube_notebooks | 984a84b2f92114040e36a533d3f476dcf384695e | [
"Apache-2.0"
] | null | null | null | odc_gee/setup.py | admariner/data_cube_notebooks | 984a84b2f92114040e36a533d3f476dcf384695e | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(name='odc-gee',
version='2.24',
description='Google Earth Engine indexing tools for Open Data Cube',
author='Andrew Lubawy',
author_email='andrew.m.lubawy@ama-inc.com',
install_requires=[
"google-auth>=1.11.0,<=1.32.0"
"click-plugins>=1.1.1",
"click>=7.1.2",
"datacube>=1.8.3",
"earthengine-api>=0.1.24",
"numpy>=1.18.4",
"rasterio>=1.1.8",
"google-api-core==1.31.2"
],
packages=find_packages(),
scripts=['scripts/index_gee', 'scripts/new_product'],)
| 29.863636 | 74 | 0.564688 |
from setuptools import setup, find_packages
setup(name='odc-gee',
version='2.24',
description='Google Earth Engine indexing tools for Open Data Cube',
author='Andrew Lubawy',
author_email='andrew.m.lubawy@ama-inc.com',
install_requires=[
"google-auth>=1.11.0,<=1.32.0"
"click-plugins>=1.1.1",
"click>=7.1.2",
"datacube>=1.8.3",
"earthengine-api>=0.1.24",
"numpy>=1.18.4",
"rasterio>=1.1.8",
"google-api-core==1.31.2"
],
packages=find_packages(),
scripts=['scripts/index_gee', 'scripts/new_product'],)
| true | true |
f716a22900c092bb89fd4f6f98a63d9202ab5429 | 7,980 | py | Python | client/deploy_kafka.py | jzmq/minos | 510b6e30758f4900a72fee1a5e6258bdc7c83f17 | [
"Apache-2.0"
] | 365 | 2015-01-26T13:56:42.000Z | 2022-03-28T06:36:31.000Z | client/deploy_kafka.py | jzmq/minos | 510b6e30758f4900a72fee1a5e6258bdc7c83f17 | [
"Apache-2.0"
] | 3 | 2015-12-29T07:44:24.000Z | 2021-03-18T06:13:07.000Z | client/deploy_kafka.py | jzmq/minos | 510b6e30758f4900a72fee1a5e6258bdc7c83f17 | [
"Apache-2.0"
] | 135 | 2015-01-31T00:46:51.000Z | 2022-03-03T06:31:09.000Z | #!/usr/bin/env python
import argparse
import os
import parallel_deploy
import service_config
import subprocess
import sys
import urlparse
import deploy_utils
from log import Log
ALL_JOBS = ["kafka", "kafkascribe"]
def _get_kafka_service_config(args):
args.kafka_config = deploy_utils.get_service_config(args)
def generate_configs(args, job_name, host_id, instance_id):
kafka_cfg_dict = args.kafka_config.configuration.generated_files["kafka.cfg"]
hosts = args.kafka_config.jobs[job_name].hosts
kafka_cfg_dict["broker.id"] = deploy_utils.get_task_id(hosts, host_id, instance_id)
kafka_cfg = deploy_utils.generate_properties_file(args, kafka_cfg_dict)
kafka_scribe_cfg_dict = args.kafka_config.configuration.generated_files["kafka-scribe.cfg"]
kafka_job = args.kafka_config.jobs["kafka"]
kafka_scribe_cfg_dict["metadata.broker.list"] = ",".join(
service_config.get_job_host_port_list(kafka_job))
kafka_scribe_cfg = deploy_utils.generate_properties_file(args, kafka_scribe_cfg_dict)
config_files = {
"kafka.cfg": kafka_cfg,
"kafka-scribe.cfg": kafka_scribe_cfg,
}
config_files.update(args.kafka_config.configuration.raw_files)
return config_files
def generate_run_scripts_params(args, host, job_name, host_id, instance_id):
job = args.kafka_config.jobs[job_name]
supervisor_client = deploy_utils.get_supervisor_client(host,
"kafka", args.kafka_config.cluster.name, job_name, instance_id=instance_id)
artifact_and_version = "kafka-" + args.kafka_config.cluster.version
jar_dirs = "$package_dir/*"
log_level = deploy_utils.get_service_log_level(args, args.kafka_config)
params = job.get_arguments(args, args.kafka_config.cluster, args.kafka_config.jobs,
args.kafka_config.arguments_dict, job_name, host_id, instance_id)
script_dict = {
"artifact": artifact_and_version,
"job_name": job_name,
"jar_dirs": jar_dirs,
"run_dir": supervisor_client.get_run_dir(),
"params": params,
}
return script_dict
def generate_start_script(args, host, job_name, host_id, instance_id):
script_params = generate_run_scripts_params(args, host, job_name, host_id, instance_id)
return deploy_utils.create_run_script(
"%s/start.sh.tmpl" % deploy_utils.get_template_dir(),
script_params)
def install(args):
_get_kafka_service_config(args)
deploy_utils.install_service(args, "kafka", args.kafka_config, "kafka")
def cleanup_job(args, host, job_name, host_id, instance_id, cleanup_token, active):
deploy_utils.cleanup_job("kafka", args.kafka_config,
host, job_name, instance_id, cleanup_token)
def cleanup(args):
_get_kafka_service_config(args)
cleanup_token = deploy_utils.confirm_cleanup(args,
"kafka", args.kafka_config)
for job_name in args.job or ALL_JOBS:
hosts = args.kafka_config.jobs[job_name].hosts
task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name,
'cleanup', cleanup_token=cleanup_token)
parallel_deploy.start_deploy_threads(cleanup_job, task_list)
def bootstrap_job(args, host, job_name, host_id, instance_id, cleanup_token, active):
# parse the service_config according to the instance_id
args.kafka_config.parse_generated_config_files(args, job_name, host_id, instance_id)
deploy_utils.bootstrap_job(args, "kafka", "kafka",
args.kafka_config, host, job_name, instance_id, cleanup_token, '0')
start_job(args, host, job_name, host_id, instance_id)
def bootstrap(args):
_get_kafka_service_config(args)
cleanup_token = deploy_utils.confirm_bootstrap("kafka", args.kafka_config)
for job_name in args.job or ALL_JOBS:
hosts = args.kafka_config.jobs[job_name].hosts
task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name,
'bootstrap', cleanup_token=cleanup_token)
parallel_deploy.start_deploy_threads(bootstrap_job, task_list)
def start_job(args, host, job_name, host_id, instance_id, is_wait=False):
if is_wait:
deploy_utils.wait_for_job_stopping("kafka",
args.kafka_config.cluster.name, job_name, host, instance_id)
# parse the service_config according to the instance_id
args.kafka_config.parse_generated_config_files(args, job_name, host_id, instance_id)
config_files = generate_configs(args, job_name, host_id, instance_id)
start_script = generate_start_script(args, host, job_name, host_id, instance_id)
http_url = deploy_utils.get_http_service_uri(host,
args.kafka_config.jobs[job_name].base_port, instance_id)
deploy_utils.start_job(args, "kafka", "kafka", args.kafka_config,
host, job_name, instance_id, start_script, http_url, **config_files)
def start(args):
if not args.skip_confirm:
deploy_utils.confirm_start(args)
_get_kafka_service_config(args)
for job_name in args.job or ALL_JOBS:
hosts = args.kafka_config.jobs[job_name].hosts
task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name, 'start')
parallel_deploy.start_deploy_threads(start_job, task_list)
def stop_job(args, host, job_name, instance_id):
deploy_utils.stop_job("kafka", args.kafka_config, host, job_name, instance_id)
def stop(args):
if not args.skip_confirm:
deploy_utils.confirm_stop(args)
_get_kafka_service_config(args)
for job_name in args.job or ALL_JOBS:
hosts = args.kafka_config.jobs[job_name].hosts
task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name, 'stop')
parallel_deploy.start_deploy_threads(stop_job, task_list)
def restart(args):
if not args.skip_confirm:
deploy_utils.confirm_restart(args)
_get_kafka_service_config(args)
for job_name in args.job or ALL_JOBS:
hosts = args.kafka_config.jobs[job_name].hosts
task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name, 'stop')
parallel_deploy.start_deploy_threads(stop_job, task_list)
for job_name in args.job or ALL_JOBS:
hosts = args.kafka_config.jobs[job_name].hosts
task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name,
'start', is_wait=True)
parallel_deploy.start_deploy_threads(start_job, task_list)
def show_job(args, host, job_name, instance_id):
deploy_utils.show_job("kafka", args.kafka_config, host, job_name, instance_id)
def show(args):
_get_kafka_service_config(args)
for job_name in args.job or ALL_JOBS:
hosts = args.kafka_config.jobs[job_name].hosts
task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name, 'show')
parallel_deploy.start_deploy_threads(show_job, task_list)
def run_shell(args):
Log.print_critical("'shell' command is not supported!")
def pack(args):
Log.print_critical("'pack' command is not supported!")
def rolling_update(args):
if not args.job:
Log.print_critical("You must specify the job name to do rolling update")
_get_kafka_service_config(args)
job_name = args.job[0]
if not args.skip_confirm:
deploy_utils.confirm_action(args, "rolling_update")
Log.print_info("Rolling updating %s" % job_name)
hosts = args.kafka_config.jobs[job_name].hosts
wait_time = 0
args.task_map = deploy_utils.parse_args_host_and_task(args, hosts)
for host_id in args.task_map.keys() or hosts.iterkeys():
for instance_id in args.task_map.get(host_id) or range(hosts[host_id].instance_num):
instance_id = -1 if not deploy_utils.is_multiple_instances(host_id, hosts) else instance_id
deploy_utils.confirm_rolling_update(host_id, instance_id, wait_time)
stop_job(args, hosts[host_id].ip, job_name, instance_id)
deploy_utils.wait_for_job_stopping("kafka",
args.kafka_config.cluster.name, job_name, hosts[host_id].ip, instance_id)
start_job(args, hosts[host_id].ip, job_name, host_id, instance_id)
deploy_utils.wait_for_job_starting("kafka",
args.kafka_config.cluster.name, job_name, hosts[host_id].ip, instance_id)
wait_time = args.time_interval
Log.print_success("Rolling updating %s success" % job_name)
if __name__ == '__main__':
test()
| 38.550725 | 97 | 0.773308 |
import argparse
import os
import parallel_deploy
import service_config
import subprocess
import sys
import urlparse
import deploy_utils
from log import Log
ALL_JOBS = ["kafka", "kafkascribe"]
def _get_kafka_service_config(args):
args.kafka_config = deploy_utils.get_service_config(args)
def generate_configs(args, job_name, host_id, instance_id):
kafka_cfg_dict = args.kafka_config.configuration.generated_files["kafka.cfg"]
hosts = args.kafka_config.jobs[job_name].hosts
kafka_cfg_dict["broker.id"] = deploy_utils.get_task_id(hosts, host_id, instance_id)
kafka_cfg = deploy_utils.generate_properties_file(args, kafka_cfg_dict)
kafka_scribe_cfg_dict = args.kafka_config.configuration.generated_files["kafka-scribe.cfg"]
kafka_job = args.kafka_config.jobs["kafka"]
kafka_scribe_cfg_dict["metadata.broker.list"] = ",".join(
service_config.get_job_host_port_list(kafka_job))
kafka_scribe_cfg = deploy_utils.generate_properties_file(args, kafka_scribe_cfg_dict)
config_files = {
"kafka.cfg": kafka_cfg,
"kafka-scribe.cfg": kafka_scribe_cfg,
}
config_files.update(args.kafka_config.configuration.raw_files)
return config_files
def generate_run_scripts_params(args, host, job_name, host_id, instance_id):
job = args.kafka_config.jobs[job_name]
supervisor_client = deploy_utils.get_supervisor_client(host,
"kafka", args.kafka_config.cluster.name, job_name, instance_id=instance_id)
artifact_and_version = "kafka-" + args.kafka_config.cluster.version
jar_dirs = "$package_dir/*"
log_level = deploy_utils.get_service_log_level(args, args.kafka_config)
params = job.get_arguments(args, args.kafka_config.cluster, args.kafka_config.jobs,
args.kafka_config.arguments_dict, job_name, host_id, instance_id)
script_dict = {
"artifact": artifact_and_version,
"job_name": job_name,
"jar_dirs": jar_dirs,
"run_dir": supervisor_client.get_run_dir(),
"params": params,
}
return script_dict
def generate_start_script(args, host, job_name, host_id, instance_id):
script_params = generate_run_scripts_params(args, host, job_name, host_id, instance_id)
return deploy_utils.create_run_script(
"%s/start.sh.tmpl" % deploy_utils.get_template_dir(),
script_params)
def install(args):
_get_kafka_service_config(args)
deploy_utils.install_service(args, "kafka", args.kafka_config, "kafka")
def cleanup_job(args, host, job_name, host_id, instance_id, cleanup_token, active):
deploy_utils.cleanup_job("kafka", args.kafka_config,
host, job_name, instance_id, cleanup_token)
def cleanup(args):
_get_kafka_service_config(args)
cleanup_token = deploy_utils.confirm_cleanup(args,
"kafka", args.kafka_config)
for job_name in args.job or ALL_JOBS:
hosts = args.kafka_config.jobs[job_name].hosts
task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name,
'cleanup', cleanup_token=cleanup_token)
parallel_deploy.start_deploy_threads(cleanup_job, task_list)
def bootstrap_job(args, host, job_name, host_id, instance_id, cleanup_token, active):
args.kafka_config.parse_generated_config_files(args, job_name, host_id, instance_id)
deploy_utils.bootstrap_job(args, "kafka", "kafka",
args.kafka_config, host, job_name, instance_id, cleanup_token, '0')
start_job(args, host, job_name, host_id, instance_id)
def bootstrap(args):
_get_kafka_service_config(args)
cleanup_token = deploy_utils.confirm_bootstrap("kafka", args.kafka_config)
for job_name in args.job or ALL_JOBS:
hosts = args.kafka_config.jobs[job_name].hosts
task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name,
'bootstrap', cleanup_token=cleanup_token)
parallel_deploy.start_deploy_threads(bootstrap_job, task_list)
def start_job(args, host, job_name, host_id, instance_id, is_wait=False):
if is_wait:
deploy_utils.wait_for_job_stopping("kafka",
args.kafka_config.cluster.name, job_name, host, instance_id)
args.kafka_config.parse_generated_config_files(args, job_name, host_id, instance_id)
config_files = generate_configs(args, job_name, host_id, instance_id)
start_script = generate_start_script(args, host, job_name, host_id, instance_id)
http_url = deploy_utils.get_http_service_uri(host,
args.kafka_config.jobs[job_name].base_port, instance_id)
deploy_utils.start_job(args, "kafka", "kafka", args.kafka_config,
host, job_name, instance_id, start_script, http_url, **config_files)
def start(args):
if not args.skip_confirm:
deploy_utils.confirm_start(args)
_get_kafka_service_config(args)
for job_name in args.job or ALL_JOBS:
hosts = args.kafka_config.jobs[job_name].hosts
task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name, 'start')
parallel_deploy.start_deploy_threads(start_job, task_list)
def stop_job(args, host, job_name, instance_id):
deploy_utils.stop_job("kafka", args.kafka_config, host, job_name, instance_id)
def stop(args):
if not args.skip_confirm:
deploy_utils.confirm_stop(args)
_get_kafka_service_config(args)
for job_name in args.job or ALL_JOBS:
hosts = args.kafka_config.jobs[job_name].hosts
task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name, 'stop')
parallel_deploy.start_deploy_threads(stop_job, task_list)
def restart(args):
if not args.skip_confirm:
deploy_utils.confirm_restart(args)
_get_kafka_service_config(args)
for job_name in args.job or ALL_JOBS:
hosts = args.kafka_config.jobs[job_name].hosts
task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name, 'stop')
parallel_deploy.start_deploy_threads(stop_job, task_list)
for job_name in args.job or ALL_JOBS:
hosts = args.kafka_config.jobs[job_name].hosts
task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name,
'start', is_wait=True)
parallel_deploy.start_deploy_threads(start_job, task_list)
def show_job(args, host, job_name, instance_id):
deploy_utils.show_job("kafka", args.kafka_config, host, job_name, instance_id)
def show(args):
_get_kafka_service_config(args)
for job_name in args.job or ALL_JOBS:
hosts = args.kafka_config.jobs[job_name].hosts
task_list = deploy_utils.schedule_task_for_threads(args, hosts, job_name, 'show')
parallel_deploy.start_deploy_threads(show_job, task_list)
def run_shell(args):
Log.print_critical("'shell' command is not supported!")
def pack(args):
Log.print_critical("'pack' command is not supported!")
def rolling_update(args):
if not args.job:
Log.print_critical("You must specify the job name to do rolling update")
_get_kafka_service_config(args)
job_name = args.job[0]
if not args.skip_confirm:
deploy_utils.confirm_action(args, "rolling_update")
Log.print_info("Rolling updating %s" % job_name)
hosts = args.kafka_config.jobs[job_name].hosts
wait_time = 0
args.task_map = deploy_utils.parse_args_host_and_task(args, hosts)
for host_id in args.task_map.keys() or hosts.iterkeys():
for instance_id in args.task_map.get(host_id) or range(hosts[host_id].instance_num):
instance_id = -1 if not deploy_utils.is_multiple_instances(host_id, hosts) else instance_id
deploy_utils.confirm_rolling_update(host_id, instance_id, wait_time)
stop_job(args, hosts[host_id].ip, job_name, instance_id)
deploy_utils.wait_for_job_stopping("kafka",
args.kafka_config.cluster.name, job_name, hosts[host_id].ip, instance_id)
start_job(args, hosts[host_id].ip, job_name, host_id, instance_id)
deploy_utils.wait_for_job_starting("kafka",
args.kafka_config.cluster.name, job_name, hosts[host_id].ip, instance_id)
wait_time = args.time_interval
Log.print_success("Rolling updating %s success" % job_name)
if __name__ == '__main__':
test()
| true | true |
f716a2954dca50e0e1254eb1298f66d92f7eacbe | 2,317 | py | Python | scripts/sanity_chk/scl.py | cinlyooi-intel/zephyr | 193fb971c24f827464982307b5b3bb34de0fa98d | [
"Apache-2.0"
] | null | null | null | scripts/sanity_chk/scl.py | cinlyooi-intel/zephyr | 193fb971c24f827464982307b5b3bb34de0fa98d | [
"Apache-2.0"
] | null | null | null | scripts/sanity_chk/scl.py | cinlyooi-intel/zephyr | 193fb971c24f827464982307b5b3bb34de0fa98d | [
"Apache-2.0"
] | null | null | null | #! /usr/bin/python
#
# Zephyr's Sanity Check library
#
# Set of code that other projects can also import to do things on
# Zephyr's sanity check testcases.
import logging
import yaml
log = logging.getLogger("scl")
#
#
def yaml_load(filename):
"""
Safely load a YAML document
Follows recomendations from
https://security.openstack.org/guidelines/dg_avoid-dangerous-input-parsing-libraries.html.
:param str filename: filename to load
:raises yaml.scanner: On YAML scan issues
:raises: any other exception on file access erors
:return: dictionary representing the YAML document
"""
try:
with open(filename, 'r') as f:
return yaml.safe_load(f)
except yaml.scanner.ScannerError as e: # For errors parsing schema.yaml
mark = e.problem_mark
cmark = e.context_mark
log.error("%s:%d:%d: error: %s (note %s context @%s:%d:%d %s)",
mark.name, mark.line, mark.column, e.problem,
e.note, cmark.name, cmark.line, cmark.column, e.context)
raise
# If pykwalify is installed, then the validate functionw ill work --
# otherwise, it is a stub and we'd warn about it.
try:
import pykwalify.core
# Don't print error messages yourself, let us do it
logging.getLogger("pykwalify.core").setLevel(50)
def _yaml_validate(data, schema):
if not schema:
return
c = pykwalify.core.Core(source_data = data, schema_data = schema)
c.validate(raise_exception = True)
except ImportError as e:
log.warning("can't import pykwalify; won't validate YAML (%s)", e)
def _yaml_validate(data, schema):
pass
def yaml_load_verify(filename, schema):
"""
Safely load a testcase/sample yaml document and validate it
against the YAML schema, returing in case of success the YAML data.
:param str filename: name of the file to load and process
:param dict schema: loaded YAML schema (can load with :func:`yaml_load`)
# 'document.yaml' contains a single YAML document.
:raises yaml.scanner.ScannerError: on YAML parsing error
:raises pykwalify.errors.SchemaError: on Schema violation error
"""
# 'document.yaml' contains a single YAML document.
y = yaml_load(filename)
_yaml_validate(y, schema)
return y
| 32.180556 | 94 | 0.678032 |
#
# Set of code that other projects can also import to do things on
# Zephyr's sanity check testcases.
import logging
import yaml
log = logging.getLogger("scl")
def yaml_load(filename):
try:
with open(filename, 'r') as f:
return yaml.safe_load(f)
except yaml.scanner.ScannerError as e:
mark = e.problem_mark
cmark = e.context_mark
log.error("%s:%d:%d: error: %s (note %s context @%s:%d:%d %s)",
mark.name, mark.line, mark.column, e.problem,
e.note, cmark.name, cmark.line, cmark.column, e.context)
raise
try:
import pykwalify.core
# Don't print error messages yourself, let us do it
logging.getLogger("pykwalify.core").setLevel(50)
def _yaml_validate(data, schema):
if not schema:
return
c = pykwalify.core.Core(source_data = data, schema_data = schema)
c.validate(raise_exception = True)
except ImportError as e:
log.warning("can't import pykwalify; won't validate YAML (%s)", e)
def _yaml_validate(data, schema):
pass
def yaml_load_verify(filename, schema):
y = yaml_load(filename)
_yaml_validate(y, schema)
return y
| true | true |
f716a3a44cd54534078de417bc370bb62502718a | 68,239 | py | Python | pandas/tests/groupby/test_groupby.py | gurukiran07/pandas | 67c9385787c4d854b75a6f2c04fdf6886fdb1a06 | [
"PSF-2.0",
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | 2 | 2017-12-14T19:50:52.000Z | 2020-04-07T16:47:23.000Z | pandas/tests/groupby/test_groupby.py | zoehuang7/pandas | 3cce96f515917170ea9bce731ffcc913750464b8 | [
"PSF-2.0",
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"MIT",
"MIT-0",
"ECL-2.0",
"BSD-3-Clause"
] | null | null | null | pandas/tests/groupby/test_groupby.py | zoehuang7/pandas | 3cce96f515917170ea9bce731ffcc913750464b8 | [
"PSF-2.0",
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"MIT",
"MIT-0",
"ECL-2.0",
"BSD-3-Clause"
] | 1 | 2018-01-26T08:33:54.000Z | 2018-01-26T08:33:54.000Z | from datetime import datetime
from decimal import Decimal
from io import StringIO
import numpy as np
import pytest
from pandas.compat import IS64
from pandas.errors import PerformanceWarning
import pandas as pd
from pandas import (
Categorical,
DataFrame,
Grouper,
Index,
MultiIndex,
Series,
Timestamp,
date_range,
read_csv,
to_datetime,
)
import pandas._testing as tm
from pandas.core.base import SpecificationError
import pandas.core.common as com
def test_repr():
# GH18203
result = repr(Grouper(key="A", level="B"))
expected = "Grouper(key='A', level='B', axis=0, sort=False)"
assert result == expected
@pytest.mark.parametrize("dtype", ["int64", "int32", "float64", "float32"])
def test_basic(dtype):
data = Series(np.arange(9) // 3, index=np.arange(9), dtype=dtype)
index = np.arange(9)
np.random.shuffle(index)
data = data.reindex(index)
grouped = data.groupby(lambda x: x // 3)
for k, v in grouped:
assert len(v) == 3
agged = grouped.aggregate(np.mean)
assert agged[1] == 1
tm.assert_series_equal(agged, grouped.agg(np.mean)) # shorthand
tm.assert_series_equal(agged, grouped.mean())
tm.assert_series_equal(grouped.agg(np.sum), grouped.sum())
expected = grouped.apply(lambda x: x * x.sum())
transformed = grouped.transform(lambda x: x * x.sum())
assert transformed[7] == 12
tm.assert_series_equal(transformed, expected)
value_grouped = data.groupby(data)
tm.assert_series_equal(
value_grouped.aggregate(np.mean), agged, check_index_type=False
)
# complex agg
agged = grouped.aggregate([np.mean, np.std])
msg = r"nested renamer is not supported"
with pytest.raises(SpecificationError, match=msg):
grouped.aggregate({"one": np.mean, "two": np.std})
group_constants = {0: 10, 1: 20, 2: 30}
agged = grouped.agg(lambda x: group_constants[x.name] + x.mean())
assert agged[1] == 21
# corner cases
msg = "Must produce aggregated value"
# exception raised is type Exception
with pytest.raises(Exception, match=msg):
grouped.aggregate(lambda x: x * 2)
def test_groupby_nonobject_dtype(mframe, df_mixed_floats):
key = mframe.index.codes[0]
grouped = mframe.groupby(key)
result = grouped.sum()
expected = mframe.groupby(key.astype("O")).sum()
tm.assert_frame_equal(result, expected)
# GH 3911, mixed frame non-conversion
df = df_mixed_floats.copy()
df["value"] = range(len(df))
def max_value(group):
return group.loc[group["value"].idxmax()]
applied = df.groupby("A").apply(max_value)
result = applied.dtypes
expected = df.dtypes
tm.assert_series_equal(result, expected)
def test_groupby_return_type():
# GH2893, return a reduced type
df1 = DataFrame(
[
{"val1": 1, "val2": 20},
{"val1": 1, "val2": 19},
{"val1": 2, "val2": 27},
{"val1": 2, "val2": 12},
]
)
def func(dataf):
return dataf["val2"] - dataf["val2"].mean()
with tm.assert_produces_warning(FutureWarning):
result = df1.groupby("val1", squeeze=True).apply(func)
assert isinstance(result, Series)
df2 = DataFrame(
[
{"val1": 1, "val2": 20},
{"val1": 1, "val2": 19},
{"val1": 1, "val2": 27},
{"val1": 1, "val2": 12},
]
)
def func(dataf):
return dataf["val2"] - dataf["val2"].mean()
with tm.assert_produces_warning(FutureWarning):
result = df2.groupby("val1", squeeze=True).apply(func)
assert isinstance(result, Series)
# GH3596, return a consistent type (regression in 0.11 from 0.10.1)
df = DataFrame([[1, 1], [1, 1]], columns=["X", "Y"])
with tm.assert_produces_warning(FutureWarning):
result = df.groupby("X", squeeze=False).count()
assert isinstance(result, DataFrame)
def test_inconsistent_return_type():
# GH5592
# inconsistent return type
df = DataFrame(
{
"A": ["Tiger", "Tiger", "Tiger", "Lamb", "Lamb", "Pony", "Pony"],
"B": Series(np.arange(7), dtype="int64"),
"C": date_range("20130101", periods=7),
}
)
def f(grp):
return grp.iloc[0]
expected = df.groupby("A").first()[["B"]]
result = df.groupby("A").apply(f)[["B"]]
tm.assert_frame_equal(result, expected)
def f(grp):
if grp.name == "Tiger":
return None
return grp.iloc[0]
result = df.groupby("A").apply(f)[["B"]]
e = expected.copy()
e.loc["Tiger"] = np.nan
tm.assert_frame_equal(result, e)
def f(grp):
if grp.name == "Pony":
return None
return grp.iloc[0]
result = df.groupby("A").apply(f)[["B"]]
e = expected.copy()
e.loc["Pony"] = np.nan
tm.assert_frame_equal(result, e)
# 5592 revisited, with datetimes
def f(grp):
if grp.name == "Pony":
return None
return grp.iloc[0]
result = df.groupby("A").apply(f)[["C"]]
e = df.groupby("A").first()[["C"]]
e.loc["Pony"] = pd.NaT
tm.assert_frame_equal(result, e)
# scalar outputs
def f(grp):
if grp.name == "Pony":
return None
return grp.iloc[0].loc["C"]
result = df.groupby("A").apply(f)
e = df.groupby("A").first()["C"].copy()
e.loc["Pony"] = np.nan
e.name = None
tm.assert_series_equal(result, e)
def test_pass_args_kwargs(ts, tsframe):
def f(x, q=None, axis=0):
return np.percentile(x, q, axis=axis)
g = lambda x: np.percentile(x, 80, axis=0)
# Series
ts_grouped = ts.groupby(lambda x: x.month)
agg_result = ts_grouped.agg(np.percentile, 80, axis=0)
apply_result = ts_grouped.apply(np.percentile, 80, axis=0)
trans_result = ts_grouped.transform(np.percentile, 80, axis=0)
agg_expected = ts_grouped.quantile(0.8)
trans_expected = ts_grouped.transform(g)
tm.assert_series_equal(apply_result, agg_expected)
tm.assert_series_equal(agg_result, agg_expected)
tm.assert_series_equal(trans_result, trans_expected)
agg_result = ts_grouped.agg(f, q=80)
apply_result = ts_grouped.apply(f, q=80)
trans_result = ts_grouped.transform(f, q=80)
tm.assert_series_equal(agg_result, agg_expected)
tm.assert_series_equal(apply_result, agg_expected)
tm.assert_series_equal(trans_result, trans_expected)
# DataFrame
df_grouped = tsframe.groupby(lambda x: x.month)
agg_result = df_grouped.agg(np.percentile, 80, axis=0)
apply_result = df_grouped.apply(DataFrame.quantile, 0.8)
expected = df_grouped.quantile(0.8)
tm.assert_frame_equal(apply_result, expected, check_names=False)
tm.assert_frame_equal(agg_result, expected)
agg_result = df_grouped.agg(f, q=80)
apply_result = df_grouped.apply(DataFrame.quantile, q=0.8)
tm.assert_frame_equal(agg_result, expected)
tm.assert_frame_equal(apply_result, expected, check_names=False)
def test_len():
df = tm.makeTimeDataFrame()
grouped = df.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day])
assert len(grouped) == len(df)
grouped = df.groupby([lambda x: x.year, lambda x: x.month])
expected = len({(x.year, x.month) for x in df.index})
assert len(grouped) == expected
# issue 11016
df = DataFrame({"a": [np.nan] * 3, "b": [1, 2, 3]})
assert len(df.groupby("a")) == 0
assert len(df.groupby("b")) == 3
assert len(df.groupby(["a", "b"])) == 3
def test_basic_regression():
# regression
result = Series([1.0 * x for x in list(range(1, 10)) * 10])
data = np.random.random(1100) * 10.0
groupings = Series(data)
grouped = result.groupby(groupings)
grouped.mean()
@pytest.mark.parametrize(
"dtype", ["float64", "float32", "int64", "int32", "int16", "int8"]
)
def test_with_na_groups(dtype):
index = Index(np.arange(10))
values = Series(np.ones(10), index, dtype=dtype)
labels = Series(
[np.nan, "foo", "bar", "bar", np.nan, np.nan, "bar", "bar", np.nan, "foo"],
index=index,
)
# this SHOULD be an int
grouped = values.groupby(labels)
agged = grouped.agg(len)
expected = Series([4, 2], index=["bar", "foo"])
tm.assert_series_equal(agged, expected, check_dtype=False)
# assert issubclass(agged.dtype.type, np.integer)
# explicitly return a float from my function
def f(x):
return float(len(x))
agged = grouped.agg(f)
expected = Series([4.0, 2.0], index=["bar", "foo"])
tm.assert_series_equal(agged, expected)
def test_indices_concatenation_order():
# GH 2808
def f1(x):
y = x[(x.b % 2) == 1] ** 2
if y.empty:
multiindex = MultiIndex(levels=[[]] * 2, codes=[[]] * 2, names=["b", "c"])
res = DataFrame(columns=["a"], index=multiindex)
return res
else:
y = y.set_index(["b", "c"])
return y
def f2(x):
y = x[(x.b % 2) == 1] ** 2
if y.empty:
return DataFrame()
else:
y = y.set_index(["b", "c"])
return y
def f3(x):
y = x[(x.b % 2) == 1] ** 2
if y.empty:
multiindex = MultiIndex(
levels=[[]] * 2, codes=[[]] * 2, names=["foo", "bar"]
)
res = DataFrame(columns=["a", "b"], index=multiindex)
return res
else:
return y
df = DataFrame({"a": [1, 2, 2, 2], "b": range(4), "c": range(5, 9)})
df2 = DataFrame({"a": [3, 2, 2, 2], "b": range(4), "c": range(5, 9)})
# correct result
result1 = df.groupby("a").apply(f1)
result2 = df2.groupby("a").apply(f1)
tm.assert_frame_equal(result1, result2)
# should fail (not the same number of levels)
msg = "Cannot concat indices that do not have the same number of levels"
with pytest.raises(AssertionError, match=msg):
df.groupby("a").apply(f2)
with pytest.raises(AssertionError, match=msg):
df2.groupby("a").apply(f2)
# should fail (incorrect shape)
with pytest.raises(AssertionError, match=msg):
df.groupby("a").apply(f3)
with pytest.raises(AssertionError, match=msg):
df2.groupby("a").apply(f3)
def test_attr_wrapper(ts):
grouped = ts.groupby(lambda x: x.weekday())
result = grouped.std()
expected = grouped.agg(lambda x: np.std(x, ddof=1))
tm.assert_series_equal(result, expected)
# this is pretty cool
result = grouped.describe()
expected = {name: gp.describe() for name, gp in grouped}
expected = DataFrame(expected).T
tm.assert_frame_equal(result, expected)
# get attribute
result = grouped.dtype
expected = grouped.agg(lambda x: x.dtype)
tm.assert_series_equal(result, expected)
# make sure raises error
msg = "'SeriesGroupBy' object has no attribute 'foo'"
with pytest.raises(AttributeError, match=msg):
getattr(grouped, "foo")
def test_frame_groupby(tsframe):
grouped = tsframe.groupby(lambda x: x.weekday())
# aggregate
aggregated = grouped.aggregate(np.mean)
assert len(aggregated) == 5
assert len(aggregated.columns) == 4
# by string
tscopy = tsframe.copy()
tscopy["weekday"] = [x.weekday() for x in tscopy.index]
stragged = tscopy.groupby("weekday").aggregate(np.mean)
tm.assert_frame_equal(stragged, aggregated, check_names=False)
# transform
grouped = tsframe.head(30).groupby(lambda x: x.weekday())
transformed = grouped.transform(lambda x: x - x.mean())
assert len(transformed) == 30
assert len(transformed.columns) == 4
# transform propagate
transformed = grouped.transform(lambda x: x.mean())
for name, group in grouped:
mean = group.mean()
for idx in group.index:
tm.assert_series_equal(transformed.xs(idx), mean, check_names=False)
# iterate
for weekday, group in grouped:
assert group.index[0].weekday() == weekday
# groups / group_indices
groups = grouped.groups
indices = grouped.indices
for k, v in groups.items():
samething = tsframe.index.take(indices[k])
assert (samething == v).all()
def test_frame_groupby_columns(tsframe):
mapping = {"A": 0, "B": 0, "C": 1, "D": 1}
grouped = tsframe.groupby(mapping, axis=1)
# aggregate
aggregated = grouped.aggregate(np.mean)
assert len(aggregated) == len(tsframe)
assert len(aggregated.columns) == 2
# transform
tf = lambda x: x - x.mean()
groupedT = tsframe.T.groupby(mapping, axis=0)
tm.assert_frame_equal(groupedT.transform(tf).T, grouped.transform(tf))
# iterate
for k, v in grouped:
assert len(v.columns) == 2
def test_frame_set_name_single(df):
grouped = df.groupby("A")
result = grouped.mean()
assert result.index.name == "A"
result = df.groupby("A", as_index=False).mean()
assert result.index.name != "A"
result = grouped.agg(np.mean)
assert result.index.name == "A"
result = grouped.agg({"C": np.mean, "D": np.std})
assert result.index.name == "A"
result = grouped["C"].mean()
assert result.index.name == "A"
result = grouped["C"].agg(np.mean)
assert result.index.name == "A"
result = grouped["C"].agg([np.mean, np.std])
assert result.index.name == "A"
msg = r"nested renamer is not supported"
with pytest.raises(SpecificationError, match=msg):
grouped["C"].agg({"foo": np.mean, "bar": np.std})
def test_multi_func(df):
col1 = df["A"]
col2 = df["B"]
grouped = df.groupby([col1.get, col2.get])
agged = grouped.mean()
expected = df.groupby(["A", "B"]).mean()
# TODO groupby get drops names
tm.assert_frame_equal(
agged.loc[:, ["C", "D"]], expected.loc[:, ["C", "D"]], check_names=False
)
# some "groups" with no data
df = DataFrame(
{
"v1": np.random.randn(6),
"v2": np.random.randn(6),
"k1": np.array(["b", "b", "b", "a", "a", "a"]),
"k2": np.array(["1", "1", "1", "2", "2", "2"]),
},
index=["one", "two", "three", "four", "five", "six"],
)
# only verify that it works for now
grouped = df.groupby(["k1", "k2"])
grouped.agg(np.sum)
def test_multi_key_multiple_functions(df):
grouped = df.groupby(["A", "B"])["C"]
agged = grouped.agg([np.mean, np.std])
expected = DataFrame({"mean": grouped.agg(np.mean), "std": grouped.agg(np.std)})
tm.assert_frame_equal(agged, expected)
def test_frame_multi_key_function_list():
data = DataFrame(
{
"A": [
"foo",
"foo",
"foo",
"foo",
"bar",
"bar",
"bar",
"bar",
"foo",
"foo",
"foo",
],
"B": [
"one",
"one",
"one",
"two",
"one",
"one",
"one",
"two",
"two",
"two",
"one",
],
"C": [
"dull",
"dull",
"shiny",
"dull",
"dull",
"shiny",
"shiny",
"dull",
"shiny",
"shiny",
"shiny",
],
"D": np.random.randn(11),
"E": np.random.randn(11),
"F": np.random.randn(11),
}
)
grouped = data.groupby(["A", "B"])
funcs = [np.mean, np.std]
agged = grouped.agg(funcs)
expected = pd.concat(
[grouped["D"].agg(funcs), grouped["E"].agg(funcs), grouped["F"].agg(funcs)],
keys=["D", "E", "F"],
axis=1,
)
assert isinstance(agged.index, MultiIndex)
assert isinstance(expected.index, MultiIndex)
tm.assert_frame_equal(agged, expected)
@pytest.mark.parametrize("op", [lambda x: x.sum(), lambda x: x.mean()])
def test_groupby_multiple_columns(df, op):
data = df
grouped = data.groupby(["A", "B"])
result1 = op(grouped)
keys = []
values = []
for n1, gp1 in data.groupby("A"):
for n2, gp2 in gp1.groupby("B"):
keys.append((n1, n2))
values.append(op(gp2.loc[:, ["C", "D"]]))
mi = MultiIndex.from_tuples(keys, names=["A", "B"])
expected = pd.concat(values, axis=1).T
expected.index = mi
# a little bit crude
for col in ["C", "D"]:
result_col = op(grouped[col])
pivoted = result1[col]
exp = expected[col]
tm.assert_series_equal(result_col, exp)
tm.assert_series_equal(pivoted, exp)
# test single series works the same
result = data["C"].groupby([data["A"], data["B"]]).mean()
expected = data.groupby(["A", "B"]).mean()["C"]
tm.assert_series_equal(result, expected)
def test_as_index_select_column():
# GH 5764
df = DataFrame([[1, 2], [1, 4], [5, 6]], columns=["A", "B"])
result = df.groupby("A", as_index=False)["B"].get_group(1)
expected = Series([2, 4], name="B")
tm.assert_series_equal(result, expected)
result = df.groupby("A", as_index=False)["B"].apply(lambda x: x.cumsum())
expected = Series(
[2, 6, 6], name="B", index=MultiIndex.from_tuples([(0, 0), (0, 1), (1, 2)])
)
tm.assert_series_equal(result, expected)
def test_groupby_as_index_select_column_sum_empty_df():
# GH 35246
df = DataFrame(columns=["A", "B", "C"])
left = df.groupby(by="A", as_index=False)["B"].sum()
assert type(left) is DataFrame
assert left.to_dict() == {"A": {}, "B": {}}
def test_groupby_as_index_agg(df):
grouped = df.groupby("A", as_index=False)
# single-key
result = grouped.agg(np.mean)
expected = grouped.mean()
tm.assert_frame_equal(result, expected)
result2 = grouped.agg({"C": np.mean, "D": np.sum})
expected2 = grouped.mean()
expected2["D"] = grouped.sum()["D"]
tm.assert_frame_equal(result2, expected2)
grouped = df.groupby("A", as_index=True)
msg = r"nested renamer is not supported"
with pytest.raises(SpecificationError, match=msg):
grouped["C"].agg({"Q": np.sum})
# multi-key
grouped = df.groupby(["A", "B"], as_index=False)
result = grouped.agg(np.mean)
expected = grouped.mean()
tm.assert_frame_equal(result, expected)
result2 = grouped.agg({"C": np.mean, "D": np.sum})
expected2 = grouped.mean()
expected2["D"] = grouped.sum()["D"]
tm.assert_frame_equal(result2, expected2)
expected3 = grouped["C"].sum()
expected3 = DataFrame(expected3).rename(columns={"C": "Q"})
result3 = grouped["C"].agg({"Q": np.sum})
tm.assert_frame_equal(result3, expected3)
# GH7115 & GH8112 & GH8582
df = DataFrame(np.random.randint(0, 100, (50, 3)), columns=["jim", "joe", "jolie"])
ts = Series(np.random.randint(5, 10, 50), name="jim")
gr = df.groupby(ts)
gr.nth(0) # invokes set_selection_from_grouper internally
tm.assert_frame_equal(gr.apply(sum), df.groupby(ts).apply(sum))
for attr in ["mean", "max", "count", "idxmax", "cumsum", "all"]:
gr = df.groupby(ts, as_index=False)
left = getattr(gr, attr)()
gr = df.groupby(ts.values, as_index=True)
right = getattr(gr, attr)().reset_index(drop=True)
tm.assert_frame_equal(left, right)
def test_ops_not_as_index(reduction_func):
# GH 10355, 21090
# Using as_index=False should not modify grouped column
if reduction_func in ("corrwith",):
pytest.skip("Test not applicable")
if reduction_func in ("nth", "ngroup"):
pytest.skip("Skip until behavior is determined (GH #5755)")
df = DataFrame(np.random.randint(0, 5, size=(100, 2)), columns=["a", "b"])
expected = getattr(df.groupby("a"), reduction_func)()
if reduction_func == "size":
expected = expected.rename("size")
expected = expected.reset_index()
g = df.groupby("a", as_index=False)
result = getattr(g, reduction_func)()
tm.assert_frame_equal(result, expected)
result = g.agg(reduction_func)
tm.assert_frame_equal(result, expected)
result = getattr(g["b"], reduction_func)()
tm.assert_frame_equal(result, expected)
result = g["b"].agg(reduction_func)
tm.assert_frame_equal(result, expected)
def test_as_index_series_return_frame(df):
grouped = df.groupby("A", as_index=False)
grouped2 = df.groupby(["A", "B"], as_index=False)
result = grouped["C"].agg(np.sum)
expected = grouped.agg(np.sum).loc[:, ["A", "C"]]
assert isinstance(result, DataFrame)
tm.assert_frame_equal(result, expected)
result2 = grouped2["C"].agg(np.sum)
expected2 = grouped2.agg(np.sum).loc[:, ["A", "B", "C"]]
assert isinstance(result2, DataFrame)
tm.assert_frame_equal(result2, expected2)
result = grouped["C"].sum()
expected = grouped.sum().loc[:, ["A", "C"]]
assert isinstance(result, DataFrame)
tm.assert_frame_equal(result, expected)
result2 = grouped2["C"].sum()
expected2 = grouped2.sum().loc[:, ["A", "B", "C"]]
assert isinstance(result2, DataFrame)
tm.assert_frame_equal(result2, expected2)
def test_as_index_series_column_slice_raises(df):
# GH15072
grouped = df.groupby("A", as_index=False)
msg = r"Column\(s\) C already selected"
with pytest.raises(IndexError, match=msg):
grouped["C"].__getitem__("D")
def test_groupby_as_index_cython(df):
data = df
# single-key
grouped = data.groupby("A", as_index=False)
result = grouped.mean()
expected = data.groupby(["A"]).mean()
expected.insert(0, "A", expected.index)
expected.index = np.arange(len(expected))
tm.assert_frame_equal(result, expected)
# multi-key
grouped = data.groupby(["A", "B"], as_index=False)
result = grouped.mean()
expected = data.groupby(["A", "B"]).mean()
arrays = list(zip(*expected.index.values))
expected.insert(0, "A", arrays[0])
expected.insert(1, "B", arrays[1])
expected.index = np.arange(len(expected))
tm.assert_frame_equal(result, expected)
def test_groupby_as_index_series_scalar(df):
grouped = df.groupby(["A", "B"], as_index=False)
# GH #421
result = grouped["C"].agg(len)
expected = grouped.agg(len).loc[:, ["A", "B", "C"]]
tm.assert_frame_equal(result, expected)
def test_groupby_as_index_corner(df, ts):
msg = "as_index=False only valid with DataFrame"
with pytest.raises(TypeError, match=msg):
ts.groupby(lambda x: x.weekday(), as_index=False)
msg = "as_index=False only valid for axis=0"
with pytest.raises(ValueError, match=msg):
df.groupby(lambda x: x.lower(), as_index=False, axis=1)
def test_groupby_multiple_key(df):
df = tm.makeTimeDataFrame()
grouped = df.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day])
agged = grouped.sum()
tm.assert_almost_equal(df.values, agged.values)
grouped = df.T.groupby(
[lambda x: x.year, lambda x: x.month, lambda x: x.day], axis=1
)
agged = grouped.agg(lambda x: x.sum())
tm.assert_index_equal(agged.index, df.columns)
tm.assert_almost_equal(df.T.values, agged.values)
agged = grouped.agg(lambda x: x.sum())
tm.assert_almost_equal(df.T.values, agged.values)
def test_groupby_multi_corner(df):
# test that having an all-NA column doesn't mess you up
df = df.copy()
df["bad"] = np.nan
agged = df.groupby(["A", "B"]).mean()
expected = df.groupby(["A", "B"]).mean()
expected["bad"] = np.nan
tm.assert_frame_equal(agged, expected)
def test_omit_nuisance(df):
grouped = df.groupby("A")
result = grouped.mean()
expected = df.loc[:, ["A", "C", "D"]].groupby("A").mean()
tm.assert_frame_equal(result, expected)
agged = grouped.agg(np.mean)
exp = grouped.mean()
tm.assert_frame_equal(agged, exp)
df = df.loc[:, ["A", "C", "D"]]
df["E"] = datetime.now()
grouped = df.groupby("A")
result = grouped.agg(np.sum)
expected = grouped.sum()
tm.assert_frame_equal(result, expected)
# won't work with axis = 1
grouped = df.groupby({"A": 0, "C": 0, "D": 1, "E": 1}, axis=1)
msg = "'DatetimeArray' does not implement reduction 'sum'"
with pytest.raises(TypeError, match=msg):
grouped.agg(lambda x: x.sum(0, numeric_only=False))
def test_omit_nuisance_sem(df):
# GH 38774 - sem should work with nuisance columns
grouped = df.groupby("A")
result = grouped.sem()
expected = df.loc[:, ["A", "C", "D"]].groupby("A").sem()
tm.assert_frame_equal(result, expected)
def test_omit_nuisance_python_multiple(three_group):
grouped = three_group.groupby(["A", "B"])
agged = grouped.agg(np.mean)
exp = grouped.mean()
tm.assert_frame_equal(agged, exp)
def test_empty_groups_corner(mframe):
# handle empty groups
df = DataFrame(
{
"k1": np.array(["b", "b", "b", "a", "a", "a"]),
"k2": np.array(["1", "1", "1", "2", "2", "2"]),
"k3": ["foo", "bar"] * 3,
"v1": np.random.randn(6),
"v2": np.random.randn(6),
}
)
grouped = df.groupby(["k1", "k2"])
result = grouped.agg(np.mean)
expected = grouped.mean()
tm.assert_frame_equal(result, expected)
grouped = mframe[3:5].groupby(level=0)
agged = grouped.apply(lambda x: x.mean())
agged_A = grouped["A"].apply(np.mean)
tm.assert_series_equal(agged["A"], agged_A)
assert agged.index.name == "first"
def test_nonsense_func():
df = DataFrame([0])
msg = r"unsupported operand type\(s\) for \+: 'int' and 'str'"
with pytest.raises(TypeError, match=msg):
df.groupby(lambda x: x + "foo")
def test_wrap_aggregated_output_multindex(mframe):
df = mframe.T
df["baz", "two"] = "peekaboo"
keys = [np.array([0, 0, 1]), np.array([0, 0, 1])]
agged = df.groupby(keys).agg(np.mean)
assert isinstance(agged.columns, MultiIndex)
def aggfun(ser):
if ser.name == ("foo", "one"):
raise TypeError
else:
return ser.sum()
agged2 = df.groupby(keys).aggregate(aggfun)
assert len(agged2.columns) + 1 == len(df.columns)
def test_groupby_level_apply(mframe):
result = mframe.groupby(level=0).count()
assert result.index.name == "first"
result = mframe.groupby(level=1).count()
assert result.index.name == "second"
result = mframe["A"].groupby(level=0).count()
assert result.index.name == "first"
def test_groupby_level_mapper(mframe):
deleveled = mframe.reset_index()
mapper0 = {"foo": 0, "bar": 0, "baz": 1, "qux": 1}
mapper1 = {"one": 0, "two": 0, "three": 1}
result0 = mframe.groupby(mapper0, level=0).sum()
result1 = mframe.groupby(mapper1, level=1).sum()
mapped_level0 = np.array([mapper0.get(x) for x in deleveled["first"]])
mapped_level1 = np.array([mapper1.get(x) for x in deleveled["second"]])
expected0 = mframe.groupby(mapped_level0).sum()
expected1 = mframe.groupby(mapped_level1).sum()
expected0.index.name, expected1.index.name = "first", "second"
tm.assert_frame_equal(result0, expected0)
tm.assert_frame_equal(result1, expected1)
def test_groupby_level_nonmulti():
# GH 1313, GH 13901
s = Series([1, 2, 3, 10, 4, 5, 20, 6], Index([1, 2, 3, 1, 4, 5, 2, 6], name="foo"))
expected = Series([11, 22, 3, 4, 5, 6], Index(range(1, 7), name="foo"))
result = s.groupby(level=0).sum()
tm.assert_series_equal(result, expected)
result = s.groupby(level=[0]).sum()
tm.assert_series_equal(result, expected)
result = s.groupby(level=-1).sum()
tm.assert_series_equal(result, expected)
result = s.groupby(level=[-1]).sum()
tm.assert_series_equal(result, expected)
msg = "level > 0 or level < -1 only valid with MultiIndex"
with pytest.raises(ValueError, match=msg):
s.groupby(level=1)
with pytest.raises(ValueError, match=msg):
s.groupby(level=-2)
msg = "No group keys passed!"
with pytest.raises(ValueError, match=msg):
s.groupby(level=[])
msg = "multiple levels only valid with MultiIndex"
with pytest.raises(ValueError, match=msg):
s.groupby(level=[0, 0])
with pytest.raises(ValueError, match=msg):
s.groupby(level=[0, 1])
msg = "level > 0 or level < -1 only valid with MultiIndex"
with pytest.raises(ValueError, match=msg):
s.groupby(level=[1])
def test_groupby_complex():
# GH 12902
a = Series(data=np.arange(4) * (1 + 2j), index=[0, 0, 1, 1])
expected = Series((1 + 2j, 5 + 10j))
result = a.groupby(level=0).sum()
tm.assert_series_equal(result, expected)
with tm.assert_produces_warning(FutureWarning):
result = a.sum(level=0)
tm.assert_series_equal(result, expected)
def test_groupby_series_indexed_differently():
s1 = Series(
[5.0, -9.0, 4.0, 100.0, -5.0, 55.0, 6.7],
index=Index(["a", "b", "c", "d", "e", "f", "g"]),
)
s2 = Series(
[1.0, 1.0, 4.0, 5.0, 5.0, 7.0], index=Index(["a", "b", "d", "f", "g", "h"])
)
grouped = s1.groupby(s2)
agged = grouped.mean()
exp = s1.groupby(s2.reindex(s1.index).get).mean()
tm.assert_series_equal(agged, exp)
def test_groupby_with_hier_columns():
tuples = list(
zip(
*[
["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
["one", "two", "one", "two", "one", "two", "one", "two"],
]
)
)
index = MultiIndex.from_tuples(tuples)
columns = MultiIndex.from_tuples(
[("A", "cat"), ("B", "dog"), ("B", "cat"), ("A", "dog")]
)
df = DataFrame(np.random.randn(8, 4), index=index, columns=columns)
result = df.groupby(level=0).mean()
tm.assert_index_equal(result.columns, columns)
result = df.groupby(level=0, axis=1).mean()
tm.assert_index_equal(result.index, df.index)
result = df.groupby(level=0).agg(np.mean)
tm.assert_index_equal(result.columns, columns)
result = df.groupby(level=0).apply(lambda x: x.mean())
tm.assert_index_equal(result.columns, columns)
result = df.groupby(level=0, axis=1).agg(lambda x: x.mean(1))
tm.assert_index_equal(result.columns, Index(["A", "B"]))
tm.assert_index_equal(result.index, df.index)
# add a nuisance column
sorted_columns, _ = columns.sortlevel(0)
df["A", "foo"] = "bar"
result = df.groupby(level=0).mean()
tm.assert_index_equal(result.columns, df.columns[:-1])
def test_grouping_ndarray(df):
grouped = df.groupby(df["A"].values)
result = grouped.sum()
expected = df.groupby("A").sum()
tm.assert_frame_equal(
result, expected, check_names=False
) # Note: no names when grouping by value
def test_groupby_wrong_multi_labels():
data = """index,foo,bar,baz,spam,data
0,foo1,bar1,baz1,spam2,20
1,foo1,bar2,baz1,spam3,30
2,foo2,bar2,baz1,spam2,40
3,foo1,bar1,baz2,spam1,50
4,foo3,bar1,baz2,spam1,60"""
data = read_csv(StringIO(data), index_col=0)
grouped = data.groupby(["foo", "bar", "baz", "spam"])
result = grouped.agg(np.mean)
expected = grouped.mean()
tm.assert_frame_equal(result, expected)
def test_groupby_series_with_name(df):
result = df.groupby(df["A"]).mean()
result2 = df.groupby(df["A"], as_index=False).mean()
assert result.index.name == "A"
assert "A" in result2
result = df.groupby([df["A"], df["B"]]).mean()
result2 = df.groupby([df["A"], df["B"]], as_index=False).mean()
assert result.index.names == ("A", "B")
assert "A" in result2
assert "B" in result2
def test_seriesgroupby_name_attr(df):
# GH 6265
result = df.groupby("A")["C"]
assert result.count().name == "C"
assert result.mean().name == "C"
testFunc = lambda x: np.sum(x) * 2
assert result.agg(testFunc).name == "C"
def test_consistency_name():
# GH 12363
df = DataFrame(
{
"A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"],
"B": ["one", "one", "two", "two", "two", "two", "one", "two"],
"C": np.random.randn(8) + 1.0,
"D": np.arange(8),
}
)
expected = df.groupby(["A"]).B.count()
result = df.B.groupby(df.A).count()
tm.assert_series_equal(result, expected)
def test_groupby_name_propagation(df):
# GH 6124
def summarize(df, name=None):
return Series({"count": 1, "mean": 2, "omissions": 3}, name=name)
def summarize_random_name(df):
# Provide a different name for each Series. In this case, groupby
# should not attempt to propagate the Series name since they are
# inconsistent.
return Series({"count": 1, "mean": 2, "omissions": 3}, name=df.iloc[0]["A"])
metrics = df.groupby("A").apply(summarize)
assert metrics.columns.name is None
metrics = df.groupby("A").apply(summarize, "metrics")
assert metrics.columns.name == "metrics"
metrics = df.groupby("A").apply(summarize_random_name)
assert metrics.columns.name is None
def test_groupby_nonstring_columns():
df = DataFrame([np.arange(10) for x in range(10)])
grouped = df.groupby(0)
result = grouped.mean()
expected = df.groupby(df[0]).mean()
tm.assert_frame_equal(result, expected)
def test_groupby_mixed_type_columns():
# GH 13432, unorderable types in py3
df = DataFrame([[0, 1, 2]], columns=["A", "B", 0])
expected = DataFrame([[1, 2]], columns=["B", 0], index=Index([0], name="A"))
result = df.groupby("A").first()
tm.assert_frame_equal(result, expected)
result = df.groupby("A").sum()
tm.assert_frame_equal(result, expected)
# TODO: Ensure warning isn't emitted in the first place
@pytest.mark.filterwarnings("ignore:Mean of:RuntimeWarning")
def test_cython_grouper_series_bug_noncontig():
arr = np.empty((100, 100))
arr.fill(np.nan)
obj = Series(arr[:, 0])
inds = np.tile(range(10), 10)
result = obj.groupby(inds).agg(Series.median)
assert result.isna().all()
def test_series_grouper_noncontig_index():
index = Index(tm.rands_array(10, 100))
values = Series(np.random.randn(50), index=index[::2])
labels = np.random.randint(0, 5, 50)
# it works!
grouped = values.groupby(labels)
# accessing the index elements causes segfault
f = lambda x: len(set(map(id, x.index)))
grouped.agg(f)
def test_convert_objects_leave_decimal_alone():
s = Series(range(5))
labels = np.array(["a", "b", "c", "d", "e"], dtype="O")
def convert_fast(x):
return Decimal(str(x.mean()))
def convert_force_pure(x):
# base will be length 0
assert len(x.values.base) > 0
return Decimal(str(x.mean()))
grouped = s.groupby(labels)
result = grouped.agg(convert_fast)
assert result.dtype == np.object_
assert isinstance(result[0], Decimal)
result = grouped.agg(convert_force_pure)
assert result.dtype == np.object_
assert isinstance(result[0], Decimal)
def test_groupby_dtype_inference_empty():
# GH 6733
df = DataFrame({"x": [], "range": np.arange(0, dtype="int64")})
assert df["x"].dtype == np.float64
result = df.groupby("x").first()
exp_index = Index([], name="x", dtype=np.float64)
expected = DataFrame({"range": Series([], index=exp_index, dtype="int64")})
tm.assert_frame_equal(result, expected, by_blocks=True)
def test_groupby_unit64_float_conversion():
# GH: 30859 groupby converts unit64 to floats sometimes
df = DataFrame({"first": [1], "second": [1], "value": [16148277970000000000]})
result = df.groupby(["first", "second"])["value"].max()
expected = Series(
[16148277970000000000],
MultiIndex.from_product([[1], [1]], names=["first", "second"]),
name="value",
)
tm.assert_series_equal(result, expected)
def test_groupby_list_infer_array_like(df):
result = df.groupby(list(df["A"])).mean()
expected = df.groupby(df["A"]).mean()
tm.assert_frame_equal(result, expected, check_names=False)
with pytest.raises(KeyError, match=r"^'foo'$"):
df.groupby(list(df["A"][:-1]))
# pathological case of ambiguity
df = DataFrame({"foo": [0, 1], "bar": [3, 4], "val": np.random.randn(2)})
result = df.groupby(["foo", "bar"]).mean()
expected = df.groupby([df["foo"], df["bar"]]).mean()[["val"]]
def test_groupby_keys_same_size_as_index():
# GH 11185
freq = "s"
index = date_range(
start=Timestamp("2015-09-29T11:34:44-0700"), periods=2, freq=freq
)
df = DataFrame([["A", 10], ["B", 15]], columns=["metric", "values"], index=index)
result = df.groupby([Grouper(level=0, freq=freq), "metric"]).mean()
expected = df.set_index([df.index, "metric"])
tm.assert_frame_equal(result, expected)
def test_groupby_one_row():
# GH 11741
msg = r"^'Z'$"
df1 = DataFrame(np.random.randn(1, 4), columns=list("ABCD"))
with pytest.raises(KeyError, match=msg):
df1.groupby("Z")
df2 = DataFrame(np.random.randn(2, 4), columns=list("ABCD"))
with pytest.raises(KeyError, match=msg):
df2.groupby("Z")
def test_groupby_nat_exclude():
# GH 6992
df = DataFrame(
{
"values": np.random.randn(8),
"dt": [
np.nan,
Timestamp("2013-01-01"),
np.nan,
Timestamp("2013-02-01"),
np.nan,
Timestamp("2013-02-01"),
np.nan,
Timestamp("2013-01-01"),
],
"str": [np.nan, "a", np.nan, "a", np.nan, "a", np.nan, "b"],
}
)
grouped = df.groupby("dt")
expected = [Index([1, 7]), Index([3, 5])]
keys = sorted(grouped.groups.keys())
assert len(keys) == 2
for k, e in zip(keys, expected):
# grouped.groups keys are np.datetime64 with system tz
# not to be affected by tz, only compare values
tm.assert_index_equal(grouped.groups[k], e)
# confirm obj is not filtered
tm.assert_frame_equal(grouped.grouper.groupings[0].obj, df)
assert grouped.ngroups == 2
expected = {
Timestamp("2013-01-01 00:00:00"): np.array([1, 7], dtype=np.intp),
Timestamp("2013-02-01 00:00:00"): np.array([3, 5], dtype=np.intp),
}
for k in grouped.indices:
tm.assert_numpy_array_equal(grouped.indices[k], expected[k])
tm.assert_frame_equal(grouped.get_group(Timestamp("2013-01-01")), df.iloc[[1, 7]])
tm.assert_frame_equal(grouped.get_group(Timestamp("2013-02-01")), df.iloc[[3, 5]])
with pytest.raises(KeyError, match=r"^NaT$"):
grouped.get_group(pd.NaT)
nan_df = DataFrame(
{"nan": [np.nan, np.nan, np.nan], "nat": [pd.NaT, pd.NaT, pd.NaT]}
)
assert nan_df["nan"].dtype == "float64"
assert nan_df["nat"].dtype == "datetime64[ns]"
for key in ["nan", "nat"]:
grouped = nan_df.groupby(key)
assert grouped.groups == {}
assert grouped.ngroups == 0
assert grouped.indices == {}
with pytest.raises(KeyError, match=r"^nan$"):
grouped.get_group(np.nan)
with pytest.raises(KeyError, match=r"^NaT$"):
grouped.get_group(pd.NaT)
def test_groupby_two_group_keys_all_nan():
# GH #36842: Grouping over two group keys shouldn't raise an error
df = DataFrame({"a": [np.nan, np.nan], "b": [np.nan, np.nan], "c": [1, 2]})
result = df.groupby(["a", "b"]).indices
assert result == {}
def test_groupby_2d_malformed():
d = DataFrame(index=range(2))
d["group"] = ["g1", "g2"]
d["zeros"] = [0, 0]
d["ones"] = [1, 1]
d["label"] = ["l1", "l2"]
tmp = d.groupby(["group"]).mean()
res_values = np.array([[0, 1], [0, 1]], dtype=np.int64)
tm.assert_index_equal(tmp.columns, Index(["zeros", "ones"]))
tm.assert_numpy_array_equal(tmp.values, res_values)
def test_int32_overflow():
B = np.concatenate((np.arange(10000), np.arange(10000), np.arange(5000)))
A = np.arange(25000)
df = DataFrame({"A": A, "B": B, "C": A, "D": B, "E": np.random.randn(25000)})
left = df.groupby(["A", "B", "C", "D"]).sum()
right = df.groupby(["D", "C", "B", "A"]).sum()
assert len(left) == len(right)
def test_groupby_sort_multi():
df = DataFrame(
{
"a": ["foo", "bar", "baz"],
"b": [3, 2, 1],
"c": [0, 1, 2],
"d": np.random.randn(3),
}
)
tups = [tuple(row) for row in df[["a", "b", "c"]].values]
tups = com.asarray_tuplesafe(tups)
result = df.groupby(["a", "b", "c"], sort=True).sum()
tm.assert_numpy_array_equal(result.index.values, tups[[1, 2, 0]])
tups = [tuple(row) for row in df[["c", "a", "b"]].values]
tups = com.asarray_tuplesafe(tups)
result = df.groupby(["c", "a", "b"], sort=True).sum()
tm.assert_numpy_array_equal(result.index.values, tups)
tups = [tuple(x) for x in df[["b", "c", "a"]].values]
tups = com.asarray_tuplesafe(tups)
result = df.groupby(["b", "c", "a"], sort=True).sum()
tm.assert_numpy_array_equal(result.index.values, tups[[2, 1, 0]])
df = DataFrame(
{"a": [0, 1, 2, 0, 1, 2], "b": [0, 0, 0, 1, 1, 1], "d": np.random.randn(6)}
)
grouped = df.groupby(["a", "b"])["d"]
result = grouped.sum()
def _check_groupby(df, result, keys, field, f=lambda x: x.sum()):
tups = [tuple(row) for row in df[keys].values]
tups = com.asarray_tuplesafe(tups)
expected = f(df.groupby(tups)[field])
for k, v in expected.items():
assert result[k] == v
_check_groupby(df, result, ["a", "b"], "d")
def test_dont_clobber_name_column():
df = DataFrame(
{"key": ["a", "a", "a", "b", "b", "b"], "name": ["foo", "bar", "baz"] * 2}
)
result = df.groupby("key").apply(lambda x: x)
tm.assert_frame_equal(result, df)
def test_skip_group_keys():
tsf = tm.makeTimeDataFrame()
grouped = tsf.groupby(lambda x: x.month, group_keys=False)
result = grouped.apply(lambda x: x.sort_values(by="A")[:3])
pieces = [group.sort_values(by="A")[:3] for key, group in grouped]
expected = pd.concat(pieces)
tm.assert_frame_equal(result, expected)
grouped = tsf["A"].groupby(lambda x: x.month, group_keys=False)
result = grouped.apply(lambda x: x.sort_values()[:3])
pieces = [group.sort_values()[:3] for key, group in grouped]
expected = pd.concat(pieces)
tm.assert_series_equal(result, expected)
def test_no_nonsense_name(float_frame):
# GH #995
s = float_frame["C"].copy()
s.name = None
result = s.groupby(float_frame["A"]).agg(np.sum)
assert result.name is None
def test_multifunc_sum_bug():
# GH #1065
x = DataFrame(np.arange(9).reshape(3, 3))
x["test"] = 0
x["fl"] = [1.3, 1.5, 1.6]
grouped = x.groupby("test")
result = grouped.agg({"fl": "sum", 2: "size"})
assert result["fl"].dtype == np.float64
def test_handle_dict_return_value(df):
def f(group):
return {"max": group.max(), "min": group.min()}
def g(group):
return Series({"max": group.max(), "min": group.min()})
result = df.groupby("A")["C"].apply(f)
expected = df.groupby("A")["C"].apply(g)
assert isinstance(result, Series)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("grouper", ["A", ["A", "B"]])
def test_set_group_name(df, grouper):
def f(group):
assert group.name is not None
return group
def freduce(group):
assert group.name is not None
return group.sum()
def foo(x):
return freduce(x)
grouped = df.groupby(grouper)
# make sure all these work
grouped.apply(f)
grouped.aggregate(freduce)
grouped.aggregate({"C": freduce, "D": freduce})
grouped.transform(f)
grouped["C"].apply(f)
grouped["C"].aggregate(freduce)
grouped["C"].aggregate([freduce, foo])
grouped["C"].transform(f)
def test_group_name_available_in_inference_pass():
# gh-15062
df = DataFrame({"a": [0, 0, 1, 1, 2, 2], "b": np.arange(6)})
names = []
def f(group):
names.append(group.name)
return group.copy()
df.groupby("a", sort=False, group_keys=False).apply(f)
expected_names = [0, 1, 2]
assert names == expected_names
def test_no_dummy_key_names(df):
# see gh-1291
result = df.groupby(df["A"].values).sum()
assert result.index.name is None
result = df.groupby([df["A"].values, df["B"].values]).sum()
assert result.index.names == (None, None)
def test_groupby_sort_multiindex_series():
# series multiindex groupby sort argument was not being passed through
# _compress_group_index
# GH 9444
index = MultiIndex(
levels=[[1, 2], [1, 2]],
codes=[[0, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 0]],
names=["a", "b"],
)
mseries = Series([0, 1, 2, 3, 4, 5], index=index)
index = MultiIndex(
levels=[[1, 2], [1, 2]], codes=[[0, 0, 1], [1, 0, 0]], names=["a", "b"]
)
mseries_result = Series([0, 2, 4], index=index)
result = mseries.groupby(level=["a", "b"], sort=False).first()
tm.assert_series_equal(result, mseries_result)
result = mseries.groupby(level=["a", "b"], sort=True).first()
tm.assert_series_equal(result, mseries_result.sort_index())
def test_groupby_reindex_inside_function():
periods = 1000
ind = date_range(start="2012/1/1", freq="5min", periods=periods)
df = DataFrame({"high": np.arange(periods), "low": np.arange(periods)}, index=ind)
def agg_before(func, fix=False):
"""
Run an aggregate func on the subset of data.
"""
def _func(data):
d = data.loc[data.index.map(lambda x: x.hour < 11)].dropna()
if fix:
data[data.index[0]]
if len(d) == 0:
return None
return func(d)
return _func
grouped = df.groupby(lambda x: datetime(x.year, x.month, x.day))
closure_bad = grouped.agg({"high": agg_before(np.max)})
closure_good = grouped.agg({"high": agg_before(np.max, True)})
tm.assert_frame_equal(closure_bad, closure_good)
def test_groupby_multiindex_missing_pair():
# GH9049
df = DataFrame(
{
"group1": ["a", "a", "a", "b"],
"group2": ["c", "c", "d", "c"],
"value": [1, 1, 1, 5],
}
)
df = df.set_index(["group1", "group2"])
df_grouped = df.groupby(level=["group1", "group2"], sort=True)
res = df_grouped.agg("sum")
idx = MultiIndex.from_tuples(
[("a", "c"), ("a", "d"), ("b", "c")], names=["group1", "group2"]
)
exp = DataFrame([[2], [1], [5]], index=idx, columns=["value"])
tm.assert_frame_equal(res, exp)
def test_groupby_multiindex_not_lexsorted():
# GH 11640
# define the lexsorted version
lexsorted_mi = MultiIndex.from_tuples(
[("a", ""), ("b1", "c1"), ("b2", "c2")], names=["b", "c"]
)
lexsorted_df = DataFrame([[1, 3, 4]], columns=lexsorted_mi)
assert lexsorted_df.columns._is_lexsorted()
# define the non-lexsorted version
not_lexsorted_df = DataFrame(
columns=["a", "b", "c", "d"], data=[[1, "b1", "c1", 3], [1, "b2", "c2", 4]]
)
not_lexsorted_df = not_lexsorted_df.pivot_table(
index="a", columns=["b", "c"], values="d"
)
not_lexsorted_df = not_lexsorted_df.reset_index()
assert not not_lexsorted_df.columns._is_lexsorted()
# compare the results
tm.assert_frame_equal(lexsorted_df, not_lexsorted_df)
expected = lexsorted_df.groupby("a").mean()
with tm.assert_produces_warning(PerformanceWarning):
result = not_lexsorted_df.groupby("a").mean()
tm.assert_frame_equal(expected, result)
# a transforming function should work regardless of sort
# GH 14776
df = DataFrame(
{"x": ["a", "a", "b", "a"], "y": [1, 1, 2, 2], "z": [1, 2, 3, 4]}
).set_index(["x", "y"])
assert not df.index._is_lexsorted()
for level in [0, 1, [0, 1]]:
for sort in [False, True]:
result = df.groupby(level=level, sort=sort).apply(DataFrame.drop_duplicates)
expected = df
tm.assert_frame_equal(expected, result)
result = (
df.sort_index()
.groupby(level=level, sort=sort)
.apply(DataFrame.drop_duplicates)
)
expected = df.sort_index()
tm.assert_frame_equal(expected, result)
def test_index_label_overlaps_location():
# checking we don't have any label/location confusion in the
# wake of GH5375
df = DataFrame(list("ABCDE"), index=[2, 0, 2, 1, 1])
g = df.groupby(list("ababb"))
actual = g.filter(lambda x: len(x) > 2)
expected = df.iloc[[1, 3, 4]]
tm.assert_frame_equal(actual, expected)
ser = df[0]
g = ser.groupby(list("ababb"))
actual = g.filter(lambda x: len(x) > 2)
expected = ser.take([1, 3, 4])
tm.assert_series_equal(actual, expected)
# ... and again, with a generic Index of floats
df.index = df.index.astype(float)
g = df.groupby(list("ababb"))
actual = g.filter(lambda x: len(x) > 2)
expected = df.iloc[[1, 3, 4]]
tm.assert_frame_equal(actual, expected)
ser = df[0]
g = ser.groupby(list("ababb"))
actual = g.filter(lambda x: len(x) > 2)
expected = ser.take([1, 3, 4])
tm.assert_series_equal(actual, expected)
def test_transform_doesnt_clobber_ints():
# GH 7972
n = 6
x = np.arange(n)
df = DataFrame({"a": x // 2, "b": 2.0 * x, "c": 3.0 * x})
df2 = DataFrame({"a": x // 2 * 1.0, "b": 2.0 * x, "c": 3.0 * x})
gb = df.groupby("a")
result = gb.transform("mean")
gb2 = df2.groupby("a")
expected = gb2.transform("mean")
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"sort_column",
["ints", "floats", "strings", ["ints", "floats"], ["ints", "strings"]],
)
@pytest.mark.parametrize(
"group_column", ["int_groups", "string_groups", ["int_groups", "string_groups"]]
)
def test_groupby_preserves_sort(sort_column, group_column):
# Test to ensure that groupby always preserves sort order of original
# object. Issue #8588 and #9651
df = DataFrame(
{
"int_groups": [3, 1, 0, 1, 0, 3, 3, 3],
"string_groups": ["z", "a", "z", "a", "a", "g", "g", "g"],
"ints": [8, 7, 4, 5, 2, 9, 1, 1],
"floats": [2.3, 5.3, 6.2, -2.4, 2.2, 1.1, 1.1, 5],
"strings": ["z", "d", "a", "e", "word", "word2", "42", "47"],
}
)
# Try sorting on different types and with different group types
df = df.sort_values(by=sort_column)
g = df.groupby(group_column)
def test_sort(x):
tm.assert_frame_equal(x, x.sort_values(by=sort_column))
g.apply(test_sort)
def test_pivot_table_values_key_error():
# This test is designed to replicate the error in issue #14938
df = DataFrame(
{
"eventDate": date_range(datetime.today(), periods=20, freq="M").tolist(),
"thename": range(0, 20),
}
)
df["year"] = df.set_index("eventDate").index.year
df["month"] = df.set_index("eventDate").index.month
with pytest.raises(KeyError, match="'badname'"):
df.reset_index().pivot_table(
index="year", columns="month", values="badname", aggfunc="count"
)
@pytest.mark.parametrize("columns", ["C", ["C"]])
@pytest.mark.parametrize("keys", [["A"], ["A", "B"]])
@pytest.mark.parametrize(
"values",
[
[True],
[0],
[0.0],
["a"],
Categorical([0]),
[to_datetime(0)],
date_range(0, 1, 1, tz="US/Eastern"),
pd.array([0], dtype="Int64"),
pd.array([0], dtype="Float64"),
pd.array([False], dtype="boolean"),
],
)
@pytest.mark.parametrize("method", ["attr", "agg", "apply"])
@pytest.mark.parametrize(
"op", ["idxmax", "idxmin", "mad", "min", "max", "sum", "prod", "skew"]
)
def test_empty_groupby(columns, keys, values, method, op, request):
# GH8093 & GH26411
if isinstance(values, Categorical) and len(keys) == 1 and method == "apply":
mark = pytest.mark.xfail(raises=TypeError, match="'str' object is not callable")
request.node.add_marker(mark)
elif (
isinstance(values, Categorical)
and len(keys) == 1
and op in ["idxmax", "idxmin"]
):
mark = pytest.mark.xfail(
raises=ValueError, match="attempt to get arg(min|max) of an empty sequence"
)
request.node.add_marker(mark)
elif (
isinstance(values, Categorical)
and len(keys) == 1
and not isinstance(columns, list)
):
mark = pytest.mark.xfail(
raises=TypeError, match="'Categorical' does not implement"
)
request.node.add_marker(mark)
elif (
isinstance(values, Categorical)
and len(keys) == 1
and op in ["mad", "min", "max", "sum", "prod", "skew"]
):
mark = pytest.mark.xfail(
raises=AssertionError, match="(DataFrame|Series) are different"
)
request.node.add_marker(mark)
elif (
isinstance(values, Categorical)
and len(keys) == 2
and op in ["min", "max", "sum"]
and method != "apply"
):
mark = pytest.mark.xfail(
raises=AssertionError, match="(DataFrame|Series) are different"
)
request.node.add_marker(mark)
elif (
isinstance(values, pd.core.arrays.BooleanArray)
and op in ["sum", "prod"]
and method != "apply"
):
mark = pytest.mark.xfail(
raises=AssertionError, match="(DataFrame|Series) are different"
)
request.node.add_marker(mark)
override_dtype = None
if isinstance(values[0], bool) and op in ("prod", "sum") and method != "apply":
# sum/product of bools is an integer
override_dtype = "int64"
df = DataFrame({"A": values, "B": values, "C": values}, columns=list("ABC"))
if hasattr(values, "dtype"):
# check that we did the construction right
assert (df.dtypes == values.dtype).all()
df = df.iloc[:0]
gb = df.groupby(keys)[columns]
if method == "attr":
result = getattr(gb, op)()
else:
result = getattr(gb, method)(op)
expected = df.set_index(keys)[columns]
if override_dtype is not None:
expected = expected.astype(override_dtype)
if len(keys) == 1:
expected.index.name = keys[0]
tm.assert_equal(result, expected)
def test_tuple_as_grouping():
# https://github.com/pandas-dev/pandas/issues/18314
df = DataFrame(
{
("a", "b"): [1, 1, 1, 1],
"a": [2, 2, 2, 2],
"b": [2, 2, 2, 2],
"c": [1, 1, 1, 1],
}
)
with pytest.raises(KeyError, match=r"('a', 'b')"):
df[["a", "b", "c"]].groupby(("a", "b"))
result = df.groupby(("a", "b"))["c"].sum()
expected = Series([4], name="c", index=Index([1], name=("a", "b")))
tm.assert_series_equal(result, expected)
def test_tuple_correct_keyerror():
# https://github.com/pandas-dev/pandas/issues/18798
df = DataFrame(1, index=range(3), columns=MultiIndex.from_product([[1, 2], [3, 4]]))
with pytest.raises(KeyError, match=r"^\(7, 8\)$"):
df.groupby((7, 8)).mean()
def test_groupby_agg_ohlc_non_first():
# GH 21716
df = DataFrame(
[[1], [1]],
columns=["foo"],
index=date_range("2018-01-01", periods=2, freq="D"),
)
expected = DataFrame(
[[1, 1, 1, 1, 1], [1, 1, 1, 1, 1]],
columns=MultiIndex.from_tuples(
(
("foo", "sum", "foo"),
("foo", "ohlc", "open"),
("foo", "ohlc", "high"),
("foo", "ohlc", "low"),
("foo", "ohlc", "close"),
)
),
index=date_range("2018-01-01", periods=2, freq="D"),
)
result = df.groupby(Grouper(freq="D")).agg(["sum", "ohlc"])
tm.assert_frame_equal(result, expected)
def test_groupby_multiindex_nat():
# GH 9236
values = [
(pd.NaT, "a"),
(datetime(2012, 1, 2), "a"),
(datetime(2012, 1, 2), "b"),
(datetime(2012, 1, 3), "a"),
]
mi = MultiIndex.from_tuples(values, names=["date", None])
ser = Series([3, 2, 2.5, 4], index=mi)
result = ser.groupby(level=1).mean()
expected = Series([3.0, 2.5], index=["a", "b"])
tm.assert_series_equal(result, expected)
def test_groupby_empty_list_raises():
# GH 5289
values = zip(range(10), range(10))
df = DataFrame(values, columns=["apple", "b"])
msg = "Grouper and axis must be same length"
with pytest.raises(ValueError, match=msg):
df.groupby([[]])
def test_groupby_multiindex_series_keys_len_equal_group_axis():
# GH 25704
index_array = [["x", "x"], ["a", "b"], ["k", "k"]]
index_names = ["first", "second", "third"]
ri = MultiIndex.from_arrays(index_array, names=index_names)
s = Series(data=[1, 2], index=ri)
result = s.groupby(["first", "third"]).sum()
index_array = [["x"], ["k"]]
index_names = ["first", "third"]
ei = MultiIndex.from_arrays(index_array, names=index_names)
expected = Series([3], index=ei)
tm.assert_series_equal(result, expected)
def test_groupby_groups_in_BaseGrouper():
# GH 26326
# Test if DataFrame grouped with a pandas.Grouper has correct groups
mi = MultiIndex.from_product([["A", "B"], ["C", "D"]], names=["alpha", "beta"])
df = DataFrame({"foo": [1, 2, 1, 2], "bar": [1, 2, 3, 4]}, index=mi)
result = df.groupby([Grouper(level="alpha"), "beta"])
expected = df.groupby(["alpha", "beta"])
assert result.groups == expected.groups
result = df.groupby(["beta", Grouper(level="alpha")])
expected = df.groupby(["beta", "alpha"])
assert result.groups == expected.groups
@pytest.mark.parametrize("group_name", ["x", ["x"]])
def test_groupby_axis_1(group_name):
# GH 27614
df = DataFrame(
np.arange(12).reshape(3, 4), index=[0, 1, 0], columns=[10, 20, 10, 20]
)
df.index.name = "y"
df.columns.name = "x"
results = df.groupby(group_name, axis=1).sum()
expected = df.T.groupby(group_name).sum().T
tm.assert_frame_equal(results, expected)
# test on MI column
iterables = [["bar", "baz", "foo"], ["one", "two"]]
mi = MultiIndex.from_product(iterables=iterables, names=["x", "x1"])
df = DataFrame(np.arange(18).reshape(3, 6), index=[0, 1, 0], columns=mi)
results = df.groupby(group_name, axis=1).sum()
expected = df.T.groupby(group_name).sum().T
tm.assert_frame_equal(results, expected)
@pytest.mark.parametrize(
"op, expected",
[
(
"shift",
{
"time": [
None,
None,
Timestamp("2019-01-01 12:00:00"),
Timestamp("2019-01-01 12:30:00"),
None,
None,
]
},
),
(
"bfill",
{
"time": [
Timestamp("2019-01-01 12:00:00"),
Timestamp("2019-01-01 12:30:00"),
Timestamp("2019-01-01 14:00:00"),
Timestamp("2019-01-01 14:30:00"),
Timestamp("2019-01-01 14:00:00"),
Timestamp("2019-01-01 14:30:00"),
]
},
),
(
"ffill",
{
"time": [
Timestamp("2019-01-01 12:00:00"),
Timestamp("2019-01-01 12:30:00"),
Timestamp("2019-01-01 12:00:00"),
Timestamp("2019-01-01 12:30:00"),
Timestamp("2019-01-01 14:00:00"),
Timestamp("2019-01-01 14:30:00"),
]
},
),
],
)
def test_shift_bfill_ffill_tz(tz_naive_fixture, op, expected):
# GH19995, GH27992: Check that timezone does not drop in shift, bfill, and ffill
tz = tz_naive_fixture
data = {
"id": ["A", "B", "A", "B", "A", "B"],
"time": [
Timestamp("2019-01-01 12:00:00"),
Timestamp("2019-01-01 12:30:00"),
None,
None,
Timestamp("2019-01-01 14:00:00"),
Timestamp("2019-01-01 14:30:00"),
],
}
df = DataFrame(data).assign(time=lambda x: x.time.dt.tz_localize(tz))
grouped = df.groupby("id")
result = getattr(grouped, op)()
expected = DataFrame(expected).assign(time=lambda x: x.time.dt.tz_localize(tz))
tm.assert_frame_equal(result, expected)
def test_groupby_only_none_group():
# see GH21624
# this was crashing with "ValueError: Length of passed values is 1, index implies 0"
df = DataFrame({"g": [None], "x": 1})
actual = df.groupby("g")["x"].transform("sum")
expected = Series([np.nan], name="x")
tm.assert_series_equal(actual, expected)
def test_groupby_duplicate_index():
# GH#29189 the groupby call here used to raise
ser = Series([2, 5, 6, 8], index=[2.0, 4.0, 4.0, 5.0])
gb = ser.groupby(level=0)
result = gb.mean()
expected = Series([2, 5.5, 8], index=[2.0, 4.0, 5.0])
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize(
"idx", [Index(["a", "a"]), MultiIndex.from_tuples((("a", "a"), ("a", "a")))]
)
@pytest.mark.filterwarnings("ignore:tshift is deprecated:FutureWarning")
def test_dup_labels_output_shape(groupby_func, idx):
if groupby_func in {"size", "ngroup", "cumcount"}:
pytest.skip("Not applicable")
df = DataFrame([[1, 1]], columns=idx)
grp_by = df.groupby([0])
args = []
if groupby_func in {"fillna", "nth"}:
args.append(0)
elif groupby_func == "corrwith":
args.append(df)
elif groupby_func == "tshift":
df.index = [Timestamp("today")]
args.extend([1, "D"])
result = getattr(grp_by, groupby_func)(*args)
assert result.shape == (1, 2)
tm.assert_index_equal(result.columns, idx)
def test_groupby_crash_on_nunique(axis):
# Fix following 30253
df = DataFrame({("A", "B"): [1, 2], ("A", "C"): [1, 3], ("D", "B"): [0, 0]})
axis_number = df._get_axis_number(axis)
if not axis_number:
df = df.T
result = df.groupby(axis=axis_number, level=0).nunique()
expected = DataFrame({"A": [1, 2], "D": [1, 1]})
if not axis_number:
expected = expected.T
tm.assert_frame_equal(result, expected)
# same thing, but empty columns
gb = df[[]].groupby(axis=axis_number, level=0)
res = gb.nunique()
exp = expected[[]]
tm.assert_frame_equal(res, exp)
def test_groupby_list_level():
# GH 9790
expected = DataFrame(np.arange(0, 9).reshape(3, 3))
result = expected.groupby(level=[0]).mean()
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"max_seq_items, expected",
[
(5, "{0: [0], 1: [1], 2: [2], 3: [3], 4: [4]}"),
(4, "{0: [0], 1: [1], 2: [2], 3: [3], ...}"),
(1, "{0: [0], ...}"),
],
)
def test_groups_repr_truncates(max_seq_items, expected):
# GH 1135
df = DataFrame(np.random.randn(5, 1))
df["a"] = df.index
with pd.option_context("display.max_seq_items", max_seq_items):
result = df.groupby("a").groups.__repr__()
assert result == expected
result = df.groupby(np.array(df.a)).groups.__repr__()
assert result == expected
def test_group_on_two_row_multiindex_returns_one_tuple_key():
# GH 18451
df = DataFrame([{"a": 1, "b": 2, "c": 99}, {"a": 1, "b": 2, "c": 88}])
df = df.set_index(["a", "b"])
grp = df.groupby(["a", "b"])
result = grp.indices
expected = {(1, 2): np.array([0, 1], dtype=np.int64)}
assert len(result) == 1
key = (1, 2)
assert (result[key] == expected[key]).all()
@pytest.mark.parametrize(
"klass, attr, value",
[
(DataFrame, "level", "a"),
(DataFrame, "as_index", False),
(DataFrame, "sort", False),
(DataFrame, "group_keys", False),
(DataFrame, "squeeze", True),
(DataFrame, "observed", True),
(DataFrame, "dropna", False),
pytest.param(
Series,
"axis",
1,
marks=pytest.mark.xfail(
reason="GH 35443: Attribute currently not passed on to series"
),
),
(Series, "level", "a"),
(Series, "as_index", False),
(Series, "sort", False),
(Series, "group_keys", False),
(Series, "squeeze", True),
(Series, "observed", True),
(Series, "dropna", False),
],
)
@pytest.mark.filterwarnings(
"ignore:The `squeeze` parameter is deprecated:FutureWarning"
)
def test_subsetting_columns_keeps_attrs(klass, attr, value):
# GH 9959 - When subsetting columns, don't drop attributes
df = DataFrame({"a": [1], "b": [2], "c": [3]})
if attr != "axis":
df = df.set_index("a")
expected = df.groupby("a", **{attr: value})
result = expected[["b"]] if klass is DataFrame else expected["b"]
assert getattr(result, attr) == getattr(expected, attr)
def test_subsetting_columns_axis_1():
# GH 37725
g = DataFrame({"A": [1], "B": [2], "C": [3]}).groupby([0, 0, 1], axis=1)
match = "Cannot subset columns when using axis=1"
with pytest.raises(ValueError, match=match):
g[["A", "B"]].sum()
@pytest.mark.parametrize("func", ["sum", "any", "shift"])
def test_groupby_column_index_name_lost(func):
# GH: 29764 groupby loses index sometimes
expected = Index(["a"], name="idx")
df = DataFrame([[1]], columns=expected)
df_grouped = df.groupby([1])
result = getattr(df_grouped, func)().columns
tm.assert_index_equal(result, expected)
def test_groupby_duplicate_columns():
# GH: 31735
df = DataFrame(
{"A": ["f", "e", "g", "h"], "B": ["a", "b", "c", "d"], "C": [1, 2, 3, 4]}
).astype(object)
df.columns = ["A", "B", "B"]
result = df.groupby([0, 0, 0, 0]).min()
expected = DataFrame([["e", "a", 1]], columns=["A", "B", "B"])
tm.assert_frame_equal(result, expected)
def test_groupby_series_with_tuple_name():
# GH 37755
ser = Series([1, 2, 3, 4], index=[1, 1, 2, 2], name=("a", "a"))
ser.index.name = ("b", "b")
result = ser.groupby(level=0).last()
expected = Series([2, 4], index=[1, 2], name=("a", "a"))
expected.index.name = ("b", "b")
tm.assert_series_equal(result, expected)
@pytest.mark.xfail(not IS64, reason="GH#38778: fail on 32-bit system")
@pytest.mark.parametrize(
"func, values", [("sum", [97.0, 98.0]), ("mean", [24.25, 24.5])]
)
def test_groupby_numerical_stability_sum_mean(func, values):
# GH#38778
data = [1e16, 1e16, 97, 98, -5e15, -5e15, -5e15, -5e15]
df = DataFrame({"group": [1, 2] * 4, "a": data, "b": data})
result = getattr(df.groupby("group"), func)()
expected = DataFrame({"a": values, "b": values}, index=Index([1, 2], name="group"))
tm.assert_frame_equal(result, expected)
@pytest.mark.xfail(not IS64, reason="GH#38778: fail on 32-bit system")
def test_groupby_numerical_stability_cumsum():
# GH#38934
data = [1e16, 1e16, 97, 98, -5e15, -5e15, -5e15, -5e15]
df = DataFrame({"group": [1, 2] * 4, "a": data, "b": data})
result = df.groupby("group").cumsum()
exp_data = (
[1e16] * 2 + [1e16 + 96, 1e16 + 98] + [5e15 + 97, 5e15 + 98] + [97.0, 98.0]
)
expected = DataFrame({"a": exp_data, "b": exp_data})
tm.assert_frame_equal(result, expected, check_exact=True)
def test_groupby_mean_duplicate_index(rand_series_with_duplicate_datetimeindex):
dups = rand_series_with_duplicate_datetimeindex
result = dups.groupby(level=0).mean()
expected = dups.groupby(dups.index).mean()
tm.assert_series_equal(result, expected)
| 30.504694 | 88 | 0.587201 | from datetime import datetime
from decimal import Decimal
from io import StringIO
import numpy as np
import pytest
from pandas.compat import IS64
from pandas.errors import PerformanceWarning
import pandas as pd
from pandas import (
Categorical,
DataFrame,
Grouper,
Index,
MultiIndex,
Series,
Timestamp,
date_range,
read_csv,
to_datetime,
)
import pandas._testing as tm
from pandas.core.base import SpecificationError
import pandas.core.common as com
def test_repr():
result = repr(Grouper(key="A", level="B"))
expected = "Grouper(key='A', level='B', axis=0, sort=False)"
assert result == expected
@pytest.mark.parametrize("dtype", ["int64", "int32", "float64", "float32"])
def test_basic(dtype):
data = Series(np.arange(9) // 3, index=np.arange(9), dtype=dtype)
index = np.arange(9)
np.random.shuffle(index)
data = data.reindex(index)
grouped = data.groupby(lambda x: x // 3)
for k, v in grouped:
assert len(v) == 3
agged = grouped.aggregate(np.mean)
assert agged[1] == 1
tm.assert_series_equal(agged, grouped.agg(np.mean))
tm.assert_series_equal(agged, grouped.mean())
tm.assert_series_equal(grouped.agg(np.sum), grouped.sum())
expected = grouped.apply(lambda x: x * x.sum())
transformed = grouped.transform(lambda x: x * x.sum())
assert transformed[7] == 12
tm.assert_series_equal(transformed, expected)
value_grouped = data.groupby(data)
tm.assert_series_equal(
value_grouped.aggregate(np.mean), agged, check_index_type=False
)
agged = grouped.aggregate([np.mean, np.std])
msg = r"nested renamer is not supported"
with pytest.raises(SpecificationError, match=msg):
grouped.aggregate({"one": np.mean, "two": np.std})
group_constants = {0: 10, 1: 20, 2: 30}
agged = grouped.agg(lambda x: group_constants[x.name] + x.mean())
assert agged[1] == 21
msg = "Must produce aggregated value"
with pytest.raises(Exception, match=msg):
grouped.aggregate(lambda x: x * 2)
def test_groupby_nonobject_dtype(mframe, df_mixed_floats):
key = mframe.index.codes[0]
grouped = mframe.groupby(key)
result = grouped.sum()
expected = mframe.groupby(key.astype("O")).sum()
tm.assert_frame_equal(result, expected)
df = df_mixed_floats.copy()
df["value"] = range(len(df))
def max_value(group):
return group.loc[group["value"].idxmax()]
applied = df.groupby("A").apply(max_value)
result = applied.dtypes
expected = df.dtypes
tm.assert_series_equal(result, expected)
def test_groupby_return_type():
df1 = DataFrame(
[
{"val1": 1, "val2": 20},
{"val1": 1, "val2": 19},
{"val1": 2, "val2": 27},
{"val1": 2, "val2": 12},
]
)
def func(dataf):
return dataf["val2"] - dataf["val2"].mean()
with tm.assert_produces_warning(FutureWarning):
result = df1.groupby("val1", squeeze=True).apply(func)
assert isinstance(result, Series)
df2 = DataFrame(
[
{"val1": 1, "val2": 20},
{"val1": 1, "val2": 19},
{"val1": 1, "val2": 27},
{"val1": 1, "val2": 12},
]
)
def func(dataf):
return dataf["val2"] - dataf["val2"].mean()
with tm.assert_produces_warning(FutureWarning):
result = df2.groupby("val1", squeeze=True).apply(func)
assert isinstance(result, Series)
df = DataFrame([[1, 1], [1, 1]], columns=["X", "Y"])
with tm.assert_produces_warning(FutureWarning):
result = df.groupby("X", squeeze=False).count()
assert isinstance(result, DataFrame)
def test_inconsistent_return_type():
df = DataFrame(
{
"A": ["Tiger", "Tiger", "Tiger", "Lamb", "Lamb", "Pony", "Pony"],
"B": Series(np.arange(7), dtype="int64"),
"C": date_range("20130101", periods=7),
}
)
def f(grp):
return grp.iloc[0]
expected = df.groupby("A").first()[["B"]]
result = df.groupby("A").apply(f)[["B"]]
tm.assert_frame_equal(result, expected)
def f(grp):
if grp.name == "Tiger":
return None
return grp.iloc[0]
result = df.groupby("A").apply(f)[["B"]]
e = expected.copy()
e.loc["Tiger"] = np.nan
tm.assert_frame_equal(result, e)
def f(grp):
if grp.name == "Pony":
return None
return grp.iloc[0]
result = df.groupby("A").apply(f)[["B"]]
e = expected.copy()
e.loc["Pony"] = np.nan
tm.assert_frame_equal(result, e)
def f(grp):
if grp.name == "Pony":
return None
return grp.iloc[0]
result = df.groupby("A").apply(f)[["C"]]
e = df.groupby("A").first()[["C"]]
e.loc["Pony"] = pd.NaT
tm.assert_frame_equal(result, e)
def f(grp):
if grp.name == "Pony":
return None
return grp.iloc[0].loc["C"]
result = df.groupby("A").apply(f)
e = df.groupby("A").first()["C"].copy()
e.loc["Pony"] = np.nan
e.name = None
tm.assert_series_equal(result, e)
def test_pass_args_kwargs(ts, tsframe):
def f(x, q=None, axis=0):
return np.percentile(x, q, axis=axis)
g = lambda x: np.percentile(x, 80, axis=0)
ts_grouped = ts.groupby(lambda x: x.month)
agg_result = ts_grouped.agg(np.percentile, 80, axis=0)
apply_result = ts_grouped.apply(np.percentile, 80, axis=0)
trans_result = ts_grouped.transform(np.percentile, 80, axis=0)
agg_expected = ts_grouped.quantile(0.8)
trans_expected = ts_grouped.transform(g)
tm.assert_series_equal(apply_result, agg_expected)
tm.assert_series_equal(agg_result, agg_expected)
tm.assert_series_equal(trans_result, trans_expected)
agg_result = ts_grouped.agg(f, q=80)
apply_result = ts_grouped.apply(f, q=80)
trans_result = ts_grouped.transform(f, q=80)
tm.assert_series_equal(agg_result, agg_expected)
tm.assert_series_equal(apply_result, agg_expected)
tm.assert_series_equal(trans_result, trans_expected)
df_grouped = tsframe.groupby(lambda x: x.month)
agg_result = df_grouped.agg(np.percentile, 80, axis=0)
apply_result = df_grouped.apply(DataFrame.quantile, 0.8)
expected = df_grouped.quantile(0.8)
tm.assert_frame_equal(apply_result, expected, check_names=False)
tm.assert_frame_equal(agg_result, expected)
agg_result = df_grouped.agg(f, q=80)
apply_result = df_grouped.apply(DataFrame.quantile, q=0.8)
tm.assert_frame_equal(agg_result, expected)
tm.assert_frame_equal(apply_result, expected, check_names=False)
def test_len():
df = tm.makeTimeDataFrame()
grouped = df.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day])
assert len(grouped) == len(df)
grouped = df.groupby([lambda x: x.year, lambda x: x.month])
expected = len({(x.year, x.month) for x in df.index})
assert len(grouped) == expected
df = DataFrame({"a": [np.nan] * 3, "b": [1, 2, 3]})
assert len(df.groupby("a")) == 0
assert len(df.groupby("b")) == 3
assert len(df.groupby(["a", "b"])) == 3
def test_basic_regression():
result = Series([1.0 * x for x in list(range(1, 10)) * 10])
data = np.random.random(1100) * 10.0
groupings = Series(data)
grouped = result.groupby(groupings)
grouped.mean()
@pytest.mark.parametrize(
"dtype", ["float64", "float32", "int64", "int32", "int16", "int8"]
)
def test_with_na_groups(dtype):
index = Index(np.arange(10))
values = Series(np.ones(10), index, dtype=dtype)
labels = Series(
[np.nan, "foo", "bar", "bar", np.nan, np.nan, "bar", "bar", np.nan, "foo"],
index=index,
)
grouped = values.groupby(labels)
agged = grouped.agg(len)
expected = Series([4, 2], index=["bar", "foo"])
tm.assert_series_equal(agged, expected, check_dtype=False)
def f(x):
return float(len(x))
agged = grouped.agg(f)
expected = Series([4.0, 2.0], index=["bar", "foo"])
tm.assert_series_equal(agged, expected)
def test_indices_concatenation_order():
def f1(x):
y = x[(x.b % 2) == 1] ** 2
if y.empty:
multiindex = MultiIndex(levels=[[]] * 2, codes=[[]] * 2, names=["b", "c"])
res = DataFrame(columns=["a"], index=multiindex)
return res
else:
y = y.set_index(["b", "c"])
return y
def f2(x):
y = x[(x.b % 2) == 1] ** 2
if y.empty:
return DataFrame()
else:
y = y.set_index(["b", "c"])
return y
def f3(x):
y = x[(x.b % 2) == 1] ** 2
if y.empty:
multiindex = MultiIndex(
levels=[[]] * 2, codes=[[]] * 2, names=["foo", "bar"]
)
res = DataFrame(columns=["a", "b"], index=multiindex)
return res
else:
return y
df = DataFrame({"a": [1, 2, 2, 2], "b": range(4), "c": range(5, 9)})
df2 = DataFrame({"a": [3, 2, 2, 2], "b": range(4), "c": range(5, 9)})
result1 = df.groupby("a").apply(f1)
result2 = df2.groupby("a").apply(f1)
tm.assert_frame_equal(result1, result2)
msg = "Cannot concat indices that do not have the same number of levels"
with pytest.raises(AssertionError, match=msg):
df.groupby("a").apply(f2)
with pytest.raises(AssertionError, match=msg):
df2.groupby("a").apply(f2)
with pytest.raises(AssertionError, match=msg):
df.groupby("a").apply(f3)
with pytest.raises(AssertionError, match=msg):
df2.groupby("a").apply(f3)
def test_attr_wrapper(ts):
grouped = ts.groupby(lambda x: x.weekday())
result = grouped.std()
expected = grouped.agg(lambda x: np.std(x, ddof=1))
tm.assert_series_equal(result, expected)
result = grouped.describe()
expected = {name: gp.describe() for name, gp in grouped}
expected = DataFrame(expected).T
tm.assert_frame_equal(result, expected)
result = grouped.dtype
expected = grouped.agg(lambda x: x.dtype)
tm.assert_series_equal(result, expected)
msg = "'SeriesGroupBy' object has no attribute 'foo'"
with pytest.raises(AttributeError, match=msg):
getattr(grouped, "foo")
def test_frame_groupby(tsframe):
grouped = tsframe.groupby(lambda x: x.weekday())
aggregated = grouped.aggregate(np.mean)
assert len(aggregated) == 5
assert len(aggregated.columns) == 4
tscopy = tsframe.copy()
tscopy["weekday"] = [x.weekday() for x in tscopy.index]
stragged = tscopy.groupby("weekday").aggregate(np.mean)
tm.assert_frame_equal(stragged, aggregated, check_names=False)
grouped = tsframe.head(30).groupby(lambda x: x.weekday())
transformed = grouped.transform(lambda x: x - x.mean())
assert len(transformed) == 30
assert len(transformed.columns) == 4
transformed = grouped.transform(lambda x: x.mean())
for name, group in grouped:
mean = group.mean()
for idx in group.index:
tm.assert_series_equal(transformed.xs(idx), mean, check_names=False)
for weekday, group in grouped:
assert group.index[0].weekday() == weekday
groups = grouped.groups
indices = grouped.indices
for k, v in groups.items():
samething = tsframe.index.take(indices[k])
assert (samething == v).all()
def test_frame_groupby_columns(tsframe):
mapping = {"A": 0, "B": 0, "C": 1, "D": 1}
grouped = tsframe.groupby(mapping, axis=1)
aggregated = grouped.aggregate(np.mean)
assert len(aggregated) == len(tsframe)
assert len(aggregated.columns) == 2
tf = lambda x: x - x.mean()
groupedT = tsframe.T.groupby(mapping, axis=0)
tm.assert_frame_equal(groupedT.transform(tf).T, grouped.transform(tf))
for k, v in grouped:
assert len(v.columns) == 2
def test_frame_set_name_single(df):
grouped = df.groupby("A")
result = grouped.mean()
assert result.index.name == "A"
result = df.groupby("A", as_index=False).mean()
assert result.index.name != "A"
result = grouped.agg(np.mean)
assert result.index.name == "A"
result = grouped.agg({"C": np.mean, "D": np.std})
assert result.index.name == "A"
result = grouped["C"].mean()
assert result.index.name == "A"
result = grouped["C"].agg(np.mean)
assert result.index.name == "A"
result = grouped["C"].agg([np.mean, np.std])
assert result.index.name == "A"
msg = r"nested renamer is not supported"
with pytest.raises(SpecificationError, match=msg):
grouped["C"].agg({"foo": np.mean, "bar": np.std})
def test_multi_func(df):
col1 = df["A"]
col2 = df["B"]
grouped = df.groupby([col1.get, col2.get])
agged = grouped.mean()
expected = df.groupby(["A", "B"]).mean()
tm.assert_frame_equal(
agged.loc[:, ["C", "D"]], expected.loc[:, ["C", "D"]], check_names=False
)
df = DataFrame(
{
"v1": np.random.randn(6),
"v2": np.random.randn(6),
"k1": np.array(["b", "b", "b", "a", "a", "a"]),
"k2": np.array(["1", "1", "1", "2", "2", "2"]),
},
index=["one", "two", "three", "four", "five", "six"],
)
grouped = df.groupby(["k1", "k2"])
grouped.agg(np.sum)
def test_multi_key_multiple_functions(df):
grouped = df.groupby(["A", "B"])["C"]
agged = grouped.agg([np.mean, np.std])
expected = DataFrame({"mean": grouped.agg(np.mean), "std": grouped.agg(np.std)})
tm.assert_frame_equal(agged, expected)
def test_frame_multi_key_function_list():
data = DataFrame(
{
"A": [
"foo",
"foo",
"foo",
"foo",
"bar",
"bar",
"bar",
"bar",
"foo",
"foo",
"foo",
],
"B": [
"one",
"one",
"one",
"two",
"one",
"one",
"one",
"two",
"two",
"two",
"one",
],
"C": [
"dull",
"dull",
"shiny",
"dull",
"dull",
"shiny",
"shiny",
"dull",
"shiny",
"shiny",
"shiny",
],
"D": np.random.randn(11),
"E": np.random.randn(11),
"F": np.random.randn(11),
}
)
grouped = data.groupby(["A", "B"])
funcs = [np.mean, np.std]
agged = grouped.agg(funcs)
expected = pd.concat(
[grouped["D"].agg(funcs), grouped["E"].agg(funcs), grouped["F"].agg(funcs)],
keys=["D", "E", "F"],
axis=1,
)
assert isinstance(agged.index, MultiIndex)
assert isinstance(expected.index, MultiIndex)
tm.assert_frame_equal(agged, expected)
@pytest.mark.parametrize("op", [lambda x: x.sum(), lambda x: x.mean()])
def test_groupby_multiple_columns(df, op):
data = df
grouped = data.groupby(["A", "B"])
result1 = op(grouped)
keys = []
values = []
for n1, gp1 in data.groupby("A"):
for n2, gp2 in gp1.groupby("B"):
keys.append((n1, n2))
values.append(op(gp2.loc[:, ["C", "D"]]))
mi = MultiIndex.from_tuples(keys, names=["A", "B"])
expected = pd.concat(values, axis=1).T
expected.index = mi
for col in ["C", "D"]:
result_col = op(grouped[col])
pivoted = result1[col]
exp = expected[col]
tm.assert_series_equal(result_col, exp)
tm.assert_series_equal(pivoted, exp)
result = data["C"].groupby([data["A"], data["B"]]).mean()
expected = data.groupby(["A", "B"]).mean()["C"]
tm.assert_series_equal(result, expected)
def test_as_index_select_column():
df = DataFrame([[1, 2], [1, 4], [5, 6]], columns=["A", "B"])
result = df.groupby("A", as_index=False)["B"].get_group(1)
expected = Series([2, 4], name="B")
tm.assert_series_equal(result, expected)
result = df.groupby("A", as_index=False)["B"].apply(lambda x: x.cumsum())
expected = Series(
[2, 6, 6], name="B", index=MultiIndex.from_tuples([(0, 0), (0, 1), (1, 2)])
)
tm.assert_series_equal(result, expected)
def test_groupby_as_index_select_column_sum_empty_df():
df = DataFrame(columns=["A", "B", "C"])
left = df.groupby(by="A", as_index=False)["B"].sum()
assert type(left) is DataFrame
assert left.to_dict() == {"A": {}, "B": {}}
def test_groupby_as_index_agg(df):
grouped = df.groupby("A", as_index=False)
result = grouped.agg(np.mean)
expected = grouped.mean()
tm.assert_frame_equal(result, expected)
result2 = grouped.agg({"C": np.mean, "D": np.sum})
expected2 = grouped.mean()
expected2["D"] = grouped.sum()["D"]
tm.assert_frame_equal(result2, expected2)
grouped = df.groupby("A", as_index=True)
msg = r"nested renamer is not supported"
with pytest.raises(SpecificationError, match=msg):
grouped["C"].agg({"Q": np.sum})
grouped = df.groupby(["A", "B"], as_index=False)
result = grouped.agg(np.mean)
expected = grouped.mean()
tm.assert_frame_equal(result, expected)
result2 = grouped.agg({"C": np.mean, "D": np.sum})
expected2 = grouped.mean()
expected2["D"] = grouped.sum()["D"]
tm.assert_frame_equal(result2, expected2)
expected3 = grouped["C"].sum()
expected3 = DataFrame(expected3).rename(columns={"C": "Q"})
result3 = grouped["C"].agg({"Q": np.sum})
tm.assert_frame_equal(result3, expected3)
df = DataFrame(np.random.randint(0, 100, (50, 3)), columns=["jim", "joe", "jolie"])
ts = Series(np.random.randint(5, 10, 50), name="jim")
gr = df.groupby(ts)
gr.nth(0)
tm.assert_frame_equal(gr.apply(sum), df.groupby(ts).apply(sum))
for attr in ["mean", "max", "count", "idxmax", "cumsum", "all"]:
gr = df.groupby(ts, as_index=False)
left = getattr(gr, attr)()
gr = df.groupby(ts.values, as_index=True)
right = getattr(gr, attr)().reset_index(drop=True)
tm.assert_frame_equal(left, right)
def test_ops_not_as_index(reduction_func):
if reduction_func in ("corrwith",):
pytest.skip("Test not applicable")
if reduction_func in ("nth", "ngroup"):
pytest.skip("Skip until behavior is determined (GH #5755)")
df = DataFrame(np.random.randint(0, 5, size=(100, 2)), columns=["a", "b"])
expected = getattr(df.groupby("a"), reduction_func)()
if reduction_func == "size":
expected = expected.rename("size")
expected = expected.reset_index()
g = df.groupby("a", as_index=False)
result = getattr(g, reduction_func)()
tm.assert_frame_equal(result, expected)
result = g.agg(reduction_func)
tm.assert_frame_equal(result, expected)
result = getattr(g["b"], reduction_func)()
tm.assert_frame_equal(result, expected)
result = g["b"].agg(reduction_func)
tm.assert_frame_equal(result, expected)
def test_as_index_series_return_frame(df):
grouped = df.groupby("A", as_index=False)
grouped2 = df.groupby(["A", "B"], as_index=False)
result = grouped["C"].agg(np.sum)
expected = grouped.agg(np.sum).loc[:, ["A", "C"]]
assert isinstance(result, DataFrame)
tm.assert_frame_equal(result, expected)
result2 = grouped2["C"].agg(np.sum)
expected2 = grouped2.agg(np.sum).loc[:, ["A", "B", "C"]]
assert isinstance(result2, DataFrame)
tm.assert_frame_equal(result2, expected2)
result = grouped["C"].sum()
expected = grouped.sum().loc[:, ["A", "C"]]
assert isinstance(result, DataFrame)
tm.assert_frame_equal(result, expected)
result2 = grouped2["C"].sum()
expected2 = grouped2.sum().loc[:, ["A", "B", "C"]]
assert isinstance(result2, DataFrame)
tm.assert_frame_equal(result2, expected2)
def test_as_index_series_column_slice_raises(df):
grouped = df.groupby("A", as_index=False)
msg = r"Column\(s\) C already selected"
with pytest.raises(IndexError, match=msg):
grouped["C"].__getitem__("D")
def test_groupby_as_index_cython(df):
data = df
grouped = data.groupby("A", as_index=False)
result = grouped.mean()
expected = data.groupby(["A"]).mean()
expected.insert(0, "A", expected.index)
expected.index = np.arange(len(expected))
tm.assert_frame_equal(result, expected)
grouped = data.groupby(["A", "B"], as_index=False)
result = grouped.mean()
expected = data.groupby(["A", "B"]).mean()
arrays = list(zip(*expected.index.values))
expected.insert(0, "A", arrays[0])
expected.insert(1, "B", arrays[1])
expected.index = np.arange(len(expected))
tm.assert_frame_equal(result, expected)
def test_groupby_as_index_series_scalar(df):
grouped = df.groupby(["A", "B"], as_index=False)
result = grouped["C"].agg(len)
expected = grouped.agg(len).loc[:, ["A", "B", "C"]]
tm.assert_frame_equal(result, expected)
def test_groupby_as_index_corner(df, ts):
msg = "as_index=False only valid with DataFrame"
with pytest.raises(TypeError, match=msg):
ts.groupby(lambda x: x.weekday(), as_index=False)
msg = "as_index=False only valid for axis=0"
with pytest.raises(ValueError, match=msg):
df.groupby(lambda x: x.lower(), as_index=False, axis=1)
def test_groupby_multiple_key(df):
df = tm.makeTimeDataFrame()
grouped = df.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day])
agged = grouped.sum()
tm.assert_almost_equal(df.values, agged.values)
grouped = df.T.groupby(
[lambda x: x.year, lambda x: x.month, lambda x: x.day], axis=1
)
agged = grouped.agg(lambda x: x.sum())
tm.assert_index_equal(agged.index, df.columns)
tm.assert_almost_equal(df.T.values, agged.values)
agged = grouped.agg(lambda x: x.sum())
tm.assert_almost_equal(df.T.values, agged.values)
def test_groupby_multi_corner(df):
df = df.copy()
df["bad"] = np.nan
agged = df.groupby(["A", "B"]).mean()
expected = df.groupby(["A", "B"]).mean()
expected["bad"] = np.nan
tm.assert_frame_equal(agged, expected)
def test_omit_nuisance(df):
grouped = df.groupby("A")
result = grouped.mean()
expected = df.loc[:, ["A", "C", "D"]].groupby("A").mean()
tm.assert_frame_equal(result, expected)
agged = grouped.agg(np.mean)
exp = grouped.mean()
tm.assert_frame_equal(agged, exp)
df = df.loc[:, ["A", "C", "D"]]
df["E"] = datetime.now()
grouped = df.groupby("A")
result = grouped.agg(np.sum)
expected = grouped.sum()
tm.assert_frame_equal(result, expected)
# won't work with axis = 1
grouped = df.groupby({"A": 0, "C": 0, "D": 1, "E": 1}, axis=1)
msg = "'DatetimeArray' does not implement reduction 'sum'"
with pytest.raises(TypeError, match=msg):
grouped.agg(lambda x: x.sum(0, numeric_only=False))
def test_omit_nuisance_sem(df):
grouped = df.groupby("A")
result = grouped.sem()
expected = df.loc[:, ["A", "C", "D"]].groupby("A").sem()
tm.assert_frame_equal(result, expected)
def test_omit_nuisance_python_multiple(three_group):
grouped = three_group.groupby(["A", "B"])
agged = grouped.agg(np.mean)
exp = grouped.mean()
tm.assert_frame_equal(agged, exp)
def test_empty_groups_corner(mframe):
df = DataFrame(
{
"k1": np.array(["b", "b", "b", "a", "a", "a"]),
"k2": np.array(["1", "1", "1", "2", "2", "2"]),
"k3": ["foo", "bar"] * 3,
"v1": np.random.randn(6),
"v2": np.random.randn(6),
}
)
grouped = df.groupby(["k1", "k2"])
result = grouped.agg(np.mean)
expected = grouped.mean()
tm.assert_frame_equal(result, expected)
grouped = mframe[3:5].groupby(level=0)
agged = grouped.apply(lambda x: x.mean())
agged_A = grouped["A"].apply(np.mean)
tm.assert_series_equal(agged["A"], agged_A)
assert agged.index.name == "first"
def test_nonsense_func():
df = DataFrame([0])
msg = r"unsupported operand type\(s\) for \+: 'int' and 'str'"
with pytest.raises(TypeError, match=msg):
df.groupby(lambda x: x + "foo")
def test_wrap_aggregated_output_multindex(mframe):
df = mframe.T
df["baz", "two"] = "peekaboo"
keys = [np.array([0, 0, 1]), np.array([0, 0, 1])]
agged = df.groupby(keys).agg(np.mean)
assert isinstance(agged.columns, MultiIndex)
def aggfun(ser):
if ser.name == ("foo", "one"):
raise TypeError
else:
return ser.sum()
agged2 = df.groupby(keys).aggregate(aggfun)
assert len(agged2.columns) + 1 == len(df.columns)
def test_groupby_level_apply(mframe):
result = mframe.groupby(level=0).count()
assert result.index.name == "first"
result = mframe.groupby(level=1).count()
assert result.index.name == "second"
result = mframe["A"].groupby(level=0).count()
assert result.index.name == "first"
def test_groupby_level_mapper(mframe):
deleveled = mframe.reset_index()
mapper0 = {"foo": 0, "bar": 0, "baz": 1, "qux": 1}
mapper1 = {"one": 0, "two": 0, "three": 1}
result0 = mframe.groupby(mapper0, level=0).sum()
result1 = mframe.groupby(mapper1, level=1).sum()
mapped_level0 = np.array([mapper0.get(x) for x in deleveled["first"]])
mapped_level1 = np.array([mapper1.get(x) for x in deleveled["second"]])
expected0 = mframe.groupby(mapped_level0).sum()
expected1 = mframe.groupby(mapped_level1).sum()
expected0.index.name, expected1.index.name = "first", "second"
tm.assert_frame_equal(result0, expected0)
tm.assert_frame_equal(result1, expected1)
def test_groupby_level_nonmulti():
s = Series([1, 2, 3, 10, 4, 5, 20, 6], Index([1, 2, 3, 1, 4, 5, 2, 6], name="foo"))
expected = Series([11, 22, 3, 4, 5, 6], Index(range(1, 7), name="foo"))
result = s.groupby(level=0).sum()
tm.assert_series_equal(result, expected)
result = s.groupby(level=[0]).sum()
tm.assert_series_equal(result, expected)
result = s.groupby(level=-1).sum()
tm.assert_series_equal(result, expected)
result = s.groupby(level=[-1]).sum()
tm.assert_series_equal(result, expected)
msg = "level > 0 or level < -1 only valid with MultiIndex"
with pytest.raises(ValueError, match=msg):
s.groupby(level=1)
with pytest.raises(ValueError, match=msg):
s.groupby(level=-2)
msg = "No group keys passed!"
with pytest.raises(ValueError, match=msg):
s.groupby(level=[])
msg = "multiple levels only valid with MultiIndex"
with pytest.raises(ValueError, match=msg):
s.groupby(level=[0, 0])
with pytest.raises(ValueError, match=msg):
s.groupby(level=[0, 1])
msg = "level > 0 or level < -1 only valid with MultiIndex"
with pytest.raises(ValueError, match=msg):
s.groupby(level=[1])
def test_groupby_complex():
a = Series(data=np.arange(4) * (1 + 2j), index=[0, 0, 1, 1])
expected = Series((1 + 2j, 5 + 10j))
result = a.groupby(level=0).sum()
tm.assert_series_equal(result, expected)
with tm.assert_produces_warning(FutureWarning):
result = a.sum(level=0)
tm.assert_series_equal(result, expected)
def test_groupby_series_indexed_differently():
s1 = Series(
[5.0, -9.0, 4.0, 100.0, -5.0, 55.0, 6.7],
index=Index(["a", "b", "c", "d", "e", "f", "g"]),
)
s2 = Series(
[1.0, 1.0, 4.0, 5.0, 5.0, 7.0], index=Index(["a", "b", "d", "f", "g", "h"])
)
grouped = s1.groupby(s2)
agged = grouped.mean()
exp = s1.groupby(s2.reindex(s1.index).get).mean()
tm.assert_series_equal(agged, exp)
def test_groupby_with_hier_columns():
tuples = list(
zip(
*[
["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
["one", "two", "one", "two", "one", "two", "one", "two"],
]
)
)
index = MultiIndex.from_tuples(tuples)
columns = MultiIndex.from_tuples(
[("A", "cat"), ("B", "dog"), ("B", "cat"), ("A", "dog")]
)
df = DataFrame(np.random.randn(8, 4), index=index, columns=columns)
result = df.groupby(level=0).mean()
tm.assert_index_equal(result.columns, columns)
result = df.groupby(level=0, axis=1).mean()
tm.assert_index_equal(result.index, df.index)
result = df.groupby(level=0).agg(np.mean)
tm.assert_index_equal(result.columns, columns)
result = df.groupby(level=0).apply(lambda x: x.mean())
tm.assert_index_equal(result.columns, columns)
result = df.groupby(level=0, axis=1).agg(lambda x: x.mean(1))
tm.assert_index_equal(result.columns, Index(["A", "B"]))
tm.assert_index_equal(result.index, df.index)
sorted_columns, _ = columns.sortlevel(0)
df["A", "foo"] = "bar"
result = df.groupby(level=0).mean()
tm.assert_index_equal(result.columns, df.columns[:-1])
def test_grouping_ndarray(df):
grouped = df.groupby(df["A"].values)
result = grouped.sum()
expected = df.groupby("A").sum()
tm.assert_frame_equal(
result, expected, check_names=False
)
def test_groupby_wrong_multi_labels():
data = """index,foo,bar,baz,spam,data
0,foo1,bar1,baz1,spam2,20
1,foo1,bar2,baz1,spam3,30
2,foo2,bar2,baz1,spam2,40
3,foo1,bar1,baz2,spam1,50
4,foo3,bar1,baz2,spam1,60"""
data = read_csv(StringIO(data), index_col=0)
grouped = data.groupby(["foo", "bar", "baz", "spam"])
result = grouped.agg(np.mean)
expected = grouped.mean()
tm.assert_frame_equal(result, expected)
def test_groupby_series_with_name(df):
result = df.groupby(df["A"]).mean()
result2 = df.groupby(df["A"], as_index=False).mean()
assert result.index.name == "A"
assert "A" in result2
result = df.groupby([df["A"], df["B"]]).mean()
result2 = df.groupby([df["A"], df["B"]], as_index=False).mean()
assert result.index.names == ("A", "B")
assert "A" in result2
assert "B" in result2
def test_seriesgroupby_name_attr(df):
result = df.groupby("A")["C"]
assert result.count().name == "C"
assert result.mean().name == "C"
testFunc = lambda x: np.sum(x) * 2
assert result.agg(testFunc).name == "C"
def test_consistency_name():
df = DataFrame(
{
"A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"],
"B": ["one", "one", "two", "two", "two", "two", "one", "two"],
"C": np.random.randn(8) + 1.0,
"D": np.arange(8),
}
)
expected = df.groupby(["A"]).B.count()
result = df.B.groupby(df.A).count()
tm.assert_series_equal(result, expected)
def test_groupby_name_propagation(df):
def summarize(df, name=None):
return Series({"count": 1, "mean": 2, "omissions": 3}, name=name)
def summarize_random_name(df):
return Series({"count": 1, "mean": 2, "omissions": 3}, name=df.iloc[0]["A"])
metrics = df.groupby("A").apply(summarize)
assert metrics.columns.name is None
metrics = df.groupby("A").apply(summarize, "metrics")
assert metrics.columns.name == "metrics"
metrics = df.groupby("A").apply(summarize_random_name)
assert metrics.columns.name is None
def test_groupby_nonstring_columns():
df = DataFrame([np.arange(10) for x in range(10)])
grouped = df.groupby(0)
result = grouped.mean()
expected = df.groupby(df[0]).mean()
tm.assert_frame_equal(result, expected)
def test_groupby_mixed_type_columns():
df = DataFrame([[0, 1, 2]], columns=["A", "B", 0])
expected = DataFrame([[1, 2]], columns=["B", 0], index=Index([0], name="A"))
result = df.groupby("A").first()
tm.assert_frame_equal(result, expected)
result = df.groupby("A").sum()
tm.assert_frame_equal(result, expected)
@pytest.mark.filterwarnings("ignore:Mean of:RuntimeWarning")
def test_cython_grouper_series_bug_noncontig():
arr = np.empty((100, 100))
arr.fill(np.nan)
obj = Series(arr[:, 0])
inds = np.tile(range(10), 10)
result = obj.groupby(inds).agg(Series.median)
assert result.isna().all()
def test_series_grouper_noncontig_index():
index = Index(tm.rands_array(10, 100))
values = Series(np.random.randn(50), index=index[::2])
labels = np.random.randint(0, 5, 50)
# it works!
grouped = values.groupby(labels)
# accessing the index elements causes segfault
f = lambda x: len(set(map(id, x.index)))
grouped.agg(f)
def test_convert_objects_leave_decimal_alone():
s = Series(range(5))
labels = np.array(["a", "b", "c", "d", "e"], dtype="O")
def convert_fast(x):
return Decimal(str(x.mean()))
def convert_force_pure(x):
# base will be length 0
assert len(x.values.base) > 0
return Decimal(str(x.mean()))
grouped = s.groupby(labels)
result = grouped.agg(convert_fast)
assert result.dtype == np.object_
assert isinstance(result[0], Decimal)
result = grouped.agg(convert_force_pure)
assert result.dtype == np.object_
assert isinstance(result[0], Decimal)
def test_groupby_dtype_inference_empty():
# GH 6733
df = DataFrame({"x": [], "range": np.arange(0, dtype="int64")})
assert df["x"].dtype == np.float64
result = df.groupby("x").first()
exp_index = Index([], name="x", dtype=np.float64)
expected = DataFrame({"range": Series([], index=exp_index, dtype="int64")})
tm.assert_frame_equal(result, expected, by_blocks=True)
def test_groupby_unit64_float_conversion():
# GH: 30859 groupby converts unit64 to floats sometimes
df = DataFrame({"first": [1], "second": [1], "value": [16148277970000000000]})
result = df.groupby(["first", "second"])["value"].max()
expected = Series(
[16148277970000000000],
MultiIndex.from_product([[1], [1]], names=["first", "second"]),
name="value",
)
tm.assert_series_equal(result, expected)
def test_groupby_list_infer_array_like(df):
result = df.groupby(list(df["A"])).mean()
expected = df.groupby(df["A"]).mean()
tm.assert_frame_equal(result, expected, check_names=False)
with pytest.raises(KeyError, match=r"^'foo'$"):
df.groupby(list(df["A"][:-1]))
# pathological case of ambiguity
df = DataFrame({"foo": [0, 1], "bar": [3, 4], "val": np.random.randn(2)})
result = df.groupby(["foo", "bar"]).mean()
expected = df.groupby([df["foo"], df["bar"]]).mean()[["val"]]
def test_groupby_keys_same_size_as_index():
# GH 11185
freq = "s"
index = date_range(
start=Timestamp("2015-09-29T11:34:44-0700"), periods=2, freq=freq
)
df = DataFrame([["A", 10], ["B", 15]], columns=["metric", "values"], index=index)
result = df.groupby([Grouper(level=0, freq=freq), "metric"]).mean()
expected = df.set_index([df.index, "metric"])
tm.assert_frame_equal(result, expected)
def test_groupby_one_row():
# GH 11741
msg = r"^'Z'$"
df1 = DataFrame(np.random.randn(1, 4), columns=list("ABCD"))
with pytest.raises(KeyError, match=msg):
df1.groupby("Z")
df2 = DataFrame(np.random.randn(2, 4), columns=list("ABCD"))
with pytest.raises(KeyError, match=msg):
df2.groupby("Z")
def test_groupby_nat_exclude():
# GH 6992
df = DataFrame(
{
"values": np.random.randn(8),
"dt": [
np.nan,
Timestamp("2013-01-01"),
np.nan,
Timestamp("2013-02-01"),
np.nan,
Timestamp("2013-02-01"),
np.nan,
Timestamp("2013-01-01"),
],
"str": [np.nan, "a", np.nan, "a", np.nan, "a", np.nan, "b"],
}
)
grouped = df.groupby("dt")
expected = [Index([1, 7]), Index([3, 5])]
keys = sorted(grouped.groups.keys())
assert len(keys) == 2
for k, e in zip(keys, expected):
# grouped.groups keys are np.datetime64 with system tz
# not to be affected by tz, only compare values
tm.assert_index_equal(grouped.groups[k], e)
# confirm obj is not filtered
tm.assert_frame_equal(grouped.grouper.groupings[0].obj, df)
assert grouped.ngroups == 2
expected = {
Timestamp("2013-01-01 00:00:00"): np.array([1, 7], dtype=np.intp),
Timestamp("2013-02-01 00:00:00"): np.array([3, 5], dtype=np.intp),
}
for k in grouped.indices:
tm.assert_numpy_array_equal(grouped.indices[k], expected[k])
tm.assert_frame_equal(grouped.get_group(Timestamp("2013-01-01")), df.iloc[[1, 7]])
tm.assert_frame_equal(grouped.get_group(Timestamp("2013-02-01")), df.iloc[[3, 5]])
with pytest.raises(KeyError, match=r"^NaT$"):
grouped.get_group(pd.NaT)
nan_df = DataFrame(
{"nan": [np.nan, np.nan, np.nan], "nat": [pd.NaT, pd.NaT, pd.NaT]}
)
assert nan_df["nan"].dtype == "float64"
assert nan_df["nat"].dtype == "datetime64[ns]"
for key in ["nan", "nat"]:
grouped = nan_df.groupby(key)
assert grouped.groups == {}
assert grouped.ngroups == 0
assert grouped.indices == {}
with pytest.raises(KeyError, match=r"^nan$"):
grouped.get_group(np.nan)
with pytest.raises(KeyError, match=r"^NaT$"):
grouped.get_group(pd.NaT)
def test_groupby_two_group_keys_all_nan():
# GH #36842: Grouping over two group keys shouldn't raise an error
df = DataFrame({"a": [np.nan, np.nan], "b": [np.nan, np.nan], "c": [1, 2]})
result = df.groupby(["a", "b"]).indices
assert result == {}
def test_groupby_2d_malformed():
d = DataFrame(index=range(2))
d["group"] = ["g1", "g2"]
d["zeros"] = [0, 0]
d["ones"] = [1, 1]
d["label"] = ["l1", "l2"]
tmp = d.groupby(["group"]).mean()
res_values = np.array([[0, 1], [0, 1]], dtype=np.int64)
tm.assert_index_equal(tmp.columns, Index(["zeros", "ones"]))
tm.assert_numpy_array_equal(tmp.values, res_values)
def test_int32_overflow():
B = np.concatenate((np.arange(10000), np.arange(10000), np.arange(5000)))
A = np.arange(25000)
df = DataFrame({"A": A, "B": B, "C": A, "D": B, "E": np.random.randn(25000)})
left = df.groupby(["A", "B", "C", "D"]).sum()
right = df.groupby(["D", "C", "B", "A"]).sum()
assert len(left) == len(right)
def test_groupby_sort_multi():
df = DataFrame(
{
"a": ["foo", "bar", "baz"],
"b": [3, 2, 1],
"c": [0, 1, 2],
"d": np.random.randn(3),
}
)
tups = [tuple(row) for row in df[["a", "b", "c"]].values]
tups = com.asarray_tuplesafe(tups)
result = df.groupby(["a", "b", "c"], sort=True).sum()
tm.assert_numpy_array_equal(result.index.values, tups[[1, 2, 0]])
tups = [tuple(row) for row in df[["c", "a", "b"]].values]
tups = com.asarray_tuplesafe(tups)
result = df.groupby(["c", "a", "b"], sort=True).sum()
tm.assert_numpy_array_equal(result.index.values, tups)
tups = [tuple(x) for x in df[["b", "c", "a"]].values]
tups = com.asarray_tuplesafe(tups)
result = df.groupby(["b", "c", "a"], sort=True).sum()
tm.assert_numpy_array_equal(result.index.values, tups[[2, 1, 0]])
df = DataFrame(
{"a": [0, 1, 2, 0, 1, 2], "b": [0, 0, 0, 1, 1, 1], "d": np.random.randn(6)}
)
grouped = df.groupby(["a", "b"])["d"]
result = grouped.sum()
def _check_groupby(df, result, keys, field, f=lambda x: x.sum()):
tups = [tuple(row) for row in df[keys].values]
tups = com.asarray_tuplesafe(tups)
expected = f(df.groupby(tups)[field])
for k, v in expected.items():
assert result[k] == v
_check_groupby(df, result, ["a", "b"], "d")
def test_dont_clobber_name_column():
df = DataFrame(
{"key": ["a", "a", "a", "b", "b", "b"], "name": ["foo", "bar", "baz"] * 2}
)
result = df.groupby("key").apply(lambda x: x)
tm.assert_frame_equal(result, df)
def test_skip_group_keys():
tsf = tm.makeTimeDataFrame()
grouped = tsf.groupby(lambda x: x.month, group_keys=False)
result = grouped.apply(lambda x: x.sort_values(by="A")[:3])
pieces = [group.sort_values(by="A")[:3] for key, group in grouped]
expected = pd.concat(pieces)
tm.assert_frame_equal(result, expected)
grouped = tsf["A"].groupby(lambda x: x.month, group_keys=False)
result = grouped.apply(lambda x: x.sort_values()[:3])
pieces = [group.sort_values()[:3] for key, group in grouped]
expected = pd.concat(pieces)
tm.assert_series_equal(result, expected)
def test_no_nonsense_name(float_frame):
s = float_frame["C"].copy()
s.name = None
result = s.groupby(float_frame["A"]).agg(np.sum)
assert result.name is None
def test_multifunc_sum_bug():
x = DataFrame(np.arange(9).reshape(3, 3))
x["test"] = 0
x["fl"] = [1.3, 1.5, 1.6]
grouped = x.groupby("test")
result = grouped.agg({"fl": "sum", 2: "size"})
assert result["fl"].dtype == np.float64
def test_handle_dict_return_value(df):
def f(group):
return {"max": group.max(), "min": group.min()}
def g(group):
return Series({"max": group.max(), "min": group.min()})
result = df.groupby("A")["C"].apply(f)
expected = df.groupby("A")["C"].apply(g)
assert isinstance(result, Series)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("grouper", ["A", ["A", "B"]])
def test_set_group_name(df, grouper):
def f(group):
assert group.name is not None
return group
def freduce(group):
assert group.name is not None
return group.sum()
def foo(x):
return freduce(x)
grouped = df.groupby(grouper)
grouped.apply(f)
grouped.aggregate(freduce)
grouped.aggregate({"C": freduce, "D": freduce})
grouped.transform(f)
grouped["C"].apply(f)
grouped["C"].aggregate(freduce)
grouped["C"].aggregate([freduce, foo])
grouped["C"].transform(f)
def test_group_name_available_in_inference_pass():
df = DataFrame({"a": [0, 0, 1, 1, 2, 2], "b": np.arange(6)})
names = []
def f(group):
names.append(group.name)
return group.copy()
df.groupby("a", sort=False, group_keys=False).apply(f)
expected_names = [0, 1, 2]
assert names == expected_names
def test_no_dummy_key_names(df):
result = df.groupby(df["A"].values).sum()
assert result.index.name is None
result = df.groupby([df["A"].values, df["B"].values]).sum()
assert result.index.names == (None, None)
def test_groupby_sort_multiindex_series():
index = MultiIndex(
levels=[[1, 2], [1, 2]],
codes=[[0, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 0]],
names=["a", "b"],
)
mseries = Series([0, 1, 2, 3, 4, 5], index=index)
index = MultiIndex(
levels=[[1, 2], [1, 2]], codes=[[0, 0, 1], [1, 0, 0]], names=["a", "b"]
)
mseries_result = Series([0, 2, 4], index=index)
result = mseries.groupby(level=["a", "b"], sort=False).first()
tm.assert_series_equal(result, mseries_result)
result = mseries.groupby(level=["a", "b"], sort=True).first()
tm.assert_series_equal(result, mseries_result.sort_index())
def test_groupby_reindex_inside_function():
periods = 1000
ind = date_range(start="2012/1/1", freq="5min", periods=periods)
df = DataFrame({"high": np.arange(periods), "low": np.arange(periods)}, index=ind)
def agg_before(func, fix=False):
def _func(data):
d = data.loc[data.index.map(lambda x: x.hour < 11)].dropna()
if fix:
data[data.index[0]]
if len(d) == 0:
return None
return func(d)
return _func
grouped = df.groupby(lambda x: datetime(x.year, x.month, x.day))
closure_bad = grouped.agg({"high": agg_before(np.max)})
closure_good = grouped.agg({"high": agg_before(np.max, True)})
tm.assert_frame_equal(closure_bad, closure_good)
def test_groupby_multiindex_missing_pair():
df = DataFrame(
{
"group1": ["a", "a", "a", "b"],
"group2": ["c", "c", "d", "c"],
"value": [1, 1, 1, 5],
}
)
df = df.set_index(["group1", "group2"])
df_grouped = df.groupby(level=["group1", "group2"], sort=True)
res = df_grouped.agg("sum")
idx = MultiIndex.from_tuples(
[("a", "c"), ("a", "d"), ("b", "c")], names=["group1", "group2"]
)
exp = DataFrame([[2], [1], [5]], index=idx, columns=["value"])
tm.assert_frame_equal(res, exp)
def test_groupby_multiindex_not_lexsorted():
lexsorted_mi = MultiIndex.from_tuples(
[("a", ""), ("b1", "c1"), ("b2", "c2")], names=["b", "c"]
)
lexsorted_df = DataFrame([[1, 3, 4]], columns=lexsorted_mi)
assert lexsorted_df.columns._is_lexsorted()
not_lexsorted_df = DataFrame(
columns=["a", "b", "c", "d"], data=[[1, "b1", "c1", 3], [1, "b2", "c2", 4]]
)
not_lexsorted_df = not_lexsorted_df.pivot_table(
index="a", columns=["b", "c"], values="d"
)
not_lexsorted_df = not_lexsorted_df.reset_index()
assert not not_lexsorted_df.columns._is_lexsorted()
tm.assert_frame_equal(lexsorted_df, not_lexsorted_df)
expected = lexsorted_df.groupby("a").mean()
with tm.assert_produces_warning(PerformanceWarning):
result = not_lexsorted_df.groupby("a").mean()
tm.assert_frame_equal(expected, result)
df = DataFrame(
{"x": ["a", "a", "b", "a"], "y": [1, 1, 2, 2], "z": [1, 2, 3, 4]}
).set_index(["x", "y"])
assert not df.index._is_lexsorted()
for level in [0, 1, [0, 1]]:
for sort in [False, True]:
result = df.groupby(level=level, sort=sort).apply(DataFrame.drop_duplicates)
expected = df
tm.assert_frame_equal(expected, result)
result = (
df.sort_index()
.groupby(level=level, sort=sort)
.apply(DataFrame.drop_duplicates)
)
expected = df.sort_index()
tm.assert_frame_equal(expected, result)
def test_index_label_overlaps_location():
# wake of GH5375
df = DataFrame(list("ABCDE"), index=[2, 0, 2, 1, 1])
g = df.groupby(list("ababb"))
actual = g.filter(lambda x: len(x) > 2)
expected = df.iloc[[1, 3, 4]]
tm.assert_frame_equal(actual, expected)
ser = df[0]
g = ser.groupby(list("ababb"))
actual = g.filter(lambda x: len(x) > 2)
expected = ser.take([1, 3, 4])
tm.assert_series_equal(actual, expected)
# ... and again, with a generic Index of floats
df.index = df.index.astype(float)
g = df.groupby(list("ababb"))
actual = g.filter(lambda x: len(x) > 2)
expected = df.iloc[[1, 3, 4]]
tm.assert_frame_equal(actual, expected)
ser = df[0]
g = ser.groupby(list("ababb"))
actual = g.filter(lambda x: len(x) > 2)
expected = ser.take([1, 3, 4])
tm.assert_series_equal(actual, expected)
def test_transform_doesnt_clobber_ints():
# GH 7972
n = 6
x = np.arange(n)
df = DataFrame({"a": x // 2, "b": 2.0 * x, "c": 3.0 * x})
df2 = DataFrame({"a": x // 2 * 1.0, "b": 2.0 * x, "c": 3.0 * x})
gb = df.groupby("a")
result = gb.transform("mean")
gb2 = df2.groupby("a")
expected = gb2.transform("mean")
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"sort_column",
["ints", "floats", "strings", ["ints", "floats"], ["ints", "strings"]],
)
@pytest.mark.parametrize(
"group_column", ["int_groups", "string_groups", ["int_groups", "string_groups"]]
)
def test_groupby_preserves_sort(sort_column, group_column):
# Test to ensure that groupby always preserves sort order of original
# object. Issue #8588 and #9651
df = DataFrame(
{
"int_groups": [3, 1, 0, 1, 0, 3, 3, 3],
"string_groups": ["z", "a", "z", "a", "a", "g", "g", "g"],
"ints": [8, 7, 4, 5, 2, 9, 1, 1],
"floats": [2.3, 5.3, 6.2, -2.4, 2.2, 1.1, 1.1, 5],
"strings": ["z", "d", "a", "e", "word", "word2", "42", "47"],
}
)
# Try sorting on different types and with different group types
df = df.sort_values(by=sort_column)
g = df.groupby(group_column)
def test_sort(x):
tm.assert_frame_equal(x, x.sort_values(by=sort_column))
g.apply(test_sort)
def test_pivot_table_values_key_error():
# This test is designed to replicate the error in issue #14938
df = DataFrame(
{
"eventDate": date_range(datetime.today(), periods=20, freq="M").tolist(),
"thename": range(0, 20),
}
)
df["year"] = df.set_index("eventDate").index.year
df["month"] = df.set_index("eventDate").index.month
with pytest.raises(KeyError, match="'badname'"):
df.reset_index().pivot_table(
index="year", columns="month", values="badname", aggfunc="count"
)
@pytest.mark.parametrize("columns", ["C", ["C"]])
@pytest.mark.parametrize("keys", [["A"], ["A", "B"]])
@pytest.mark.parametrize(
"values",
[
[True],
[0],
[0.0],
["a"],
Categorical([0]),
[to_datetime(0)],
date_range(0, 1, 1, tz="US/Eastern"),
pd.array([0], dtype="Int64"),
pd.array([0], dtype="Float64"),
pd.array([False], dtype="boolean"),
],
)
@pytest.mark.parametrize("method", ["attr", "agg", "apply"])
@pytest.mark.parametrize(
"op", ["idxmax", "idxmin", "mad", "min", "max", "sum", "prod", "skew"]
)
def test_empty_groupby(columns, keys, values, method, op, request):
# GH8093 & GH26411
if isinstance(values, Categorical) and len(keys) == 1 and method == "apply":
mark = pytest.mark.xfail(raises=TypeError, match="'str' object is not callable")
request.node.add_marker(mark)
elif (
isinstance(values, Categorical)
and len(keys) == 1
and op in ["idxmax", "idxmin"]
):
mark = pytest.mark.xfail(
raises=ValueError, match="attempt to get arg(min|max) of an empty sequence"
)
request.node.add_marker(mark)
elif (
isinstance(values, Categorical)
and len(keys) == 1
and not isinstance(columns, list)
):
mark = pytest.mark.xfail(
raises=TypeError, match="'Categorical' does not implement"
)
request.node.add_marker(mark)
elif (
isinstance(values, Categorical)
and len(keys) == 1
and op in ["mad", "min", "max", "sum", "prod", "skew"]
):
mark = pytest.mark.xfail(
raises=AssertionError, match="(DataFrame|Series) are different"
)
request.node.add_marker(mark)
elif (
isinstance(values, Categorical)
and len(keys) == 2
and op in ["min", "max", "sum"]
and method != "apply"
):
mark = pytest.mark.xfail(
raises=AssertionError, match="(DataFrame|Series) are different"
)
request.node.add_marker(mark)
elif (
isinstance(values, pd.core.arrays.BooleanArray)
and op in ["sum", "prod"]
and method != "apply"
):
mark = pytest.mark.xfail(
raises=AssertionError, match="(DataFrame|Series) are different"
)
request.node.add_marker(mark)
override_dtype = None
if isinstance(values[0], bool) and op in ("prod", "sum") and method != "apply":
# sum/product of bools is an integer
override_dtype = "int64"
df = DataFrame({"A": values, "B": values, "C": values}, columns=list("ABC"))
if hasattr(values, "dtype"):
# check that we did the construction right
assert (df.dtypes == values.dtype).all()
df = df.iloc[:0]
gb = df.groupby(keys)[columns]
if method == "attr":
result = getattr(gb, op)()
else:
result = getattr(gb, method)(op)
expected = df.set_index(keys)[columns]
if override_dtype is not None:
expected = expected.astype(override_dtype)
if len(keys) == 1:
expected.index.name = keys[0]
tm.assert_equal(result, expected)
def test_tuple_as_grouping():
# https://github.com/pandas-dev/pandas/issues/18314
df = DataFrame(
{
("a", "b"): [1, 1, 1, 1],
"a": [2, 2, 2, 2],
"b": [2, 2, 2, 2],
"c": [1, 1, 1, 1],
}
)
with pytest.raises(KeyError, match=r"('a', 'b')"):
df[["a", "b", "c"]].groupby(("a", "b"))
result = df.groupby(("a", "b"))["c"].sum()
expected = Series([4], name="c", index=Index([1], name=("a", "b")))
tm.assert_series_equal(result, expected)
def test_tuple_correct_keyerror():
# https://github.com/pandas-dev/pandas/issues/18798
df = DataFrame(1, index=range(3), columns=MultiIndex.from_product([[1, 2], [3, 4]]))
with pytest.raises(KeyError, match=r"^\(7, 8\)$"):
df.groupby((7, 8)).mean()
def test_groupby_agg_ohlc_non_first():
# GH 21716
df = DataFrame(
[[1], [1]],
columns=["foo"],
index=date_range("2018-01-01", periods=2, freq="D"),
)
expected = DataFrame(
[[1, 1, 1, 1, 1], [1, 1, 1, 1, 1]],
columns=MultiIndex.from_tuples(
(
("foo", "sum", "foo"),
("foo", "ohlc", "open"),
("foo", "ohlc", "high"),
("foo", "ohlc", "low"),
("foo", "ohlc", "close"),
)
),
index=date_range("2018-01-01", periods=2, freq="D"),
)
result = df.groupby(Grouper(freq="D")).agg(["sum", "ohlc"])
tm.assert_frame_equal(result, expected)
def test_groupby_multiindex_nat():
# GH 9236
values = [
(pd.NaT, "a"),
(datetime(2012, 1, 2), "a"),
(datetime(2012, 1, 2), "b"),
(datetime(2012, 1, 3), "a"),
]
mi = MultiIndex.from_tuples(values, names=["date", None])
ser = Series([3, 2, 2.5, 4], index=mi)
result = ser.groupby(level=1).mean()
expected = Series([3.0, 2.5], index=["a", "b"])
tm.assert_series_equal(result, expected)
def test_groupby_empty_list_raises():
# GH 5289
values = zip(range(10), range(10))
df = DataFrame(values, columns=["apple", "b"])
msg = "Grouper and axis must be same length"
with pytest.raises(ValueError, match=msg):
df.groupby([[]])
def test_groupby_multiindex_series_keys_len_equal_group_axis():
# GH 25704
index_array = [["x", "x"], ["a", "b"], ["k", "k"]]
index_names = ["first", "second", "third"]
ri = MultiIndex.from_arrays(index_array, names=index_names)
s = Series(data=[1, 2], index=ri)
result = s.groupby(["first", "third"]).sum()
index_array = [["x"], ["k"]]
index_names = ["first", "third"]
ei = MultiIndex.from_arrays(index_array, names=index_names)
expected = Series([3], index=ei)
tm.assert_series_equal(result, expected)
def test_groupby_groups_in_BaseGrouper():
# GH 26326
# Test if DataFrame grouped with a pandas.Grouper has correct groups
mi = MultiIndex.from_product([["A", "B"], ["C", "D"]], names=["alpha", "beta"])
df = DataFrame({"foo": [1, 2, 1, 2], "bar": [1, 2, 3, 4]}, index=mi)
result = df.groupby([Grouper(level="alpha"), "beta"])
expected = df.groupby(["alpha", "beta"])
assert result.groups == expected.groups
result = df.groupby(["beta", Grouper(level="alpha")])
expected = df.groupby(["beta", "alpha"])
assert result.groups == expected.groups
@pytest.mark.parametrize("group_name", ["x", ["x"]])
def test_groupby_axis_1(group_name):
# GH 27614
df = DataFrame(
np.arange(12).reshape(3, 4), index=[0, 1, 0], columns=[10, 20, 10, 20]
)
df.index.name = "y"
df.columns.name = "x"
results = df.groupby(group_name, axis=1).sum()
expected = df.T.groupby(group_name).sum().T
tm.assert_frame_equal(results, expected)
# test on MI column
iterables = [["bar", "baz", "foo"], ["one", "two"]]
mi = MultiIndex.from_product(iterables=iterables, names=["x", "x1"])
df = DataFrame(np.arange(18).reshape(3, 6), index=[0, 1, 0], columns=mi)
results = df.groupby(group_name, axis=1).sum()
expected = df.T.groupby(group_name).sum().T
tm.assert_frame_equal(results, expected)
@pytest.mark.parametrize(
"op, expected",
[
(
"shift",
{
"time": [
None,
None,
Timestamp("2019-01-01 12:00:00"),
Timestamp("2019-01-01 12:30:00"),
None,
None,
]
},
),
(
"bfill",
{
"time": [
Timestamp("2019-01-01 12:00:00"),
Timestamp("2019-01-01 12:30:00"),
Timestamp("2019-01-01 14:00:00"),
Timestamp("2019-01-01 14:30:00"),
Timestamp("2019-01-01 14:00:00"),
Timestamp("2019-01-01 14:30:00"),
]
},
),
(
"ffill",
{
"time": [
Timestamp("2019-01-01 12:00:00"),
Timestamp("2019-01-01 12:30:00"),
Timestamp("2019-01-01 12:00:00"),
Timestamp("2019-01-01 12:30:00"),
Timestamp("2019-01-01 14:00:00"),
Timestamp("2019-01-01 14:30:00"),
]
},
),
],
)
def test_shift_bfill_ffill_tz(tz_naive_fixture, op, expected):
# GH19995, GH27992: Check that timezone does not drop in shift, bfill, and ffill
tz = tz_naive_fixture
data = {
"id": ["A", "B", "A", "B", "A", "B"],
"time": [
Timestamp("2019-01-01 12:00:00"),
Timestamp("2019-01-01 12:30:00"),
None,
None,
Timestamp("2019-01-01 14:00:00"),
Timestamp("2019-01-01 14:30:00"),
],
}
df = DataFrame(data).assign(time=lambda x: x.time.dt.tz_localize(tz))
grouped = df.groupby("id")
result = getattr(grouped, op)()
expected = DataFrame(expected).assign(time=lambda x: x.time.dt.tz_localize(tz))
tm.assert_frame_equal(result, expected)
def test_groupby_only_none_group():
# see GH21624
# this was crashing with "ValueError: Length of passed values is 1, index implies 0"
df = DataFrame({"g": [None], "x": 1})
actual = df.groupby("g")["x"].transform("sum")
expected = Series([np.nan], name="x")
tm.assert_series_equal(actual, expected)
def test_groupby_duplicate_index():
# GH#29189 the groupby call here used to raise
ser = Series([2, 5, 6, 8], index=[2.0, 4.0, 4.0, 5.0])
gb = ser.groupby(level=0)
result = gb.mean()
expected = Series([2, 5.5, 8], index=[2.0, 4.0, 5.0])
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize(
"idx", [Index(["a", "a"]), MultiIndex.from_tuples((("a", "a"), ("a", "a")))]
)
@pytest.mark.filterwarnings("ignore:tshift is deprecated:FutureWarning")
def test_dup_labels_output_shape(groupby_func, idx):
if groupby_func in {"size", "ngroup", "cumcount"}:
pytest.skip("Not applicable")
df = DataFrame([[1, 1]], columns=idx)
grp_by = df.groupby([0])
args = []
if groupby_func in {"fillna", "nth"}:
args.append(0)
elif groupby_func == "corrwith":
args.append(df)
elif groupby_func == "tshift":
df.index = [Timestamp("today")]
args.extend([1, "D"])
result = getattr(grp_by, groupby_func)(*args)
assert result.shape == (1, 2)
tm.assert_index_equal(result.columns, idx)
def test_groupby_crash_on_nunique(axis):
# Fix following 30253
df = DataFrame({("A", "B"): [1, 2], ("A", "C"): [1, 3], ("D", "B"): [0, 0]})
axis_number = df._get_axis_number(axis)
if not axis_number:
df = df.T
result = df.groupby(axis=axis_number, level=0).nunique()
expected = DataFrame({"A": [1, 2], "D": [1, 1]})
if not axis_number:
expected = expected.T
tm.assert_frame_equal(result, expected)
# same thing, but empty columns
gb = df[[]].groupby(axis=axis_number, level=0)
res = gb.nunique()
exp = expected[[]]
tm.assert_frame_equal(res, exp)
def test_groupby_list_level():
# GH 9790
expected = DataFrame(np.arange(0, 9).reshape(3, 3))
result = expected.groupby(level=[0]).mean()
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"max_seq_items, expected",
[
(5, "{0: [0], 1: [1], 2: [2], 3: [3], 4: [4]}"),
(4, "{0: [0], 1: [1], 2: [2], 3: [3], ...}"),
(1, "{0: [0], ...}"),
],
)
def test_groups_repr_truncates(max_seq_items, expected):
# GH 1135
df = DataFrame(np.random.randn(5, 1))
df["a"] = df.index
with pd.option_context("display.max_seq_items", max_seq_items):
result = df.groupby("a").groups.__repr__()
assert result == expected
result = df.groupby(np.array(df.a)).groups.__repr__()
assert result == expected
def test_group_on_two_row_multiindex_returns_one_tuple_key():
# GH 18451
df = DataFrame([{"a": 1, "b": 2, "c": 99}, {"a": 1, "b": 2, "c": 88}])
df = df.set_index(["a", "b"])
grp = df.groupby(["a", "b"])
result = grp.indices
expected = {(1, 2): np.array([0, 1], dtype=np.int64)}
assert len(result) == 1
key = (1, 2)
assert (result[key] == expected[key]).all()
@pytest.mark.parametrize(
"klass, attr, value",
[
(DataFrame, "level", "a"),
(DataFrame, "as_index", False),
(DataFrame, "sort", False),
(DataFrame, "group_keys", False),
(DataFrame, "squeeze", True),
(DataFrame, "observed", True),
(DataFrame, "dropna", False),
pytest.param(
Series,
"axis",
1,
marks=pytest.mark.xfail(
reason="GH 35443: Attribute currently not passed on to series"
),
),
(Series, "level", "a"),
(Series, "as_index", False),
(Series, "sort", False),
(Series, "group_keys", False),
(Series, "squeeze", True),
(Series, "observed", True),
(Series, "dropna", False),
],
)
@pytest.mark.filterwarnings(
"ignore:The `squeeze` parameter is deprecated:FutureWarning"
)
def test_subsetting_columns_keeps_attrs(klass, attr, value):
# GH 9959 - When subsetting columns, don't drop attributes
df = DataFrame({"a": [1], "b": [2], "c": [3]})
if attr != "axis":
df = df.set_index("a")
expected = df.groupby("a", **{attr: value})
result = expected[["b"]] if klass is DataFrame else expected["b"]
assert getattr(result, attr) == getattr(expected, attr)
def test_subsetting_columns_axis_1():
g = DataFrame({"A": [1], "B": [2], "C": [3]}).groupby([0, 0, 1], axis=1)
match = "Cannot subset columns when using axis=1"
with pytest.raises(ValueError, match=match):
g[["A", "B"]].sum()
@pytest.mark.parametrize("func", ["sum", "any", "shift"])
def test_groupby_column_index_name_lost(func):
expected = Index(["a"], name="idx")
df = DataFrame([[1]], columns=expected)
df_grouped = df.groupby([1])
result = getattr(df_grouped, func)().columns
tm.assert_index_equal(result, expected)
def test_groupby_duplicate_columns():
df = DataFrame(
{"A": ["f", "e", "g", "h"], "B": ["a", "b", "c", "d"], "C": [1, 2, 3, 4]}
).astype(object)
df.columns = ["A", "B", "B"]
result = df.groupby([0, 0, 0, 0]).min()
expected = DataFrame([["e", "a", 1]], columns=["A", "B", "B"])
tm.assert_frame_equal(result, expected)
def test_groupby_series_with_tuple_name():
ser = Series([1, 2, 3, 4], index=[1, 1, 2, 2], name=("a", "a"))
ser.index.name = ("b", "b")
result = ser.groupby(level=0).last()
expected = Series([2, 4], index=[1, 2], name=("a", "a"))
expected.index.name = ("b", "b")
tm.assert_series_equal(result, expected)
@pytest.mark.xfail(not IS64, reason="GH#38778: fail on 32-bit system")
@pytest.mark.parametrize(
"func, values", [("sum", [97.0, 98.0]), ("mean", [24.25, 24.5])]
)
def test_groupby_numerical_stability_sum_mean(func, values):
ata = [1e16, 1e16, 97, 98, -5e15, -5e15, -5e15, -5e15]
df = DataFrame({"group": [1, 2] * 4, "a": data, "b": data})
result = getattr(df.groupby("group"), func)()
expected = DataFrame({"a": values, "b": values}, index=Index([1, 2], name="group"))
tm.assert_frame_equal(result, expected)
@pytest.mark.xfail(not IS64, reason="GH#38778: fail on 32-bit system")
def test_groupby_numerical_stability_cumsum():
ata = [1e16, 1e16, 97, 98, -5e15, -5e15, -5e15, -5e15]
df = DataFrame({"group": [1, 2] * 4, "a": data, "b": data})
result = df.groupby("group").cumsum()
exp_data = (
[1e16] * 2 + [1e16 + 96, 1e16 + 98] + [5e15 + 97, 5e15 + 98] + [97.0, 98.0]
)
expected = DataFrame({"a": exp_data, "b": exp_data})
tm.assert_frame_equal(result, expected, check_exact=True)
def test_groupby_mean_duplicate_index(rand_series_with_duplicate_datetimeindex):
dups = rand_series_with_duplicate_datetimeindex
result = dups.groupby(level=0).mean()
expected = dups.groupby(dups.index).mean()
tm.assert_series_equal(result, expected)
| true | true |
f716a3b6932792541e61b438e6424ea8e3b6dd6f | 5,536 | py | Python | src/modules/site/base/views/tools/heritability.py | AndersenLab/CAENDR | ce4cdb74db736db8226ffc90988959b71b0d5ff5 | [
"MIT"
] | 3 | 2022-02-09T07:04:37.000Z | 2022-03-11T02:46:35.000Z | src/modules/site/base/views/tools/heritability.py | AndersenLab/CAENDR | ce4cdb74db736db8226ffc90988959b71b0d5ff5 | [
"MIT"
] | 4 | 2022-01-28T22:28:08.000Z | 2022-02-11T21:47:15.000Z | src/modules/site/base/views/tools/heritability.py | AndersenLab/CAENDR | ce4cdb74db736db8226ffc90988959b71b0d5ff5 | [
"MIT"
] | 1 | 2022-01-11T03:39:02.000Z | 2022-01-11T03:39:02.000Z | import io
import pandas as pd
import json
from flask import (flash,
request,
redirect,
url_for,
jsonify,
render_template,
Blueprint,
abort)
from logzero import logger
from datetime import datetime
from base.forms import HeritabilityForm
from base.utils.auth import jwt_required, admin_required, get_jwt, get_current_user
from caendr.api.strain import get_strains
from caendr.services.heritability_report import get_all_heritability_results, get_user_heritability_results, create_new_heritability_report, get_heritability_report
from caendr.utils.data import unique_id, convert_data_table_to_tsv, get_object_hash
from caendr.services.cloud.storage import get_blob, generate_blob_url
# ================== #
# heritability #
# ================== #
# Tools blueprint
heritability_bp = Blueprint('heritability',
__name__)
@heritability_bp.route('/heritability')
def heritability():
title = "Heritability Calculator"
alt_parent_breadcrumb = {"title": "Tools", "url": url_for('tools.tools')}
form = HeritabilityForm()
hide_form = True
strain_list = []
return render_template('tools/heritability/submit.html', **locals())
@heritability_bp.route('/heritability/create', methods=["GET"])
@jwt_required()
def heritability_create():
""" This endpoint is used to create a heritability job. """
title = "Heritability Calculator"
alt_parent_breadcrumb = {"title": "Tools", "url": url_for('tools.tools')}
jwt_csrf_token = (get_jwt() or {}).get("csrf")
form = HeritabilityForm()
strain_data = get_strains()
strain_list = []
for x in strain_data:
strain_list.append(x.strain)
hide_form = False
id = unique_id()
return render_template('tools/heritability/submit.html', **locals())
@heritability_bp.route("/heritability/all-results")
@admin_required()
def heritability_all_results():
title = "All Heritability Results"
alt_parent_breadcrumb = {"title": "Tools", "url": url_for('tools.tools')}
user = get_current_user()
items = get_all_heritability_results()
return render_template('tools/heritability/list-all.html', **locals())
@heritability_bp.route("/heritability/my-results")
@jwt_required()
def heritability_user_results():
title = "My Heritability Results"
alt_parent_breadcrumb = {"title": "Tools", "url": url_for('tools.tools')}
user = get_current_user()
items = get_user_heritability_results(user.name)
return render_template('tools/heritability/list-user.html', **locals())
@heritability_bp.route('/heritability/submit', methods=["POST"])
@jwt_required()
def submit_h2():
user = get_current_user()
label = request.values['label']
columns = ["AssayNumber", "Strain", "TraitName", "Replicate", "Value"]
# Extract table data
data = json.loads(request.values['table_data'])
data = [x for x in data[1:] if x[0] is not None]
trait = data[0][2]
data_tsv = convert_data_table_to_tsv(data, columns)
# Generate an ID for the data based on its hash
data_hash = get_object_hash(data, length=32)
logger.debug(data_hash)
id = unique_id()
try:
h = create_new_heritability_report(id, user.name, label, data_hash, trait, data_tsv)
except Exception as ex:
if str(type(ex).__name__) == 'DuplicateDataError':
flash('It looks like you submitted that data already - redirecting to your list of Heritability Reports', 'danger')
return jsonify({'duplicate': True,
'data_hash': data_hash,
'id': id})
if str(type(ex).__name__) == 'CachedDataError':
flash('It looks like that data has already been submitted - redirecting to the saved results', 'danger')
return jsonify({'cached': True,
'data_hash': data_hash,
'id': id})
return jsonify({'started': True,
'data_hash': data_hash,
'id': id})
# TODO: Move this into a separate service
@heritability_bp.route("/heritability/h2/<id>")
@jwt_required()
def heritability_result(id):
title = "Heritability Results"
alt_parent_breadcrumb = {"title": "Tools", "url": url_for('tools.tools')}
user = get_current_user()
hr = get_heritability_report(id)
ready = False
data_url = generate_blob_url(hr.get_bucket_name(), hr.get_data_blob_path())
if (not hr._exists) or (hr.username != user.name):
flash('You do not have access to that report', 'danger')
abort(401)
data_hash = hr.data_hash
data_blob = hr.get_data_blob_path()
result_blob = hr.get_result_blob_path()
data = get_blob(hr.get_bucket_name(), hr.get_data_blob_path())
result = get_blob(hr.get_bucket_name(), hr.get_result_blob_path())
if data is None:
return abort(404, description="Heritability report not found")
data = data.download_as_string().decode('utf-8')
data = pd.read_csv(io.StringIO(data), sep="\t")
data['AssayNumber'] = data['AssayNumber'].astype(str)
data['label'] = data.apply(lambda x: f"{x['AssayNumber']}: {x['Value']}", 1)
data = data.to_dict('records')
trait = data[0]['TraitName']
# Get trait and set title
subtitle = trait
if result:
hr.status = 'COMPLETE'
hr.save()
result = result.download_as_string().decode('utf-8')
result = pd.read_csv(io.StringIO(result), sep="\t")
result = result.to_dict('records')[0]
fnam=datetime.today().strftime('%Y%m%d.')+trait
ready = True
return render_template("tools/heritability/view.html", **locals())
| 33.756098 | 164 | 0.684429 | import io
import pandas as pd
import json
from flask import (flash,
request,
redirect,
url_for,
jsonify,
render_template,
Blueprint,
abort)
from logzero import logger
from datetime import datetime
from base.forms import HeritabilityForm
from base.utils.auth import jwt_required, admin_required, get_jwt, get_current_user
from caendr.api.strain import get_strains
from caendr.services.heritability_report import get_all_heritability_results, get_user_heritability_results, create_new_heritability_report, get_heritability_report
from caendr.utils.data import unique_id, convert_data_table_to_tsv, get_object_hash
from caendr.services.cloud.storage import get_blob, generate_blob_url
heritability_bp = Blueprint('heritability',
__name__)
@heritability_bp.route('/heritability')
def heritability():
title = "Heritability Calculator"
alt_parent_breadcrumb = {"title": "Tools", "url": url_for('tools.tools')}
form = HeritabilityForm()
hide_form = True
strain_list = []
return render_template('tools/heritability/submit.html', **locals())
@heritability_bp.route('/heritability/create', methods=["GET"])
@jwt_required()
def heritability_create():
title = "Heritability Calculator"
alt_parent_breadcrumb = {"title": "Tools", "url": url_for('tools.tools')}
jwt_csrf_token = (get_jwt() or {}).get("csrf")
form = HeritabilityForm()
strain_data = get_strains()
strain_list = []
for x in strain_data:
strain_list.append(x.strain)
hide_form = False
id = unique_id()
return render_template('tools/heritability/submit.html', **locals())
@heritability_bp.route("/heritability/all-results")
@admin_required()
def heritability_all_results():
title = "All Heritability Results"
alt_parent_breadcrumb = {"title": "Tools", "url": url_for('tools.tools')}
user = get_current_user()
items = get_all_heritability_results()
return render_template('tools/heritability/list-all.html', **locals())
@heritability_bp.route("/heritability/my-results")
@jwt_required()
def heritability_user_results():
title = "My Heritability Results"
alt_parent_breadcrumb = {"title": "Tools", "url": url_for('tools.tools')}
user = get_current_user()
items = get_user_heritability_results(user.name)
return render_template('tools/heritability/list-user.html', **locals())
@heritability_bp.route('/heritability/submit', methods=["POST"])
@jwt_required()
def submit_h2():
user = get_current_user()
label = request.values['label']
columns = ["AssayNumber", "Strain", "TraitName", "Replicate", "Value"]
data = json.loads(request.values['table_data'])
data = [x for x in data[1:] if x[0] is not None]
trait = data[0][2]
data_tsv = convert_data_table_to_tsv(data, columns)
data_hash = get_object_hash(data, length=32)
logger.debug(data_hash)
id = unique_id()
try:
h = create_new_heritability_report(id, user.name, label, data_hash, trait, data_tsv)
except Exception as ex:
if str(type(ex).__name__) == 'DuplicateDataError':
flash('It looks like you submitted that data already - redirecting to your list of Heritability Reports', 'danger')
return jsonify({'duplicate': True,
'data_hash': data_hash,
'id': id})
if str(type(ex).__name__) == 'CachedDataError':
flash('It looks like that data has already been submitted - redirecting to the saved results', 'danger')
return jsonify({'cached': True,
'data_hash': data_hash,
'id': id})
return jsonify({'started': True,
'data_hash': data_hash,
'id': id})
@heritability_bp.route("/heritability/h2/<id>")
@jwt_required()
def heritability_result(id):
title = "Heritability Results"
alt_parent_breadcrumb = {"title": "Tools", "url": url_for('tools.tools')}
user = get_current_user()
hr = get_heritability_report(id)
ready = False
data_url = generate_blob_url(hr.get_bucket_name(), hr.get_data_blob_path())
if (not hr._exists) or (hr.username != user.name):
flash('You do not have access to that report', 'danger')
abort(401)
data_hash = hr.data_hash
data_blob = hr.get_data_blob_path()
result_blob = hr.get_result_blob_path()
data = get_blob(hr.get_bucket_name(), hr.get_data_blob_path())
result = get_blob(hr.get_bucket_name(), hr.get_result_blob_path())
if data is None:
return abort(404, description="Heritability report not found")
data = data.download_as_string().decode('utf-8')
data = pd.read_csv(io.StringIO(data), sep="\t")
data['AssayNumber'] = data['AssayNumber'].astype(str)
data['label'] = data.apply(lambda x: f"{x['AssayNumber']}: {x['Value']}", 1)
data = data.to_dict('records')
trait = data[0]['TraitName']
subtitle = trait
if result:
hr.status = 'COMPLETE'
hr.save()
result = result.download_as_string().decode('utf-8')
result = pd.read_csv(io.StringIO(result), sep="\t")
result = result.to_dict('records')[0]
fnam=datetime.today().strftime('%Y%m%d.')+trait
ready = True
return render_template("tools/heritability/view.html", **locals())
| true | true |
f716a488f4da02f72691c1194f86e83d967d3e2b | 45,335 | py | Python | test/test_sort_and_select.py | kbrose/pytorch | fc0b8e60337ae46b90ed5d2f6d1f623f0f8d6581 | [
"Intel"
] | null | null | null | test/test_sort_and_select.py | kbrose/pytorch | fc0b8e60337ae46b90ed5d2f6d1f623f0f8d6581 | [
"Intel"
] | null | null | null | test/test_sort_and_select.py | kbrose/pytorch | fc0b8e60337ae46b90ed5d2f6d1f623f0f8d6581 | [
"Intel"
] | null | null | null | import torch
import numpy as np
import random
from torch._six import nan
from itertools import permutations, product
from torch.testing import all_types, all_types_and
from torch.testing._internal.common_utils import \
(TEST_WITH_ROCM, TestCase, run_tests, make_tensor, slowTest)
from torch.testing._internal.common_device_type import \
(instantiate_device_type_tests, dtypes, onlyOnCPUAndCUDA,
skipCUDAIfRocm, onlyCUDA, dtypesIfCUDA, dtypesIfCPU, onlyCPU, largeTensorTest)
# TODO: remove this
SIZE = 100
class TestSortAndSelect(TestCase):
def assertIsOrdered(self, order, x, mxx, ixx, task):
SIZE = x.size(1)
if order == 'descending':
def check_order(a, b):
# `a != a` because we put NaNs
# at the end of ascending sorted lists,
# and the beginning of descending ones.
return ((a != a) | (a >= b)).all().item()
elif order == 'ascending':
def check_order(a, b):
# see above
return ((b != b) | (a <= b)).all().item()
else:
error('unknown order "{}", must be "ascending" or "descending"'.format(order))
are_ordered = True
for k in range(1, SIZE):
self.assertTrue(check_order(mxx[:, k - 1], mxx[:, k]),
'torch.sort ({}) values unordered for {}'.format(order, task))
seen = set()
indicesCorrect = True
size0 = x.size(0)
size = x.size(x.dim() - 1)
x = x.tolist()
mxx = mxx.tolist()
ixx = ixx.tolist()
for k in range(size0):
seen.clear()
for j in range(size):
self.assertEqual(x[k][ixx[k][j]], mxx[k][j],
msg='torch.sort ({}) indices wrong for {}'.format(order, task))
seen.add(ixx[k][j])
self.assertEqual(len(seen), size)
def test_sort(self, device):
# on CUDA 2048 vs >2048 have different code path for the dim being sorted
for SIZE in (4, 2049):
x = torch.rand(4, SIZE, device=device)
res1val, res1ind = torch.sort(x)
# Test inplace
y = x.clone()
y_inds = torch.tensor((), dtype=torch.int64, device=device)
torch.sort(y, out=(y, y_inds))
x_vals, x_inds = torch.sort(x)
self.assertEqual(x_vals, y)
self.assertEqual(x_inds, y_inds)
# Test use of result tensor
res2val = torch.tensor((), device=device)
res2ind = torch.tensor((), device=device, dtype=torch.long)
torch.sort(x, out=(res2val, res2ind))
self.assertEqual(res1val, res2val, atol=0, rtol=0)
self.assertEqual(res1ind, res2ind, atol=0, rtol=0)
self.assertEqual(torch.argsort(x), res1ind)
self.assertEqual(x.argsort(), res1ind)
# Test sorting of random numbers
self.assertIsOrdered('ascending', x, res2val, res2ind, 'random')
# Test simple sort
self.assertEqual(
torch.sort(torch.tensor((50, 40, 30, 20, 10), device=device))[0],
torch.tensor((10, 20, 30, 40, 50), device=device),
atol=0, rtol=0
)
# Test that we still have proper sorting with duplicate keys
x = torch.floor(torch.rand(4, SIZE, device=device) * 10)
torch.sort(x, out=(res2val, res2ind))
self.assertIsOrdered('ascending', x, res2val, res2ind, 'random with duplicate keys')
# DESCENDING SORT
x = torch.rand(4, SIZE, device=device)
res1val, res1ind = torch.sort(x, x.dim() - 1, True)
# Test use of result tensor
res2val = torch.tensor((), device=device)
res2ind = torch.tensor((), device=device, dtype=torch.long)
torch.sort(x, x.dim() - 1, True, out=(res2val, res2ind))
self.assertEqual(res1val, res2val, atol=0, rtol=0)
self.assertEqual(res1ind, res2ind, atol=0, rtol=0)
self.assertEqual(torch.argsort(x, x.dim() - 1, True), res1ind)
self.assertEqual(x.argsort(x.dim() - 1, True), res1ind)
# Test sorting of random numbers
self.assertIsOrdered('descending', x, res2val, res2ind, 'random')
# Test simple sort task
self.assertEqual(
torch.sort(torch.tensor((10, 20, 30, 40, 50), device=device), 0, True)[0],
torch.tensor((50, 40, 30, 20, 10), device=device),
atol=0, rtol=0
)
# Test that we still have proper sorting with duplicate keys
self.assertIsOrdered('descending', x, res2val, res2ind, 'random with duplicate keys')
# Test sorting with NaNs
x = torch.rand(4, SIZE, device=device)
x[1][2] = float('NaN')
x[3][0] = float('NaN')
torch.sort(x, out=(res2val, res2ind))
self.assertIsOrdered('ascending', x, res2val, res2ind,
'random with NaNs')
torch.sort(x, out=(res2val, res2ind), descending=True)
self.assertIsOrdered('descending', x, res2val, res2ind,
'random with NaNs')
# FIXME: remove torch.bool from unsupported types once support is added for cub sort
@dtypes(*set(torch.testing.get_all_dtypes()) - {torch.bool, torch.complex64, torch.complex128})
def test_stable_sort(self, device, dtype):
if TEST_WITH_ROCM and dtype == torch.bfloat16:
return
sizes = (100, 1000, 10000)
for ncopies in sizes:
x = torch.tensor([0, 1] * ncopies, dtype=dtype, device=device)
_, idx = x.sort(stable=True)
self.assertEqual(
idx[:ncopies],
torch.arange(start=0, end=2 * ncopies, step=2, device=device)
)
self.assertEqual(
idx[ncopies:],
torch.arange(start=1, end=2 * ncopies, step=2, device=device)
)
@onlyCUDA
@dtypes(torch.uint8)
@largeTensorTest('200GB') # Unfortunately 80GB A100 is not large enough
def test_sort_large(self, device, dtype):
t0 = torch.randperm(8192, device=device).to(dtype)
t = t0.view(1, 8192).expand(2 ** 18 + 1, -1).contiguous()
v, i = t.sort()
del t
iv, im = i.var_mean(dim=0)
del i
vv, vm = v.var_mean(dim=0)
del v
self.assertEqual(vv, torch.zeros_like(vv))
self.assertEqual(iv, torch.zeros_like(iv))
self.assertEqual(vm, torch.arange(255, dtype=dtype, device=device))
self.assertEqual(im, t0.sort().indices)
def _test_sort_discontiguous(self, device, dtype):
# on CUDA 2048 vs >2048 have different code path for the dim being sorted
sizes = (5, 7, 2049)
for shape in permutations(sizes):
for perm in permutations((0, 1, 2)):
for dim in range(3):
t = torch.randn(shape, device=device, dtype=dtype).permute(perm)
r1 = t.sort(dim=dim)
r2 = t.contiguous().sort(dim=dim)
self.assertEqual(r1, r2)
n = t.size(dim)
# assert ordered
self.assertTrue((r1.values.narrow(dim, 1, n - 1) >= r1.values.narrow(dim, 0, n - 1)).all())
# assert that different segments does not mix, which can easily happen
# if the stride is not handled correctly
self.assertTrue((t.unsqueeze(-1).transpose(dim, -1) == r1.values.unsqueeze(-1)).any(dim=dim).any(dim=-1).all())
# assert stride is preserved
if self.device_type == 'cuda':
# FIXME: this behavior should be true for all cases, not
# just the one specified in if condition
self.assertEqual(r1.values.stride(), t.stride())
self.assertEqual(r1.indices.stride(), t.stride())
@onlyCUDA
@dtypes(torch.float32)
def test_sort_discontiguous(self, device, dtype):
self._test_sort_discontiguous(device, dtype)
@slowTest # this test is slow on CPU, but not on CUDA
@onlyCPU
@dtypes(torch.float32)
def test_sort_discontiguous_slow(self, device, dtype):
self._test_sort_discontiguous(device, dtype)
# FIXME: remove torch.bool from unsupported types once support is added for cub sort
@dtypes(*set(torch.testing.get_all_dtypes()) - {torch.bool, torch.complex64, torch.complex128})
def test_stable_sort_against_numpy(self, device, dtype):
if TEST_WITH_ROCM and dtype == torch.bfloat16:
return
if dtype in torch.testing.floating_types_and(torch.float16, torch.bfloat16):
inf = float('inf')
neg_inf = -float('inf')
nan = float('nan')
else:
if dtype != torch.bool:
# no torch.iinfo support for torch.bool
inf = torch.iinfo(dtype).max
neg_inf = torch.iinfo(dtype).min
else:
inf = True
neg_inf = ~inf
# no nan for integral types, we use inf instead for simplicity
nan = inf
def generate_samples():
from itertools import chain, combinations
for sizes in [(1025,), (10000,)]:
size = sizes[0]
# binary strings
yield (torch.tensor([0, 1] * size, dtype=dtype, device=device), 0)
if self.device_type == 'cuda':
return
yield (torch.tensor([0, 1] * 100, dtype=dtype, device=device), 0)
def repeated_index_fill(t, dim, idxs, vals):
res = t
for idx, val in zip(idxs, vals):
res = res.index_fill(dim, idx, val)
return res
for sizes in [(1, 10), (10, 1), (10, 10), (10, 10, 10)]:
size = min(*sizes)
x = (torch.randn(*sizes, device=device) * size).to(dtype)
yield (x, 0)
# Generate tensors which are being filled at random locations
# with values from the non-empty subsets of the set (inf, neg_inf, nan)
# for each dimension.
n_fill_vals = 3 # cardinality of (inf, neg_inf, nan)
for dim in range(len(sizes)):
idxs = (torch.randint(high=size, size=(size // 10,)) for i in range(n_fill_vals))
vals = (inf, neg_inf, nan)
subsets = chain.from_iterable(combinations(list(zip(idxs, vals)), r)
for r in range(1, n_fill_vals + 1))
for subset in subsets:
idxs_subset, vals_subset = zip(*subset)
yield (repeated_index_fill(x, dim, idxs_subset, vals_subset), dim)
for sample, dim in generate_samples():
_, idx_torch = sample.sort(dim=dim, stable=True)
if dtype is torch.bfloat16:
sample_numpy = sample.float().cpu().numpy()
else:
sample_numpy = sample.cpu().numpy()
idx_numpy = np.argsort(sample_numpy, axis=dim, kind='stable')
self.assertEqual(idx_torch, idx_numpy)
@dtypes(*(torch.testing.get_all_int_dtypes() + torch.testing.get_all_fp_dtypes()))
def test_msort(self, device, dtype):
if TEST_WITH_ROCM and dtype == torch.bfloat16:
return
def test(shape):
tensor = make_tensor(shape, device, dtype, low=-9, high=9)
if tensor.size() != torch.Size([]):
if dtype is torch.bfloat16:
expected = torch.from_numpy(np.msort(tensor.float().cpu().numpy())).bfloat16()
else:
expected = torch.from_numpy(np.msort(tensor.cpu().numpy()))
else:
expected = tensor # numpy.msort() does not support empty shapes tensor
result = torch.msort(tensor)
self.assertEqual(result, expected)
out = torch.empty_like(result)
torch.msort(tensor, out=out)
self.assertEqual(out, expected)
shapes = (
[],
[0, ],
[20, ],
[1, 20],
[30, 30],
[10, 20, 30]
)
for shape in shapes:
test(shape)
def test_topk(self, device):
def topKViaSort(t, k, dim, dir):
sorted, indices = t.sort(dim, dir)
return sorted.narrow(dim, 0, k), indices.narrow(dim, 0, k)
def compareTensors(t, res1, ind1, res2, ind2, dim):
# Values should be exactly equivalent
self.assertEqual(res1, res2, atol=0, rtol=0)
# Indices might differ based on the implementation, since there is
# no guarantee of the relative order of selection
if not ind1.eq(ind2).all():
# To verify that the indices represent equivalent elements,
# gather from the input using the topk indices and compare against
# the sort indices
vals = t.gather(dim, ind2)
self.assertEqual(res1, vals, atol=0, rtol=0)
def compare(t, k, dim, dir):
topKVal, topKInd = t.topk(k, dim, dir, True)
sortKVal, sortKInd = topKViaSort(t, k, dim, dir)
compareTensors(t, sortKVal, sortKInd, topKVal, topKInd, dim)
t = torch.rand(random.randint(1, SIZE),
random.randint(1, SIZE),
random.randint(1, SIZE), device=device)
for _kTries in range(3):
for _dimTries in range(3):
for transpose in (True, False):
for dir in (True, False):
testTensor = t
if transpose:
dim1 = random.randrange(t.ndimension())
dim2 = dim1
while dim1 == dim2:
dim2 = random.randrange(t.ndimension())
testTensor = t.transpose(dim1, dim2)
dim = random.randrange(testTensor.ndimension())
k = random.randint(1, testTensor.size(dim))
compare(testTensor, k, dim, dir)
def test_topk_arguments(self, device):
q = torch.randn(10, 2, 10, device=device)
# Make sure True isn't mistakenly taken as the 2nd dimension (interpreted as 1)
self.assertRaises(TypeError, lambda: q.topk(4, True))
@skipCUDAIfRocm
def test_unique_dim(self, device):
self.assertFalse(hasattr(torch, 'unique_dim'))
def run_test(device, dtype):
x = torch.tensor([[[1., 1.],
[0., 1.],
[2., 1.],
[0., 1.]],
[[1., 1.],
[0., 1.],
[2., 1.],
[0., 1.]]],
dtype=dtype,
device=device)
x_empty = torch.empty(5, 0, dtype=dtype, device=device)
x_ill_formed_empty = torch.empty(5, 0, 0, dtype=dtype, device=device)
x_ill_formed_empty_another = torch.empty(5, 0, 5, dtype=dtype, device=device)
expected_unique_dim0 = torch.tensor([[[1., 1.],
[0., 1.],
[2., 1.],
[0., 1.]]],
dtype=dtype,
device=device)
expected_inverse_dim0 = torch.tensor([0, 0])
expected_counts_dim0 = torch.tensor([2])
expected_unique_dim1 = torch.tensor([[[0., 1.],
[1., 1.],
[2., 1.]],
[[0., 1.],
[1., 1.],
[2., 1.]]],
dtype=dtype,
device=device)
expected_unique_dim1_bool = torch.tensor([[[False, True], [True, True]],
[[False, True], [True, True]]],
dtype=torch.bool,
device=device)
expected_inverse_dim1 = torch.tensor([1, 0, 2, 0])
expected_inverse_dim1_bool = torch.tensor([1, 0, 1, 0])
expected_counts_dim1 = torch.tensor([2, 1, 1])
expected_counts_dim1_bool = torch.tensor([2, 2])
expected_unique_dim2 = torch.tensor([[[1., 1.],
[0., 1.],
[2., 1.],
[0., 1.]],
[[1., 1.],
[0., 1.],
[2., 1.],
[0., 1.]]],
dtype=dtype,
device=device)
expected_inverse_dim2 = torch.tensor([0, 1])
expected_counts_dim2 = torch.tensor([1, 1])
expected_unique_empty = torch.tensor([], dtype=dtype, device=device)
expected_inverse_empty = torch.tensor([], dtype=torch.long, device=device)
expected_counts_empty = torch.tensor([], dtype=torch.long, device=device)
# dim0
x_unique = torch.unique(x, dim=0)
self.assertEqual(expected_unique_dim0, x_unique)
x_unique, x_inverse = torch.unique(
x,
return_inverse=True,
dim=0)
self.assertEqual(expected_unique_dim0, x_unique)
self.assertEqual(expected_inverse_dim0, x_inverse)
x_unique, x_counts = torch.unique(
x,
return_inverse=False,
return_counts=True,
dim=0)
self.assertEqual(expected_unique_dim0, x_unique)
self.assertEqual(expected_counts_dim0, x_counts)
x_unique, x_inverse, x_counts = torch.unique(
x,
return_inverse=True,
return_counts=True,
dim=0)
self.assertEqual(expected_unique_dim0, x_unique)
self.assertEqual(expected_inverse_dim0, x_inverse)
self.assertEqual(expected_counts_dim0, x_counts)
# dim1
x_unique = torch.unique(x, dim=1)
if x.dtype == torch.bool:
self.assertEqual(expected_unique_dim1_bool, x_unique)
else:
self.assertEqual(expected_unique_dim1, x_unique)
x_unique, x_inverse = torch.unique(
x,
return_inverse=True,
dim=1)
if x.dtype == torch.bool:
self.assertEqual(expected_unique_dim1_bool, x_unique)
self.assertEqual(expected_inverse_dim1_bool, x_inverse)
else:
self.assertEqual(expected_unique_dim1, x_unique)
self.assertEqual(expected_inverse_dim1, x_inverse)
x_unique, x_counts = torch.unique(
x,
return_inverse=False,
return_counts=True,
dim=1)
if x.dtype == torch.bool:
self.assertEqual(expected_unique_dim1_bool, x_unique)
self.assertEqual(expected_counts_dim1_bool, x_counts)
else:
self.assertEqual(expected_unique_dim1, x_unique)
self.assertEqual(expected_counts_dim1, x_counts)
x_unique, x_inverse, x_counts = torch.unique(
x,
return_inverse=True,
return_counts=True,
dim=1)
if x.dtype == torch.bool:
self.assertEqual(expected_unique_dim1_bool, x_unique)
self.assertEqual(expected_inverse_dim1_bool, x_inverse)
self.assertEqual(expected_counts_dim1_bool, x_counts)
else:
self.assertEqual(expected_unique_dim1, x_unique)
self.assertEqual(expected_inverse_dim1, x_inverse)
self.assertEqual(expected_counts_dim1, x_counts)
# dim2
x_unique = torch.unique(x, dim=2)
self.assertEqual(expected_unique_dim2, x_unique)
x_unique, x_inverse = torch.unique(
x,
return_inverse=True,
dim=2)
self.assertEqual(expected_unique_dim2, x_unique)
self.assertEqual(expected_inverse_dim2, x_inverse)
x_unique, x_counts = torch.unique(
x,
return_inverse=False,
return_counts=True,
dim=2)
self.assertEqual(expected_unique_dim2, x_unique)
self.assertEqual(expected_counts_dim2, x_counts)
x_unique, x_inverse, x_counts = torch.unique(
x,
return_inverse=True,
return_counts=True,
dim=2)
self.assertEqual(expected_unique_dim2, x_unique)
self.assertEqual(expected_inverse_dim2, x_inverse)
self.assertEqual(expected_counts_dim2, x_counts)
# test empty tensor
x_unique, x_inverse, x_counts = torch.unique(
x_empty,
return_inverse=True,
return_counts=True,
dim=1)
self.assertEqual(expected_unique_empty, x_unique)
self.assertEqual(expected_inverse_empty, x_inverse)
self.assertEqual(expected_counts_empty, x_counts)
# test not a well formed tensor
# Checking for runtime error, as this is the expected behaviour
with self.assertRaises(RuntimeError):
torch.unique(
x_ill_formed_empty,
return_inverse=True,
return_counts=True,
dim=1)
# test along dim2
with self.assertRaises(RuntimeError):
torch.unique(
x_ill_formed_empty_another,
return_inverse=True,
return_counts=True,
dim=2)
# test consecutive version
y = torch.tensor(
[[0, 1],
[0, 1],
[0, 1],
[1, 2],
[1, 2],
[3, 4],
[0, 1],
[0, 1],
[3, 4],
[1, 2]],
dtype=dtype,
device=device
)
expected_y_unique = torch.tensor(
[[0, 1],
[1, 2],
[3, 4],
[0, 1],
[3, 4],
[1, 2]],
dtype=dtype,
device=device
)
expected_y_inverse = torch.tensor([0, 0, 0, 1, 1, 2, 3, 3, 4, 5], dtype=torch.int64, device=device)
expected_y_counts = torch.tensor([3, 2, 1, 2, 1, 1], dtype=torch.int64, device=device)
expected_y_inverse_bool = torch.tensor([0, 0, 0, 1, 1, 1, 2, 2, 3, 3], dtype=torch.int64, device=device)
expected_y_counts_bool = torch.tensor([3, 3, 2, 2], dtype=torch.int64, device=device)
y_unique, y_inverse, y_counts = torch.unique_consecutive(y, return_inverse=True, return_counts=True, dim=0)
if x.dtype == torch.bool:
self.assertEqual(expected_y_inverse_bool, y_inverse)
self.assertEqual(expected_y_counts_bool, y_counts)
else:
self.assertEqual(expected_y_inverse, y_inverse)
self.assertEqual(expected_y_counts, y_counts)
run_test(device, torch.float)
run_test(device, torch.double)
run_test(device, torch.long)
run_test(device, torch.uint8)
run_test(device, torch.bool)
@onlyCUDA
def test_topk_noncontiguous_gpu(self, device):
t = torch.randn(20, device=device)[::2]
top1, idx1 = t.topk(5)
top2, idx2 = t.contiguous().topk(5)
self.assertEqual(top1, top2)
self.assertEqual(idx1, idx2)
def _test_topk_dtype(self, device, dtype, integral, size):
if integral:
a = torch.randint(torch.iinfo(dtype).min, torch.iinfo(dtype).max,
size=(size,), dtype=dtype, device=device)
else:
a = torch.randn(size=(size,), dtype=dtype, device=device)
sort_topk = a.sort()[0][-(size // 2):].flip(0)
topk = a.topk(size // 2)
self.assertEqual(sort_topk, topk[0]) # check values
self.assertEqual(sort_topk, a[topk[1]]) # check indices
@dtypes(torch.int8, torch.uint8, torch.int16, torch.int32, torch.int64)
def test_topk_integral(self, device, dtype):
small = 10
large = 4096
for curr_size in (small, large):
self._test_topk_dtype(device, dtype, True, curr_size)
@onlyCUDA
@dtypes(torch.bfloat16)
@skipCUDAIfRocm
def test_topk_bfloat16(self, device, dtype):
small = 10
large = 8192
for curr_size in (small, large):
self._test_topk_dtype(device, dtype, False, curr_size)
@dtypesIfCUDA(*torch.testing.get_all_fp_dtypes())
@dtypes(torch.float, torch.double, torch.bfloat16)
def test_topk_nonfinite(self, device, dtype):
if TEST_WITH_ROCM and dtype == torch.bfloat16:
return
x = torch.tensor([float('nan'), float('inf'), 1e4, 0, -1e4, -float('inf')], device=device, dtype=dtype)
val, idx = x.topk(4)
expect = torch.tensor([float('nan'), float('inf'), 1e4, 0], device=device, dtype=dtype)
self.assertEqual(val, expect)
self.assertEqual(idx, [0, 1, 2, 3])
val, idx = x.topk(4, largest=False)
expect = torch.tensor([-float('inf'), -1e4, 0, 1e4], device=device, dtype=dtype)
self.assertEqual(val, expect)
self.assertEqual(idx, [5, 4, 3, 2])
def test_topk_4d(self, device):
x = torch.ones(2, 3072, 2, 2, device=device)
x[:, 1, :, :] *= 2.
x[:, 10, :, :] *= 1.5
val, ind = torch.topk(x, k=2, dim=1)
expected_ind = torch.ones(2, 2, 2, 2, dtype=torch.long, device=device)
expected_ind[:, 1, :, :] = 10
expected_val = torch.ones(2, 2, 2, 2, device=device)
expected_val[:, 0, :, :] *= 2.
expected_val[:, 1, :, :] *= 1.5
self.assertEqual(val, expected_val, atol=0, rtol=0)
self.assertEqual(ind, expected_ind, atol=0, rtol=0)
@onlyOnCPUAndCUDA
@dtypesIfCUDA(*(torch.testing.get_all_dtypes(include_complex=False,
include_bool=False,
include_half=False,
include_bfloat16=True)))
@dtypes(*(torch.testing.get_all_dtypes(include_complex=False, include_bool=False, include_half=False, include_bfloat16=False)))
def test_topk_zero(self, device, dtype):
if TEST_WITH_ROCM and dtype == torch.bfloat16:
return
# https://github.com/pytorch/pytorch/issues/49205
t = torch.rand(2, 2, device=device).to(dtype=dtype)
val, idx = torch.topk(t, k=0, largest=False)
self.assertEqual(val.size(), torch.Size([2, 0]))
self.assertEqual(idx.size(), torch.Size([2, 0]))
def _test_unique_scalar_empty(self, dtype, device, f):
# test scalar
x = torch.tensor(0, dtype=dtype, device=device)
unique, inverse, counts = f(x, return_inverse=True, return_counts=True)
expected_unique = torch.tensor([0], dtype=dtype, device=device)
expected_inverse = torch.tensor(0, device=device)
expected_counts = torch.tensor([1], device=device)
self.assertEqual(unique, expected_unique)
self.assertEqual(inverse, expected_inverse)
self.assertEqual(counts, expected_counts)
# test zero sized tensor
x = torch.zeros((0, 0, 3), dtype=dtype, device=device)
unique, inverse, counts = f(x, return_inverse=True, return_counts=True)
expected_unique = torch.tensor([], dtype=dtype, device=device)
expected_inverse = torch.empty((0, 0, 3), dtype=torch.long, device=device)
expected_counts = torch.tensor([], dtype=torch.long, device=device)
self.assertEqual(unique, expected_unique)
self.assertEqual(inverse, expected_inverse)
self.assertEqual(counts, expected_counts)
def _test_unique_with_expects(self, device, dtype, f, x, expected_unique, expected_inverse, expected_counts, additional_shape):
def ensure_tuple(x):
if isinstance(x, torch.Tensor):
return (x,)
return x
for return_inverse in [True, False]:
for return_counts in [True, False]:
# test with expected
ret = ensure_tuple(f(x, return_inverse=return_inverse, return_counts=return_counts))
self.assertEqual(len(ret), 1 + int(return_inverse) + int(return_counts))
self.assertEqual(expected_unique, ret[0])
if return_inverse:
self.assertEqual(expected_inverse, ret[1])
if return_counts:
count_index = 1 + int(return_inverse)
self.assertEqual(expected_counts, ret[count_index])
# tests per-element unique on a higher rank tensor.
y = x.view(additional_shape)
y_unique, y_inverse, y_counts = f(y, return_inverse=True, return_counts=True)
self.assertEqual(expected_unique, y_unique)
self.assertEqual(expected_inverse.view(additional_shape), y_inverse)
self.assertEqual(expected_counts, y_counts)
@dtypesIfCPU(*set(torch.testing.get_all_dtypes()) - {torch.complex64, torch.complex128})
@dtypes(*set(torch.testing.get_all_dtypes()) - {torch.bfloat16, torch.complex64, torch.complex128})
def test_unique(self, device, dtype):
if dtype is torch.half and self.device_type == 'cpu':
return # CPU does not have half support
def ensure_tuple(x):
if isinstance(x, torch.Tensor):
return (x,)
return x
if dtype is torch.bool:
x = torch.tensor([True, False, False, False, True, False, True, False], dtype=torch.bool, device=device)
expected_unique = torch.tensor([False, True], dtype=torch.bool, device=device)
expected_inverse = torch.tensor([1, 0, 0, 0, 1, 0, 1, 0], dtype=torch.long, device=device)
expected_counts = torch.tensor([5, 3], dtype=torch.long, device=device)
else:
x = torch.tensor([1, 2, 3, 2, 8, 5, 2, 3], dtype=dtype, device=device)
expected_unique = torch.tensor([1, 2, 3, 5, 8], dtype=dtype, device=device)
expected_inverse = torch.tensor([0, 1, 2, 1, 4, 3, 1, 2], device=device)
expected_counts = torch.tensor([1, 3, 2, 1, 1], device=device)
# test sorted unique
fs = (
lambda x, **kwargs: torch.unique(x, sorted=True, **kwargs),
lambda x, **kwargs: x.unique(sorted=True, **kwargs),
)
x_sliced = torch.empty(x.size(0) * 2, dtype=dtype, device=device)[::2].copy_(x)
xs = (x, x_sliced)
for f, x in product(fs, xs):
self._test_unique_with_expects(device, dtype, f, x, expected_unique, expected_inverse, expected_counts, (2, 2, 2))
self._test_unique_scalar_empty(dtype, device, f)
# test unsorted unique
fs = (
lambda x, **kwargs: torch.unique(x, sorted=False, **kwargs),
lambda x, **kwargs: x.unique(sorted=False, **kwargs)
)
for f, x in product(fs, xs):
self._test_unique_scalar_empty(dtype, device, f)
for return_inverse, return_counts in product((True, False), repeat=2):
ret = ensure_tuple(f(x, return_inverse=return_inverse, return_counts=return_counts))
self.assertEqual(len(ret), 1 + int(return_inverse) + int(return_counts))
x_list = x.tolist()
x_unique_list = ret[0].tolist()
self.assertEqual(expected_unique.tolist(), sorted(x_unique_list))
if return_inverse:
x_inverse_list = ret[1].tolist()
for i, j in enumerate(x_inverse_list):
self.assertEqual(x_list[i], x_unique_list[j])
if return_counts:
count_index = 1 + int(return_inverse)
x_counts_list = ret[count_index].tolist()
for i, j in zip(x_unique_list, x_counts_list):
count = 0
for k in x_list:
if k == i:
count += 1
self.assertEqual(j, count)
@dtypesIfCPU(*set(torch.testing.get_all_dtypes()) - {torch.complex64, torch.complex128})
@dtypes(*set(torch.testing.get_all_dtypes()) - {torch.bfloat16, torch.complex64, torch.complex128})
def test_unique_consecutive(self, device, dtype):
if dtype is torch.half and self.device_type == 'cpu':
return # CPU does not have half support
if dtype is torch.bool:
x = torch.tensor([True, False, False, False, True, True, False, False, False], dtype=torch.bool, device=device)
expected_unique = torch.tensor([True, False, True, False], dtype=torch.bool, device=device)
expected_inverse = torch.tensor([0, 1, 1, 1, 2, 2, 3, 3, 3], dtype=torch.long, device=device)
expected_counts = torch.tensor([1, 3, 2, 3], dtype=torch.long, device=device)
else:
x = torch.tensor([1, 2, 2, 2, 5, 5, 2, 2, 3], dtype=dtype, device=device)
expected_unique = torch.tensor([1, 2, 5, 2, 3], dtype=dtype, device=device)
expected_inverse = torch.tensor([0, 1, 1, 1, 2, 2, 3, 3, 4], device=device)
expected_counts = torch.tensor([1, 3, 2, 2, 1], device=device)
for f in [torch.unique_consecutive, lambda x, **kwargs: x.unique_consecutive(**kwargs)]:
self._test_unique_with_expects(device, dtype, f, x, expected_unique, expected_inverse, expected_counts, (3, 3))
self._test_unique_scalar_empty(dtype, device, f)
@dtypes(torch.double)
def test_kthvalue(self, device, dtype):
SIZE = 50
x = torch.rand(SIZE, SIZE, SIZE, dtype=dtype, device=device)
x0 = x.clone()
k = random.randint(1, SIZE)
res1val, res1ind = torch.kthvalue(x, k, keepdim=False)
res2val, res2ind = torch.sort(x)
self.assertEqual(res1val[:, :], res2val[:, :, k - 1], atol=0, rtol=0)
self.assertEqual(res1ind[:, :], res2ind[:, :, k - 1], atol=0, rtol=0)
# test use of result tensors
k = random.randint(1, SIZE)
res1val = torch.tensor([], dtype=dtype, device=device)
res1ind = torch.tensor([], dtype=torch.long, device=device)
torch.kthvalue(x, k, keepdim=False, out=(res1val, res1ind))
res2val, res2ind = torch.sort(x)
self.assertEqual(res1val[:, :], res2val[:, :, k - 1], atol=0, rtol=0)
self.assertEqual(res1ind[:, :], res2ind[:, :, k - 1], atol=0, rtol=0)
# test non-default dim
k = random.randint(1, SIZE)
res1val, res1ind = torch.kthvalue(x, k, 0, keepdim=False)
res2val, res2ind = torch.sort(x, 0)
self.assertEqual(res1val, res2val[k - 1], atol=0, rtol=0)
self.assertEqual(res1ind, res2ind[k - 1], atol=0, rtol=0)
# non-contiguous
y = x.narrow(1, 0, 1)
y0 = y.contiguous()
k = random.randint(1, SIZE)
res1val, res1ind = torch.kthvalue(y, k)
res2val, res2ind = torch.kthvalue(y0, k)
self.assertEqual(res1val, res2val, atol=0, rtol=0)
self.assertEqual(res1ind, res2ind, atol=0, rtol=0)
# non-contiguous [Reference: https://github.com/pytorch/pytorch/issues/45721]
non_contig_t = torch.tensor([0, -1, 1, -2, 2], dtype=dtype, device=device)[::2]
expected_val, expected_ind = non_contig_t.contiguous().kthvalue(2)
non_contig_cpu_t = non_contig_t.cpu()
expected_val_cpu, expected_ind_cpu = non_contig_cpu_t.kthvalue(2)
out_val, out_ind = non_contig_t.kthvalue(2)
self.assertEqual(expected_val, out_val, atol=0, rtol=0)
self.assertEqual(expected_ind, out_ind, atol=0, rtol=0)
self.assertEqual(expected_val_cpu, out_val, atol=0, rtol=0)
self.assertEqual(expected_ind_cpu, out_ind, atol=0, rtol=0)
# check that the input wasn't modified
self.assertEqual(x, x0, atol=0, rtol=0)
# simple test case (with repetitions)
y = torch.tensor((3., 5, 4, 1, 1, 5), dtype=dtype, device=device)
self.assertEqual(torch.kthvalue(y, 3)[0], 3, atol=0, rtol=0)
self.assertEqual(torch.kthvalue(y, 2)[0], 1, atol=0, rtol=0)
# simple test case (with NaN)
SIZE = 50
x = torch.rand(SIZE, SIZE, SIZE, dtype=dtype, device=device)
x[torch.arange(SIZE), :, torch.randint(50, (50,))] = nan
ks = [random.randint(1, SIZE), 1, SIZE, SIZE - 1]
res2val, res2ind = torch.sort(x)
for k in ks:
res1val, res1ind = torch.kthvalue(x, k, keepdim=False)
self.assertEqual(res1val[:, :], res2val[:, :, k - 1], atol=0, rtol=0)
self.assertEqual(res1ind[:, :], res2ind[:, :, k - 1], atol=0, rtol=0)
# test overlapping output
@dtypes(torch.double)
@onlyOnCPUAndCUDA # Fails on XLA
def test_kthvalue_overlap(self, device, dtype):
S = 10
k = 5
a = torch.randn(S, device=device)
indices = torch.empty((), device=device, dtype=torch.long)
with self.assertRaisesRegex(RuntimeError, "unsupported operation:"):
torch.kthvalue(a, k, out=(a, indices))
@dtypes(torch.float)
@onlyOnCPUAndCUDA # Fails on XLA
def test_kthvalue_scalar(self, device, dtype):
# Test scalar input (test case from https://github.com/pytorch/pytorch/issues/30818)
# Tests that passing a scalar tensor or 1D tensor with 1 element work either way
res = torch.tensor(2, device=device, dtype=dtype).kthvalue(1)
ref = torch.tensor([2], device=device, dtype=dtype).kthvalue(1)
self.assertEqual(res[0], ref[0].squeeze())
self.assertEqual(res[1], ref[1].squeeze())
@dtypes(*all_types())
@dtypesIfCUDA(*all_types_and(torch.half))
def test_isin(self, device, dtype):
def assert_isin_equal(a, b):
# Compare to the numpy reference implementation.
x = torch.isin(a, b)
a = a.cpu().numpy() if torch.is_tensor(a) else np.array(a)
b = b.cpu().numpy() if torch.is_tensor(b) else np.array(b)
y = np.isin(a, b)
self.assertEqual(x, y)
# multi-dim tensor, multi-dim tensor
a = torch.arange(24, device=device, dtype=dtype).reshape([2, 3, 4])
b = torch.tensor([[10, 20, 30], [0, 1, 3], [11, 22, 33]], device=device, dtype=dtype)
assert_isin_equal(a, b)
# zero-dim tensor
zero_d = torch.tensor(3, device=device, dtype=dtype)
assert_isin_equal(zero_d, b)
assert_isin_equal(a, zero_d)
assert_isin_equal(zero_d, zero_d)
# empty tensor
empty = torch.tensor([], device=device, dtype=dtype)
assert_isin_equal(empty, b)
assert_isin_equal(a, empty)
assert_isin_equal(empty, empty)
# scalar
assert_isin_equal(a, 6)
assert_isin_equal(5, b)
def define_expected(lst, invert=False):
expected = torch.tensor(lst, device=device)
if invert:
expected = expected.logical_not()
return expected
# Adapted from numpy's in1d tests
for mult in [1, 10]:
for invert in [False, True]:
a = torch.tensor([5, 7, 1, 2], device=device, dtype=dtype)
b = torch.tensor([2, 4, 3, 1, 5] * mult, device=device, dtype=dtype)
ec = define_expected([True, False, True, True], invert=invert)
c = torch.isin(a, b, assume_unique=True, invert=invert)
self.assertEqual(c, ec)
a[0] = 8
ec = define_expected([False, False, True, True], invert=invert)
c = torch.isin(a, b, assume_unique=True, invert=invert)
self.assertEqual(c, ec)
a[0], a[3] = 4, 8
ec = define_expected([True, False, True, False], invert=invert)
c = torch.isin(a, b, assume_unique=True, invert=invert)
self.assertEqual(c, ec)
a = torch.tensor([5, 4, 5, 3, 4, 4, 3, 4, 3, 5, 2, 1, 5, 5], device=device, dtype=dtype)
b = torch.tensor([2, 3, 4] * mult, device=device, dtype=dtype)
ec = define_expected([False, True, False, True, True, True, True, True, True,
False, True, False, False, False], invert=invert)
c = torch.isin(a, b, invert=invert)
self.assertEqual(c, ec)
b = torch.tensor([2, 3, 4] * mult + [5, 5, 4] * mult, device=device, dtype=dtype)
ec = define_expected([True, True, True, True, True, True, True, True, True, True,
True, False, True, True], invert=invert)
c = torch.isin(a, b, invert=invert)
self.assertEqual(c, ec)
a = torch.tensor([5, 7, 1, 2], device=device, dtype=dtype)
b = torch.tensor([2, 4, 3, 1, 5] * mult, device=device, dtype=dtype)
ec = define_expected([True, False, True, True], invert=invert)
c = torch.isin(a, b, invert=invert)
self.assertEqual(c, ec)
a = torch.tensor([5, 7, 1, 1, 2], device=device, dtype=dtype)
b = torch.tensor([2, 4, 3, 3, 1, 5] * mult, device=device, dtype=dtype)
ec = define_expected([True, False, True, True, True], invert=invert)
c = torch.isin(a, b, invert=invert)
self.assertEqual(c, ec)
a = torch.tensor([5, 5], device=device, dtype=dtype)
b = torch.tensor([2, 2] * mult, device=device, dtype=dtype)
ec = define_expected([False, False], invert=invert)
c = torch.isin(a, b, invert=invert)
self.assertEqual(c, ec)
# multi-dimensional input case using sort-based algo
for assume_unique in [False, True]:
a = torch.arange(6, device=device, dtype=dtype).reshape([2, 3])
b = torch.arange(3, 30, device=device, dtype=dtype)
ec = define_expected([[False, False, False], [True, True, True]], invert=invert)
c = torch.isin(a, b, invert=invert, assume_unique=assume_unique)
self.assertEqual(c, ec)
def test_isin_different_dtypes(self, device):
supported_types = all_types() if device == 'cpu' else all_types_and(torch.half)
for mult in [1, 10]:
for assume_unique in [False, True]:
for dtype1, dtype2 in product(supported_types, supported_types):
a = torch.tensor([1, 2, 3], device=device, dtype=dtype1)
b = torch.tensor([3, 4, 5] * mult, device=device, dtype=dtype2)
ec = torch.tensor([False, False, True], device=device)
c = torch.isin(a, b, assume_unique=assume_unique)
self.assertEqual(c, ec)
@onlyCUDA
@dtypes(*all_types())
def test_isin_different_devices(self, device, dtype):
a = torch.arange(6, device=device, dtype=dtype).reshape([2, 3])
b = torch.arange(3, 30, device='cpu', dtype=dtype)
with self.assertRaises(RuntimeError):
torch.isin(a, b)
c = torch.arange(6, device='cpu', dtype=dtype).reshape([2, 3])
d = torch.arange(3, 30, device=device, dtype=dtype)
with self.assertRaises(RuntimeError):
torch.isin(c, d)
instantiate_device_type_tests(TestSortAndSelect, globals())
if __name__ == '__main__':
run_tests()
| 45.28971 | 131 | 0.543179 | import torch
import numpy as np
import random
from torch._six import nan
from itertools import permutations, product
from torch.testing import all_types, all_types_and
from torch.testing._internal.common_utils import \
(TEST_WITH_ROCM, TestCase, run_tests, make_tensor, slowTest)
from torch.testing._internal.common_device_type import \
(instantiate_device_type_tests, dtypes, onlyOnCPUAndCUDA,
skipCUDAIfRocm, onlyCUDA, dtypesIfCUDA, dtypesIfCPU, onlyCPU, largeTensorTest)
SIZE = 100
class TestSortAndSelect(TestCase):
def assertIsOrdered(self, order, x, mxx, ixx, task):
SIZE = x.size(1)
if order == 'descending':
def check_order(a, b):
return ((a != a) | (a >= b)).all().item()
elif order == 'ascending':
def check_order(a, b):
return ((b != b) | (a <= b)).all().item()
else:
error('unknown order "{}", must be "ascending" or "descending"'.format(order))
are_ordered = True
for k in range(1, SIZE):
self.assertTrue(check_order(mxx[:, k - 1], mxx[:, k]),
'torch.sort ({}) values unordered for {}'.format(order, task))
seen = set()
indicesCorrect = True
size0 = x.size(0)
size = x.size(x.dim() - 1)
x = x.tolist()
mxx = mxx.tolist()
ixx = ixx.tolist()
for k in range(size0):
seen.clear()
for j in range(size):
self.assertEqual(x[k][ixx[k][j]], mxx[k][j],
msg='torch.sort ({}) indices wrong for {}'.format(order, task))
seen.add(ixx[k][j])
self.assertEqual(len(seen), size)
def test_sort(self, device):
for SIZE in (4, 2049):
x = torch.rand(4, SIZE, device=device)
res1val, res1ind = torch.sort(x)
y = x.clone()
y_inds = torch.tensor((), dtype=torch.int64, device=device)
torch.sort(y, out=(y, y_inds))
x_vals, x_inds = torch.sort(x)
self.assertEqual(x_vals, y)
self.assertEqual(x_inds, y_inds)
res2val = torch.tensor((), device=device)
res2ind = torch.tensor((), device=device, dtype=torch.long)
torch.sort(x, out=(res2val, res2ind))
self.assertEqual(res1val, res2val, atol=0, rtol=0)
self.assertEqual(res1ind, res2ind, atol=0, rtol=0)
self.assertEqual(torch.argsort(x), res1ind)
self.assertEqual(x.argsort(), res1ind)
self.assertIsOrdered('ascending', x, res2val, res2ind, 'random')
self.assertEqual(
torch.sort(torch.tensor((50, 40, 30, 20, 10), device=device))[0],
torch.tensor((10, 20, 30, 40, 50), device=device),
atol=0, rtol=0
)
x = torch.floor(torch.rand(4, SIZE, device=device) * 10)
torch.sort(x, out=(res2val, res2ind))
self.assertIsOrdered('ascending', x, res2val, res2ind, 'random with duplicate keys')
x = torch.rand(4, SIZE, device=device)
res1val, res1ind = torch.sort(x, x.dim() - 1, True)
res2val = torch.tensor((), device=device)
res2ind = torch.tensor((), device=device, dtype=torch.long)
torch.sort(x, x.dim() - 1, True, out=(res2val, res2ind))
self.assertEqual(res1val, res2val, atol=0, rtol=0)
self.assertEqual(res1ind, res2ind, atol=0, rtol=0)
self.assertEqual(torch.argsort(x, x.dim() - 1, True), res1ind)
self.assertEqual(x.argsort(x.dim() - 1, True), res1ind)
self.assertIsOrdered('descending', x, res2val, res2ind, 'random')
self.assertEqual(
torch.sort(torch.tensor((10, 20, 30, 40, 50), device=device), 0, True)[0],
torch.tensor((50, 40, 30, 20, 10), device=device),
atol=0, rtol=0
)
self.assertIsOrdered('descending', x, res2val, res2ind, 'random with duplicate keys')
x = torch.rand(4, SIZE, device=device)
x[1][2] = float('NaN')
x[3][0] = float('NaN')
torch.sort(x, out=(res2val, res2ind))
self.assertIsOrdered('ascending', x, res2val, res2ind,
'random with NaNs')
torch.sort(x, out=(res2val, res2ind), descending=True)
self.assertIsOrdered('descending', x, res2val, res2ind,
'random with NaNs')
@dtypes(*set(torch.testing.get_all_dtypes()) - {torch.bool, torch.complex64, torch.complex128})
def test_stable_sort(self, device, dtype):
if TEST_WITH_ROCM and dtype == torch.bfloat16:
return
sizes = (100, 1000, 10000)
for ncopies in sizes:
x = torch.tensor([0, 1] * ncopies, dtype=dtype, device=device)
_, idx = x.sort(stable=True)
self.assertEqual(
idx[:ncopies],
torch.arange(start=0, end=2 * ncopies, step=2, device=device)
)
self.assertEqual(
idx[ncopies:],
torch.arange(start=1, end=2 * ncopies, step=2, device=device)
)
@onlyCUDA
@dtypes(torch.uint8)
@largeTensorTest('200GB')
def test_sort_large(self, device, dtype):
t0 = torch.randperm(8192, device=device).to(dtype)
t = t0.view(1, 8192).expand(2 ** 18 + 1, -1).contiguous()
v, i = t.sort()
del t
iv, im = i.var_mean(dim=0)
del i
vv, vm = v.var_mean(dim=0)
del v
self.assertEqual(vv, torch.zeros_like(vv))
self.assertEqual(iv, torch.zeros_like(iv))
self.assertEqual(vm, torch.arange(255, dtype=dtype, device=device))
self.assertEqual(im, t0.sort().indices)
def _test_sort_discontiguous(self, device, dtype):
sizes = (5, 7, 2049)
for shape in permutations(sizes):
for perm in permutations((0, 1, 2)):
for dim in range(3):
t = torch.randn(shape, device=device, dtype=dtype).permute(perm)
r1 = t.sort(dim=dim)
r2 = t.contiguous().sort(dim=dim)
self.assertEqual(r1, r2)
n = t.size(dim)
self.assertTrue((r1.values.narrow(dim, 1, n - 1) >= r1.values.narrow(dim, 0, n - 1)).all())
self.assertTrue((t.unsqueeze(-1).transpose(dim, -1) == r1.values.unsqueeze(-1)).any(dim=dim).any(dim=-1).all())
if self.device_type == 'cuda':
self.assertEqual(r1.values.stride(), t.stride())
self.assertEqual(r1.indices.stride(), t.stride())
@onlyCUDA
@dtypes(torch.float32)
def test_sort_discontiguous(self, device, dtype):
self._test_sort_discontiguous(device, dtype)
@slowTest
@onlyCPU
@dtypes(torch.float32)
def test_sort_discontiguous_slow(self, device, dtype):
self._test_sort_discontiguous(device, dtype)
@dtypes(*set(torch.testing.get_all_dtypes()) - {torch.bool, torch.complex64, torch.complex128})
def test_stable_sort_against_numpy(self, device, dtype):
if TEST_WITH_ROCM and dtype == torch.bfloat16:
return
if dtype in torch.testing.floating_types_and(torch.float16, torch.bfloat16):
inf = float('inf')
neg_inf = -float('inf')
nan = float('nan')
else:
if dtype != torch.bool:
inf = torch.iinfo(dtype).max
neg_inf = torch.iinfo(dtype).min
else:
inf = True
neg_inf = ~inf
nan = inf
def generate_samples():
from itertools import chain, combinations
for sizes in [(1025,), (10000,)]:
size = sizes[0]
yield (torch.tensor([0, 1] * size, dtype=dtype, device=device), 0)
if self.device_type == 'cuda':
return
yield (torch.tensor([0, 1] * 100, dtype=dtype, device=device), 0)
def repeated_index_fill(t, dim, idxs, vals):
res = t
for idx, val in zip(idxs, vals):
res = res.index_fill(dim, idx, val)
return res
for sizes in [(1, 10), (10, 1), (10, 10), (10, 10, 10)]:
size = min(*sizes)
x = (torch.randn(*sizes, device=device) * size).to(dtype)
yield (x, 0)
n_fill_vals = 3
for dim in range(len(sizes)):
idxs = (torch.randint(high=size, size=(size // 10,)) for i in range(n_fill_vals))
vals = (inf, neg_inf, nan)
subsets = chain.from_iterable(combinations(list(zip(idxs, vals)), r)
for r in range(1, n_fill_vals + 1))
for subset in subsets:
idxs_subset, vals_subset = zip(*subset)
yield (repeated_index_fill(x, dim, idxs_subset, vals_subset), dim)
for sample, dim in generate_samples():
_, idx_torch = sample.sort(dim=dim, stable=True)
if dtype is torch.bfloat16:
sample_numpy = sample.float().cpu().numpy()
else:
sample_numpy = sample.cpu().numpy()
idx_numpy = np.argsort(sample_numpy, axis=dim, kind='stable')
self.assertEqual(idx_torch, idx_numpy)
@dtypes(*(torch.testing.get_all_int_dtypes() + torch.testing.get_all_fp_dtypes()))
def test_msort(self, device, dtype):
if TEST_WITH_ROCM and dtype == torch.bfloat16:
return
def test(shape):
tensor = make_tensor(shape, device, dtype, low=-9, high=9)
if tensor.size() != torch.Size([]):
if dtype is torch.bfloat16:
expected = torch.from_numpy(np.msort(tensor.float().cpu().numpy())).bfloat16()
else:
expected = torch.from_numpy(np.msort(tensor.cpu().numpy()))
else:
expected = tensor
result = torch.msort(tensor)
self.assertEqual(result, expected)
out = torch.empty_like(result)
torch.msort(tensor, out=out)
self.assertEqual(out, expected)
shapes = (
[],
[0, ],
[20, ],
[1, 20],
[30, 30],
[10, 20, 30]
)
for shape in shapes:
test(shape)
def test_topk(self, device):
def topKViaSort(t, k, dim, dir):
sorted, indices = t.sort(dim, dir)
return sorted.narrow(dim, 0, k), indices.narrow(dim, 0, k)
def compareTensors(t, res1, ind1, res2, ind2, dim):
self.assertEqual(res1, res2, atol=0, rtol=0)
if not ind1.eq(ind2).all():
vals = t.gather(dim, ind2)
self.assertEqual(res1, vals, atol=0, rtol=0)
def compare(t, k, dim, dir):
topKVal, topKInd = t.topk(k, dim, dir, True)
sortKVal, sortKInd = topKViaSort(t, k, dim, dir)
compareTensors(t, sortKVal, sortKInd, topKVal, topKInd, dim)
t = torch.rand(random.randint(1, SIZE),
random.randint(1, SIZE),
random.randint(1, SIZE), device=device)
for _kTries in range(3):
for _dimTries in range(3):
for transpose in (True, False):
for dir in (True, False):
testTensor = t
if transpose:
dim1 = random.randrange(t.ndimension())
dim2 = dim1
while dim1 == dim2:
dim2 = random.randrange(t.ndimension())
testTensor = t.transpose(dim1, dim2)
dim = random.randrange(testTensor.ndimension())
k = random.randint(1, testTensor.size(dim))
compare(testTensor, k, dim, dir)
def test_topk_arguments(self, device):
q = torch.randn(10, 2, 10, device=device)
self.assertRaises(TypeError, lambda: q.topk(4, True))
@skipCUDAIfRocm
def test_unique_dim(self, device):
self.assertFalse(hasattr(torch, 'unique_dim'))
def run_test(device, dtype):
x = torch.tensor([[[1., 1.],
[0., 1.],
[2., 1.],
[0., 1.]],
[[1., 1.],
[0., 1.],
[2., 1.],
[0., 1.]]],
dtype=dtype,
device=device)
x_empty = torch.empty(5, 0, dtype=dtype, device=device)
x_ill_formed_empty = torch.empty(5, 0, 0, dtype=dtype, device=device)
x_ill_formed_empty_another = torch.empty(5, 0, 5, dtype=dtype, device=device)
expected_unique_dim0 = torch.tensor([[[1., 1.],
[0., 1.],
[2., 1.],
[0., 1.]]],
dtype=dtype,
device=device)
expected_inverse_dim0 = torch.tensor([0, 0])
expected_counts_dim0 = torch.tensor([2])
expected_unique_dim1 = torch.tensor([[[0., 1.],
[1., 1.],
[2., 1.]],
[[0., 1.],
[1., 1.],
[2., 1.]]],
dtype=dtype,
device=device)
expected_unique_dim1_bool = torch.tensor([[[False, True], [True, True]],
[[False, True], [True, True]]],
dtype=torch.bool,
device=device)
expected_inverse_dim1 = torch.tensor([1, 0, 2, 0])
expected_inverse_dim1_bool = torch.tensor([1, 0, 1, 0])
expected_counts_dim1 = torch.tensor([2, 1, 1])
expected_counts_dim1_bool = torch.tensor([2, 2])
expected_unique_dim2 = torch.tensor([[[1., 1.],
[0., 1.],
[2., 1.],
[0., 1.]],
[[1., 1.],
[0., 1.],
[2., 1.],
[0., 1.]]],
dtype=dtype,
device=device)
expected_inverse_dim2 = torch.tensor([0, 1])
expected_counts_dim2 = torch.tensor([1, 1])
expected_unique_empty = torch.tensor([], dtype=dtype, device=device)
expected_inverse_empty = torch.tensor([], dtype=torch.long, device=device)
expected_counts_empty = torch.tensor([], dtype=torch.long, device=device)
# dim0
x_unique = torch.unique(x, dim=0)
self.assertEqual(expected_unique_dim0, x_unique)
x_unique, x_inverse = torch.unique(
x,
return_inverse=True,
dim=0)
self.assertEqual(expected_unique_dim0, x_unique)
self.assertEqual(expected_inverse_dim0, x_inverse)
x_unique, x_counts = torch.unique(
x,
return_inverse=False,
return_counts=True,
dim=0)
self.assertEqual(expected_unique_dim0, x_unique)
self.assertEqual(expected_counts_dim0, x_counts)
x_unique, x_inverse, x_counts = torch.unique(
x,
return_inverse=True,
return_counts=True,
dim=0)
self.assertEqual(expected_unique_dim0, x_unique)
self.assertEqual(expected_inverse_dim0, x_inverse)
self.assertEqual(expected_counts_dim0, x_counts)
# dim1
x_unique = torch.unique(x, dim=1)
if x.dtype == torch.bool:
self.assertEqual(expected_unique_dim1_bool, x_unique)
else:
self.assertEqual(expected_unique_dim1, x_unique)
x_unique, x_inverse = torch.unique(
x,
return_inverse=True,
dim=1)
if x.dtype == torch.bool:
self.assertEqual(expected_unique_dim1_bool, x_unique)
self.assertEqual(expected_inverse_dim1_bool, x_inverse)
else:
self.assertEqual(expected_unique_dim1, x_unique)
self.assertEqual(expected_inverse_dim1, x_inverse)
x_unique, x_counts = torch.unique(
x,
return_inverse=False,
return_counts=True,
dim=1)
if x.dtype == torch.bool:
self.assertEqual(expected_unique_dim1_bool, x_unique)
self.assertEqual(expected_counts_dim1_bool, x_counts)
else:
self.assertEqual(expected_unique_dim1, x_unique)
self.assertEqual(expected_counts_dim1, x_counts)
x_unique, x_inverse, x_counts = torch.unique(
x,
return_inverse=True,
return_counts=True,
dim=1)
if x.dtype == torch.bool:
self.assertEqual(expected_unique_dim1_bool, x_unique)
self.assertEqual(expected_inverse_dim1_bool, x_inverse)
self.assertEqual(expected_counts_dim1_bool, x_counts)
else:
self.assertEqual(expected_unique_dim1, x_unique)
self.assertEqual(expected_inverse_dim1, x_inverse)
self.assertEqual(expected_counts_dim1, x_counts)
# dim2
x_unique = torch.unique(x, dim=2)
self.assertEqual(expected_unique_dim2, x_unique)
x_unique, x_inverse = torch.unique(
x,
return_inverse=True,
dim=2)
self.assertEqual(expected_unique_dim2, x_unique)
self.assertEqual(expected_inverse_dim2, x_inverse)
x_unique, x_counts = torch.unique(
x,
return_inverse=False,
return_counts=True,
dim=2)
self.assertEqual(expected_unique_dim2, x_unique)
self.assertEqual(expected_counts_dim2, x_counts)
x_unique, x_inverse, x_counts = torch.unique(
x,
return_inverse=True,
return_counts=True,
dim=2)
self.assertEqual(expected_unique_dim2, x_unique)
self.assertEqual(expected_inverse_dim2, x_inverse)
self.assertEqual(expected_counts_dim2, x_counts)
# test empty tensor
x_unique, x_inverse, x_counts = torch.unique(
x_empty,
return_inverse=True,
return_counts=True,
dim=1)
self.assertEqual(expected_unique_empty, x_unique)
self.assertEqual(expected_inverse_empty, x_inverse)
self.assertEqual(expected_counts_empty, x_counts)
# test not a well formed tensor
# Checking for runtime error, as this is the expected behaviour
with self.assertRaises(RuntimeError):
torch.unique(
x_ill_formed_empty,
return_inverse=True,
return_counts=True,
dim=1)
# test along dim2
with self.assertRaises(RuntimeError):
torch.unique(
x_ill_formed_empty_another,
return_inverse=True,
return_counts=True,
dim=2)
# test consecutive version
y = torch.tensor(
[[0, 1],
[0, 1],
[0, 1],
[1, 2],
[1, 2],
[3, 4],
[0, 1],
[0, 1],
[3, 4],
[1, 2]],
dtype=dtype,
device=device
)
expected_y_unique = torch.tensor(
[[0, 1],
[1, 2],
[3, 4],
[0, 1],
[3, 4],
[1, 2]],
dtype=dtype,
device=device
)
expected_y_inverse = torch.tensor([0, 0, 0, 1, 1, 2, 3, 3, 4, 5], dtype=torch.int64, device=device)
expected_y_counts = torch.tensor([3, 2, 1, 2, 1, 1], dtype=torch.int64, device=device)
expected_y_inverse_bool = torch.tensor([0, 0, 0, 1, 1, 1, 2, 2, 3, 3], dtype=torch.int64, device=device)
expected_y_counts_bool = torch.tensor([3, 3, 2, 2], dtype=torch.int64, device=device)
y_unique, y_inverse, y_counts = torch.unique_consecutive(y, return_inverse=True, return_counts=True, dim=0)
if x.dtype == torch.bool:
self.assertEqual(expected_y_inverse_bool, y_inverse)
self.assertEqual(expected_y_counts_bool, y_counts)
else:
self.assertEqual(expected_y_inverse, y_inverse)
self.assertEqual(expected_y_counts, y_counts)
run_test(device, torch.float)
run_test(device, torch.double)
run_test(device, torch.long)
run_test(device, torch.uint8)
run_test(device, torch.bool)
@onlyCUDA
def test_topk_noncontiguous_gpu(self, device):
t = torch.randn(20, device=device)[::2]
top1, idx1 = t.topk(5)
top2, idx2 = t.contiguous().topk(5)
self.assertEqual(top1, top2)
self.assertEqual(idx1, idx2)
def _test_topk_dtype(self, device, dtype, integral, size):
if integral:
a = torch.randint(torch.iinfo(dtype).min, torch.iinfo(dtype).max,
size=(size,), dtype=dtype, device=device)
else:
a = torch.randn(size=(size,), dtype=dtype, device=device)
sort_topk = a.sort()[0][-(size // 2):].flip(0)
topk = a.topk(size // 2)
self.assertEqual(sort_topk, topk[0]) # check values
self.assertEqual(sort_topk, a[topk[1]]) # check indices
@dtypes(torch.int8, torch.uint8, torch.int16, torch.int32, torch.int64)
def test_topk_integral(self, device, dtype):
small = 10
large = 4096
for curr_size in (small, large):
self._test_topk_dtype(device, dtype, True, curr_size)
@onlyCUDA
@dtypes(torch.bfloat16)
@skipCUDAIfRocm
def test_topk_bfloat16(self, device, dtype):
small = 10
large = 8192
for curr_size in (small, large):
self._test_topk_dtype(device, dtype, False, curr_size)
@dtypesIfCUDA(*torch.testing.get_all_fp_dtypes())
@dtypes(torch.float, torch.double, torch.bfloat16)
def test_topk_nonfinite(self, device, dtype):
if TEST_WITH_ROCM and dtype == torch.bfloat16:
return
x = torch.tensor([float('nan'), float('inf'), 1e4, 0, -1e4, -float('inf')], device=device, dtype=dtype)
val, idx = x.topk(4)
expect = torch.tensor([float('nan'), float('inf'), 1e4, 0], device=device, dtype=dtype)
self.assertEqual(val, expect)
self.assertEqual(idx, [0, 1, 2, 3])
val, idx = x.topk(4, largest=False)
expect = torch.tensor([-float('inf'), -1e4, 0, 1e4], device=device, dtype=dtype)
self.assertEqual(val, expect)
self.assertEqual(idx, [5, 4, 3, 2])
def test_topk_4d(self, device):
x = torch.ones(2, 3072, 2, 2, device=device)
x[:, 1, :, :] *= 2.
x[:, 10, :, :] *= 1.5
val, ind = torch.topk(x, k=2, dim=1)
expected_ind = torch.ones(2, 2, 2, 2, dtype=torch.long, device=device)
expected_ind[:, 1, :, :] = 10
expected_val = torch.ones(2, 2, 2, 2, device=device)
expected_val[:, 0, :, :] *= 2.
expected_val[:, 1, :, :] *= 1.5
self.assertEqual(val, expected_val, atol=0, rtol=0)
self.assertEqual(ind, expected_ind, atol=0, rtol=0)
@onlyOnCPUAndCUDA
@dtypesIfCUDA(*(torch.testing.get_all_dtypes(include_complex=False,
include_bool=False,
include_half=False,
include_bfloat16=True)))
@dtypes(*(torch.testing.get_all_dtypes(include_complex=False, include_bool=False, include_half=False, include_bfloat16=False)))
def test_topk_zero(self, device, dtype):
if TEST_WITH_ROCM and dtype == torch.bfloat16:
return
# https://github.com/pytorch/pytorch/issues/49205
t = torch.rand(2, 2, device=device).to(dtype=dtype)
val, idx = torch.topk(t, k=0, largest=False)
self.assertEqual(val.size(), torch.Size([2, 0]))
self.assertEqual(idx.size(), torch.Size([2, 0]))
def _test_unique_scalar_empty(self, dtype, device, f):
# test scalar
x = torch.tensor(0, dtype=dtype, device=device)
unique, inverse, counts = f(x, return_inverse=True, return_counts=True)
expected_unique = torch.tensor([0], dtype=dtype, device=device)
expected_inverse = torch.tensor(0, device=device)
expected_counts = torch.tensor([1], device=device)
self.assertEqual(unique, expected_unique)
self.assertEqual(inverse, expected_inverse)
self.assertEqual(counts, expected_counts)
# test zero sized tensor
x = torch.zeros((0, 0, 3), dtype=dtype, device=device)
unique, inverse, counts = f(x, return_inverse=True, return_counts=True)
expected_unique = torch.tensor([], dtype=dtype, device=device)
expected_inverse = torch.empty((0, 0, 3), dtype=torch.long, device=device)
expected_counts = torch.tensor([], dtype=torch.long, device=device)
self.assertEqual(unique, expected_unique)
self.assertEqual(inverse, expected_inverse)
self.assertEqual(counts, expected_counts)
def _test_unique_with_expects(self, device, dtype, f, x, expected_unique, expected_inverse, expected_counts, additional_shape):
def ensure_tuple(x):
if isinstance(x, torch.Tensor):
return (x,)
return x
for return_inverse in [True, False]:
for return_counts in [True, False]:
# test with expected
ret = ensure_tuple(f(x, return_inverse=return_inverse, return_counts=return_counts))
self.assertEqual(len(ret), 1 + int(return_inverse) + int(return_counts))
self.assertEqual(expected_unique, ret[0])
if return_inverse:
self.assertEqual(expected_inverse, ret[1])
if return_counts:
count_index = 1 + int(return_inverse)
self.assertEqual(expected_counts, ret[count_index])
# tests per-element unique on a higher rank tensor.
y = x.view(additional_shape)
y_unique, y_inverse, y_counts = f(y, return_inverse=True, return_counts=True)
self.assertEqual(expected_unique, y_unique)
self.assertEqual(expected_inverse.view(additional_shape), y_inverse)
self.assertEqual(expected_counts, y_counts)
@dtypesIfCPU(*set(torch.testing.get_all_dtypes()) - {torch.complex64, torch.complex128})
@dtypes(*set(torch.testing.get_all_dtypes()) - {torch.bfloat16, torch.complex64, torch.complex128})
def test_unique(self, device, dtype):
if dtype is torch.half and self.device_type == 'cpu':
return # CPU does not have half support
def ensure_tuple(x):
if isinstance(x, torch.Tensor):
return (x,)
return x
if dtype is torch.bool:
x = torch.tensor([True, False, False, False, True, False, True, False], dtype=torch.bool, device=device)
expected_unique = torch.tensor([False, True], dtype=torch.bool, device=device)
expected_inverse = torch.tensor([1, 0, 0, 0, 1, 0, 1, 0], dtype=torch.long, device=device)
expected_counts = torch.tensor([5, 3], dtype=torch.long, device=device)
else:
x = torch.tensor([1, 2, 3, 2, 8, 5, 2, 3], dtype=dtype, device=device)
expected_unique = torch.tensor([1, 2, 3, 5, 8], dtype=dtype, device=device)
expected_inverse = torch.tensor([0, 1, 2, 1, 4, 3, 1, 2], device=device)
expected_counts = torch.tensor([1, 3, 2, 1, 1], device=device)
# test sorted unique
fs = (
lambda x, **kwargs: torch.unique(x, sorted=True, **kwargs),
lambda x, **kwargs: x.unique(sorted=True, **kwargs),
)
x_sliced = torch.empty(x.size(0) * 2, dtype=dtype, device=device)[::2].copy_(x)
xs = (x, x_sliced)
for f, x in product(fs, xs):
self._test_unique_with_expects(device, dtype, f, x, expected_unique, expected_inverse, expected_counts, (2, 2, 2))
self._test_unique_scalar_empty(dtype, device, f)
# test unsorted unique
fs = (
lambda x, **kwargs: torch.unique(x, sorted=False, **kwargs),
lambda x, **kwargs: x.unique(sorted=False, **kwargs)
)
for f, x in product(fs, xs):
self._test_unique_scalar_empty(dtype, device, f)
for return_inverse, return_counts in product((True, False), repeat=2):
ret = ensure_tuple(f(x, return_inverse=return_inverse, return_counts=return_counts))
self.assertEqual(len(ret), 1 + int(return_inverse) + int(return_counts))
x_list = x.tolist()
x_unique_list = ret[0].tolist()
self.assertEqual(expected_unique.tolist(), sorted(x_unique_list))
if return_inverse:
x_inverse_list = ret[1].tolist()
for i, j in enumerate(x_inverse_list):
self.assertEqual(x_list[i], x_unique_list[j])
if return_counts:
count_index = 1 + int(return_inverse)
x_counts_list = ret[count_index].tolist()
for i, j in zip(x_unique_list, x_counts_list):
count = 0
for k in x_list:
if k == i:
count += 1
self.assertEqual(j, count)
@dtypesIfCPU(*set(torch.testing.get_all_dtypes()) - {torch.complex64, torch.complex128})
@dtypes(*set(torch.testing.get_all_dtypes()) - {torch.bfloat16, torch.complex64, torch.complex128})
def test_unique_consecutive(self, device, dtype):
if dtype is torch.half and self.device_type == 'cpu':
return # CPU does not have half support
if dtype is torch.bool:
x = torch.tensor([True, False, False, False, True, True, False, False, False], dtype=torch.bool, device=device)
expected_unique = torch.tensor([True, False, True, False], dtype=torch.bool, device=device)
expected_inverse = torch.tensor([0, 1, 1, 1, 2, 2, 3, 3, 3], dtype=torch.long, device=device)
expected_counts = torch.tensor([1, 3, 2, 3], dtype=torch.long, device=device)
else:
x = torch.tensor([1, 2, 2, 2, 5, 5, 2, 2, 3], dtype=dtype, device=device)
expected_unique = torch.tensor([1, 2, 5, 2, 3], dtype=dtype, device=device)
expected_inverse = torch.tensor([0, 1, 1, 1, 2, 2, 3, 3, 4], device=device)
expected_counts = torch.tensor([1, 3, 2, 2, 1], device=device)
for f in [torch.unique_consecutive, lambda x, **kwargs: x.unique_consecutive(**kwargs)]:
self._test_unique_with_expects(device, dtype, f, x, expected_unique, expected_inverse, expected_counts, (3, 3))
self._test_unique_scalar_empty(dtype, device, f)
@dtypes(torch.double)
def test_kthvalue(self, device, dtype):
SIZE = 50
x = torch.rand(SIZE, SIZE, SIZE, dtype=dtype, device=device)
x0 = x.clone()
k = random.randint(1, SIZE)
res1val, res1ind = torch.kthvalue(x, k, keepdim=False)
res2val, res2ind = torch.sort(x)
self.assertEqual(res1val[:, :], res2val[:, :, k - 1], atol=0, rtol=0)
self.assertEqual(res1ind[:, :], res2ind[:, :, k - 1], atol=0, rtol=0)
# test use of result tensors
k = random.randint(1, SIZE)
res1val = torch.tensor([], dtype=dtype, device=device)
res1ind = torch.tensor([], dtype=torch.long, device=device)
torch.kthvalue(x, k, keepdim=False, out=(res1val, res1ind))
res2val, res2ind = torch.sort(x)
self.assertEqual(res1val[:, :], res2val[:, :, k - 1], atol=0, rtol=0)
self.assertEqual(res1ind[:, :], res2ind[:, :, k - 1], atol=0, rtol=0)
# test non-default dim
k = random.randint(1, SIZE)
res1val, res1ind = torch.kthvalue(x, k, 0, keepdim=False)
res2val, res2ind = torch.sort(x, 0)
self.assertEqual(res1val, res2val[k - 1], atol=0, rtol=0)
self.assertEqual(res1ind, res2ind[k - 1], atol=0, rtol=0)
# non-contiguous
y = x.narrow(1, 0, 1)
y0 = y.contiguous()
k = random.randint(1, SIZE)
res1val, res1ind = torch.kthvalue(y, k)
res2val, res2ind = torch.kthvalue(y0, k)
self.assertEqual(res1val, res2val, atol=0, rtol=0)
self.assertEqual(res1ind, res2ind, atol=0, rtol=0)
# non-contiguous [Reference: https://github.com/pytorch/pytorch/issues/45721]
non_contig_t = torch.tensor([0, -1, 1, -2, 2], dtype=dtype, device=device)[::2]
expected_val, expected_ind = non_contig_t.contiguous().kthvalue(2)
non_contig_cpu_t = non_contig_t.cpu()
expected_val_cpu, expected_ind_cpu = non_contig_cpu_t.kthvalue(2)
out_val, out_ind = non_contig_t.kthvalue(2)
self.assertEqual(expected_val, out_val, atol=0, rtol=0)
self.assertEqual(expected_ind, out_ind, atol=0, rtol=0)
self.assertEqual(expected_val_cpu, out_val, atol=0, rtol=0)
self.assertEqual(expected_ind_cpu, out_ind, atol=0, rtol=0)
# check that the input wasn't modified
self.assertEqual(x, x0, atol=0, rtol=0)
y = torch.tensor((3., 5, 4, 1, 1, 5), dtype=dtype, device=device)
self.assertEqual(torch.kthvalue(y, 3)[0], 3, atol=0, rtol=0)
self.assertEqual(torch.kthvalue(y, 2)[0], 1, atol=0, rtol=0)
SIZE = 50
x = torch.rand(SIZE, SIZE, SIZE, dtype=dtype, device=device)
x[torch.arange(SIZE), :, torch.randint(50, (50,))] = nan
ks = [random.randint(1, SIZE), 1, SIZE, SIZE - 1]
res2val, res2ind = torch.sort(x)
for k in ks:
res1val, res1ind = torch.kthvalue(x, k, keepdim=False)
self.assertEqual(res1val[:, :], res2val[:, :, k - 1], atol=0, rtol=0)
self.assertEqual(res1ind[:, :], res2ind[:, :, k - 1], atol=0, rtol=0)
@dtypes(torch.double)
@onlyOnCPUAndCUDA
def test_kthvalue_overlap(self, device, dtype):
S = 10
k = 5
a = torch.randn(S, device=device)
indices = torch.empty((), device=device, dtype=torch.long)
with self.assertRaisesRegex(RuntimeError, "unsupported operation:"):
torch.kthvalue(a, k, out=(a, indices))
@dtypes(torch.float)
@onlyOnCPUAndCUDA
def test_kthvalue_scalar(self, device, dtype):
res = torch.tensor(2, device=device, dtype=dtype).kthvalue(1)
ref = torch.tensor([2], device=device, dtype=dtype).kthvalue(1)
self.assertEqual(res[0], ref[0].squeeze())
self.assertEqual(res[1], ref[1].squeeze())
@dtypes(*all_types())
@dtypesIfCUDA(*all_types_and(torch.half))
def test_isin(self, device, dtype):
def assert_isin_equal(a, b):
x = torch.isin(a, b)
a = a.cpu().numpy() if torch.is_tensor(a) else np.array(a)
b = b.cpu().numpy() if torch.is_tensor(b) else np.array(b)
y = np.isin(a, b)
self.assertEqual(x, y)
a = torch.arange(24, device=device, dtype=dtype).reshape([2, 3, 4])
b = torch.tensor([[10, 20, 30], [0, 1, 3], [11, 22, 33]], device=device, dtype=dtype)
assert_isin_equal(a, b)
zero_d = torch.tensor(3, device=device, dtype=dtype)
assert_isin_equal(zero_d, b)
assert_isin_equal(a, zero_d)
assert_isin_equal(zero_d, zero_d)
empty = torch.tensor([], device=device, dtype=dtype)
assert_isin_equal(empty, b)
assert_isin_equal(a, empty)
assert_isin_equal(empty, empty)
assert_isin_equal(a, 6)
assert_isin_equal(5, b)
def define_expected(lst, invert=False):
expected = torch.tensor(lst, device=device)
if invert:
expected = expected.logical_not()
return expected
for mult in [1, 10]:
for invert in [False, True]:
a = torch.tensor([5, 7, 1, 2], device=device, dtype=dtype)
b = torch.tensor([2, 4, 3, 1, 5] * mult, device=device, dtype=dtype)
ec = define_expected([True, False, True, True], invert=invert)
c = torch.isin(a, b, assume_unique=True, invert=invert)
self.assertEqual(c, ec)
a[0] = 8
ec = define_expected([False, False, True, True], invert=invert)
c = torch.isin(a, b, assume_unique=True, invert=invert)
self.assertEqual(c, ec)
a[0], a[3] = 4, 8
ec = define_expected([True, False, True, False], invert=invert)
c = torch.isin(a, b, assume_unique=True, invert=invert)
self.assertEqual(c, ec)
a = torch.tensor([5, 4, 5, 3, 4, 4, 3, 4, 3, 5, 2, 1, 5, 5], device=device, dtype=dtype)
b = torch.tensor([2, 3, 4] * mult, device=device, dtype=dtype)
ec = define_expected([False, True, False, True, True, True, True, True, True,
False, True, False, False, False], invert=invert)
c = torch.isin(a, b, invert=invert)
self.assertEqual(c, ec)
b = torch.tensor([2, 3, 4] * mult + [5, 5, 4] * mult, device=device, dtype=dtype)
ec = define_expected([True, True, True, True, True, True, True, True, True, True,
True, False, True, True], invert=invert)
c = torch.isin(a, b, invert=invert)
self.assertEqual(c, ec)
a = torch.tensor([5, 7, 1, 2], device=device, dtype=dtype)
b = torch.tensor([2, 4, 3, 1, 5] * mult, device=device, dtype=dtype)
ec = define_expected([True, False, True, True], invert=invert)
c = torch.isin(a, b, invert=invert)
self.assertEqual(c, ec)
a = torch.tensor([5, 7, 1, 1, 2], device=device, dtype=dtype)
b = torch.tensor([2, 4, 3, 3, 1, 5] * mult, device=device, dtype=dtype)
ec = define_expected([True, False, True, True, True], invert=invert)
c = torch.isin(a, b, invert=invert)
self.assertEqual(c, ec)
a = torch.tensor([5, 5], device=device, dtype=dtype)
b = torch.tensor([2, 2] * mult, device=device, dtype=dtype)
ec = define_expected([False, False], invert=invert)
c = torch.isin(a, b, invert=invert)
self.assertEqual(c, ec)
# multi-dimensional input case using sort-based algo
for assume_unique in [False, True]:
a = torch.arange(6, device=device, dtype=dtype).reshape([2, 3])
b = torch.arange(3, 30, device=device, dtype=dtype)
ec = define_expected([[False, False, False], [True, True, True]], invert=invert)
c = torch.isin(a, b, invert=invert, assume_unique=assume_unique)
self.assertEqual(c, ec)
def test_isin_different_dtypes(self, device):
supported_types = all_types() if device == 'cpu' else all_types_and(torch.half)
for mult in [1, 10]:
for assume_unique in [False, True]:
for dtype1, dtype2 in product(supported_types, supported_types):
a = torch.tensor([1, 2, 3], device=device, dtype=dtype1)
b = torch.tensor([3, 4, 5] * mult, device=device, dtype=dtype2)
ec = torch.tensor([False, False, True], device=device)
c = torch.isin(a, b, assume_unique=assume_unique)
self.assertEqual(c, ec)
@onlyCUDA
@dtypes(*all_types())
def test_isin_different_devices(self, device, dtype):
a = torch.arange(6, device=device, dtype=dtype).reshape([2, 3])
b = torch.arange(3, 30, device='cpu', dtype=dtype)
with self.assertRaises(RuntimeError):
torch.isin(a, b)
c = torch.arange(6, device='cpu', dtype=dtype).reshape([2, 3])
d = torch.arange(3, 30, device=device, dtype=dtype)
with self.assertRaises(RuntimeError):
torch.isin(c, d)
instantiate_device_type_tests(TestSortAndSelect, globals())
if __name__ == '__main__':
run_tests()
| true | true |
f716a4e754c3e3f35917e5279cd691b574a49a9b | 798 | py | Python | tests/test_api_v1_services_sshd_stop.py | pincher95/pfsense-api | 001a4b8a1ec39138668d6d92b3c9d0c89a7f1b45 | [
"Apache-2.0"
] | null | null | null | tests/test_api_v1_services_sshd_stop.py | pincher95/pfsense-api | 001a4b8a1ec39138668d6d92b3c9d0c89a7f1b45 | [
"Apache-2.0"
] | null | null | null | tests/test_api_v1_services_sshd_stop.py | pincher95/pfsense-api | 001a4b8a1ec39138668d6d92b3c9d0c89a7f1b45 | [
"Apache-2.0"
] | null | null | null | # Copyright 2022 Jared Hendrickson
#
# 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 e2e_test_framework
class APIE2ETestServicesSSHdStop(e2e_test_framework.APIE2ETest):
uri = "/api/v1/services/sshd/stop"
post_tests = [{"name": "Stop the SSHd service"}]
APIE2ETestServicesSSHdStop()
| 33.25 | 74 | 0.764411 |
import e2e_test_framework
class APIE2ETestServicesSSHdStop(e2e_test_framework.APIE2ETest):
uri = "/api/v1/services/sshd/stop"
post_tests = [{"name": "Stop the SSHd service"}]
APIE2ETestServicesSSHdStop()
| true | true |
f716a628b677fa7e5aaed86bc610566d88632de5 | 1,598 | py | Python | mySpider/spiders/wangyi.py | songw831/mySpider | 04312701e891e14ba7e470c3f2c0aa9997074096 | [
"MIT"
] | null | null | null | mySpider/spiders/wangyi.py | songw831/mySpider | 04312701e891e14ba7e470c3f2c0aa9997074096 | [
"MIT"
] | null | null | null | mySpider/spiders/wangyi.py | songw831/mySpider | 04312701e891e14ba7e470c3f2c0aa9997074096 | [
"MIT"
] | null | null | null | import scrapy
from selenium import webdriver
from mySpider.items import MyspiderItem
class FundSpider(scrapy.Spider):
name = 'wangyi'
#allowed_domains = ['www.xxx.com']
start_urls = ['http://news.163.com/']
modules_url = [] #存放五个版块的url
def __init__(self):
self.bro = webdriver.Chrome(executable_path='D:\PyCharm\mySpider\chromedriver.exe')
def parse(self, response):
li_list = response.xpath('//*[@id="index2016_wrap"]/div[1]/div[2]/div[2]/div[2]/div[2]/div/ul')
alist = [3,4,6,7,8]
for index in alist:
module_url = li_list[index].xpath('./a/@href').extract_first()
self.modules_url.append(module_url)
#依次对每一个版块进行请求
for url in self.module_url:
yield scrapy.Request(url, callback= self.parse_module)
def parse_module(self, response):
div_list = response.xpath('/html/body/div/div[3]/div[4]/div[1]/div[1]/div/ul/li/div/div')
for div in div_list:
title = div.xpath('./div/div[1]/h3/a/text()').extract_fisrt()
new_detail_url = div.xpath('./div/div[1]/h3/a/@href').extract_first()
item = MyspiderItem()
item.title = title
yield scrapy.Request(url=new_detail_url, callback=self.parse_detail, meta={'item':item})
def parse_detail(self,response):
content = response.xpath('//*[@id="content"]/div[2]//text()').extract()
content = ''.join(content)
item = response.meta('item')
item['content'] = content
yield item
def closed(self, spider):
self.bro.quit()
| 38.97561 | 103 | 0.61577 | import scrapy
from selenium import webdriver
from mySpider.items import MyspiderItem
class FundSpider(scrapy.Spider):
name = 'wangyi'
start_urls = ['http://news.163.com/']
modules_url = []
def __init__(self):
self.bro = webdriver.Chrome(executable_path='D:\PyCharm\mySpider\chromedriver.exe')
def parse(self, response):
li_list = response.xpath('//*[@id="index2016_wrap"]/div[1]/div[2]/div[2]/div[2]/div[2]/div/ul')
alist = [3,4,6,7,8]
for index in alist:
module_url = li_list[index].xpath('./a/@href').extract_first()
self.modules_url.append(module_url)
for url in self.module_url:
yield scrapy.Request(url, callback= self.parse_module)
def parse_module(self, response):
div_list = response.xpath('/html/body/div/div[3]/div[4]/div[1]/div[1]/div/ul/li/div/div')
for div in div_list:
title = div.xpath('./div/div[1]/h3/a/text()').extract_fisrt()
new_detail_url = div.xpath('./div/div[1]/h3/a/@href').extract_first()
item = MyspiderItem()
item.title = title
yield scrapy.Request(url=new_detail_url, callback=self.parse_detail, meta={'item':item})
def parse_detail(self,response):
content = response.xpath('//*[@id="content"]/div[2]//text()').extract()
content = ''.join(content)
item = response.meta('item')
item['content'] = content
yield item
def closed(self, spider):
self.bro.quit()
| true | true |
f716a6346eb2c4bb4c555f3cc80875549f7a88fc | 1,780 | py | Python | pandas_ta/performance/log_return.py | yssource/pandas-ta | 0f975320684a91db3c04f6ea3dd739177dcb65aa | [
"MIT"
] | 2 | 2021-03-30T01:23:14.000Z | 2021-04-02T18:04:51.000Z | pandas_ta/performance/log_return.py | lukaszbinden/pandas-ta | 98478f8bf049a4c8748d6f3c795f4f335ced05ca | [
"MIT"
] | null | null | null | pandas_ta/performance/log_return.py | lukaszbinden/pandas-ta | 98478f8bf049a4c8748d6f3c795f4f335ced05ca | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
from numpy import log as nplog
from pandas_ta.utils import get_offset, verify_series
def log_return(close, length=None, cumulative=False, offset=None, **kwargs):
"""Indicator: Log Return"""
# Validate Arguments
close = verify_series(close)
length = int(length) if length and length > 0 else 1
offset = get_offset(offset)
# Calculate Result
log_return = nplog(close).diff(periods=length)
if cumulative:
log_return = log_return.cumsum()
# Offset
if offset != 0:
log_return = log_return.shift(offset)
# Handle fills
if "fillna" in kwargs:
log_return.fillna(kwargs["fillna"], inplace=True)
if "fill_method" in kwargs:
log_return.fillna(method=kwargs["fill_method"], inplace=True)
# Name & Category
log_return.name = f"{'CUM' if cumulative else ''}LOGRET_{length}"
log_return.category = "performance"
return log_return
log_return.__doc__ = \
"""Log Return
Calculates the logarithmic return of a Series.
See also: help(df.ta.log_return) for additional **kwargs a valid 'df'.
Sources:
https://stackoverflow.com/questions/31287552/logarithmic-returns-in-pandas-dataframe
Calculation:
Default Inputs:
length=1, cumulative=False
LOGRET = log( close.diff(periods=length) )
CUMLOGRET = LOGRET.cumsum() if cumulative
Args:
close (pd.Series): Series of 'close's
length (int): It's period. Default: 20
cumulative (bool): If True, returns the cumulative returns. Default: False
offset (int): How many periods to offset the result. Default: 0
Kwargs:
fillna (value, optional): pd.DataFrame.fillna(value)
fill_method (value, optional): Type of fill method
Returns:
pd.Series: New feature generated.
"""
| 27.8125 | 88 | 0.690449 |
from numpy import log as nplog
from pandas_ta.utils import get_offset, verify_series
def log_return(close, length=None, cumulative=False, offset=None, **kwargs):
close = verify_series(close)
length = int(length) if length and length > 0 else 1
offset = get_offset(offset)
log_return = nplog(close).diff(periods=length)
if cumulative:
log_return = log_return.cumsum()
if offset != 0:
log_return = log_return.shift(offset)
if "fillna" in kwargs:
log_return.fillna(kwargs["fillna"], inplace=True)
if "fill_method" in kwargs:
log_return.fillna(method=kwargs["fill_method"], inplace=True)
log_return.name = f"{'CUM' if cumulative else ''}LOGRET_{length}"
log_return.category = "performance"
return log_return
log_return.__doc__ = \
"""Log Return
Calculates the logarithmic return of a Series.
See also: help(df.ta.log_return) for additional **kwargs a valid 'df'.
Sources:
https://stackoverflow.com/questions/31287552/logarithmic-returns-in-pandas-dataframe
Calculation:
Default Inputs:
length=1, cumulative=False
LOGRET = log( close.diff(periods=length) )
CUMLOGRET = LOGRET.cumsum() if cumulative
Args:
close (pd.Series): Series of 'close's
length (int): It's period. Default: 20
cumulative (bool): If True, returns the cumulative returns. Default: False
offset (int): How many periods to offset the result. Default: 0
Kwargs:
fillna (value, optional): pd.DataFrame.fillna(value)
fill_method (value, optional): Type of fill method
Returns:
pd.Series: New feature generated.
"""
| true | true |
f716a9d014c49a805a816c403771d17f603d78f9 | 5,119 | py | Python | resolwe_bio/tools/basespace_download.py | JureZmrzlikar/resolwe-bio | 54cde9b293abebad2db0564c9fefa33d6d2fe835 | [
"Apache-2.0"
] | null | null | null | resolwe_bio/tools/basespace_download.py | JureZmrzlikar/resolwe-bio | 54cde9b293abebad2db0564c9fefa33d6d2fe835 | [
"Apache-2.0"
] | null | null | null | resolwe_bio/tools/basespace_download.py | JureZmrzlikar/resolwe-bio | 54cde9b293abebad2db0564c9fefa33d6d2fe835 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python3
"""Tool to download files from BaseSpace."""
import sys
import traceback
import atexit
import argparse
import requests
class BaseSpaceDownloadError(Exception):
"""BaseSpace download error."""
pass
def main():
"""Entry point."""
session = requests.Session()
atexit.register(on_exit, session)
parser = argparse.ArgumentParser(description='Download file from Illumina BaseSpace.')
parser.add_argument('--file-id',
dest='file_ids',
action='append',
required=True,
help="BaseSpace file ID. This argument can be repeated to specify multiple files.")
parser.add_argument('--access-token-secret-path',
dest='access_token_secret_path',
required=True,
help="BaseSpace access token secret path.")
parser.add_argument('--output',
dest='output',
type=str,
choices=['full', 'filename'],
default='full',
help="Sets what is printed to standard output. "
"Argument 'full' outputs everything, "
"argument 'filename' outputs only file names of downloaded files.")
parser.add_argument('--verbose',
dest='verbose',
action='store_true',
default=False,
help="Print detailed exception information when error occurs. "
"Output argument had no effect on this argument.")
args = parser.parse_args()
try:
file_ids = args.file_ids
access_token = get_token_from_secret_file(args.access_token_secret_path)
headers = {'x-access-token': access_token}
for file_id in file_ids:
file_name = get_file_name(session, file_id, headers)
download_file(session, file_id, file_name, headers)
output(args.output, 'filename={}'.format(file_name))
except:
if args.verbose:
traceback.print_exc()
else:
print("An error occurred while processing the Basespace download request. Use --verbose to see details.")
sys.exit(1)
def on_exit(session):
"""Clean up function called on exit."""
session.close()
def output(output_option, value):
"""
Print to standard output.
This function should be used instead of ``print`` function. Printing errors is exempted
and can be printed without using this function.
"""
if output_option == 'full':
print(value)
elif output_option == 'filename':
if value.startswith('filename='):
print(value[len('filename='):])
else:
print("Internal error: output argument {} handling not implemented".format(output_option))
sys.exit(1)
def get_token_from_secret_file(secret_file_path):
"""Read secret file to obtain access token."""
try:
with open(secret_file_path, 'r') as f:
return f.readline()
except FileNotFoundError:
raise BaseSpaceDownloadError('Secret file not found')
except PermissionError:
raise BaseSpaceDownloadError('No permissions to read secret file')
def make_get_request(session, url, headers, stream=False):
"""Make a get request."""
response = session.get(url, headers=headers, stream=stream)
if response.status_code == 401:
raise BaseSpaceDownloadError('Authentication failed on URL {}'.format(url))
elif response.status_code == 404:
raise BaseSpaceDownloadError('BaseSpace file {} not found'.format(url))
return response
def get_basespace_api_url():
"""Get base BaseSpace API URL."""
return 'https://api.basespace.illumina.com/v1pre3'
def get_basespace_api_file_url(file_id):
"""Get BaseSpace API file URL."""
return '{}/files/{}'.format(get_basespace_api_url(), file_id)
def get_basespace_api_file_content_url(file_id):
"""Get BaseSpace API file contents URL."""
return '{}/content'.format(get_basespace_api_file_url(file_id))
def get_file_name(session, file_id, request_headers):
"""Get file name."""
response = make_get_request(session, get_basespace_api_file_url(file_id), request_headers)
return response.json()['Response']['Name']
def download_file(session, file_id, file_name, request_headers):
"""Download BaseSpace file."""
response = make_get_request(session, get_basespace_api_file_content_url(file_id), request_headers, True)
try:
with open(file_name, 'wb') as f:
for chunk in response.iter_content(chunk_size=1024):
f.write(chunk)
except FileNotFoundError:
raise BaseSpaceDownloadError('Could not save file to {}, due to directory not being found'.format(file_name))
except PermissionError:
raise BaseSpaceDownloadError('Could not save file to {}, due to insufficient permissions'.format(file_name))
if __name__ == "__main__":
main()
| 34.126667 | 117 | 0.632936 |
import sys
import traceback
import atexit
import argparse
import requests
class BaseSpaceDownloadError(Exception):
pass
def main():
session = requests.Session()
atexit.register(on_exit, session)
parser = argparse.ArgumentParser(description='Download file from Illumina BaseSpace.')
parser.add_argument('--file-id',
dest='file_ids',
action='append',
required=True,
help="BaseSpace file ID. This argument can be repeated to specify multiple files.")
parser.add_argument('--access-token-secret-path',
dest='access_token_secret_path',
required=True,
help="BaseSpace access token secret path.")
parser.add_argument('--output',
dest='output',
type=str,
choices=['full', 'filename'],
default='full',
help="Sets what is printed to standard output. "
"Argument 'full' outputs everything, "
"argument 'filename' outputs only file names of downloaded files.")
parser.add_argument('--verbose',
dest='verbose',
action='store_true',
default=False,
help="Print detailed exception information when error occurs. "
"Output argument had no effect on this argument.")
args = parser.parse_args()
try:
file_ids = args.file_ids
access_token = get_token_from_secret_file(args.access_token_secret_path)
headers = {'x-access-token': access_token}
for file_id in file_ids:
file_name = get_file_name(session, file_id, headers)
download_file(session, file_id, file_name, headers)
output(args.output, 'filename={}'.format(file_name))
except:
if args.verbose:
traceback.print_exc()
else:
print("An error occurred while processing the Basespace download request. Use --verbose to see details.")
sys.exit(1)
def on_exit(session):
session.close()
def output(output_option, value):
if output_option == 'full':
print(value)
elif output_option == 'filename':
if value.startswith('filename='):
print(value[len('filename='):])
else:
print("Internal error: output argument {} handling not implemented".format(output_option))
sys.exit(1)
def get_token_from_secret_file(secret_file_path):
try:
with open(secret_file_path, 'r') as f:
return f.readline()
except FileNotFoundError:
raise BaseSpaceDownloadError('Secret file not found')
except PermissionError:
raise BaseSpaceDownloadError('No permissions to read secret file')
def make_get_request(session, url, headers, stream=False):
response = session.get(url, headers=headers, stream=stream)
if response.status_code == 401:
raise BaseSpaceDownloadError('Authentication failed on URL {}'.format(url))
elif response.status_code == 404:
raise BaseSpaceDownloadError('BaseSpace file {} not found'.format(url))
return response
def get_basespace_api_url():
return 'https://api.basespace.illumina.com/v1pre3'
def get_basespace_api_file_url(file_id):
return '{}/files/{}'.format(get_basespace_api_url(), file_id)
def get_basespace_api_file_content_url(file_id):
return '{}/content'.format(get_basespace_api_file_url(file_id))
def get_file_name(session, file_id, request_headers):
response = make_get_request(session, get_basespace_api_file_url(file_id), request_headers)
return response.json()['Response']['Name']
def download_file(session, file_id, file_name, request_headers):
response = make_get_request(session, get_basespace_api_file_content_url(file_id), request_headers, True)
try:
with open(file_name, 'wb') as f:
for chunk in response.iter_content(chunk_size=1024):
f.write(chunk)
except FileNotFoundError:
raise BaseSpaceDownloadError('Could not save file to {}, due to directory not being found'.format(file_name))
except PermissionError:
raise BaseSpaceDownloadError('Could not save file to {}, due to insufficient permissions'.format(file_name))
if __name__ == "__main__":
main()
| true | true |
f716aa1fd41279e8e408620b6f55302402277111 | 26,185 | py | Python | tests/test_sdb.py | peppelinux/pyoidc | 2e751ed84039259a2b138148eae204c877518950 | [
"Apache-2.0"
] | 1 | 2020-09-30T13:08:14.000Z | 2020-09-30T13:08:14.000Z | tests/test_sdb.py | peppelinux/pyoidc | 2e751ed84039259a2b138148eae204c877518950 | [
"Apache-2.0"
] | null | null | null | tests/test_sdb.py | peppelinux/pyoidc | 2e751ed84039259a2b138148eae204c877518950 | [
"Apache-2.0"
] | null | null | null | import base64
import datetime
import hashlib
import hmac
import json
import random
import time
from unittest import TestCase
import pytest
from freezegun import freeze_time
from oic.oic.message import AuthorizationRequest
from oic.oic.message import OpenIDRequest
from oic.utils.sdb import AccessCodeUsed
from oic.utils.sdb import AuthnEvent
from oic.utils.sdb import Crypt
from oic.utils.sdb import DefaultToken
from oic.utils.sdb import DictRefreshDB
from oic.utils.sdb import DictSessionBackend
from oic.utils.sdb import ExpiredToken
from oic.utils.sdb import WrongTokenType
from oic.utils.sdb import create_session_db
__author__ = "rohe0002"
AREQ = AuthorizationRequest(
response_type="code",
client_id="client1",
redirect_uri="http://example.com/authz",
scope=["openid"],
state="state000",
)
AREQN = AuthorizationRequest(
response_type="code",
client_id="client1",
redirect_uri="http://example.com/authz",
scope=["openid"],
state="state000",
nonce="something",
)
AREQO = AuthorizationRequest(
response_type="code",
client_id="client1",
redirect_uri="http://example.com/authz",
scope=["openid", "offlien_access"],
prompt="consent",
state="state000",
)
OIDR = OpenIDRequest(
response_type="code",
client_id="client1",
redirect_uri="http://example.com/authz",
scope=["openid"],
state="state000",
)
def _eq(l1, l2):
return set(l1) == set(l2)
class TestAuthnEvent(object):
"""Tests for AuthnEvent class."""
def test_from_json(self):
dic = {"uid": "uid", "salt": "salt", "authn_time": 1000, "valid_until": 1500}
ae = AuthnEvent.from_json(json.dumps(dic))
assert ae.uid == "uid"
assert ae.salt == "salt"
assert ae.authn_time == 1000
assert ae.valid_until == 1500
def test_to_json(self):
ae = AuthnEvent("uid", "salt", authn_time=1000, valid_until=1500)
json_repr = ae.to_json()
assert json.loads(json_repr) == {
"uid": "uid",
"salt": "salt",
"authn_time": 1000,
"valid_until": 1500,
"authn_info": None,
}
class TestDictRefreshDB(object):
@pytest.fixture(autouse=True)
def create_rdb(self):
self.rdb = DictRefreshDB()
def test_verify_token(self):
token = self.rdb.create_token(
"client1", "uid", "openid", "sub1", "authzreq", "sid"
)
assert self.rdb.verify_token("client1", token)
assert self.rdb.verify_token("client2", token) is False
def test_revoke_token(self):
token = self.rdb.create_token(
"client1", "uid", "openid", "sub1", "authzreq", "sid"
)
self.rdb.remove(token)
assert self.rdb.verify_token("client1", token) is False
with pytest.raises(KeyError):
self.rdb.get(token)
def test_get_token(self):
with pytest.raises(KeyError):
self.rdb.get("token")
token = self.rdb.create_token(
"client1", "uid", ["openid"], "sub1", "authzreq", "sid"
)
assert self.rdb.get(token) == {
"client_id": "client1",
"sub": "sub1",
"scope": ["openid"],
"uid": "uid",
"authzreq": "authzreq",
"sid": "sid",
}
class TestToken(object):
@pytest.fixture(autouse=True)
def create_token(self):
self.token = DefaultToken("secret", "password", lifetime=60)
def test_token(self):
sid = self.token.key(areq=AREQ)
assert len(sid) == 56
def test_new_token(self):
sid = self.token.key(areq=AREQ)
assert len(sid) == 56
self.token(sid=sid, ttype="T")
assert len(sid) == 56
sid2 = self.token.key(areq=AREQ, user="jones")
assert len(sid2) == 56
assert sid != sid2
def test_type_and_key(self):
sid = self.token.key(areq=AREQ)
code = self.token(sid=sid)
part = self.token.type_and_key(code)
assert part[0] == "A"
assert part[1] == sid
def test_expired_fresh(self):
factory = DefaultToken("secret", "password", lifetime=60)
token = factory(sid="abc", ttype="T")
assert factory.is_expired(token) is False
def test_expired_stale(self):
initial_datetime = datetime.datetime(2018, 2, 5, 10, 0, 0, 0)
final_datetime = datetime.datetime(2018, 2, 5, 10, 1, 0, 0)
factory = DefaultToken("secret", "password", lifetime=2)
with freeze_time(initial_datetime) as frozen:
token = factory(sid="abc", ttype="T")
frozen.move_to(final_datetime)
assert factory.is_expired(token) is True
def test_expired_when(self):
factory = DefaultToken("secret", "password", lifetime=2)
token = factory(sid="abc", ttype="T")
when = time.time() + 5 # 5 seconds from now
assert factory.is_expired(token, when=when) is True
class TestSessionBackend(TestCase):
"""Unittests for SessionBackend - using the DictSessionBackend."""
def setUp(self):
self.backend = DictSessionBackend()
def test_setitem(self):
self.backend["key"] = "value"
self.assertEqual(self.backend.storage["key"], "value")
self.backend["key"] = "new_value"
self.assertEqual(self.backend.storage["key"], "new_value")
def test_getitem(self):
self.backend.storage = {"key": "value"}
self.assertEqual(self.backend["key"], "value")
with self.assertRaises(KeyError):
self.backend["missing"]
def test_delitem(self):
self.backend.storage = {"key": "value"}
del self.backend["key"]
self.assertEqual(self.backend.storage, {})
def test_contains(self):
self.backend["key"] = "value"
self.assertTrue("key" in self.backend)
self.assertFalse("missing" in self.backend)
def test_get_by_sub(self):
self.backend.storage = {"session_id": {"sub": "my_sub"}}
self.assertEqual(set(self.backend.get_by_sub("my_sub")), {"session_id"})
self.assertEqual(set(self.backend.get_by_sub("missing")), set())
def test_get_by_sub_multiple(self):
self.backend.storage = {
"session_id1": {"sub": "my_sub"},
"session_id2": {"sub": "my_sub"},
}
self.assertEqual(
set(self.backend.get_by_sub("my_sub")), {"session_id1", "session_id2"}
)
def test_get_by_uid(self):
aevent = AuthnEvent("my_uid", "some_salt").to_json()
self.backend.storage = {"session_id": {"authn_event": aevent}}
self.assertEqual(set(self.backend.get_by_uid("my_uid")), {"session_id"})
self.assertEqual(set(self.backend.get_by_uid("missing")), set())
def test_get_by_uid_multiple(self):
aevent1 = AuthnEvent("my_uid", "some_salt").to_json()
aevent2 = AuthnEvent("my_uid", "some_salt").to_json()
self.backend.storage = {
"session_id1": {"authn_event": aevent1},
"session_id2": {"authn_event": aevent2},
}
self.assertEqual(
set(self.backend.get_by_uid("my_uid")), {"session_id1", "session_id2"}
)
def test_get_client_ids_for_uid(self):
aevent = AuthnEvent("my_uid", "some_salt").to_json()
self.backend.storage = {
"session_id": {"authn_event": aevent, "client_id": "my_client"}
}
self.assertEqual(
set(self.backend.get_client_ids_for_uid("my_uid")), {"my_client"}
)
self.assertEqual(set(self.backend.get_client_ids_for_uid("missing")), set())
def test_get_client_ids_for_uid_multiple(self):
aevent1 = AuthnEvent("my_uid", "some_salt").to_json()
aevent2 = AuthnEvent("my_uid", "some_salt").to_json()
self.backend.storage = {
"session_id1": {"authn_event": aevent1, "client_id": "my_client"},
"session_id2": {"authn_event": aevent2, "client_id": "my_other"},
}
self.assertEqual(
set(self.backend.get_client_ids_for_uid("my_uid")),
{"my_client", "my_other"},
)
def test_get_verified_logout(self):
aevent1 = AuthnEvent("my_uid1", "some_salt").to_json()
aevent2 = AuthnEvent("my_uid2", "some_salt").to_json()
self.backend.storage = {
"session_id": {
"authn_event": aevent1,
"verified_logout": "verification key",
},
"session_id2": {"authn_event": aevent2},
}
self.assertEqual(
self.backend.get_verified_logout("my_uid1"), "verification key"
)
self.assertIsNone(self.backend.get_verified_logout("my_uid2"))
self.assertIsNone(self.backend.get_verified_logout("missing"))
def test_get_verified_logout_multiple(self):
aevent1 = AuthnEvent("my_uid", "some_salt").to_json()
aevent2 = AuthnEvent("my_uid", "some_salt").to_json()
self.backend.storage = {
"session_id1": {
"authn_event": aevent1,
"verified_logout": "verification key",
},
"session_id2": {
"authn_event": aevent2,
"verified_logout": "verification key",
},
}
self.assertEqual(self.backend.get_verified_logout("my_uid"), "verification key")
def test_get_token_ids(self):
aevent = AuthnEvent("my_uid", "some_salt").to_json()
self.backend.storage = {
"session_id": {"authn_event": aevent, "id_token": "Id token"}
}
self.assertEqual(set(self.backend.get_token_ids("my_uid")), {"Id token"})
self.assertEqual(set(self.backend.get_token_ids("missing")), set())
def test_get_token_ids_multiple(self):
aevent1 = AuthnEvent("my_uid", "some_salt").to_json()
aevent2 = AuthnEvent("my_uid", "some_salt").to_json()
self.backend.storage = {
"session_id1": {"authn_event": aevent1, "id_token": "Id token 1"},
"session_id2": {"authn_event": aevent2, "id_token": "Id token 2"},
}
self.assertEqual(
set(self.backend.get_token_ids("my_uid")), {"Id token 1", "Id token 2"}
)
def test_is_revoke_uid_false(self):
aevent = AuthnEvent("my_uid", "some_salt").to_json()
self.backend.storage = {"session_id": {"authn_event": aevent, "revoked": False}}
self.assertFalse(self.backend.is_revoke_uid("my_uid"))
def test_is_revoke_uid_true(self):
aevent = AuthnEvent("my_uid", "some_salt").to_json()
self.backend.storage = {"session_id": {"authn_event": aevent, "revoked": True}}
self.assertTrue(self.backend.is_revoke_uid("my_uid"))
def test_is_revoke_uid_multiple(self):
aevent1 = AuthnEvent("my_uid", "some_salt").to_json()
aevent2 = AuthnEvent("my_uid", "some_salt").to_json()
self.backend.storage = {
"session_id1": {"authn_event": aevent1, "revoked": True},
"session_id2": {"authn_event": aevent2, "revoked": False},
}
self.assertTrue(self.backend.is_revoke_uid("my_uid"))
class TestSessionDB(object):
@pytest.fixture(autouse=True)
def create_sdb(self, session_db_factory):
self.sdb = session_db_factory("https://example.com/")
def test_create_authz_session(self):
ae = AuthnEvent("uid", "salt")
sid = self.sdb.create_authz_session(ae, AREQ)
self.sdb.do_sub(sid, "client_salt")
info = self.sdb[sid]
assert info["oauth_state"] == "authz"
def test_create_authz_session_without_nonce(self):
ae = AuthnEvent("sub", "salt")
sid = self.sdb.create_authz_session(ae, AREQ)
info = self.sdb[sid]
assert info["oauth_state"] == "authz"
def test_create_authz_session_with_nonce(self):
ae = AuthnEvent("sub", "salt")
sid = self.sdb.create_authz_session(ae, AREQN)
info = self.sdb[sid]
assert info["nonce"] == "something"
def test_create_authz_session_with_id_token(self):
ae = AuthnEvent("sub", "salt")
sid = self.sdb.create_authz_session(ae, AREQN, id_token="id_token")
info = self.sdb[sid]
assert info["id_token"] == "id_token"
def test_create_authz_session_with_oidreq(self):
ae = AuthnEvent("sub", "salt")
sid = self.sdb.create_authz_session(ae, AREQN, oidreq=OIDR)
info = self.sdb[sid]
assert "id_token" not in info
assert "oidreq" in info
def test_create_authz_session_with_sector_id(self):
ae = AuthnEvent("sub", "salt")
sid = self.sdb.create_authz_session(ae, AREQN, oidreq=OIDR)
self.sdb.do_sub(sid, "client_salt", "http://example.com/si.jwt", "pairwise")
info_1 = self.sdb[sid].copy()
assert "id_token" not in info_1
assert "oidreq" in info_1
assert info_1["sub"] != "sub"
self.sdb.do_sub(sid, "client_salt", "http://example.net/si.jwt", "pairwise")
info_2 = self.sdb[sid]
assert info_2["sub"] != "sub"
assert info_2["sub"] != info_1["sub"]
def test_upgrade_to_token(self):
ae1 = AuthnEvent("uid", "salt")
sid = self.sdb.create_authz_session(ae1, AREQ)
self.sdb[sid]["sub"] = "sub"
grant = self.sdb[sid]["code"]
_dict = self.sdb.upgrade_to_token(grant)
print(_dict.keys())
assert _eq(
list(_dict.keys()),
[
"authn_event",
"code",
"authzreq",
"revoked",
"access_token",
"token_type",
"state",
"redirect_uri",
"code_used",
"client_id",
"scope",
"oauth_state",
"access_token_scope",
"sub",
"response_type",
],
)
# can't update again
with pytest.raises(AccessCodeUsed):
self.sdb.upgrade_to_token(grant)
self.sdb.upgrade_to_token(_dict["access_token"])
def test_upgrade_to_token_refresh(self):
ae1 = AuthnEvent("sub", "salt")
sid = self.sdb.create_authz_session(ae1, AREQO)
self.sdb.do_sub(sid, ae1.salt)
grant = self.sdb[sid]["code"]
_dict = self.sdb.upgrade_to_token(grant, issue_refresh=True)
print(_dict.keys())
assert _eq(
_dict.keys(),
[
"authn_event",
"code",
"authzreq",
"revoked",
"access_token",
"response_type",
"token_type",
"state",
"redirect_uri",
"code_used",
"client_id",
"scope",
"oauth_state",
"access_token_scope",
"refresh_token",
"sub",
],
)
# can't update again
with pytest.raises(AccessCodeUsed):
self.sdb.upgrade_to_token(grant)
self.sdb.upgrade_to_token(_dict["access_token"])
def test_upgrade_to_token_with_id_token_and_oidreq(self):
ae2 = AuthnEvent("another_user_id", "salt")
sid = self.sdb.create_authz_session(ae2, AREQ)
self.sdb[sid]["sub"] = "sub"
grant = self.sdb[sid]["code"]
_dict = self.sdb.upgrade_to_token(grant, id_token="id_token", oidreq=OIDR)
print(_dict.keys())
assert _eq(
list(_dict.keys()),
[
"authn_event",
"code",
"authzreq",
"revoked",
"oidreq",
"access_token",
"id_token",
"response_type",
"token_type",
"state",
"redirect_uri",
"code_used",
"client_id",
"scope",
"oauth_state",
"access_token_scope",
"sub",
],
)
assert _dict["id_token"] == "id_token"
assert isinstance(_dict["oidreq"], OpenIDRequest)
def test_refresh_token(self):
ae = AuthnEvent("uid", "salt")
sid = self.sdb.create_authz_session(ae, AREQ)
self.sdb[sid]["sub"] = "sub"
grant = self.sdb[sid]["code"]
dict1 = self.sdb.upgrade_to_token(grant, issue_refresh=True).copy()
rtoken = dict1["refresh_token"]
dict2 = self.sdb.refresh_token(rtoken, AREQ["client_id"])
assert dict1["access_token"] != dict2["access_token"]
with pytest.raises(WrongTokenType):
self.sdb.refresh_token(dict2["access_token"], AREQ["client_id"])
def test_refresh_token_cleared_session(self):
ae = AuthnEvent("uid", "salt")
sid = self.sdb.create_authz_session(ae, AREQ)
self.sdb[sid]["sub"] = "sub"
grant = self.sdb[sid]["code"]
dict1 = self.sdb.upgrade_to_token(grant, issue_refresh=True)
ac1 = dict1["access_token"]
# Purge the SessionDB
self.sdb._db = {}
rtoken = dict1["refresh_token"]
dict2 = self.sdb.refresh_token(rtoken, AREQ["client_id"])
assert ac1 != dict2["access_token"]
assert self.sdb.is_valid(dict2["access_token"])
def test_is_valid(self):
ae1 = AuthnEvent("uid", "salt")
sid = self.sdb.create_authz_session(ae1, AREQ)
self.sdb[sid]["sub"] = "sub"
grant = self.sdb[sid]["code"]
assert self.sdb.is_valid(grant)
sinfo = self.sdb.upgrade_to_token(grant, issue_refresh=True)
assert not self.sdb.is_valid(grant)
access_token = sinfo["access_token"]
assert self.sdb.access_token.valid(access_token)
refresh_token = sinfo["refresh_token"]
sinfo = self.sdb.refresh_token(refresh_token, AREQ["client_id"])
access_token2 = sinfo["access_token"]
assert self.sdb.is_valid(access_token2)
# The old access code should be invalid
try:
self.sdb.is_valid(access_token)
except KeyError:
pass
def test_valid_grant(self):
ae = AuthnEvent("another:user", "salt")
sid = self.sdb.create_authz_session(ae, AREQ)
grant = self.sdb[sid]["code"]
assert self.sdb.is_valid(grant)
def test_revoke_token(self):
ae1 = AuthnEvent("uid", "salt")
sid = self.sdb.create_authz_session(ae1, AREQ)
self.sdb[sid]["sub"] = "sub"
grant = self.sdb[sid]["code"]
tokens = self.sdb.upgrade_to_token(grant, issue_refresh=True)
access_token = tokens["access_token"]
refresh_token = tokens["refresh_token"]
assert self.sdb.is_valid(access_token)
self.sdb.revoke_token(access_token)
assert not self.sdb.is_valid(access_token)
sinfo = self.sdb.refresh_token(refresh_token, AREQ["client_id"])
access_token = sinfo["access_token"]
assert self.sdb.is_valid(access_token)
self.sdb.revoke_refresh_token(refresh_token)
assert not self.sdb.is_valid(refresh_token)
try:
self.sdb.refresh_token(refresh_token, AREQ["client_id"])
except ExpiredToken:
pass
assert self.sdb.is_valid(access_token)
ae2 = AuthnEvent("sub", "salt")
sid = self.sdb.create_authz_session(ae2, AREQ)
grant = self.sdb[sid]["code"]
self.sdb.revoke_token(grant)
assert not self.sdb.is_valid(grant)
def test_revoke_all_tokens(self):
ae1 = AuthnEvent("uid", "salt")
sid = self.sdb.create_authz_session(ae1, AREQ)
self.sdb[sid]["sub"] = "sub"
grant = self.sdb[sid]["code"]
tokens = self.sdb.upgrade_to_token(grant, issue_refresh=True)
access_token = tokens["access_token"]
refresh_token = tokens["refresh_token"]
self.sdb.revoke_all_tokens(access_token)
assert not self.sdb.is_valid(access_token)
assert not self.sdb.is_valid(refresh_token)
def test_sub_to_authn_event(self):
ae = AuthnEvent("sub", "salt", time_stamp=time.time())
sid = self.sdb.create_authz_session(ae, AREQ)
sub = self.sdb.do_sub(sid, "client_salt")
# given the sub find out whether the authn event is still valid
sids = self.sdb.get_sids_by_sub(sub)
ae = self.sdb[sids[0]]["authn_event"]
assert AuthnEvent.from_json(ae).valid()
def test_do_sub_deterministic(self):
ae = AuthnEvent("tester", "random_value")
sid = self.sdb.create_authz_session(ae, AREQ)
self.sdb.do_sub(sid, "other_random_value")
info = self.sdb[sid]
assert (
info["sub"]
== "179670cdee6375c48e577317b2abd7d5cd26a5cdb1cfb7ef84af3d703c71d013"
)
self.sdb.do_sub(
sid,
"other_random_value",
sector_id="http://example.com",
subject_type="pairwise",
)
info2 = self.sdb[sid]
assert (
info2["sub"]
== "aaa50d80f8780cf1c4beb39e8e126556292f5091b9e39596424fefa2b99d9c53"
)
self.sdb.do_sub(
sid,
"another_random_value",
sector_id="http://other.example.com",
subject_type="pairwise",
)
info2 = self.sdb[sid]
assert (
info2["sub"]
== "62fb630e29f0d41b88e049ac0ef49a9c3ac5418c029d6e4f5417df7e9443976b"
)
def test_get_authentication_event_dict(self):
self.sdb._db["123"] = {}
self.sdb._db["123"]["authn_event"] = {
"uid": "uid",
"salt": "salt",
"authn_time": 1000,
"valid_until": 1500,
}
ae = self.sdb.get_authentication_event("123")
assert ae.uid == "uid"
assert ae.salt == "salt"
assert ae.authn_time == 1000
assert ae.valid_until == 1500
def test_get_authentication_event_json(self):
self.sdb._db["123"] = {}
self.sdb._db["123"]["authn_event"] = json.dumps(
{"uid": "uid", "salt": "salt", "authn_time": 1000, "valid_until": 1500}
)
ae = self.sdb.get_authentication_event("123")
assert ae.uid == "uid"
assert ae.salt == "salt"
assert ae.authn_time == 1000
assert ae.valid_until == 1500
def test_get_sids_from_uid_distributed(self):
db = DictSessionBackend()
sdb1 = create_session_db("https://example.com/1", "secret", "password", db=db)
sdb2 = create_session_db("https://example.com/2", "secret", "password", db=db)
ae = AuthnEvent("sub", "salt", time_stamp=time.time())
sid1 = sdb1.create_authz_session(ae, AREQ)
sdb1.do_sub(sid1, "salt")
sid2 = sdb2.create_authz_session(ae, AREQ)
sdb2.do_sub(sid2, "salt")
sdb1sids = sdb1.get_sids_from_uid("sub")
sdb2sids = sdb2.get_sids_from_uid("sub")
assert sdb1sids == sdb2sids
def test_get_client_ids_for_uid(self):
self.sdb._db["123"] = {
"authn_event": json.dumps({"uid": "my_uid", "salt": "salt"}),
"client_id": "my_client",
}
assert self.sdb.get_client_ids_for_uid("my_uid") == ["my_client"]
def test_get_verify_logout(self):
self.sdb._db["123"] = {
"authn_event": json.dumps({"uid": "my_uid", "salt": "salt"}),
"verified_logout": "something",
}
assert self.sdb.get_verify_logout("my_uid") == "something"
def test_set_verify_logout(self):
self.sdb._db["123"] = {
"authn_event": json.dumps({"uid": "my_uid", "salt": "salt"})
}
self.sdb.set_verify_logout("my_uid")
assert self.sdb.get_verify_logout("my_uid") is not None
def test_set_verify_logout_multiple(self):
self.sdb._db["123"] = {
"authn_event": json.dumps({"uid": "my_uid", "salt": "salt"})
}
self.sdb._db["321"] = {
"authn_event": json.dumps({"uid": "my_uid", "salt": "salt"})
}
self.sdb.set_verify_logout("my_uid")
assert self.sdb.get_verify_logout("my_uid") is not None
assert (
self.sdb._db["123"]["verified_logout"]
== self.sdb._db["321"]["verified_logout"]
)
def test_get_token_ids(self):
self.sdb._db["123"] = {
"authn_event": json.dumps({"uid": "my_uid", "salt": "salt"}),
"id_token": "Id token",
}
assert set(self.sdb.get_token_ids("my_uid")) == {"Id token"}
def test_get_is_revoke_uid(self):
self.sdb._db["123"] = {
"authn_event": json.dumps({"uid": "my_uid", "salt": "salt"}),
"revoked": True,
}
assert self.sdb.is_revoke_uid("my_uid")
def test_revoke_uid(self):
self.sdb._db["123"] = {
"authn_event": json.dumps({"uid": "my_uid", "salt": "salt"})
}
self.sdb.revoke_uid("my_uid")
assert self.sdb.is_revoke_uid("my_uid")
class TestCrypt(object):
@pytest.fixture(autouse=True)
def create_crypt(self):
self.crypt = Crypt("4-amino-1H-pyrimidine-2-one")
def test_encrypt_decrypt(self):
ctext = self.crypt.encrypt("Cytosine")
plain = self.crypt.decrypt(ctext).decode("utf-8")
assert plain == "Cytosine "
ctext = self.crypt.encrypt("cytidinetriphosp")
plain = self.crypt.decrypt(ctext).decode("utf-8")
assert plain == "cytidinetriphosp"
def test_crypt_with_b64(self):
db = {}
msg = "secret{}{}".format(time.time(), random.random())
csum = hmac.new(msg.encode("utf-8"), digestmod=hashlib.sha224)
txt = csum.digest() # 28 bytes long, 224 bits
db[txt] = "foobar"
txt = txt + b"aces" # another 4 bytes
ctext = self.crypt.encrypt(txt)
onthewire = base64.b64encode(ctext)
plain = self.crypt.decrypt(base64.b64decode(onthewire))
assert plain.endswith(b"aces")
assert db[plain[:-4]] == "foobar"
| 34.228758 | 88 | 0.586901 | import base64
import datetime
import hashlib
import hmac
import json
import random
import time
from unittest import TestCase
import pytest
from freezegun import freeze_time
from oic.oic.message import AuthorizationRequest
from oic.oic.message import OpenIDRequest
from oic.utils.sdb import AccessCodeUsed
from oic.utils.sdb import AuthnEvent
from oic.utils.sdb import Crypt
from oic.utils.sdb import DefaultToken
from oic.utils.sdb import DictRefreshDB
from oic.utils.sdb import DictSessionBackend
from oic.utils.sdb import ExpiredToken
from oic.utils.sdb import WrongTokenType
from oic.utils.sdb import create_session_db
__author__ = "rohe0002"
AREQ = AuthorizationRequest(
response_type="code",
client_id="client1",
redirect_uri="http://example.com/authz",
scope=["openid"],
state="state000",
)
AREQN = AuthorizationRequest(
response_type="code",
client_id="client1",
redirect_uri="http://example.com/authz",
scope=["openid"],
state="state000",
nonce="something",
)
AREQO = AuthorizationRequest(
response_type="code",
client_id="client1",
redirect_uri="http://example.com/authz",
scope=["openid", "offlien_access"],
prompt="consent",
state="state000",
)
OIDR = OpenIDRequest(
response_type="code",
client_id="client1",
redirect_uri="http://example.com/authz",
scope=["openid"],
state="state000",
)
def _eq(l1, l2):
return set(l1) == set(l2)
class TestAuthnEvent(object):
def test_from_json(self):
dic = {"uid": "uid", "salt": "salt", "authn_time": 1000, "valid_until": 1500}
ae = AuthnEvent.from_json(json.dumps(dic))
assert ae.uid == "uid"
assert ae.salt == "salt"
assert ae.authn_time == 1000
assert ae.valid_until == 1500
def test_to_json(self):
ae = AuthnEvent("uid", "salt", authn_time=1000, valid_until=1500)
json_repr = ae.to_json()
assert json.loads(json_repr) == {
"uid": "uid",
"salt": "salt",
"authn_time": 1000,
"valid_until": 1500,
"authn_info": None,
}
class TestDictRefreshDB(object):
@pytest.fixture(autouse=True)
def create_rdb(self):
self.rdb = DictRefreshDB()
def test_verify_token(self):
token = self.rdb.create_token(
"client1", "uid", "openid", "sub1", "authzreq", "sid"
)
assert self.rdb.verify_token("client1", token)
assert self.rdb.verify_token("client2", token) is False
def test_revoke_token(self):
token = self.rdb.create_token(
"client1", "uid", "openid", "sub1", "authzreq", "sid"
)
self.rdb.remove(token)
assert self.rdb.verify_token("client1", token) is False
with pytest.raises(KeyError):
self.rdb.get(token)
def test_get_token(self):
with pytest.raises(KeyError):
self.rdb.get("token")
token = self.rdb.create_token(
"client1", "uid", ["openid"], "sub1", "authzreq", "sid"
)
assert self.rdb.get(token) == {
"client_id": "client1",
"sub": "sub1",
"scope": ["openid"],
"uid": "uid",
"authzreq": "authzreq",
"sid": "sid",
}
class TestToken(object):
@pytest.fixture(autouse=True)
def create_token(self):
self.token = DefaultToken("secret", "password", lifetime=60)
def test_token(self):
sid = self.token.key(areq=AREQ)
assert len(sid) == 56
def test_new_token(self):
sid = self.token.key(areq=AREQ)
assert len(sid) == 56
self.token(sid=sid, ttype="T")
assert len(sid) == 56
sid2 = self.token.key(areq=AREQ, user="jones")
assert len(sid2) == 56
assert sid != sid2
def test_type_and_key(self):
sid = self.token.key(areq=AREQ)
code = self.token(sid=sid)
part = self.token.type_and_key(code)
assert part[0] == "A"
assert part[1] == sid
def test_expired_fresh(self):
factory = DefaultToken("secret", "password", lifetime=60)
token = factory(sid="abc", ttype="T")
assert factory.is_expired(token) is False
def test_expired_stale(self):
initial_datetime = datetime.datetime(2018, 2, 5, 10, 0, 0, 0)
final_datetime = datetime.datetime(2018, 2, 5, 10, 1, 0, 0)
factory = DefaultToken("secret", "password", lifetime=2)
with freeze_time(initial_datetime) as frozen:
token = factory(sid="abc", ttype="T")
frozen.move_to(final_datetime)
assert factory.is_expired(token) is True
def test_expired_when(self):
factory = DefaultToken("secret", "password", lifetime=2)
token = factory(sid="abc", ttype="T")
when = time.time() + 5
assert factory.is_expired(token, when=when) is True
class TestSessionBackend(TestCase):
def setUp(self):
self.backend = DictSessionBackend()
def test_setitem(self):
self.backend["key"] = "value"
self.assertEqual(self.backend.storage["key"], "value")
self.backend["key"] = "new_value"
self.assertEqual(self.backend.storage["key"], "new_value")
def test_getitem(self):
self.backend.storage = {"key": "value"}
self.assertEqual(self.backend["key"], "value")
with self.assertRaises(KeyError):
self.backend["missing"]
def test_delitem(self):
self.backend.storage = {"key": "value"}
del self.backend["key"]
self.assertEqual(self.backend.storage, {})
def test_contains(self):
self.backend["key"] = "value"
self.assertTrue("key" in self.backend)
self.assertFalse("missing" in self.backend)
def test_get_by_sub(self):
self.backend.storage = {"session_id": {"sub": "my_sub"}}
self.assertEqual(set(self.backend.get_by_sub("my_sub")), {"session_id"})
self.assertEqual(set(self.backend.get_by_sub("missing")), set())
def test_get_by_sub_multiple(self):
self.backend.storage = {
"session_id1": {"sub": "my_sub"},
"session_id2": {"sub": "my_sub"},
}
self.assertEqual(
set(self.backend.get_by_sub("my_sub")), {"session_id1", "session_id2"}
)
def test_get_by_uid(self):
aevent = AuthnEvent("my_uid", "some_salt").to_json()
self.backend.storage = {"session_id": {"authn_event": aevent}}
self.assertEqual(set(self.backend.get_by_uid("my_uid")), {"session_id"})
self.assertEqual(set(self.backend.get_by_uid("missing")), set())
def test_get_by_uid_multiple(self):
aevent1 = AuthnEvent("my_uid", "some_salt").to_json()
aevent2 = AuthnEvent("my_uid", "some_salt").to_json()
self.backend.storage = {
"session_id1": {"authn_event": aevent1},
"session_id2": {"authn_event": aevent2},
}
self.assertEqual(
set(self.backend.get_by_uid("my_uid")), {"session_id1", "session_id2"}
)
def test_get_client_ids_for_uid(self):
aevent = AuthnEvent("my_uid", "some_salt").to_json()
self.backend.storage = {
"session_id": {"authn_event": aevent, "client_id": "my_client"}
}
self.assertEqual(
set(self.backend.get_client_ids_for_uid("my_uid")), {"my_client"}
)
self.assertEqual(set(self.backend.get_client_ids_for_uid("missing")), set())
def test_get_client_ids_for_uid_multiple(self):
aevent1 = AuthnEvent("my_uid", "some_salt").to_json()
aevent2 = AuthnEvent("my_uid", "some_salt").to_json()
self.backend.storage = {
"session_id1": {"authn_event": aevent1, "client_id": "my_client"},
"session_id2": {"authn_event": aevent2, "client_id": "my_other"},
}
self.assertEqual(
set(self.backend.get_client_ids_for_uid("my_uid")),
{"my_client", "my_other"},
)
def test_get_verified_logout(self):
aevent1 = AuthnEvent("my_uid1", "some_salt").to_json()
aevent2 = AuthnEvent("my_uid2", "some_salt").to_json()
self.backend.storage = {
"session_id": {
"authn_event": aevent1,
"verified_logout": "verification key",
},
"session_id2": {"authn_event": aevent2},
}
self.assertEqual(
self.backend.get_verified_logout("my_uid1"), "verification key"
)
self.assertIsNone(self.backend.get_verified_logout("my_uid2"))
self.assertIsNone(self.backend.get_verified_logout("missing"))
def test_get_verified_logout_multiple(self):
aevent1 = AuthnEvent("my_uid", "some_salt").to_json()
aevent2 = AuthnEvent("my_uid", "some_salt").to_json()
self.backend.storage = {
"session_id1": {
"authn_event": aevent1,
"verified_logout": "verification key",
},
"session_id2": {
"authn_event": aevent2,
"verified_logout": "verification key",
},
}
self.assertEqual(self.backend.get_verified_logout("my_uid"), "verification key")
def test_get_token_ids(self):
aevent = AuthnEvent("my_uid", "some_salt").to_json()
self.backend.storage = {
"session_id": {"authn_event": aevent, "id_token": "Id token"}
}
self.assertEqual(set(self.backend.get_token_ids("my_uid")), {"Id token"})
self.assertEqual(set(self.backend.get_token_ids("missing")), set())
def test_get_token_ids_multiple(self):
aevent1 = AuthnEvent("my_uid", "some_salt").to_json()
aevent2 = AuthnEvent("my_uid", "some_salt").to_json()
self.backend.storage = {
"session_id1": {"authn_event": aevent1, "id_token": "Id token 1"},
"session_id2": {"authn_event": aevent2, "id_token": "Id token 2"},
}
self.assertEqual(
set(self.backend.get_token_ids("my_uid")), {"Id token 1", "Id token 2"}
)
def test_is_revoke_uid_false(self):
aevent = AuthnEvent("my_uid", "some_salt").to_json()
self.backend.storage = {"session_id": {"authn_event": aevent, "revoked": False}}
self.assertFalse(self.backend.is_revoke_uid("my_uid"))
def test_is_revoke_uid_true(self):
aevent = AuthnEvent("my_uid", "some_salt").to_json()
self.backend.storage = {"session_id": {"authn_event": aevent, "revoked": True}}
self.assertTrue(self.backend.is_revoke_uid("my_uid"))
def test_is_revoke_uid_multiple(self):
aevent1 = AuthnEvent("my_uid", "some_salt").to_json()
aevent2 = AuthnEvent("my_uid", "some_salt").to_json()
self.backend.storage = {
"session_id1": {"authn_event": aevent1, "revoked": True},
"session_id2": {"authn_event": aevent2, "revoked": False},
}
self.assertTrue(self.backend.is_revoke_uid("my_uid"))
class TestSessionDB(object):
@pytest.fixture(autouse=True)
def create_sdb(self, session_db_factory):
self.sdb = session_db_factory("https://example.com/")
def test_create_authz_session(self):
ae = AuthnEvent("uid", "salt")
sid = self.sdb.create_authz_session(ae, AREQ)
self.sdb.do_sub(sid, "client_salt")
info = self.sdb[sid]
assert info["oauth_state"] == "authz"
def test_create_authz_session_without_nonce(self):
ae = AuthnEvent("sub", "salt")
sid = self.sdb.create_authz_session(ae, AREQ)
info = self.sdb[sid]
assert info["oauth_state"] == "authz"
def test_create_authz_session_with_nonce(self):
ae = AuthnEvent("sub", "salt")
sid = self.sdb.create_authz_session(ae, AREQN)
info = self.sdb[sid]
assert info["nonce"] == "something"
def test_create_authz_session_with_id_token(self):
ae = AuthnEvent("sub", "salt")
sid = self.sdb.create_authz_session(ae, AREQN, id_token="id_token")
info = self.sdb[sid]
assert info["id_token"] == "id_token"
def test_create_authz_session_with_oidreq(self):
ae = AuthnEvent("sub", "salt")
sid = self.sdb.create_authz_session(ae, AREQN, oidreq=OIDR)
info = self.sdb[sid]
assert "id_token" not in info
assert "oidreq" in info
def test_create_authz_session_with_sector_id(self):
ae = AuthnEvent("sub", "salt")
sid = self.sdb.create_authz_session(ae, AREQN, oidreq=OIDR)
self.sdb.do_sub(sid, "client_salt", "http://example.com/si.jwt", "pairwise")
info_1 = self.sdb[sid].copy()
assert "id_token" not in info_1
assert "oidreq" in info_1
assert info_1["sub"] != "sub"
self.sdb.do_sub(sid, "client_salt", "http://example.net/si.jwt", "pairwise")
info_2 = self.sdb[sid]
assert info_2["sub"] != "sub"
assert info_2["sub"] != info_1["sub"]
def test_upgrade_to_token(self):
ae1 = AuthnEvent("uid", "salt")
sid = self.sdb.create_authz_session(ae1, AREQ)
self.sdb[sid]["sub"] = "sub"
grant = self.sdb[sid]["code"]
_dict = self.sdb.upgrade_to_token(grant)
print(_dict.keys())
assert _eq(
list(_dict.keys()),
[
"authn_event",
"code",
"authzreq",
"revoked",
"access_token",
"token_type",
"state",
"redirect_uri",
"code_used",
"client_id",
"scope",
"oauth_state",
"access_token_scope",
"sub",
"response_type",
],
)
with pytest.raises(AccessCodeUsed):
self.sdb.upgrade_to_token(grant)
self.sdb.upgrade_to_token(_dict["access_token"])
def test_upgrade_to_token_refresh(self):
ae1 = AuthnEvent("sub", "salt")
sid = self.sdb.create_authz_session(ae1, AREQO)
self.sdb.do_sub(sid, ae1.salt)
grant = self.sdb[sid]["code"]
_dict = self.sdb.upgrade_to_token(grant, issue_refresh=True)
print(_dict.keys())
assert _eq(
_dict.keys(),
[
"authn_event",
"code",
"authzreq",
"revoked",
"access_token",
"response_type",
"token_type",
"state",
"redirect_uri",
"code_used",
"client_id",
"scope",
"oauth_state",
"access_token_scope",
"refresh_token",
"sub",
],
)
# can't update again
with pytest.raises(AccessCodeUsed):
self.sdb.upgrade_to_token(grant)
self.sdb.upgrade_to_token(_dict["access_token"])
def test_upgrade_to_token_with_id_token_and_oidreq(self):
ae2 = AuthnEvent("another_user_id", "salt")
sid = self.sdb.create_authz_session(ae2, AREQ)
self.sdb[sid]["sub"] = "sub"
grant = self.sdb[sid]["code"]
_dict = self.sdb.upgrade_to_token(grant, id_token="id_token", oidreq=OIDR)
print(_dict.keys())
assert _eq(
list(_dict.keys()),
[
"authn_event",
"code",
"authzreq",
"revoked",
"oidreq",
"access_token",
"id_token",
"response_type",
"token_type",
"state",
"redirect_uri",
"code_used",
"client_id",
"scope",
"oauth_state",
"access_token_scope",
"sub",
],
)
assert _dict["id_token"] == "id_token"
assert isinstance(_dict["oidreq"], OpenIDRequest)
def test_refresh_token(self):
ae = AuthnEvent("uid", "salt")
sid = self.sdb.create_authz_session(ae, AREQ)
self.sdb[sid]["sub"] = "sub"
grant = self.sdb[sid]["code"]
dict1 = self.sdb.upgrade_to_token(grant, issue_refresh=True).copy()
rtoken = dict1["refresh_token"]
dict2 = self.sdb.refresh_token(rtoken, AREQ["client_id"])
assert dict1["access_token"] != dict2["access_token"]
with pytest.raises(WrongTokenType):
self.sdb.refresh_token(dict2["access_token"], AREQ["client_id"])
def test_refresh_token_cleared_session(self):
ae = AuthnEvent("uid", "salt")
sid = self.sdb.create_authz_session(ae, AREQ)
self.sdb[sid]["sub"] = "sub"
grant = self.sdb[sid]["code"]
dict1 = self.sdb.upgrade_to_token(grant, issue_refresh=True)
ac1 = dict1["access_token"]
self.sdb._db = {}
rtoken = dict1["refresh_token"]
dict2 = self.sdb.refresh_token(rtoken, AREQ["client_id"])
assert ac1 != dict2["access_token"]
assert self.sdb.is_valid(dict2["access_token"])
def test_is_valid(self):
ae1 = AuthnEvent("uid", "salt")
sid = self.sdb.create_authz_session(ae1, AREQ)
self.sdb[sid]["sub"] = "sub"
grant = self.sdb[sid]["code"]
assert self.sdb.is_valid(grant)
sinfo = self.sdb.upgrade_to_token(grant, issue_refresh=True)
assert not self.sdb.is_valid(grant)
access_token = sinfo["access_token"]
assert self.sdb.access_token.valid(access_token)
refresh_token = sinfo["refresh_token"]
sinfo = self.sdb.refresh_token(refresh_token, AREQ["client_id"])
access_token2 = sinfo["access_token"]
assert self.sdb.is_valid(access_token2)
try:
self.sdb.is_valid(access_token)
except KeyError:
pass
def test_valid_grant(self):
ae = AuthnEvent("another:user", "salt")
sid = self.sdb.create_authz_session(ae, AREQ)
grant = self.sdb[sid]["code"]
assert self.sdb.is_valid(grant)
def test_revoke_token(self):
ae1 = AuthnEvent("uid", "salt")
sid = self.sdb.create_authz_session(ae1, AREQ)
self.sdb[sid]["sub"] = "sub"
grant = self.sdb[sid]["code"]
tokens = self.sdb.upgrade_to_token(grant, issue_refresh=True)
access_token = tokens["access_token"]
refresh_token = tokens["refresh_token"]
assert self.sdb.is_valid(access_token)
self.sdb.revoke_token(access_token)
assert not self.sdb.is_valid(access_token)
sinfo = self.sdb.refresh_token(refresh_token, AREQ["client_id"])
access_token = sinfo["access_token"]
assert self.sdb.is_valid(access_token)
self.sdb.revoke_refresh_token(refresh_token)
assert not self.sdb.is_valid(refresh_token)
try:
self.sdb.refresh_token(refresh_token, AREQ["client_id"])
except ExpiredToken:
pass
assert self.sdb.is_valid(access_token)
ae2 = AuthnEvent("sub", "salt")
sid = self.sdb.create_authz_session(ae2, AREQ)
grant = self.sdb[sid]["code"]
self.sdb.revoke_token(grant)
assert not self.sdb.is_valid(grant)
def test_revoke_all_tokens(self):
ae1 = AuthnEvent("uid", "salt")
sid = self.sdb.create_authz_session(ae1, AREQ)
self.sdb[sid]["sub"] = "sub"
grant = self.sdb[sid]["code"]
tokens = self.sdb.upgrade_to_token(grant, issue_refresh=True)
access_token = tokens["access_token"]
refresh_token = tokens["refresh_token"]
self.sdb.revoke_all_tokens(access_token)
assert not self.sdb.is_valid(access_token)
assert not self.sdb.is_valid(refresh_token)
def test_sub_to_authn_event(self):
ae = AuthnEvent("sub", "salt", time_stamp=time.time())
sid = self.sdb.create_authz_session(ae, AREQ)
sub = self.sdb.do_sub(sid, "client_salt")
sids = self.sdb.get_sids_by_sub(sub)
ae = self.sdb[sids[0]]["authn_event"]
assert AuthnEvent.from_json(ae).valid()
def test_do_sub_deterministic(self):
ae = AuthnEvent("tester", "random_value")
sid = self.sdb.create_authz_session(ae, AREQ)
self.sdb.do_sub(sid, "other_random_value")
info = self.sdb[sid]
assert (
info["sub"]
== "179670cdee6375c48e577317b2abd7d5cd26a5cdb1cfb7ef84af3d703c71d013"
)
self.sdb.do_sub(
sid,
"other_random_value",
sector_id="http://example.com",
subject_type="pairwise",
)
info2 = self.sdb[sid]
assert (
info2["sub"]
== "aaa50d80f8780cf1c4beb39e8e126556292f5091b9e39596424fefa2b99d9c53"
)
self.sdb.do_sub(
sid,
"another_random_value",
sector_id="http://other.example.com",
subject_type="pairwise",
)
info2 = self.sdb[sid]
assert (
info2["sub"]
== "62fb630e29f0d41b88e049ac0ef49a9c3ac5418c029d6e4f5417df7e9443976b"
)
def test_get_authentication_event_dict(self):
self.sdb._db["123"] = {}
self.sdb._db["123"]["authn_event"] = {
"uid": "uid",
"salt": "salt",
"authn_time": 1000,
"valid_until": 1500,
}
ae = self.sdb.get_authentication_event("123")
assert ae.uid == "uid"
assert ae.salt == "salt"
assert ae.authn_time == 1000
assert ae.valid_until == 1500
def test_get_authentication_event_json(self):
self.sdb._db["123"] = {}
self.sdb._db["123"]["authn_event"] = json.dumps(
{"uid": "uid", "salt": "salt", "authn_time": 1000, "valid_until": 1500}
)
ae = self.sdb.get_authentication_event("123")
assert ae.uid == "uid"
assert ae.salt == "salt"
assert ae.authn_time == 1000
assert ae.valid_until == 1500
def test_get_sids_from_uid_distributed(self):
db = DictSessionBackend()
sdb1 = create_session_db("https://example.com/1", "secret", "password", db=db)
sdb2 = create_session_db("https://example.com/2", "secret", "password", db=db)
ae = AuthnEvent("sub", "salt", time_stamp=time.time())
sid1 = sdb1.create_authz_session(ae, AREQ)
sdb1.do_sub(sid1, "salt")
sid2 = sdb2.create_authz_session(ae, AREQ)
sdb2.do_sub(sid2, "salt")
sdb1sids = sdb1.get_sids_from_uid("sub")
sdb2sids = sdb2.get_sids_from_uid("sub")
assert sdb1sids == sdb2sids
def test_get_client_ids_for_uid(self):
self.sdb._db["123"] = {
"authn_event": json.dumps({"uid": "my_uid", "salt": "salt"}),
"client_id": "my_client",
}
assert self.sdb.get_client_ids_for_uid("my_uid") == ["my_client"]
def test_get_verify_logout(self):
self.sdb._db["123"] = {
"authn_event": json.dumps({"uid": "my_uid", "salt": "salt"}),
"verified_logout": "something",
}
assert self.sdb.get_verify_logout("my_uid") == "something"
def test_set_verify_logout(self):
self.sdb._db["123"] = {
"authn_event": json.dumps({"uid": "my_uid", "salt": "salt"})
}
self.sdb.set_verify_logout("my_uid")
assert self.sdb.get_verify_logout("my_uid") is not None
def test_set_verify_logout_multiple(self):
self.sdb._db["123"] = {
"authn_event": json.dumps({"uid": "my_uid", "salt": "salt"})
}
self.sdb._db["321"] = {
"authn_event": json.dumps({"uid": "my_uid", "salt": "salt"})
}
self.sdb.set_verify_logout("my_uid")
assert self.sdb.get_verify_logout("my_uid") is not None
assert (
self.sdb._db["123"]["verified_logout"]
== self.sdb._db["321"]["verified_logout"]
)
def test_get_token_ids(self):
self.sdb._db["123"] = {
"authn_event": json.dumps({"uid": "my_uid", "salt": "salt"}),
"id_token": "Id token",
}
assert set(self.sdb.get_token_ids("my_uid")) == {"Id token"}
def test_get_is_revoke_uid(self):
self.sdb._db["123"] = {
"authn_event": json.dumps({"uid": "my_uid", "salt": "salt"}),
"revoked": True,
}
assert self.sdb.is_revoke_uid("my_uid")
def test_revoke_uid(self):
self.sdb._db["123"] = {
"authn_event": json.dumps({"uid": "my_uid", "salt": "salt"})
}
self.sdb.revoke_uid("my_uid")
assert self.sdb.is_revoke_uid("my_uid")
class TestCrypt(object):
@pytest.fixture(autouse=True)
def create_crypt(self):
self.crypt = Crypt("4-amino-1H-pyrimidine-2-one")
def test_encrypt_decrypt(self):
ctext = self.crypt.encrypt("Cytosine")
plain = self.crypt.decrypt(ctext).decode("utf-8")
assert plain == "Cytosine "
ctext = self.crypt.encrypt("cytidinetriphosp")
plain = self.crypt.decrypt(ctext).decode("utf-8")
assert plain == "cytidinetriphosp"
def test_crypt_with_b64(self):
db = {}
msg = "secret{}{}".format(time.time(), random.random())
csum = hmac.new(msg.encode("utf-8"), digestmod=hashlib.sha224)
txt = csum.digest()
db[txt] = "foobar"
txt = txt + b"aces"
ctext = self.crypt.encrypt(txt)
onthewire = base64.b64encode(ctext)
plain = self.crypt.decrypt(base64.b64decode(onthewire))
assert plain.endswith(b"aces")
assert db[plain[:-4]] == "foobar"
| true | true |
f716aa23ec2670b3b6679f13ad0859e223f380ff | 309 | py | Python | dataset/proxies.py | unknown/reddit-aita | 557fd67120e529db8b014b74a71e3b926b0ed528 | [
"MIT"
] | null | null | null | dataset/proxies.py | unknown/reddit-aita | 557fd67120e529db8b014b74a71e3b926b0ed528 | [
"MIT"
] | null | null | null | dataset/proxies.py | unknown/reddit-aita | 557fd67120e529db8b014b74a71e3b926b0ed528 | [
"MIT"
] | null | null | null | import random
proxy_list = [
'http://p.webshare.io:19999'
]
def random_proxy():
i = random.randint(0, len(proxy_list) - 1)
p = {
'http': proxy_list[i]
}
return p
def remove_proxy(proxy):
proxy_list.remove(proxy)
print(f'Removed {proxy}-- {len(proxy_list)} proxies left') | 19.3125 | 62 | 0.621359 | import random
proxy_list = [
'http://p.webshare.io:19999'
]
def random_proxy():
i = random.randint(0, len(proxy_list) - 1)
p = {
'http': proxy_list[i]
}
return p
def remove_proxy(proxy):
proxy_list.remove(proxy)
print(f'Removed {proxy}-- {len(proxy_list)} proxies left') | true | true |
f716ab6b8551b5a9bf03bfb3d99382d22fe6e166 | 30,230 | py | Python | Scripts/simulation/interactions/utils/creation.py | velocist/TS4CheatsInfo | b59ea7e5f4bd01d3b3bd7603843d525a9c179867 | [
"Apache-2.0"
] | null | null | null | Scripts/simulation/interactions/utils/creation.py | velocist/TS4CheatsInfo | b59ea7e5f4bd01d3b3bd7603843d525a9c179867 | [
"Apache-2.0"
] | null | null | null | Scripts/simulation/interactions/utils/creation.py | velocist/TS4CheatsInfo | b59ea7e5f4bd01d3b3bd7603843d525a9c179867 | [
"Apache-2.0"
] | null | null | null | # uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\interactions\utils\creation.py
# Compiled at: 2019-12-03 21:37:40
# Size of source mod 2**32: 42011 bytes
from animation.animation_utils import flush_all_animations
from carry.carry_elements import enter_carry_while_holding
from element_utils import build_critical_section
from event_testing.resolver import SingleSimResolver
from filters.sim_template import TunableSimTemplate
from filters.tunable import TunableSimFilter
from interactions import ParticipantType, ParticipantTypeActorTargetSim, ParticipantTypeSingleSim, ParticipantTypeSingle
from interactions.interaction_finisher import FinishingType
from interactions.utils.interaction_elements import XevtTriggeredElement
from objects import VisibilityState
from objects.object_creation import ObjectCreationMixin
from objects.slots import RuntimeSlot
from sims.genealogy_tracker import genealogy_caching, FamilyRelationshipIndex
from sims.pregnancy.pregnancy_tracker import PregnancyTracker
from sims.sim_info_lod import SimInfoLODLevel
from sims.sim_spawner import SimSpawner, SimCreator
from sims4.tuning.geometric import TunableDistanceSquared
from sims4.tuning.tunable import TunableList, OptionalTunable, Tunable, TunableEnumEntry, TunableVariant, TunableFactory, TunableReference, HasTunableSingletonFactory, AutoFactoryInit
from singletons import EMPTY_SET, DEFAULT
from tag import Tag
from venues.venue_constants import NPCSummoningPurpose
from world.spawn_actions import TunableSpawnActionVariant
import element_utils, id_generator, interactions, services, sims.ghost, sims4.log, sims4.math, sims4.telemetry, telemetry_helper
logger = sims4.log.Logger('Creation')
TELEMETRY_GROUP_OBJECT = 'OBJC'
TELEMETRY_HOOK_OBJECT_CREATE_BSCEXTRA = 'CRBE'
TELEMETRY_FIELD_OBJECT_INTERACTION = 'intr'
TELEMETRY_FIELD_OBJECT_DEFINITION = 'objc'
writer = sims4.telemetry.TelemetryWriter(TELEMETRY_GROUP_OBJECT)
class ObjectCreationElement(XevtTriggeredElement, ObjectCreationMixin):
FACTORY_TUNABLES = {'cancel_on_destroy':Tunable(description='\n If checked, the interaction will be canceled if object is destroyed\n due to placement failure or if destroy on placement failure is\n unchecked and the fallback fails.\n ',
tunable_type=bool,
default=True),
'transient':Tunable(description='\n If checked, the created object will be destroyed when the interaction ends.\n ',
tunable_type=bool,
default=False),
'set_to_invisible':Tunable(description='\n If checked, the created object will be set to invisible when the \n interaction ends.\n ',
tunable_type=bool,
default=False)}
def __init__(self, interaction, *args, sequence=(), **kwargs):
(super().__init__)(interaction, *args, sequence=sequence, **kwargs)
self._definition_cache = None
self._placement_failed = False
self.initialize_helper(interaction.get_resolver())
if self.transient:
self.require_claim = True
@property
def definition(self):
if self._definition_cache is None:
self._definition_cache = super().definition
return self._definition_cache
@property
def placement_failed(self):
return self._placement_failed
def create_object_in_sequence(self):
self._place_object(self._object_helper.object)
if self._placement_failed:
if self.cancel_on_destroy:
self.interaction.cancel((FinishingType.FAILED_TESTS), cancel_reason_msg='Cannot place object')
return False
return True
if not self.transient:
self._object_helper.claim()
if self.set_to_invisible:
self._object_helper.object.visibility = VisibilityState(False)
with telemetry_helper.begin_hook(writer, TELEMETRY_HOOK_OBJECT_CREATE_BSCEXTRA) as (hook):
hook.write_enum(TELEMETRY_FIELD_OBJECT_INTERACTION, self.interaction.guid64)
hook.write_guid(TELEMETRY_FIELD_OBJECT_DEFINITION, self._object_helper.object.definition.id)
return True
def _setup_created_object(self, created_object):
self.interaction.object_create_helper = self._object_helper
super()._setup_created_object(created_object)
def _place_object(self, created_object):
place_object = super()._place_object(created_object)
if not place_object:
self._placement_failed = True
return place_object
def _build_outer_elements(self, sequence):
def set_carry_target(_):
self.interaction.track = DEFAULT
self.interaction.map_create_target(self.interaction.created_target)
def enter_carry(timeline):
result = yield from element_utils.run_child(timeline, enter_carry_while_holding((self.interaction), obj=(self.interaction.created_target),
carry_track_override=(self.location.carry_track_override),
owning_affordance=None,
sequence=(build_critical_section(sequence, flush_all_animations))))
return result
if False:
yield None
location_type = getattr(self.location, 'location', None)
if location_type == self.CARRY:
return self._object_helper.create(set_carry_target, enter_carry)
return self._object_helper.create(sequence)
def _do_behavior(self):
self.create_object_in_sequence()
class SimCreationElement(XevtTriggeredElement):
class _ActiveHouseholdFactory(TunableFactory):
@staticmethod
def factory(_):
return services.active_household()
FACTORY_TYPE = factory
class _ParticipantHouseholdFactory(TunableFactory):
@staticmethod
def factory(interaction, participant):
sim = interaction.get_participant(participant)
if sim is None:
logger.error('_ParticipantHouseholdFactory: {} does not have participant {}', interaction,
participant,
owner='jjacobson')
return
return sim.household
FACTORY_TYPE = factory
def __init__(self, *args, **kwargs):
(super().__init__)(participant=TunableEnumEntry(description='\n The participant that will have their household used to put the\n sim into.\n ',
tunable_type=ParticipantTypeActorTargetSim,
default=(ParticipantTypeActorTargetSim.Actor)), **kwargs)
class _NoHousheoldFactory(TunableFactory):
@staticmethod
def factory(_):
pass
FACTORY_TYPE = factory
class _HiddenHouseholdFactory(TunableFactory):
@staticmethod
def factory(_):
household = services.household_manager().create_household(services.get_first_client().account)
household.set_to_hidden(family_funds=0)
return household
FACTORY_TYPE = factory
class _BaseSimInfoSource(HasTunableSingletonFactory, AutoFactoryInit):
def get_sim_infos_and_positions(self, resolver):
raise NotImplementedError('Attempting to use the _BaseSimInfoSource base class, use sub-classes instead.')
def _try_add_sim_info_to_household(self, sim_info, resolver, household, skip_household_check=False):
if household is not None:
if skip_household_check or household is not sim_info.household:
if not household.can_add_sim_info(sim_info):
logger.warn('create_sim_from_sim_info element on the interaction: {} could not add a new sim to the tuned household.', resolver.interaction)
return False
if sim_info.household is not household:
sim_info.household.remove_sim_info(sim_info)
household.add_sim_info_to_household(sim_info)
return True
def do_pre_spawn_behavior(self, sim_info, resolver, household):
self._try_add_sim_info_to_household(sim_info, resolver, household)
def do_post_spawn_behavior(self, sim_info, resolver, client_manager):
client = client_manager.get_client_by_household_id(sim_info.household_id)
if client is not None:
client.add_selectable_sim_info(sim_info)
class _TargetedObjectResurrection(_BaseSimInfoSource):
FACTORY_TUNABLES = {'participant':TunableEnumEntry(description='\n The participant of the interaction against whom any relationship\n and genealogy tunables are applied.\n ',
tunable_type=ParticipantType,
default=ParticipantType.Actor),
'sim_info_subject':TunableEnumEntry(description='\n The subject from which the Sim Info used to create the new Sim\n should be fetched.\n ',
tunable_type=ParticipantType,
default=ParticipantType.Object),
'resurrect':Tunable(description='\n If checked, all Ghost traits are removed from the created Sim\n and its death type is cleared.\n \n If unchecked, this is a simple spawn operation.\n ',
tunable_type=bool,
default=True)}
def get_sim_infos_and_positions(self, resolver, household):
use_fgl = True
stored_sim_info_object = resolver.get_participant(self.sim_info_subject)
if stored_sim_info_object is None:
return ()
sim_info = stored_sim_info_object.get_stored_sim_info()
if sim_info is None:
return ()
return (
(
sim_info, stored_sim_info_object.position, None, use_fgl),)
def do_pre_spawn_behavior(self, sim_info, resolver, household):
super().do_pre_spawn_behavior(sim_info, resolver, household)
if self.resurrect:
sims.ghost.Ghost.remove_ghost_from_sim(sim_info)
class _MassObjectResurrection(_BaseSimInfoSource):
FACTORY_TUNABLES = {'participant':TunableEnumEntry(description='\n The participant of the interaction that will have sims resurrected\n around their position.\n ',
tunable_type=ParticipantType,
default=ParticipantType.Actor),
'radius':TunableDistanceSquared(description='\n The distance around a participant that will resurrect all of the\n dead sim objects.\n ',
default=1),
'tag':TunableEnumEntry(description='\n Tag the delineates an object that we want to resurrect sims\n from.\n ',
tunable_type=Tag,
default=Tag.INVALID)}
def get_sim_infos_and_positions(self, resolver, household):
use_fgl = True
sim_infos_and_positions = []
participant = resolver.get_participant(self.participant)
position = participant.position
for obj in services.object_manager().get_objects_with_tag_gen(self.tag):
obj_position = obj.position
distance_from_pos = obj_position - position
if distance_from_pos.magnitude_squared() > self.radius:
continue
sim_info = obj.get_stored_sim_info()
if sim_info is None:
continue
sim_infos_and_positions.append((sim_info, obj_position, None, use_fgl))
return tuple(sim_infos_and_positions)
def do_pre_spawn_behavior(self, sim_info, resolver, household):
super().do_pre_spawn_behavior(sim_info, resolver, household)
sims.ghost.Ghost.remove_ghost_from_sim(sim_info)
class _SlotSpawningSimInfoSource(_BaseSimInfoSource):
class _SlotByName(HasTunableSingletonFactory, AutoFactoryInit):
FACTORY_TUNABLES = {'slot_name': Tunable(description='\n The exact name of a slot on the parent object.\n ',
tunable_type=str,
default='_ctnm_')}
def get_slot_type_and_hash(self):
return (
None, sims4.hash_util.hash32(self.slot_name))
class _SlotByType(HasTunableSingletonFactory, AutoFactoryInit):
FACTORY_TUNABLES = {'slot_type': TunableReference(description='\n A particular slot type in which the should spawn.\n ',
manager=(services.get_instance_manager(sims4.resources.Types.SLOT_TYPE)))}
def get_slot_type_and_hash(self):
return (
self.slot_type, None)
FACTORY_TUNABLES = {'participant':TunableEnumEntry(description='\n The participant that is a sim that will be cloned\n Note: MUST be a sim. Use create object - clone object for non-sim objects.\n ',
tunable_type=ParticipantTypeSingleSim,
default=ParticipantTypeSingleSim.Actor),
'sim_spawn_slot':TunableVariant(description="\n The slot on the parent object where the sim should spawn. This\n may be either the exact name of a bone on the parent object or a\n slot type, in which case the first empty slot of the specified type\n will be used. If None is chosen, then the sim will at or near\n the interaction target's location.\n ",
by_name=_SlotByName.TunableFactory(),
by_type=_SlotByType.TunableFactory()),
'spawn_location_participant':TunableEnumEntry(description='\n The participant used for finding where to spawn the Sim. Typically you want to leave this as object.\n \n Special cases include:\n - For self-interactions, Object will resolve to None. This can be set to Actor if you want to spawn\n near the Sim running the interaction.\n ',
tunable_type=ParticipantTypeSingle,
default=ParticipantTypeSingle.Object)}
def __init__(self, sim_spawn_slot=None, **kwargs):
(super().__init__)(sim_spawn_slot=sim_spawn_slot, **kwargs)
self._slot_type = None
self._bone_name_hash = None
if sim_spawn_slot is not None:
self._slot_type, self._bone_name_hash = sim_spawn_slot.get_slot_type_and_hash()
def _get_position_and_location(self, spawning_object, resolver):
position, location = (None, None)
if self._slot_type is not None:
for runtime_slot in spawning_object.get_runtime_slots_gen(slot_types={self._slot_type}, bone_name_hash=(self._bone_name_hash)):
location = runtime_slot.location
else:
if self._bone_name_hash is not None:
runtime_slot = RuntimeSlot(spawning_object, self._bone_name_hash, EMPTY_SET)
if runtime_slot is not None:
location = runtime_slot.location
else:
location = spawning_object.location
if location is not None:
location = sims4.math.Location((location.world_transform), (spawning_object.routing_surface), slot_hash=(location.slot_hash))
position = location.transform.translation
return (position, location)
def _get_spawning_object(self, resolver):
spawning_object = resolver.get_participant(self.spawn_location_participant)
if spawning_object.is_sim:
spawning_object = spawning_object.get_sim_instance()
return spawning_object
class _CloneSimInfoSource(_SlotSpawningSimInfoSource):
FACTORY_TUNABLES = {'force_fgl': Tunable(description="\n Normally, FGL will only be invoked if no spawning position is found. Use this tunable to force\n FGL to run. e.g. Cloning spell uses caster Sim's position as a spawning position. In that case,\n we still want to force FGL so the clone spawns near that Sim rather than directly on top of the Sim. \n ",
tunable_type=bool,
default=False)}
def _ensure_parental_lineage_exists(self, source_sim_info, clone_sim_info):
with genealogy_caching():
if any(source_sim_info.genealogy.get_parent_sim_ids_gen()):
return
mom_id = id_generator.generate_object_id()
source_sim_info.genealogy.set_family_relation(FamilyRelationshipIndex.MOTHER, mom_id)
clone_sim_info.genealogy.set_family_relation(FamilyRelationshipIndex.MOTHER, mom_id)
sim_info_manager = services.sim_info_manager()
for child_sim_id in source_sim_info.genealogy.get_children_sim_ids_gen():
child_sim_info = sim_info_manager.get(child_sim_id)
if child_sim_info is not None:
grandparent_relation = FamilyRelationshipIndex.MOTHERS_MOM if source_sim_info.is_female else FamilyRelationshipIndex.FATHERS_MOM
child_sim_info.genealogy.set_family_relation(grandparent_relation, mom_id)
def _create_clone_sim_info(self, source_sim_info, resolver, household):
sim_creator = SimCreator(gender=(source_sim_info.gender), age=(source_sim_info.age),
first_name=(SimSpawner.get_random_first_name(source_sim_info.gender, source_sim_info.species)),
last_name=(source_sim_info._base.last_name),
traits=(source_sim_info.trait_tracker.equipped_traits))
sim_info_list, _ = SimSpawner.create_sim_infos((sim_creator,), household=household,
account=(source_sim_info.account),
generate_deterministic_sim=True,
creation_source='cloning',
skip_adding_to_household=True)
clone_sim_info = sim_info_list[0]
source_sim_proto = source_sim_info.save_sim(for_cloning=True)
clone_sim_id = clone_sim_info.sim_id
clone_first_name = clone_sim_info._base.first_name
clone_last_name = clone_sim_info._base.last_name
clone_breed_name = clone_sim_info._base.breed_name
clone_first_name_key = clone_sim_info._base.first_name_key
clone_last_name_key = clone_sim_info._base.last_name_key
clone_full_name_key = clone_sim_info._base.full_name_key
clone_breed_name_key = clone_sim_info._base.breed_name_key
clone_sim_info.load_sim_info(source_sim_proto, is_clone=True, default_lod=(SimInfoLODLevel.FULL))
clone_sim_info.sim_id = clone_sim_id
clone_sim_info._base.first_name = clone_first_name
clone_sim_info._base.last_name = clone_last_name
clone_sim_info._base.breed_name = clone_breed_name
clone_sim_info._base.first_name_key = clone_first_name_key
clone_sim_info._base.last_name_key = clone_last_name_key
clone_sim_info._base.full_name_key = clone_full_name_key
clone_sim_info._base.breed_name_key = clone_breed_name_key
clone_sim_info._household_id = household.id
if not self._try_add_sim_info_to_household(clone_sim_info, resolver, household, skip_household_check=True):
return
source_trait_tracker = source_sim_info.trait_tracker
clone_trait_tracker = clone_sim_info.trait_tracker
for trait in clone_trait_tracker.personality_traits:
if not source_trait_tracker.has_trait(trait):
clone_sim_info.remove_trait(trait)
for trait in clone_trait_tracker.gender_option_traits:
if not source_trait_tracker.has_trait(trait):
clone_sim_info.remove_trait(trait)
correct_aspiration_trait = clone_sim_info.primary_aspiration.primary_trait
for trait in tuple(clone_trait_tracker.aspiration_traits):
if trait is not correct_aspiration_trait:
clone_sim_info.remove_trait(trait)
source_sim_info.relationship_tracker.create_relationship(clone_sim_info.sim_id)
source_sim_info.relationship_tracker.add_relationship_score(clone_sim_info.sim_id, 1)
self._ensure_parental_lineage_exists(source_sim_info, clone_sim_info)
services.sim_info_manager().set_default_genealogy(sim_infos=(clone_sim_info,))
clone_sim_info.set_default_data()
clone_sim_info.save_sim()
household.save_data()
if not household.is_active_household:
clone_sim_info.request_lod(SimInfoLODLevel.BASE)
clone_sim_info.resend_physical_attributes()
clone_sim_info.relationship_tracker.clean_and_send_remaining_relationship_info()
return clone_sim_info
def do_pre_spawn_behavior(self, sim_info, resolver, household):
pass
def get_sim_infos_and_positions(self, resolver, household):
use_fgl = False
sim_info = resolver.get_participant(self.participant)
clone_sim_info = self._create_clone_sim_info(sim_info, resolver, household)
if clone_sim_info is None:
return ()
position, location = (None, None)
spawning_object = self._get_spawning_object(resolver)
if spawning_object is not None:
position, location = self._get_position_and_location(spawning_object, resolver)
use_fgl = self.force_fgl or position is None
return ((clone_sim_info, position, location, use_fgl),)
def do_post_spawn_behavior(self, sim_info, resolver, client_manager):
super().do_post_spawn_behavior(sim_info, resolver, client_manager)
sim_info.commodity_tracker.set_all_commodities_to_best_value(visible_only=True)
class _SimFilterSimInfoSource(_SlotSpawningSimInfoSource):
FACTORY_TUNABLES = {'filter': TunableSimFilter.TunableReference(description='\n Sim filter that is used to create or find a Sim that matches\n this filter request.\n ')}
def get_sim_filter_gsi_name(self):
return str(self)
def get_sim_infos_and_positions(self, resolver, household):
use_fgl = True
sim_info = resolver.get_participant(self.participant)
filter_result = services.sim_filter_service().submit_matching_filter(sim_filter=(self.filter), requesting_sim_info=sim_info,
allow_yielding=False,
gsi_source_fn=(self.get_sim_filter_gsi_name))
if not filter_result:
return ()
position, location = (None, None)
spawning_object = self._get_spawning_object(resolver)
if spawning_object is not None:
position, location = self._get_position_and_location(spawning_object, resolver)
use_fgl = position is None
return ((filter_result[0].sim_info, position, location, use_fgl),)
class _SimTemplateSimInfoSource(_SlotSpawningSimInfoSource):
FACTORY_TUNABLES = {'template': TunableSimTemplate.TunableReference(description='\n The template to use.\n ')}
def get_sim_infos_and_positions(self, resolver, household):
sim_creator = self.template.sim_creator
sim_info_list, _ = SimSpawner.create_sim_infos((sim_creator,), sim_name_type=(sim_creator.sim_name_type),
household=household)
self.template.add_template_data_to_sim((sim_info_list[0]), sim_creator=sim_creator)
position, location = (None, None)
spawning_object = self._get_spawning_object(resolver)
if spawning_object is not None:
position, location = self._get_position_and_location(spawning_object, resolver)
use_fgl = position is None
return ((sim_info_list[0], position, location, use_fgl),)
class _GenalogySetAsChild(HasTunableSingletonFactory):
def __call__(self, actor_sim_info, created_sim_info):
created_sim_info.last_name = SimSpawner.get_last_name(actor_sim_info.last_name, created_sim_info.gender, created_sim_info.species)
parent_a = actor_sim_info
parent_b = services.sim_info_manager().get(parent_a.spouse_sim_id)
created_sim_info.relationship_tracker.destroy_all_relationships()
for relation in FamilyRelationshipIndex:
relation_id = created_sim_info.get_relation(relation)
relation_info = services.sim_info_manager().get(relation_id)
if relation_info is not None:
created_sim_info.genealogy.remove_family_link(relation)
family_relation = relation_info.genealogy.get_family_relationship_bit(created_sim_info.sim_id)
relation_info.genealogy.clear_family_relation(family_relation)
relation_info.relationship_tracker.destroy_relationship(created_sim_info.sim_id)
created_sim_info.genealogy.clear_family_relation(relation)
PregnancyTracker.initialize_sim_info(created_sim_info, parent_a, parent_b)
FACTORY_TUNABLES = {'sim_info_source':TunableVariant(description='\n The source of the sim_info and position data for the sims to be\n created.\n ',
targeted=_TargetedObjectResurrection.TunableFactory(),
mass_object=_MassObjectResurrection.TunableFactory(),
clone_a_sim=_CloneSimInfoSource.TunableFactory(),
sim_filter=_SimFilterSimInfoSource.TunableFactory(),
sim_template=_SimTemplateSimInfoSource.TunableFactory(),
default='targeted'),
'household_option':TunableVariant(description='\n The household that the created sim should be put into.\n ',
active_household=_ActiveHouseholdFactory(),
participant_household=_ParticipantHouseholdFactory(),
no_household=_NoHousheoldFactory(),
hidden_household=_HiddenHouseholdFactory(),
default='participant_household'),
'spawn_action':TunableSpawnActionVariant(description='\n Define the methods to show the Sim after spawning on the lot. This\n defaults to fading the Sim in, but can be a specific interaction or\n an animation.\n '),
'relationship_bits_to_add':TunableList(description='\n A list of relationship bits to add between the source sim\n and the created sim.\n ',
tunable=TunableReference(manager=(services.get_instance_manager(sims4.resources.Types.RELATIONSHIP_BIT)))),
'set_summoning_purpose':OptionalTunable(description="\n If enabled this will trigger the summon NPC situation depending\n on the summoning purpose type set. This should be tuned when\n we create Sims and don't add them into the active household.\n ",
tunable=TunableEnumEntry(description='\n The purpose that is used to summon the sim to the lot. \n Defined in venue tuning.\n ',
tunable_type=NPCSummoningPurpose,
default=(NPCSummoningPurpose.DEFAULT))),
'set_genealogy':TunableVariant(description='\n Genealogy option to set on the created Sim. \n Example: Setting a child of a family.\n ',
set_as_child=_GenalogySetAsChild.TunableFactory(),
locked_args={'no_action': None},
default='no_action'),
'pre_spawn_loot':TunableList(description='\n List of loot actions to apply to the created sim info before it is\n spawned.\n ',
tunable=TunableReference(manager=(services.get_instance_manager(sims4.resources.Types.ACTION)),
class_restrictions=('LootActions', )))}
def _apply_relationship_bits(self, actor_sim_info, created_sim_info):
for rel_bit in self.relationship_bits_to_add:
actor_sim_info.relationship_tracker.add_relationship_bit((created_sim_info.sim_id), rel_bit, force_add=True)
def _do_behavior(self):
resolver = self.interaction.get_resolver()
target_participant = resolver.get_participant(self.sim_info_source.participant)
household = self.household_option(self.interaction)
client_manager = services.client_manager()
for sim_info, position, location, use_fgl in self.sim_info_source.get_sim_infos_and_positions(resolver, household):
if target_participant is not None:
self._apply_relationship_bits(target_participant, sim_info)
else:
single_sim_resolver = SingleSimResolver(sim_info)
for loot in self.pre_spawn_loot:
loot.apply_to_resolver(single_sim_resolver)
self.sim_info_source.do_pre_spawn_behavior(sim_info, resolver, household)
SimSpawner.spawn_sim(sim_info, position, spawn_action=(self.spawn_action), sim_location=location, use_fgl=use_fgl)
if self.set_summoning_purpose is not None:
services.current_zone().venue_service.active_venue.summon_npcs((sim_info,), self.set_summoning_purpose)
if self.set_genealogy is not None and target_participant is not None:
self.set_genealogy(target_participant, sim_info)
self.sim_info_source.do_post_spawn_behavior(sim_info, resolver, client_manager)
return True | 58.927875 | 452 | 0.673139 |
from animation.animation_utils import flush_all_animations
from carry.carry_elements import enter_carry_while_holding
from element_utils import build_critical_section
from event_testing.resolver import SingleSimResolver
from filters.sim_template import TunableSimTemplate
from filters.tunable import TunableSimFilter
from interactions import ParticipantType, ParticipantTypeActorTargetSim, ParticipantTypeSingleSim, ParticipantTypeSingle
from interactions.interaction_finisher import FinishingType
from interactions.utils.interaction_elements import XevtTriggeredElement
from objects import VisibilityState
from objects.object_creation import ObjectCreationMixin
from objects.slots import RuntimeSlot
from sims.genealogy_tracker import genealogy_caching, FamilyRelationshipIndex
from sims.pregnancy.pregnancy_tracker import PregnancyTracker
from sims.sim_info_lod import SimInfoLODLevel
from sims.sim_spawner import SimSpawner, SimCreator
from sims4.tuning.geometric import TunableDistanceSquared
from sims4.tuning.tunable import TunableList, OptionalTunable, Tunable, TunableEnumEntry, TunableVariant, TunableFactory, TunableReference, HasTunableSingletonFactory, AutoFactoryInit
from singletons import EMPTY_SET, DEFAULT
from tag import Tag
from venues.venue_constants import NPCSummoningPurpose
from world.spawn_actions import TunableSpawnActionVariant
import element_utils, id_generator, interactions, services, sims.ghost, sims4.log, sims4.math, sims4.telemetry, telemetry_helper
logger = sims4.log.Logger('Creation')
TELEMETRY_GROUP_OBJECT = 'OBJC'
TELEMETRY_HOOK_OBJECT_CREATE_BSCEXTRA = 'CRBE'
TELEMETRY_FIELD_OBJECT_INTERACTION = 'intr'
TELEMETRY_FIELD_OBJECT_DEFINITION = 'objc'
writer = sims4.telemetry.TelemetryWriter(TELEMETRY_GROUP_OBJECT)
class ObjectCreationElement(XevtTriggeredElement, ObjectCreationMixin):
FACTORY_TUNABLES = {'cancel_on_destroy':Tunable(description='\n If checked, the interaction will be canceled if object is destroyed\n due to placement failure or if destroy on placement failure is\n unchecked and the fallback fails.\n ',
tunable_type=bool,
default=True),
'transient':Tunable(description='\n If checked, the created object will be destroyed when the interaction ends.\n ',
tunable_type=bool,
default=False),
'set_to_invisible':Tunable(description='\n If checked, the created object will be set to invisible when the \n interaction ends.\n ',
tunable_type=bool,
default=False)}
def __init__(self, interaction, *args, sequence=(), **kwargs):
(super().__init__)(interaction, *args, sequence=sequence, **kwargs)
self._definition_cache = None
self._placement_failed = False
self.initialize_helper(interaction.get_resolver())
if self.transient:
self.require_claim = True
@property
def definition(self):
if self._definition_cache is None:
self._definition_cache = super().definition
return self._definition_cache
@property
def placement_failed(self):
return self._placement_failed
def create_object_in_sequence(self):
self._place_object(self._object_helper.object)
if self._placement_failed:
if self.cancel_on_destroy:
self.interaction.cancel((FinishingType.FAILED_TESTS), cancel_reason_msg='Cannot place object')
return False
return True
if not self.transient:
self._object_helper.claim()
if self.set_to_invisible:
self._object_helper.object.visibility = VisibilityState(False)
with telemetry_helper.begin_hook(writer, TELEMETRY_HOOK_OBJECT_CREATE_BSCEXTRA) as (hook):
hook.write_enum(TELEMETRY_FIELD_OBJECT_INTERACTION, self.interaction.guid64)
hook.write_guid(TELEMETRY_FIELD_OBJECT_DEFINITION, self._object_helper.object.definition.id)
return True
def _setup_created_object(self, created_object):
self.interaction.object_create_helper = self._object_helper
super()._setup_created_object(created_object)
def _place_object(self, created_object):
place_object = super()._place_object(created_object)
if not place_object:
self._placement_failed = True
return place_object
def _build_outer_elements(self, sequence):
def set_carry_target(_):
self.interaction.track = DEFAULT
self.interaction.map_create_target(self.interaction.created_target)
def enter_carry(timeline):
result = yield from element_utils.run_child(timeline, enter_carry_while_holding((self.interaction), obj=(self.interaction.created_target),
carry_track_override=(self.location.carry_track_override),
owning_affordance=None,
sequence=(build_critical_section(sequence, flush_all_animations))))
return result
if False:
yield None
location_type = getattr(self.location, 'location', None)
if location_type == self.CARRY:
return self._object_helper.create(set_carry_target, enter_carry)
return self._object_helper.create(sequence)
def _do_behavior(self):
self.create_object_in_sequence()
class SimCreationElement(XevtTriggeredElement):
class _ActiveHouseholdFactory(TunableFactory):
@staticmethod
def factory(_):
return services.active_household()
FACTORY_TYPE = factory
class _ParticipantHouseholdFactory(TunableFactory):
@staticmethod
def factory(interaction, participant):
sim = interaction.get_participant(participant)
if sim is None:
logger.error('_ParticipantHouseholdFactory: {} does not have participant {}', interaction,
participant,
owner='jjacobson')
return
return sim.household
FACTORY_TYPE = factory
def __init__(self, *args, **kwargs):
(super().__init__)(participant=TunableEnumEntry(description='\n The participant that will have their household used to put the\n sim into.\n ',
tunable_type=ParticipantTypeActorTargetSim,
default=(ParticipantTypeActorTargetSim.Actor)), **kwargs)
class _NoHousheoldFactory(TunableFactory):
@staticmethod
def factory(_):
pass
FACTORY_TYPE = factory
class _HiddenHouseholdFactory(TunableFactory):
@staticmethod
def factory(_):
household = services.household_manager().create_household(services.get_first_client().account)
household.set_to_hidden(family_funds=0)
return household
FACTORY_TYPE = factory
class _BaseSimInfoSource(HasTunableSingletonFactory, AutoFactoryInit):
def get_sim_infos_and_positions(self, resolver):
raise NotImplementedError('Attempting to use the _BaseSimInfoSource base class, use sub-classes instead.')
def _try_add_sim_info_to_household(self, sim_info, resolver, household, skip_household_check=False):
if household is not None:
if skip_household_check or household is not sim_info.household:
if not household.can_add_sim_info(sim_info):
logger.warn('create_sim_from_sim_info element on the interaction: {} could not add a new sim to the tuned household.', resolver.interaction)
return False
if sim_info.household is not household:
sim_info.household.remove_sim_info(sim_info)
household.add_sim_info_to_household(sim_info)
return True
def do_pre_spawn_behavior(self, sim_info, resolver, household):
self._try_add_sim_info_to_household(sim_info, resolver, household)
def do_post_spawn_behavior(self, sim_info, resolver, client_manager):
client = client_manager.get_client_by_household_id(sim_info.household_id)
if client is not None:
client.add_selectable_sim_info(sim_info)
class _TargetedObjectResurrection(_BaseSimInfoSource):
FACTORY_TUNABLES = {'participant':TunableEnumEntry(description='\n The participant of the interaction against whom any relationship\n and genealogy tunables are applied.\n ',
tunable_type=ParticipantType,
default=ParticipantType.Actor),
'sim_info_subject':TunableEnumEntry(description='\n The subject from which the Sim Info used to create the new Sim\n should be fetched.\n ',
tunable_type=ParticipantType,
default=ParticipantType.Object),
'resurrect':Tunable(description='\n If checked, all Ghost traits are removed from the created Sim\n and its death type is cleared.\n \n If unchecked, this is a simple spawn operation.\n ',
tunable_type=bool,
default=True)}
def get_sim_infos_and_positions(self, resolver, household):
use_fgl = True
stored_sim_info_object = resolver.get_participant(self.sim_info_subject)
if stored_sim_info_object is None:
return ()
sim_info = stored_sim_info_object.get_stored_sim_info()
if sim_info is None:
return ()
return (
(
sim_info, stored_sim_info_object.position, None, use_fgl),)
def do_pre_spawn_behavior(self, sim_info, resolver, household):
super().do_pre_spawn_behavior(sim_info, resolver, household)
if self.resurrect:
sims.ghost.Ghost.remove_ghost_from_sim(sim_info)
class _MassObjectResurrection(_BaseSimInfoSource):
FACTORY_TUNABLES = {'participant':TunableEnumEntry(description='\n The participant of the interaction that will have sims resurrected\n around their position.\n ',
tunable_type=ParticipantType,
default=ParticipantType.Actor),
'radius':TunableDistanceSquared(description='\n The distance around a participant that will resurrect all of the\n dead sim objects.\n ',
default=1),
'tag':TunableEnumEntry(description='\n Tag the delineates an object that we want to resurrect sims\n from.\n ',
tunable_type=Tag,
default=Tag.INVALID)}
def get_sim_infos_and_positions(self, resolver, household):
use_fgl = True
sim_infos_and_positions = []
participant = resolver.get_participant(self.participant)
position = participant.position
for obj in services.object_manager().get_objects_with_tag_gen(self.tag):
obj_position = obj.position
distance_from_pos = obj_position - position
if distance_from_pos.magnitude_squared() > self.radius:
continue
sim_info = obj.get_stored_sim_info()
if sim_info is None:
continue
sim_infos_and_positions.append((sim_info, obj_position, None, use_fgl))
return tuple(sim_infos_and_positions)
def do_pre_spawn_behavior(self, sim_info, resolver, household):
super().do_pre_spawn_behavior(sim_info, resolver, household)
sims.ghost.Ghost.remove_ghost_from_sim(sim_info)
class _SlotSpawningSimInfoSource(_BaseSimInfoSource):
class _SlotByName(HasTunableSingletonFactory, AutoFactoryInit):
FACTORY_TUNABLES = {'slot_name': Tunable(description='\n The exact name of a slot on the parent object.\n ',
tunable_type=str,
default='_ctnm_')}
def get_slot_type_and_hash(self):
return (
None, sims4.hash_util.hash32(self.slot_name))
class _SlotByType(HasTunableSingletonFactory, AutoFactoryInit):
FACTORY_TUNABLES = {'slot_type': TunableReference(description='\n A particular slot type in which the should spawn.\n ',
manager=(services.get_instance_manager(sims4.resources.Types.SLOT_TYPE)))}
def get_slot_type_and_hash(self):
return (
self.slot_type, None)
FACTORY_TUNABLES = {'participant':TunableEnumEntry(description='\n The participant that is a sim that will be cloned\n Note: MUST be a sim. Use create object - clone object for non-sim objects.\n ',
tunable_type=ParticipantTypeSingleSim,
default=ParticipantTypeSingleSim.Actor),
'sim_spawn_slot':TunableVariant(description="\n The slot on the parent object where the sim should spawn. This\n may be either the exact name of a bone on the parent object or a\n slot type, in which case the first empty slot of the specified type\n will be used. If None is chosen, then the sim will at or near\n the interaction target's location.\n ",
by_name=_SlotByName.TunableFactory(),
by_type=_SlotByType.TunableFactory()),
'spawn_location_participant':TunableEnumEntry(description='\n The participant used for finding where to spawn the Sim. Typically you want to leave this as object.\n \n Special cases include:\n - For self-interactions, Object will resolve to None. This can be set to Actor if you want to spawn\n near the Sim running the interaction.\n ',
tunable_type=ParticipantTypeSingle,
default=ParticipantTypeSingle.Object)}
def __init__(self, sim_spawn_slot=None, **kwargs):
(super().__init__)(sim_spawn_slot=sim_spawn_slot, **kwargs)
self._slot_type = None
self._bone_name_hash = None
if sim_spawn_slot is not None:
self._slot_type, self._bone_name_hash = sim_spawn_slot.get_slot_type_and_hash()
def _get_position_and_location(self, spawning_object, resolver):
position, location = (None, None)
if self._slot_type is not None:
for runtime_slot in spawning_object.get_runtime_slots_gen(slot_types={self._slot_type}, bone_name_hash=(self._bone_name_hash)):
location = runtime_slot.location
else:
if self._bone_name_hash is not None:
runtime_slot = RuntimeSlot(spawning_object, self._bone_name_hash, EMPTY_SET)
if runtime_slot is not None:
location = runtime_slot.location
else:
location = spawning_object.location
if location is not None:
location = sims4.math.Location((location.world_transform), (spawning_object.routing_surface), slot_hash=(location.slot_hash))
position = location.transform.translation
return (position, location)
def _get_spawning_object(self, resolver):
spawning_object = resolver.get_participant(self.spawn_location_participant)
if spawning_object.is_sim:
spawning_object = spawning_object.get_sim_instance()
return spawning_object
class _CloneSimInfoSource(_SlotSpawningSimInfoSource):
FACTORY_TUNABLES = {'force_fgl': Tunable(description="\n Normally, FGL will only be invoked if no spawning position is found. Use this tunable to force\n FGL to run. e.g. Cloning spell uses caster Sim's position as a spawning position. In that case,\n we still want to force FGL so the clone spawns near that Sim rather than directly on top of the Sim. \n ",
tunable_type=bool,
default=False)}
def _ensure_parental_lineage_exists(self, source_sim_info, clone_sim_info):
with genealogy_caching():
if any(source_sim_info.genealogy.get_parent_sim_ids_gen()):
return
mom_id = id_generator.generate_object_id()
source_sim_info.genealogy.set_family_relation(FamilyRelationshipIndex.MOTHER, mom_id)
clone_sim_info.genealogy.set_family_relation(FamilyRelationshipIndex.MOTHER, mom_id)
sim_info_manager = services.sim_info_manager()
for child_sim_id in source_sim_info.genealogy.get_children_sim_ids_gen():
child_sim_info = sim_info_manager.get(child_sim_id)
if child_sim_info is not None:
grandparent_relation = FamilyRelationshipIndex.MOTHERS_MOM if source_sim_info.is_female else FamilyRelationshipIndex.FATHERS_MOM
child_sim_info.genealogy.set_family_relation(grandparent_relation, mom_id)
def _create_clone_sim_info(self, source_sim_info, resolver, household):
sim_creator = SimCreator(gender=(source_sim_info.gender), age=(source_sim_info.age),
first_name=(SimSpawner.get_random_first_name(source_sim_info.gender, source_sim_info.species)),
last_name=(source_sim_info._base.last_name),
traits=(source_sim_info.trait_tracker.equipped_traits))
sim_info_list, _ = SimSpawner.create_sim_infos((sim_creator,), household=household,
account=(source_sim_info.account),
generate_deterministic_sim=True,
creation_source='cloning',
skip_adding_to_household=True)
clone_sim_info = sim_info_list[0]
source_sim_proto = source_sim_info.save_sim(for_cloning=True)
clone_sim_id = clone_sim_info.sim_id
clone_first_name = clone_sim_info._base.first_name
clone_last_name = clone_sim_info._base.last_name
clone_breed_name = clone_sim_info._base.breed_name
clone_first_name_key = clone_sim_info._base.first_name_key
clone_last_name_key = clone_sim_info._base.last_name_key
clone_full_name_key = clone_sim_info._base.full_name_key
clone_breed_name_key = clone_sim_info._base.breed_name_key
clone_sim_info.load_sim_info(source_sim_proto, is_clone=True, default_lod=(SimInfoLODLevel.FULL))
clone_sim_info.sim_id = clone_sim_id
clone_sim_info._base.first_name = clone_first_name
clone_sim_info._base.last_name = clone_last_name
clone_sim_info._base.breed_name = clone_breed_name
clone_sim_info._base.first_name_key = clone_first_name_key
clone_sim_info._base.last_name_key = clone_last_name_key
clone_sim_info._base.full_name_key = clone_full_name_key
clone_sim_info._base.breed_name_key = clone_breed_name_key
clone_sim_info._household_id = household.id
if not self._try_add_sim_info_to_household(clone_sim_info, resolver, household, skip_household_check=True):
return
source_trait_tracker = source_sim_info.trait_tracker
clone_trait_tracker = clone_sim_info.trait_tracker
for trait in clone_trait_tracker.personality_traits:
if not source_trait_tracker.has_trait(trait):
clone_sim_info.remove_trait(trait)
for trait in clone_trait_tracker.gender_option_traits:
if not source_trait_tracker.has_trait(trait):
clone_sim_info.remove_trait(trait)
correct_aspiration_trait = clone_sim_info.primary_aspiration.primary_trait
for trait in tuple(clone_trait_tracker.aspiration_traits):
if trait is not correct_aspiration_trait:
clone_sim_info.remove_trait(trait)
source_sim_info.relationship_tracker.create_relationship(clone_sim_info.sim_id)
source_sim_info.relationship_tracker.add_relationship_score(clone_sim_info.sim_id, 1)
self._ensure_parental_lineage_exists(source_sim_info, clone_sim_info)
services.sim_info_manager().set_default_genealogy(sim_infos=(clone_sim_info,))
clone_sim_info.set_default_data()
clone_sim_info.save_sim()
household.save_data()
if not household.is_active_household:
clone_sim_info.request_lod(SimInfoLODLevel.BASE)
clone_sim_info.resend_physical_attributes()
clone_sim_info.relationship_tracker.clean_and_send_remaining_relationship_info()
return clone_sim_info
def do_pre_spawn_behavior(self, sim_info, resolver, household):
pass
def get_sim_infos_and_positions(self, resolver, household):
use_fgl = False
sim_info = resolver.get_participant(self.participant)
clone_sim_info = self._create_clone_sim_info(sim_info, resolver, household)
if clone_sim_info is None:
return ()
position, location = (None, None)
spawning_object = self._get_spawning_object(resolver)
if spawning_object is not None:
position, location = self._get_position_and_location(spawning_object, resolver)
use_fgl = self.force_fgl or position is None
return ((clone_sim_info, position, location, use_fgl),)
def do_post_spawn_behavior(self, sim_info, resolver, client_manager):
super().do_post_spawn_behavior(sim_info, resolver, client_manager)
sim_info.commodity_tracker.set_all_commodities_to_best_value(visible_only=True)
class _SimFilterSimInfoSource(_SlotSpawningSimInfoSource):
FACTORY_TUNABLES = {'filter': TunableSimFilter.TunableReference(description='\n Sim filter that is used to create or find a Sim that matches\n this filter request.\n ')}
def get_sim_filter_gsi_name(self):
return str(self)
def get_sim_infos_and_positions(self, resolver, household):
use_fgl = True
sim_info = resolver.get_participant(self.participant)
filter_result = services.sim_filter_service().submit_matching_filter(sim_filter=(self.filter), requesting_sim_info=sim_info,
allow_yielding=False,
gsi_source_fn=(self.get_sim_filter_gsi_name))
if not filter_result:
return ()
position, location = (None, None)
spawning_object = self._get_spawning_object(resolver)
if spawning_object is not None:
position, location = self._get_position_and_location(spawning_object, resolver)
use_fgl = position is None
return ((filter_result[0].sim_info, position, location, use_fgl),)
class _SimTemplateSimInfoSource(_SlotSpawningSimInfoSource):
FACTORY_TUNABLES = {'template': TunableSimTemplate.TunableReference(description='\n The template to use.\n ')}
def get_sim_infos_and_positions(self, resolver, household):
sim_creator = self.template.sim_creator
sim_info_list, _ = SimSpawner.create_sim_infos((sim_creator,), sim_name_type=(sim_creator.sim_name_type),
household=household)
self.template.add_template_data_to_sim((sim_info_list[0]), sim_creator=sim_creator)
position, location = (None, None)
spawning_object = self._get_spawning_object(resolver)
if spawning_object is not None:
position, location = self._get_position_and_location(spawning_object, resolver)
use_fgl = position is None
return ((sim_info_list[0], position, location, use_fgl),)
class _GenalogySetAsChild(HasTunableSingletonFactory):
def __call__(self, actor_sim_info, created_sim_info):
created_sim_info.last_name = SimSpawner.get_last_name(actor_sim_info.last_name, created_sim_info.gender, created_sim_info.species)
parent_a = actor_sim_info
parent_b = services.sim_info_manager().get(parent_a.spouse_sim_id)
created_sim_info.relationship_tracker.destroy_all_relationships()
for relation in FamilyRelationshipIndex:
relation_id = created_sim_info.get_relation(relation)
relation_info = services.sim_info_manager().get(relation_id)
if relation_info is not None:
created_sim_info.genealogy.remove_family_link(relation)
family_relation = relation_info.genealogy.get_family_relationship_bit(created_sim_info.sim_id)
relation_info.genealogy.clear_family_relation(family_relation)
relation_info.relationship_tracker.destroy_relationship(created_sim_info.sim_id)
created_sim_info.genealogy.clear_family_relation(relation)
PregnancyTracker.initialize_sim_info(created_sim_info, parent_a, parent_b)
FACTORY_TUNABLES = {'sim_info_source':TunableVariant(description='\n The source of the sim_info and position data for the sims to be\n created.\n ',
targeted=_TargetedObjectResurrection.TunableFactory(),
mass_object=_MassObjectResurrection.TunableFactory(),
clone_a_sim=_CloneSimInfoSource.TunableFactory(),
sim_filter=_SimFilterSimInfoSource.TunableFactory(),
sim_template=_SimTemplateSimInfoSource.TunableFactory(),
default='targeted'),
'household_option':TunableVariant(description='\n The household that the created sim should be put into.\n ',
active_household=_ActiveHouseholdFactory(),
participant_household=_ParticipantHouseholdFactory(),
no_household=_NoHousheoldFactory(),
hidden_household=_HiddenHouseholdFactory(),
default='participant_household'),
'spawn_action':TunableSpawnActionVariant(description='\n Define the methods to show the Sim after spawning on the lot. This\n defaults to fading the Sim in, but can be a specific interaction or\n an animation.\n '),
'relationship_bits_to_add':TunableList(description='\n A list of relationship bits to add between the source sim\n and the created sim.\n ',
tunable=TunableReference(manager=(services.get_instance_manager(sims4.resources.Types.RELATIONSHIP_BIT)))),
'set_summoning_purpose':OptionalTunable(description="\n If enabled this will trigger the summon NPC situation depending\n on the summoning purpose type set. This should be tuned when\n we create Sims and don't add them into the active household.\n ",
tunable=TunableEnumEntry(description='\n The purpose that is used to summon the sim to the lot. \n Defined in venue tuning.\n ',
tunable_type=NPCSummoningPurpose,
default=(NPCSummoningPurpose.DEFAULT))),
'set_genealogy':TunableVariant(description='\n Genealogy option to set on the created Sim. \n Example: Setting a child of a family.\n ',
set_as_child=_GenalogySetAsChild.TunableFactory(),
locked_args={'no_action': None},
default='no_action'),
'pre_spawn_loot':TunableList(description='\n List of loot actions to apply to the created sim info before it is\n spawned.\n ',
tunable=TunableReference(manager=(services.get_instance_manager(sims4.resources.Types.ACTION)),
class_restrictions=('LootActions', )))}
def _apply_relationship_bits(self, actor_sim_info, created_sim_info):
for rel_bit in self.relationship_bits_to_add:
actor_sim_info.relationship_tracker.add_relationship_bit((created_sim_info.sim_id), rel_bit, force_add=True)
def _do_behavior(self):
resolver = self.interaction.get_resolver()
target_participant = resolver.get_participant(self.sim_info_source.participant)
household = self.household_option(self.interaction)
client_manager = services.client_manager()
for sim_info, position, location, use_fgl in self.sim_info_source.get_sim_infos_and_positions(resolver, household):
if target_participant is not None:
self._apply_relationship_bits(target_participant, sim_info)
else:
single_sim_resolver = SingleSimResolver(sim_info)
for loot in self.pre_spawn_loot:
loot.apply_to_resolver(single_sim_resolver)
self.sim_info_source.do_pre_spawn_behavior(sim_info, resolver, household)
SimSpawner.spawn_sim(sim_info, position, spawn_action=(self.spawn_action), sim_location=location, use_fgl=use_fgl)
if self.set_summoning_purpose is not None:
services.current_zone().venue_service.active_venue.summon_npcs((sim_info,), self.set_summoning_purpose)
if self.set_genealogy is not None and target_participant is not None:
self.set_genealogy(target_participant, sim_info)
self.sim_info_source.do_post_spawn_behavior(sim_info, resolver, client_manager)
return True | true | true |
f716ac0e3959c71c4d5608a0af8d5faae868b677 | 93 | py | Python | src/bot.py | amirsafiee/template_telegram_bot | 2dfaba93de6ff6066a8b2ac64e1ee95be19c1548 | [
"MIT"
] | null | null | null | src/bot.py | amirsafiee/template_telegram_bot | 2dfaba93de6ff6066a8b2ac64e1ee95be19c1548 | [
"MIT"
] | null | null | null | src/bot.py | amirsafiee/template_telegram_bot | 2dfaba93de6ff6066a8b2ac64e1ee95be19c1548 | [
"MIT"
] | 1 | 2022-01-24T12:59:19.000Z | 2022-01-24T12:59:19.000Z | import os
import telebot
bot = telebot.TeleBot(os.environ['BOT_TOKEN'], parse_mode='HTML')
| 15.5 | 65 | 0.752688 | import os
import telebot
bot = telebot.TeleBot(os.environ['BOT_TOKEN'], parse_mode='HTML')
| true | true |
f716ac52c89aa1029f08962d2e19db4bbf190274 | 796 | py | Python | util/plaintext.py | seounghwan-oh/homomorphic_encryption | be700505547b81671c37026e55c4eefbd44dcaae | [
"MIT"
] | 25 | 2020-11-06T13:54:33.000Z | 2022-03-18T18:53:37.000Z | util/plaintext.py | seounghwan-oh/homomorphic_encryption | be700505547b81671c37026e55c4eefbd44dcaae | [
"MIT"
] | 1 | 2021-04-04T17:49:00.000Z | 2021-04-05T13:46:21.000Z | util/plaintext.py | seounghwan-oh/homomorphic_encryption | be700505547b81671c37026e55c4eefbd44dcaae | [
"MIT"
] | 6 | 2021-04-04T17:26:09.000Z | 2022-03-28T19:26:29.000Z | """A module to keep track of a plaintext."""
class Plaintext:
"""An instance of a plaintext.
This is a wrapper class for a plaintext, which consists
of one polynomial.
Attributes:
poly (Polynomial): Plaintext polynomial.
scaling_factor (float): Scaling factor.
"""
def __init__(self, poly, scaling_factor=None):
"""Sets plaintext to given polynomial.
Args:
poly (Polynomial): Plaintext polynomial.
scaling_factor (float): Scaling factor.
"""
self.poly = poly
self.scaling_factor = scaling_factor
def __str__(self):
"""Represents plaintext as a readable string.
Returns:
A string which represents the Plaintext.
"""
return str(self.poly) | 25.677419 | 59 | 0.614322 |
class Plaintext:
def __init__(self, poly, scaling_factor=None):
self.poly = poly
self.scaling_factor = scaling_factor
def __str__(self):
return str(self.poly) | true | true |
f716acb54b4962beca238b19ba8258573c3ffe65 | 766 | py | Python | tst/util/chain_utils.py | TST-Group-BE/flax-blockchain | ed850df4f28ef4b6f71c175c8b6d07d27f7b3cd5 | [
"Apache-2.0"
] | null | null | null | tst/util/chain_utils.py | TST-Group-BE/flax-blockchain | ed850df4f28ef4b6f71c175c8b6d07d27f7b3cd5 | [
"Apache-2.0"
] | null | null | null | tst/util/chain_utils.py | TST-Group-BE/flax-blockchain | ed850df4f28ef4b6f71c175c8b6d07d27f7b3cd5 | [
"Apache-2.0"
] | null | null | null | from typing import List
from tst.types.blockchain_format.coin import Coin
from tst.types.blockchain_format.program import SerializedProgram
from tst.types.blockchain_format.sized_bytes import bytes32
from tst.util.condition_tools import (
conditions_dict_for_solution,
created_outputs_for_conditions_dict,
)
def additions_for_solution(
coin_name: bytes32, puzzle_reveal: SerializedProgram, solution: SerializedProgram, max_cost: int
) -> List[Coin]:
"""
Checks the conditions created by CoinSolution and returns the list of all coins created
"""
err, dic, cost = conditions_dict_for_solution(puzzle_reveal, solution, max_cost)
if err or dic is None:
return []
return created_outputs_for_conditions_dict(dic, coin_name)
| 34.818182 | 100 | 0.784595 | from typing import List
from tst.types.blockchain_format.coin import Coin
from tst.types.blockchain_format.program import SerializedProgram
from tst.types.blockchain_format.sized_bytes import bytes32
from tst.util.condition_tools import (
conditions_dict_for_solution,
created_outputs_for_conditions_dict,
)
def additions_for_solution(
coin_name: bytes32, puzzle_reveal: SerializedProgram, solution: SerializedProgram, max_cost: int
) -> List[Coin]:
err, dic, cost = conditions_dict_for_solution(puzzle_reveal, solution, max_cost)
if err or dic is None:
return []
return created_outputs_for_conditions_dict(dic, coin_name)
| true | true |
f716ada0abc16a0476ced0d0b57cf8389076e57f | 7,206 | py | Python | ABA_PY/CHK_2D_postp_part_A_v4.4.py | SunilAnandatheertha/ABAPYMAT | 48d4d178de38c1f3c4510ad7f06fe1647ae6227c | [
"BSD-3-Clause"
] | 1 | 2021-01-13T14:06:34.000Z | 2021-01-13T14:06:34.000Z | ABA_PY/CHK_2D_postp_part_A_v4.4.py | SunilAnandatheertha/ABAPYMAT | 48d4d178de38c1f3c4510ad7f06fe1647ae6227c | [
"BSD-3-Clause"
] | 5 | 2020-12-21T14:51:57.000Z | 2021-01-21T13:42:44.000Z | ABA_PY/CHK_2D_postp_part_A_v4.4.py | SunilAnandatheertha/ABAPYMAT-PXTAL-2D | 48d4d178de38c1f3c4510ad7f06fe1647ae6227c | [
"BSD-3-Clause"
] | 1 | 2022-02-25T20:03:18.000Z | 2022-02-25T20:03:18.000Z | """
COMPLETE DESCRIPTION HERE
"""
#-----------------------------------------------------------------
#1. Seperate this file for calibration models
# MAKE THE PYTHON PRE, MATLAB AND PYTHON POST and SPYDER pipelines ready for calibrations
# Set up the required folders
# Set up the excel file where to store the file numbers and model numbers
#2. Seperate this file for residual stress induce model
#3. Seperate this file for residual stress induce and relaxation model
#-----------------------------------------------------------------
# ANYTHING TO AID DEVELOPEMENT GOES HERE
# Snippet: to get strain atv centroids and SOLUTION DEPENDENT VARIABLES AT THE CENTROIDAL POSITIONS
# Strain = lastFrame.fieldOutputs['LE'].getSubset(region=polyI)
# Strain = myOdb.steps['Step-1'].frames[1].fieldOutputs['LE' ].getSubset(region=polyI, position=CENTROID)
# p01 = myOdb.steps['Step-1'].frames[1].fieldOutputs['SDV7' ].getSubset(region=polyI, position=CENTROID)
#-----------------------------------------------------------------
# Compatibility listing
# 1. CPS4, CPS4R
#-----------------------------------------------------------------
from abaqus import *
from abaqusConstants import *
from caeModules import *
from driverUtils import executeOnCaeStartup
import os
import visualization
import time
import numpy as np
#-----------------------------------------------------------------
executeOnCaeStartup()
Mdb()
#-----------------------------------------------------------------
# model and basic element dimensions
# GET USER REQUIREMENTS FOR UPPER CAPPING AND LOWER CAPPING THE CONTOUR DISPLAY LEGEND LEVELS
from abaqus import getInputs
fields = (('Model_origin_x:', '0'),
('Model_origin_y:', '0'),
('Model_enddim_x:', '100'),
('Model_enddim_y:', '6'),
('Model_enddim_z:', '1'),
)
Model_origin_x, Model_origin_y, Model_enddim_x,\
Model_enddim_y, Model_enddim_z, \
= getInputs(fields = fields, label = 'Specify Checkerboard model dimsnions:', dialogTitle = 'Keep origin at (0, 0) for now', )
Model_origin_x = float(Model_origin_x)
Model_origin_y = float(Model_origin_y)
Model_enddim_x = float(Model_enddim_x)
Model_enddim_y = float(Model_enddim_y)
Model_enddim_z = float(Model_enddim_z)
del fields
#-----------------------------------------------------------------
# Acquire level 0 solution metadata
odbinfo = (('Location', 'B'),
('Calibration iteration number(as: 00n, 0mn, mno', '009'),
('ODB_FileName (enter without the .odb):', 'Loc_B_009'),
('# of frames:', '16'),
('# of grains along x:', '24'),
('# of grains along y:', '4'),
('Element factor used:', '1'),
('SolutionInstance_metadata_Num (keep unchanged for now)', '1'),
('SolutionInstance_folder_path', 'C:\\Users\\anandats\\OneDrive - Coventry University\\coventry-thesis\\Chapter7\\ABAQUS_CAL_DATA_FILES\\LocationB\\'),
)
Cal_Location, Calib_Iteration_Num, This_ODB_FILENAME, NumOfFrames, NumGrains_X,\
NumGrains_Y, Elem_Factor_Used, SolInst_metadata_Num, SolInst_folder_path\
= getInputs(fields = odbinfo, label = 'Specify details of solution file', dialogTitle = 'Level 0 solution metadata', )
del odbinfo
MODEL_INFORMATION = {1:['ODBfilename', This_ODB_FILENAME, 'frames', NumOfFrames, 'Ngx', NumGrains_X, 'Ngy', NumGrains_Y, 'ElemFacUSED', Elem_Factor_Used],
2:[SolInst_folder_path],}
# only enter odd number IDs for ODB_ID, i.e. only line number containing meta-data and not folder address
ODB_ID = 1
ODB_FileName = MODEL_INFORMATION[ODB_ID][1]
TotalNumFrames = int(MODEL_INFORMATION[ODB_ID][3])
NumPartitions_x = int(MODEL_INFORMATION[ODB_ID][5])
NumPartitions_y = int(MODEL_INFORMATION[ODB_ID][7])
factorUSED = float(MODEL_INFORMATION[ODB_ID][9])
ElementSize = (Model_enddim_y/NumPartitions_y)/factorUSED
# frame incerements needed
# texture id value
# Elements per grain value
# elemebnt type value
frincr = 1
TEXIDVALUE = '02'
EPGValue = '003'
ElementType = 'CPS4'
#-----------------------------------------------------------------
# generate variable values needed to re-create element set names
Num_DatumPlanes_x = NumPartitions_x - 1
Num_DatumPlanes_y = NumPartitions_y - 1
#--------------------------------------------------------
# should the elemental results at centrouids be extracted? If extracted, they will be written to file
Extract_S11_ELCEN = 0
Extract_S22_ELCEN = 0
Extract_S12_ELCEN = 0
#--------------------------------------------------------
# defining filenames
import random
RandomNumber_START_MATLAB_OUTPUT = str(random.randint(10, 99))
RandomNumber_END_MATLAB_OUTPUT = str(random.randint(10, 99))
#--------------------------------------------------------
# GET USER REQUIREMENTS FOR UPPER CAPPING AND LOWER CAPPING THE CONTOUR DISPLAY LEGEND LEVELS
from abaqus import getInputs
fields = (('S11_contour_label_max_MPa:', '+0500'),
('S11_contour_label_min_MPa:', '+0000'),
('S22_contour_label_max_MPa:', '+0100'),
('S22_contour_label_min_MPa:', '-0100'),
('S12_contour_label_max_MPa:', '+0050'),
('S12_contour_label_min_MPa:', '-0050'),
)
S11_contour_label_max_MPa, S11_contour_label_min_MPa,\
S22_contour_label_max_MPa, S22_contour_label_min_MPa,\
S12_contour_label_max_MPa, S12_contour_label_min_MPa, \
= getInputs(fields = fields, label = 'Specify UPPER AND LOWER CAPPING LEVELS FOR CONTOUR LEGEND:', dialogTitle = 'Legend limits: STRESS', )
S11_contour_label_max_MPa = float(S11_contour_label_max_MPa)
S11_contour_label_min_MPa = float(S11_contour_label_min_MPa)
S22_contour_label_max_MPa = float(S22_contour_label_max_MPa)
S22_contour_label_min_MPa = float(S22_contour_label_min_MPa)
S12_contour_label_max_MPa = float(S12_contour_label_max_MPa)
S12_contour_label_min_MPa = float(S12_contour_label_min_MPa)
del fields
#--------------------------------------------------------
# PRINT FLAGS TO SPECIFY WHTHER IMAGES ARE TO BE PRINTED TO PNG FILES
fields = (('Print_S11_Contours_File:', '0'), ('Print_S22_Contours_File:', '0'),
('Print_S12_Contours_File:', '0'),
)
Print_S11_Contours_File, Print_S22_Contours_File,\
Print_S12_Contours_File,\
= getInputs(fields = fields, label = 'Enter 1(print) and 0(dont print)', dialogTitle = 'Set print to .png file requirements', )
Print_S11_Contours_File = float(Print_S11_Contours_File)
del fields
#-----------------------------------------------------------------
# VIEWPORT - 1
VP_num = 1
VP_name = 'Viewport: ' + str(VP_num)
#VP_ODB_PathName = 'C:/Temp/CalibrationModels/Cal_100ng/'
VP_ODB_PathName = MODEL_INFORMATION[ODB_ID+1][0]
#VP_ODB_FileName = ODB_FileName + '.odb'
VP_ODB_FileName = MODEL_INFORMATION[ODB_ID][1]
VP_ODB_FullPathName = VP_ODB_PathName + VP_ODB_FileName + '.odb'
VP_UpGraded_ODB_FullPathName = VP_ODB_PathName + VP_ODB_FileName + '_UpGraded' + '.odb'
MVPport = session.Viewport(name = VP_name, origin = (0.0, 0.0), width = 150, height = 100)
SESS_VP = session.viewports[VP_name]
SESS_VP.makeCurrent()
SESS_VP.maximize()
SESS_VP.partDisplay.geometryOptions.setValues(referenceRepresentation = ON)
SESS_VP.setValues(displayedObject = None)
import os.path
import odbAccess
import visualization
import abaqus
| 44.481481 | 156 | 0.664585 |
from abaqus import *
from abaqusConstants import *
from caeModules import *
from driverUtils import executeOnCaeStartup
import os
import visualization
import time
import numpy as np
executeOnCaeStartup()
Mdb()
from abaqus import getInputs
fields = (('Model_origin_x:', '0'),
('Model_origin_y:', '0'),
('Model_enddim_x:', '100'),
('Model_enddim_y:', '6'),
('Model_enddim_z:', '1'),
)
Model_origin_x, Model_origin_y, Model_enddim_x,\
Model_enddim_y, Model_enddim_z, \
= getInputs(fields = fields, label = 'Specify Checkerboard model dimsnions:', dialogTitle = 'Keep origin at (0, 0) for now', )
Model_origin_x = float(Model_origin_x)
Model_origin_y = float(Model_origin_y)
Model_enddim_x = float(Model_enddim_x)
Model_enddim_y = float(Model_enddim_y)
Model_enddim_z = float(Model_enddim_z)
del fields
odbinfo = (('Location', 'B'),
('Calibration iteration number(as: 00n, 0mn, mno', '009'),
('ODB_FileName (enter without the .odb):', 'Loc_B_009'),
('# of frames:', '16'),
('# of grains along x:', '24'),
('# of grains along y:', '4'),
('Element factor used:', '1'),
('SolutionInstance_metadata_Num (keep unchanged for now)', '1'),
('SolutionInstance_folder_path', 'C:\\Users\\anandats\\OneDrive - Coventry University\\coventry-thesis\\Chapter7\\ABAQUS_CAL_DATA_FILES\\LocationB\\'),
)
Cal_Location, Calib_Iteration_Num, This_ODB_FILENAME, NumOfFrames, NumGrains_X,\
NumGrains_Y, Elem_Factor_Used, SolInst_metadata_Num, SolInst_folder_path\
= getInputs(fields = odbinfo, label = 'Specify details of solution file', dialogTitle = 'Level 0 solution metadata', )
del odbinfo
MODEL_INFORMATION = {1:['ODBfilename', This_ODB_FILENAME, 'frames', NumOfFrames, 'Ngx', NumGrains_X, 'Ngy', NumGrains_Y, 'ElemFacUSED', Elem_Factor_Used],
2:[SolInst_folder_path],}
ODB_ID = 1
ODB_FileName = MODEL_INFORMATION[ODB_ID][1]
TotalNumFrames = int(MODEL_INFORMATION[ODB_ID][3])
NumPartitions_x = int(MODEL_INFORMATION[ODB_ID][5])
NumPartitions_y = int(MODEL_INFORMATION[ODB_ID][7])
factorUSED = float(MODEL_INFORMATION[ODB_ID][9])
ElementSize = (Model_enddim_y/NumPartitions_y)/factorUSED
frincr = 1
TEXIDVALUE = '02'
EPGValue = '003'
ElementType = 'CPS4'
Num_DatumPlanes_x = NumPartitions_x - 1
Num_DatumPlanes_y = NumPartitions_y - 1
Extract_S11_ELCEN = 0
Extract_S22_ELCEN = 0
Extract_S12_ELCEN = 0
import random
RandomNumber_START_MATLAB_OUTPUT = str(random.randint(10, 99))
RandomNumber_END_MATLAB_OUTPUT = str(random.randint(10, 99))
from abaqus import getInputs
fields = (('S11_contour_label_max_MPa:', '+0500'),
('S11_contour_label_min_MPa:', '+0000'),
('S22_contour_label_max_MPa:', '+0100'),
('S22_contour_label_min_MPa:', '-0100'),
('S12_contour_label_max_MPa:', '+0050'),
('S12_contour_label_min_MPa:', '-0050'),
)
S11_contour_label_max_MPa, S11_contour_label_min_MPa,\
S22_contour_label_max_MPa, S22_contour_label_min_MPa,\
S12_contour_label_max_MPa, S12_contour_label_min_MPa, \
= getInputs(fields = fields, label = 'Specify UPPER AND LOWER CAPPING LEVELS FOR CONTOUR LEGEND:', dialogTitle = 'Legend limits: STRESS', )
S11_contour_label_max_MPa = float(S11_contour_label_max_MPa)
S11_contour_label_min_MPa = float(S11_contour_label_min_MPa)
S22_contour_label_max_MPa = float(S22_contour_label_max_MPa)
S22_contour_label_min_MPa = float(S22_contour_label_min_MPa)
S12_contour_label_max_MPa = float(S12_contour_label_max_MPa)
S12_contour_label_min_MPa = float(S12_contour_label_min_MPa)
del fields
fields = (('Print_S11_Contours_File:', '0'), ('Print_S22_Contours_File:', '0'),
('Print_S12_Contours_File:', '0'),
)
Print_S11_Contours_File, Print_S22_Contours_File,\
Print_S12_Contours_File,\
= getInputs(fields = fields, label = 'Enter 1(print) and 0(dont print)', dialogTitle = 'Set print to .png file requirements', )
Print_S11_Contours_File = float(Print_S11_Contours_File)
del fields
VP_num = 1
VP_name = 'Viewport: ' + str(VP_num)
VP_ODB_PathName = MODEL_INFORMATION[ODB_ID+1][0]
VP_ODB_FileName = MODEL_INFORMATION[ODB_ID][1]
VP_ODB_FullPathName = VP_ODB_PathName + VP_ODB_FileName + '.odb'
VP_UpGraded_ODB_FullPathName = VP_ODB_PathName + VP_ODB_FileName + '_UpGraded' + '.odb'
MVPport = session.Viewport(name = VP_name, origin = (0.0, 0.0), width = 150, height = 100)
SESS_VP = session.viewports[VP_name]
SESS_VP.makeCurrent()
SESS_VP.maximize()
SESS_VP.partDisplay.geometryOptions.setValues(referenceRepresentation = ON)
SESS_VP.setValues(displayedObject = None)
import os.path
import odbAccess
import visualization
import abaqus
| true | true |
f716adfe3834f0888422f74ed1401389c19dd141 | 21,995 | py | Python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_06_01/aio/operations/_vpn_connections_operations.py | rsdoherty/azure-sdk-for-python | 6bba5326677468e6660845a703686327178bb7b1 | [
"MIT"
] | 3 | 2020-06-23T02:25:27.000Z | 2021-09-07T18:48:11.000Z | sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_06_01/aio/operations/_vpn_connections_operations.py | rsdoherty/azure-sdk-for-python | 6bba5326677468e6660845a703686327178bb7b1 | [
"MIT"
] | 510 | 2019-07-17T16:11:19.000Z | 2021-08-02T08:38:32.000Z | sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_06_01/aio/operations/_vpn_connections_operations.py | rsdoherty/azure-sdk-for-python | 6bba5326677468e6660845a703686327178bb7b1 | [
"MIT"
] | 5 | 2019-09-04T12:51:37.000Z | 2020-09-16T07:28:40.000Z | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class VpnConnectionsOperations:
"""VpnConnectionsOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.network.v2018_06_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
async def get(
self,
resource_group_name: str,
gateway_name: str,
connection_name: str,
**kwargs
) -> "_models.VpnConnection":
"""Retrieves the details of a vpn connection.
:param resource_group_name: The resource group name of the VpnGateway.
:type resource_group_name: str
:param gateway_name: The name of the gateway.
:type gateway_name: str
:param connection_name: The name of the vpn connection.
:type connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: VpnConnection, or the result of cls(response)
:rtype: ~azure.mgmt.network.v2018_06_01.models.VpnConnection
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnConnection"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2018-06-01"
accept = "application/json"
# Construct URL
url = self.get.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('VpnConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} # type: ignore
async def _create_or_update_initial(
self,
resource_group_name: str,
gateway_name: str,
connection_name: str,
vpn_connection_parameters: "_models.VpnConnection",
**kwargs
) -> "_models.VpnConnection":
cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnConnection"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2018-06-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._create_or_update_initial.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(vpn_connection_parameters, 'VpnConnection')
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('VpnConnection', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('VpnConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} # type: ignore
async def begin_create_or_update(
self,
resource_group_name: str,
gateway_name: str,
connection_name: str,
vpn_connection_parameters: "_models.VpnConnection",
**kwargs
) -> AsyncLROPoller["_models.VpnConnection"]:
"""Creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the
existing connection.
:param resource_group_name: The resource group name of the VpnGateway.
:type resource_group_name: str
:param gateway_name: The name of the gateway.
:type gateway_name: str
:param connection_name: The name of the connection.
:type connection_name: str
:param vpn_connection_parameters: Parameters supplied to create or Update a VPN Connection.
:type vpn_connection_parameters: ~azure.mgmt.network.v2018_06_01.models.VpnConnection
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: Pass in True if you'd like the AsyncARMPolling polling method,
False for no polling, or your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either VpnConnection or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2018_06_01.models.VpnConnection]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnConnection"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_or_update_initial(
resource_group_name=resource_group_name,
gateway_name=gateway_name,
connection_name=connection_name,
vpn_connection_parameters=vpn_connection_parameters,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('VpnConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} # type: ignore
async def _delete_initial(
self,
resource_group_name: str,
gateway_name: str,
connection_name: str,
**kwargs
) -> None:
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2018-06-01"
accept = "application/json"
# Construct URL
url = self._delete_initial.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} # type: ignore
async def begin_delete(
self,
resource_group_name: str,
gateway_name: str,
connection_name: str,
**kwargs
) -> AsyncLROPoller[None]:
"""Deletes a vpn connection.
:param resource_group_name: The resource group name of the VpnGateway.
:type resource_group_name: str
:param gateway_name: The name of the gateway.
:type gateway_name: str
:param connection_name: The name of the connection.
:type connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: Pass in True if you'd like the AsyncARMPolling polling method,
False for no polling, or your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType[None]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial(
resource_group_name=resource_group_name,
gateway_name=gateway_name,
connection_name=connection_name,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
if cls:
return cls(pipeline_response, None, {})
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} # type: ignore
def list_by_vpn_gateway(
self,
resource_group_name: str,
gateway_name: str,
**kwargs
) -> AsyncIterable["_models.ListVpnConnectionsResult"]:
"""Retrieves all vpn connections for a particular virtual wan vpn gateway.
:param resource_group_name: The resource group name of the VpnGateway.
:type resource_group_name: str
:param gateway_name: The name of the gateway.
:type gateway_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ListVpnConnectionsResult or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2018_06_01.models.ListVpnConnectionsResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ListVpnConnectionsResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2018-06-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list_by_vpn_gateway.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('ListVpnConnectionsResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
error = self._deserialize.failsafe_deserialize(_models.Error, response)
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list_by_vpn_gateway.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections'} # type: ignore
| 50.447248 | 220 | 0.672926 |
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class VpnConnectionsOperations:
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
async def get(
self,
resource_group_name: str,
gateway_name: str,
connection_name: str,
**kwargs
) -> "_models.VpnConnection":
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2018-06-01"
accept = "application/json"
url = self.get.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
header_parameters = {}
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('VpnConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'}
async def _create_or_update_initial(
self,
resource_group_name: str,
gateway_name: str,
connection_name: str,
vpn_connection_parameters: "_models.VpnConnection",
**kwargs
) -> "_models.VpnConnection":
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2018-06-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
url = self._create_or_update_initial.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
header_parameters = {}
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {}
body_content = self._serialize.body(vpn_connection_parameters, 'VpnConnection')
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('VpnConnection', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('VpnConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'}
async def begin_create_or_update(
self,
resource_group_name: str,
gateway_name: str,
connection_name: str,
vpn_connection_parameters: "_models.VpnConnection",
**kwargs
) -> AsyncLROPoller["_models.VpnConnection"]:
polling = kwargs.pop('polling', True)
cls = kwargs.pop('cls', None)
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None)
if cont_token is None:
raw_result = await self._create_or_update_initial(
resource_group_name=resource_group_name,
gateway_name=gateway_name,
connection_name=connection_name,
vpn_connection_parameters=vpn_connection_parameters,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('VpnConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'}
async def _delete_initial(
self,
resource_group_name: str,
gateway_name: str,
connection_name: str,
**kwargs
) -> None:
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2018-06-01"
accept = "application/json"
url = self._delete_initial.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
header_parameters = {}
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'}
async def begin_delete(
self,
resource_group_name: str,
gateway_name: str,
connection_name: str,
**kwargs
) -> AsyncLROPoller[None]:
polling = kwargs.pop('polling', True)
cls = kwargs.pop('cls', None)
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None)
if cont_token is None:
raw_result = await self._delete_initial(
resource_group_name=resource_group_name,
gateway_name=gateway_name,
connection_name=connection_name,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
if cls:
return cls(pipeline_response, None, {})
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'}
def list_by_vpn_gateway(
self,
resource_group_name: str,
gateway_name: str,
**kwargs
) -> AsyncIterable["_models.ListVpnConnectionsResult"]:
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2018-06-01"
accept = "application/json"
def prepare_request(next_link=None):
header_parameters = {}
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
url = self.list_by_vpn_gateway.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {}
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('ListVpnConnectionsResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
error = self._deserialize.failsafe_deserialize(_models.Error, response)
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list_by_vpn_gateway.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections'}
| true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.